Android Media Player App services - java

I am developing a media player app that has a bound service to an activity.It works fine when i press the home button or the app switcher and then come back to the app from the recent app, but as i press the back button the activity also ends the Music Service. Please guide me the exact steps that can solve these minor issues, so that i can give media controls to the app.My App has 2 main classes
MyActivity
AudioService
My code is given below.
AudioService.java
public class AudioService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
// -----------------------------------------Attributes--------------------------------------------------------
private ArrayList<File> songs;
private ArrayList<File> audio;
private MediaPlayer player;
private int songPosn;
private String name="";
private final IBinder musicBind = new AudioBinder();
private Uri trackUri;
private int NOTIFY_ID=1;
// -----------------------------------------------------------------------------------------------------------
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void onCreate(){
//create the service
//create the service
super.onCreate();
//initialize position
songPosn=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
// to initialize the media class
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<File> theSongs){
songs=theSongs;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
songPosn = intent.getIntExtra("pos",0);
audio=(ArrayList)intent.getParcelableArrayListExtra("songlist");
name = intent.getStringExtra("name");
Log.e("Service","name"+audio.get(0));
Log.e("Service","position "+songPosn);
return START_STICKY;
}
public void playSong(){
//play a song
player.reset();
Log.e("TRACH the URI",""+trackUri);
trackUri =Uri.parse(audio.get(songPosn).toString());
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
private void showNotification(){
Intent notIntent = new Intent(this, MyActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(name)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(name);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
#Override
public void onDestroy()
{
stopForeground(true);
}
}
MyActivity.java
public class MyActivity extends Activity {
// ***************************** Attributes Start ******************************************************
private ArrayList<File> myfiles= new ArrayList<File>();
private ListView listView;
private ArrayAdapter<String> adapter ;
private String name="";
private int position;
private AudioService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
// ***************************** Attributes End ******************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String toneslist[] ={"Airtel"
,"sherlock_theme"};
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(getApplication(),R.layout.list_item,R.id.list_textview,toneslist);
listView.setAdapter(adapter);
getMp3();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
name =adapter.getItem(pos);
position =pos;
Log.e("MAINACTIVITY (clickListener) pos =",""+position+" name = "+name);
musicSrv.setSong(position);
musicSrv.playSong();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
Log.e("MAINACTIVITY pos =",""+position+" name = "+name);
playIntent = new Intent(this, AudioService.class).putExtra("pos",position).putExtra("songlist", myfiles).putExtra("name", name);
bindService(playIntent, audioConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
private ServiceConnection audioConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
AudioService.AudioBinder binder = (AudioService.AudioBinder)service;
musicSrv = binder.getService();
musicSrv.setList(myfiles);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getMp3(){
String s=(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)).toString();
// s="content://media/external/audio/media";
GetFiles(s);
}
private void GetFiles(String path) {
File file = new File(path);
File[] allfiles = file.listFiles();
if (allfiles.length == 0) {
} else {
for (int i = 0; i < allfiles.length; i++)
{
Log.e("FFFFFFFFF", allfiles[i].getName().toString());
myfiles.add(allfiles[i]);
}
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}

Try with this in your Activity:
#Override
public void onDestroy(){
if (!isChangingConfigurations()) stopService(new Intent (this, YourService.class));
super.onDestroy();
}
#Override
public void onBackPressed(){
if (mediaIsPlaying) moveTaskToBack(true);
else super.onBackPressed();
}

Related

how to pause mp3 using mediaplayer in another activity when an item is clicked?

i'm make mp3 player offline, in the MainActivity there is a song list when an item is clicked it will send the song data with intent to PlayActivity. I want when another song is clicked then the current song is paused. What should i do? below is my code
MainActivity
public class MainActivity extends AppCompatActivity {
//deklarasi variabel -->
MediaPlayer mediaPlayer;
ListView listView;
final String[] song_name = { "intuisi", "krisis solusi" };
final int[] ResID = {R.raw.intuisi, R.raw.krisis};
ImageView img_play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//inisialisasi variabel
mediaPlayer = new MediaPlayer();
listView = findViewById(R.id.list_item);
//make adapter for listview
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, song_name);
listView.setAdapter(adapter);
//onClick item
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
playSong(i);
}
});
}
private void playSong(int songIndex) {
//send song data to playActivity
Intent intent = new Intent(MainActivity.this, Play.class);
intent.putExtra("song", ResID[songIndex]);
startActivity(intent);
}
PlayActivity
int Nama = getIntent().getIntExtra("song",0);
mediaPlayer = MediaPlayer.create(getApplicationContext(), Nama);
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
You can create a separate singleton helper class for handling your music player with some contextual method like play, pause, stop etc.
public class MusicHelper {
private static MusicHelper instance;
MediaPlayer mPlayer;
private MusicHelper() {
instance = new MusicHelper();
}
public static MusicHelper getInstance() {
return instance;
}
public void init(Context ctx, int nama) {
mPlayer = MediaPlayer.create(getApplicationContext(), nama);
}
public void play() {
if (mPlayer != null && !mPlayer.isPlaying()) {
mPlayer.start();
}
}
public void pause() {
if (mPlayer!= null && mPlayer.isPlaying()) {
mPlayer.pause();
}
}
}
Then in your PlayActivity,
MusicHelper musicHelper = MusicHelper.getInstance();
musicHelper.init(getApplicationContext(), Nama);
musicHelper.play();
When clicked on another item, again fetch the helper instance and call pause.
private void playSong(int songIndex) {
MusicHelper musicHelper = MusicHelper.getInstance();
musicHelper.pause();
Intent intent = new Intent(MainActivity.this, Play.class);
intent.putExtra("song", ResID[songIndex]);
startActivity(intent);
}

Android: Back click exists from app when using YouTube API

I am using Youtube API for android. Below is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = true;
}
});
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
Toast.makeText(this,"Back pressed",Toast.LENGTH_LONG).show();
if(isFullScreen)
{
player.setFullscreen(false);
}
else
{
super.onBackPressed();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--<com.google.android.youtube.player.YouTubePlayerView-->
<!--android:id="#+id/youtube_view"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"/>-->
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
When the Full Screen is visible and if the user clicked back, I want my Activity to be displayed. Instead what is happening now is the back button exists from the app.
How can I fix this?
UPDATE
I Identified the error, inside the setOnFullScreenListener it was never identified the app is in Full screen, even though it is. I tried forcing the boolean into true, but it ended up crashing saying the player is null
I'm not sure but in your onFullScreen() override method, you have set
isFullScreen = true;
Rather, use
isFullScreen = b;
Hope this helps.
I found the answer, just remove the if condition in onInitializationSuccess. Below is the code.
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
this.player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
if(isFullScreen)
{
Toast.makeText(this,"Full Screen",Toast.LENGTH_LONG).show();
player.setFullscreen(false);
}
else
{
Toast.makeText(this,"Not Full Screen",Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
}

mediaplayer starts a new instance when i return to the app

Im making a simple radio streaming app. Everything works great but having a few buggy issues.
When i press the home screen of my device i want the radio to carry on playing. which it does, But as soon as i go to my app history and re-open the app. It starts a new session. this make for a very Un-Pleasurble piece of music lol.
The app is very simple in the way it works i have a media player and a media controller which is attached to a surfaceView in my xml.
Can some one please tell me the correct way to fix this issue as this is the first time making an app that contains a live stream.
Thanks as always guys
my code for the media player and controller
public class radiostation extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener,
MediaController.MediaPlayerControl {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
String videoSource =
"my radio station source address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radiostation);
surfaceView = (SurfaceView)findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaController != null){
mediaController.show();
}
return false;
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(radiostation.this,
"Media Controls active lets mash it up", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(videoSource);
mediaPlayer.prepare();
mediaController = new MediaController(this);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(radiostation.this,
"Radio Station off Air or no internet connection!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(radiostation.this,
"You are now connected ", Toast.LENGTH_LONG).show();
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(surfaceView);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
finish();
}

Setting up MediaController

Im trying to set up the MediaController so I can have controls when playing back audio but when I try to declare it the "this" is coming up as an error. What am I doing wrong?
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class MainActivity extends AppCompatActivity implements MediaRecorder.OnInfoListener {
private boolean cont;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String OUTPUT_FILE;
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/androidaudio1.3gpp";
cont=true;
}
public void buttonClicked(View view){
switch (view.getId()){
case R.id.startRec:
beginRecord();
break;
case R.id.stopRec:
stopRecord();
break;
case R.id.startPlay:
try {
begginPlaying();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stopPlay:
stopPlaying();
break;
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void begginPlaying() throws IOException {
if (mediaPlayer != null)
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaController = new MediaController(this);
mediaController.setMediaPlayer(this);
mediaController.show();
mediaPlayer.prepare();
mediaPlayer.start();
}
private void stopPlaying(){
if (mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
MediaController requires the context to be passed to the constructor. Without anymore code or knowing where you declared the MediaController, my best guess is that you don't have access to the context in the place where you declared the MediaController. Either pass the context from the activity where you would like to use the MediaController, or put this code in that activity.
https://developer.android.com/reference/android/widget/MediaController.html
EDIT:
I tried your code, check your imports & ensure you have, import android.widget.MediaController & not import android.media.session.MediaController.
Try this
if you are using in Activity then you can pass this
if you are using in Fragment then use getActivity() or context
and to set MediaController
use this code
video.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/*
* add media controller
*/
mc = new MediaController(YourActivity.this);
video.setMediaController(mc);
/*
* and set its position on screen
*/
mc.setAnchorView(video);
}
});
}
});

Updating RecyclerView with adapter.notifyDataSetChanged()

I've implemented a RecyclerView which has a user interface of a timer counting down. I created a BroadcastService class which creates a CountDownTimer and broadcasts the timer's contents in the onTick() method to my MainActivity, where I use a BroadCast receiever to update the UI.
My BroadcastReceiver is only receiving the initial value from the BroadcastService. I figured that's because I hadn't notified the recycler view's adapter that the data had changed. However, because of variable scope, I'm unable to access my adapter from my broadcast receiver.
Perhaps I have a fundamental lack of understanding of variable scope, but how can I access the adapter from
adapter = new DataAdapter(getApplicationContext(), data);
in my broadcast receiver class? Because right now it's not being recognized.
This is my class definition + onCreate()
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private RecyclerView recyclerView;
public DataAdapter adapter;
private Context context;
String currentUser;
Data current = new Data();
final List<Data> data = new ArrayList<>();
public static String BROADCAST_ACTION =
"packagename.countdown_br";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
startService(new Intent(this, Broadcast_Service.class));
setContentView(R.layout.activity_profile__page);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.whereEqualTo("author", ParseUser.getCurrentUser());
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
for (ParseObject getData : list)
{
current.1= getData.getString("1");
current.2= getData.getString("2");
current.3= getData.getString("3");
current.4= getData.getString("4");
current.5= getData.getString("5");
data.add(current);
}
}
else {
}
adapter = new DataAdapter(getApplicationContext(), data);
recyclerView.setAdapter(adapter); //set recyclerView to this adapter
}
});
}
And here's my Broadcast Receiver code [which is also in MainActivity.java]
public BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
//HOW TO NOTIFY DATA SET CHANGE
}
};
public void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
current.goalTimer = String.valueOf(intent.getExtras().getLong("countdown") / 1000);
}
}
And, if it is of any use, here's my Broadcast Service class:
public class Broadcast_Service extends Service {
private final static String TAG = "BroadcastService";
LocalBroadcastManager broadcastManager;
public static final String COUNTDOWN_BR = "packagename.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
First of all, extend the BroadcastReciever class as follows:
public class MyReciever extends BroadcastReciever{
private Profile_Page activity;
public MyReciever(Profile_Page activity){
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
activity.updateGUI(intent);
}
}
Create a static instance of your activity and pass it to your receiver.
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private static Profile_Page instance;
private MyReciever myReceiver;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
myReceiver = new MyReciever(instance);
...
}
public void updateGUI(Intent intent) {
...
}
}
Now you can access your adapter quite easily. Hope this helps.

Categories

Resources