我有2个活动,A& B.服务在B中以这样的代码开始:
startService(new Intent(this,PlayerService.class)); Intent connectionIntent = new Intent(this,PlayerService.class); bindService(connectionIntent,mp3PlayerServiceConnection,Context.BIND_AUTO_CREATE); private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0,IBinder binder) { mp3Service = ((LocalBinder) binder).getService(); Thread t = new Thread() { public void run() { mp3Service.playSong(getApplicationContext(),url); } }; t.start(); } @Override public void onServiceDisconnected(ComponentName arg0) { } };
当我在活动A(B关闭但音乐播放)时,我需要有可能关闭服务.如何从A onDestroy()调用StopService?需要我解开它,如果是的话,如何以及在哪里?
简单地把stopService(new Intent(this,PlayerService.class));导致错误:活动B已泄露服务连接…最初绑定在这里. (但B已经关闭)
解决方法
你应该在B onStop()中取消绑定服务,然后你可以在A中调用stopService.