I have a particular situation: a service started by a broadcast receiver starts an activity. I want to make it possible for this activity to communicate back to the service.
One more thing is that if you are calling bindservice
method inside the oncreate
method then the onserviceconnected
is called after the oncreate
method is finished.
So any references to the interface functions before the oncreate
ends (or before onserviceconnected
is called) shows null pointer exception.
Yet another cause to the original question might be that the service isn't already running and you are passing 0 as flag to bindService. Like so:
bindService(intent, serviceConnection, 0);
When what you are looking for would be:
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
I was calling bind with an empty Intent - getContext().bindService(new Intent(), mConnection, Context.BIND_AUTO_CREATE)
. I have to make the intent more specific to indicate which service I want to bind to. This is obviously a code error, but the Logcat output was unfortunately not clear enough.
I can't make up the exact problem out of your description, so I'm going to guess here!
How can bindService()
throw a NullPointerException
? The only way this could (/should) happen is when you don't supply a Service
or a ServiceConnection
listener.
bindService()
can't throw a NullPointerException
because onServiceConnected()
isn't called. The call to onServiceConnected()
is a product of bindService()
.
So I guess you are calling a AIDL
method, before the Service
has actually bonded?
You Must Wait To Complete onCreate() method. Example: Set Your Buy Service in Buttom:
Button button_useservice=findViewById(R.id.button_useservice);
button_useservice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UsinService();
}
});
I also encountered the same problem. And minutes later I found that my code had absolutely no problem. It was the manifest file that had the issue. Earlier I was declaring the service with its name only.
<service android:name=".MyBoundService"/>
Change it to the full name with the package name
<service android:name="com.pb.servicedemo.MyBoundService"/>
This way you will be able to see your service bound to the activity.