Android: problem with bindService () & # 8594; service is zero

I have a problem with activity binding. I get play_service == null. I cannot find what I am doing wrong. Why is play_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 } } 

class 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; } } 
+4
source share
1 answer

Your service may not be null, because service binding is an asynchronous method, so instead of checking the availability of your service even after calling the binding method, you should do this in your implementation of connecting to the service, for example:

 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 } }; 
+15
source

Source: https://habr.com/ru/post/1395605/


All Articles