2012-02-09 2 views
4

У меня возникла проблема с привязкой к активности. Я получаю play_service == null. Я не могу найти, что я делаю неправильно. Почему play_service null?Android: проблема с bindService() -> service is 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; 
    } 
} 

ответ

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

Ничего себе, вам. Я часами бил головой о стену. –

+0

Еще одна вещь - когда я вызываю playTrack() во второй раз, OnServiceConnected() больше не вызывается. Почему это? То, как я убиваю первую услугу, - это play_service.stopPlaying(), которая также вызывает selfStop(). –

+0

он ничего не сделает, поскольку ваш сервис уже привязан. – waqaslam