Service communicates with activity
This is my code:
public class MainActivity extends Activity {
private ComponentName mService;
private Servicio serviceBinder;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
serviceBinder = ((Servicio.MyBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
serviceBinder = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent bindIntent = new Intent(this, Servicio.class);
bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStart() {
serviceBinder.somethingThatTakesTooMuch();
super.onStart();
}
public class Servicio extends Service {
private final IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public int somethingThatTakesTooMuch() {
return 1;
}
public class MyBinder extends Binder {
Servicio getService() {
return Servicio.this;
}
}
When I run it, It gets a NullPointerException on this line:
serviceBinder.somethingThatTakesTooMuch();
+2
a source to share
1 answer
Your call onStart
is called before the connection to the service ends. It is not instantaneous.
You can ensure that the service is connected AFTER onServiceConnected CALL. Only then can you call methods on the serviceBinder.
Try to call serviceBinder.somethingThatTakesTooMuch()
on the line afterserviceBinder = ((Servicio.MyBinder)service).getService();
+5
a source to share