Android:bindService() 的问题 - > 服务为空



我在将服务绑定到活动时遇到问题。我得到playing_service==null。我找不出我做错了什么。为什么playing_service为空??

MyActivity类:

private playService playing_service=null;
private ServiceConnection service_conn=new ServiceConnection(){
    public void onServiceConnected(ComponentName className, IBinder service) {
        LocalBinder binder=(LocalBinder)service;
        playing_service=binder.getService();
    }
    public void onServiceDisconnected(ComponentName arg0) {
        // TODO Auto-generated method stub
    }
};
public void playTrack(View view){       
        Intent i=new Intent(this,playService.class);
        i.setAction("com.c0dehunter.soundrelaxer.PLAY");
        bindService(i,service_conn,Context.BIND_AUTO_CREATE);
        if(playing_service==null) //here I get true,
             //if I try to access playing_service I get NullPointerException
    }
}

播放服务类:

private final IBinder binder=new LocalBinder();
public int onStartCommand(Intent intent, int flags, int startId){       
     return 1; //dummy
}
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return binder;
}
public class LocalBinder extends Binder{
    public playService getService(){
        return playService.this;
    }
}

您的服务可能不是null,因为绑定服务是一种asynchronous方法,所以您不应该在调用绑定方法后检查服务的可用性,而是应该在服务连接实现中进行检查,例如:

private ServiceConnection service_conn=new ServiceConnection(){
    public void onServiceConnected(ComponentName className, IBinder service) {
        LocalBinder binder=(LocalBinder)service;
        playing_service=binder.getService();
        if(playing_service != null){
            Log.i("service-bind", "Service is bonded successfully!");
            //do whatever you want to do after successful binding
        }
    }
    public void onServiceDisconnected(ComponentName arg0) {
        // TODO Auto-generated method stub
    }
};

最新更新