2012-02-09 83 views
4

我遇到绑定服务到活动的问题。我得到了playing_service == null。我找不到我做错了什么。为什么playing_service为空?Android:与bindService() - >服务为空的问题

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

回答

15

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

    } 
}; 
+0

哇,谢谢你。几个小时以来,我的头撞在墙上。虽然 – 2012-02-09 14:05:17

+0

一件事 - 当我打电话playTrack()第二次,OnServiceConnected()不会被调用了。为什么是这样? 我杀的第一个服务的方式是playing_service.stopPlaying(),它也要求selfStop()。 – 2012-02-09 14:31:05

+0

由于您的服务已被绑定,因此它不会执行任何操作。 – waqaslam 2012-02-09 14:34:56