4

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

我的活动类:

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

1 回答 1

18

您的服务可能不为空,因为绑定服务是一种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

    }
};
于 2012-02-09T13:59:11.337 回答