0
我正在創建音樂播放器應用程序,其中我創建了一個用於播放曲目的Service
。如何從其他尚未綁定的課程中取消綁定服務
爲了控制球員我使用bindService()
下面是代碼,我使用ServiceController的類綁定(內inistService()),並解除綁定(內releaseService()):
public class ServiceController {
MusicServiceAidl aidlObject;
CallMService serviceConnection = new CallMService();
Context context;
public ServiceController(Context c) {
this.context = c;
}
class CallMService implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder boundService) {
aidlObject = MusicServiceAidl.Stub
.asInterface((IBinder) boundService);
Toast.makeText(context, "Service Connected",
Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName paramComponentName) {
aidlObject = null;
Toast.makeText(context, "Service Disconnected",
Toast.LENGTH_SHORT).show();
}
}
public void initService() {
try {
Intent serviceIntent = new Intent();
serviceIntent.setClassName("com.example.async",
com.example.async.PlayTrack.class.getName());
boolean ret = context.bindService(serviceIntent, serviceConnection,
Context.BIND_AUTO_CREATE);
Toast.makeText(context, "Service bound with " + ret,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context,
"initService(): " + e.toString(), Toast.LENGTH_LONG).show();
}
}
public void releaseService() {
context.unbindService(serviceConnection);
serviceConnection = null;
Toast.makeText(context, "Service Released",
Toast.LENGTH_SHORT).show();
}
public String getTrackName() throws RemoteException{
return aidlObject.getTrackName();
}
public String getAlbumName() throws RemoteException{
return aidlObject.getAlbumName();
}
public String getArtistName() throws RemoteException{
return aidlObject.getArtistName();
}
public void playPreviousTrack() throws RemoteException{
aidlObject.playPreviousTrack();
}
public void playNextTrack() throws RemoteException{
aidlObject.playNextTrack();
}
}
要調用這個綁定類,我使用的是:
ServiceController serviceController = new ServiceController(getApplicationContext());
serviceController.initService();
serviceController.releaseService();
問題是我想從一個不同的類停止服務,也就是我要打電話來自不同班級的。但顯然,它給出IllegalArgumentException
。
編輯: 當我運行下面的代碼:
public void onBackPressed() {
try {
Intent intent = new Intent(this,
Class.forName("com.example.async.PlayTrack"));
stopService(intent);
serviceController.releaseService();
} catch (Exception e) {
Log.e("Listing.java", e.toString());
Toast.makeText(Listing.this,
"Listing->onBackPressed: " + e.toString(), Toast.LENGTH_SHORT)
.show();
}
}
我得到異常
java.lang.IllegalArgumentException: Service not registered: [email protected]8
我怎樣才能實現這一目標以下?
試過..在這個類的構造函數中,我使用了'this.context = c.getApplicationContext();'但還是不行......告訴我如果我做錯了 – 2012-08-14 09:23:43
這個「類」是一個活動嗎?如果不是,你如何創建綁定到服務的這個「類」的實例?請顯示更多代碼。 – 2012-08-14 10:39:43
沒有課程不是「活動」。 代碼更新並感謝您的幫助 – 2012-08-14 11:20:09