如何将服务从一个活动传递到另一个活动?我有一个显示歌曲列表的音乐播放器(Activity1),当您点击它时,它会在Activity1中启动该服务。我有一个按钮,用户可以单击该按钮打开Activity2。
那么我将服务从Activity1传递给Activity2的最佳方式是什么。如果服务在Activity1中启动,则Activity2应继续播放。如果服务未在Activity1中启动,则Activity2应在使用之前启动该服务。
感谢。
这里有一些示例代码,MusicService是一个扩展服务类的类。
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) {
}
};
}
答案 0 :(得分:6)
我认为绑定服务而不是传递 静态全局服务会更好。由于您有多个将使用相同服务的活动,因此应创建基本活动,如下所示:
BasicServiceActivity.java
public abstract class BasicServiceActivity extends AppCompatActivity {
protected DvrService mDvrService;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
attachService();
}
@Override
protected void onDestroy() {
detachService();
super.onDestroy();
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
DvrService.DvrServiceBinder serviceBinder = (DvrService.DvrServiceBinder) binder;
mDvrService = serviceBinder.getService();
onServiceAttached(mDvrService);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mDvrService = null;
}
};
private void attachService() {
Intent service = new Intent(this, DvrService.class);
bindService(service, mServiceConnection, Service.BIND_AUTO_CREATE);
}
private void detachService() {
unbindService(mServiceConnection);
}
/** Callback when service attached. */
protected void onServiceAttached(DvrService service) {
// do something necessary by its subclass.
}
}
然后你可以实现这样的子类活动:
public class ServiceActivity extends BasicServiceActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, DvrService.class));
}
@Override
protected void onDestroy() {
if (mDvrService != null) {
mDvrService.removeListener1(mListener1);
}
super.onDestroy();
}
@Override
protected void onServiceAttached(DvrService service) {
// do your stuff, for example add a listener.
service.addListener1(mListener1);
}
}
答案 1 :(得分:3)
您可以定义Application扩展类并在此类中使用公共静态变量,并在所有活动中访问此变量。
像这样:public class G extends Aplication{
public static MusicService serviceMusic;
}
并在清单中:
<application ...
android:name=".G">
现在您可以在任何地方访问G.serviceMusic。