启动我的应用程序时,我在助手类中调用了一个方法,该方法将Service与ApplicationContext绑定在一起。
服务绑定/取消绑定类
private Context context = MainApplication.getAppContext();
private static Main mainInstance;
public synchronized static Main getInstance(){
if (mainInstance == null){
mainInstance = new Main();
}
return mainInstance;
}
public void bindMusicService(){
/*mediaPlayerServiceIntent binds our connection to the MediaPlayerService. */
if (!mServiceIsBound) {
try {
mediaPlayerServiceIntent = new Intent(context, MediaPlayerService.class);
context.bindService(mediaPlayerServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
Log.e("Main", "An exception was caught: Service is not bound!");
}
}
}
public void unbindService(){
context.unbindService(serviceConnection);
mServiceIsBound = false;
}
在我的MainActivity的onCreate()中,然后调用Main.getInstance().bindMusicService();
从“最新应用”中删除应用后,我是否需要取消服务绑定?
我仅在单击通知中的关闭按钮时取消绑定服务,该按钮在 mMediaSessionCompat 中调用onStop()方法。
如果我没有在MainActivity的onDestroy()方法中取消绑定,这会导致泄漏吗?
MediaSessionCompat回调中的onStop()方法
@Override
public void onStop() {
super.onStop();
if (Main.getInstance().mServiceIsBound) {
Main.getInstance().unbindService();
}
stopSelf();
Log.d(TAG,"stop!");
}