Android:使用bindService()时遇到问题 - >服务为空

时间:2012-02-09 13:47:37

标签: android android-service android-binder

我遇到了将活动绑定到活动的问题。我得到playing_service == null。我找不到我做错了什么。为什么playing_service为null ??

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

    }
}

playService类:

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;
    }
}

1 个答案:

答案 0 :(得分:18)

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

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

    }
};