how do I pass a service from one activity to another? I have a music player (Activity1) that displays a list of songs, and when you click on it, it starts the service within Activity1. I have a button that users can click that will open Activity2.
So what is the best way for me to pass the service from Activity1 to Activity2. If the service is started in Activity1, then Activity2 should continue playing. If the service is not started in Activity1, then Activity2 should start the service before using it.
Thanks.
Here's some sample code, the MusicService is a class that extends the service class.
public class Activity1 extends AppCompatActivity {
private MusicService serviceMusic;
private ServiceConnection musicConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.PlayerBinder binder = (MusicService.PlayerBinder) service;
//get service
serviceMusic = binder.getService();
serviceMusic.setSongList(songList);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
you can define Application extend class and use public static variable in this class and access this variable in all activity .
like this :
and in manifest :
Now you can access G.serviceMusic any where.
I think it would be better to bind service instead of pass a static global service. Since you have multiple activities which will use the same service, a base activity should be created like this:
BasicServiceActivity.java
Then you can implement subclass activity like this: