Android: trouble with bindService() -> service is null

久未见 提交于 2019-11-28 08:21:21

问题


I'm having a problem with binding service to an activity. I get playing_service==null. I can't find what I'm doing wrong. Why is playing_service null??

MyActivity class:

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 class:

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:


Your service might not be null because binding a service is an asynchronous method, so instead of checking the availability of your service yet after calling the bind method, you should do it in your service connection implementation, for e.g.:

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

    }
};


来源:https://stackoverflow.com/questions/9211994/android-trouble-with-bindservice-service-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!