我正在创建一个音乐播放器应用程序,我在其中创建了一个Service
用于播放曲目的应用程序。
用于控制我正在使用的播放器bindService()
下面是代码,我使用 ServiceController 类来绑定(inistService() 内部)和 unbind(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();
问题是我试图从不同的类停止服务,即我想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: com.example.async.classes.ServiceController$CallMService@40547298
我怎样才能做到这一点?