Reputation: 65
I have 2 activities: MainActivity and PlayActivity. In the MainActivity I'm playing a song and in the PlayActivity I'm showing an image and a stop button of that song. How can I stop the song playing from the MainActivity while the PlayActivity is displaying? Can you guys give me an example?
Upvotes: 0
Views: 247
Reputation: 379
Personally, I would prefer to let a service play the song. The PlayActivity could then just show the current song of the service and playing and stopping the songs would then send a message to the service to play or stop the song. The MainActivity would let the service know what song to play and the playactivity would then be able to show the currently playing song and would be able to control it as well without some elaborate messaging being send back and forth.
public class MusicApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Context context = getApplicationContext();
context.startService(new Intent(context, MusicService.class));
}
}
public interface MusicControlInterface {
public void startMusic(Track track);
public void stopMusic();
...
forward, rewind, whatever controls you need
...
}
public class MusicService extends Service implements MusicControlInterface {
private final IBinder binder = new LocalBinder();
public IBinder inBind(Intent intent) {
return binder;
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
...
whatever methods you more need, onCreate, etc.
...
//implementation of the MusicControlInterface
public void playMusic(Track track) {
//start playing the track using whatever means you use to pay the tracks
}
public void stopMusic() {
//Stop the music using whatever method you play with.
}
public class LocalBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
}
Then, the activity would just bind to the service like this.
public class MainActivity {
private MusicService musicService;
private final ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
}
public void onServiceDisconnected(ComponentName name) {
musicService = null;
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MusicService.class);
this.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
public void playButtonClick() {
if (musicService != null) musicService.playMusic(...sometrack...);
}
}
Then, whenever you need to call the service, you just call if (musicService != null) musicService.stopMusic();
It is a good idea to check for null as it can take a while for a service to be bound.
Upvotes: 1