3

I'm trying to use an Android Service from a BroadcastReceiver. The Service lives in a different application than the BroadcastReceiver. My understanding is that the right way to do this is to first call Context#startService, followed by BroadcastReceiver#peekService. The call to startService seems to work correctly, as it returns the expected ComponentName. However, when I make the call to peekService, null is returned. Any thoughts on what I'm doing wrong?

Thank you! Here is a code listing with the relevant parts.

// The Service in question is com.tingley.myapp.MyService
// Note that this Receiver is in a different application
package com.tingley.myotherapp;

public class MyReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    // Start the Service
    Intent serviceIntent = new Intent();
    serviceIntent.setClassName("com.tingley.myapp", "com.tingley.myapp.MyService");
    ComponentName componentNameOfStartedService = context.startService(serviceIntent);
    Log.d("", "Started service name: " + componentNameOfStartedService);

    // Get an IBinder to the Service
    IBinder serviceBinder = peekService(context, serviceIntent);
    Log.d("", "Got binder from peeking service: " + serviceBinder);
  }
}

The Log statements print the following:

Started service name: ComponentInfo{com.tingley.myapp/com.tingley.myapp.MyService}
Got binder from peeking service: null

1 Answers1

3

The documentation for peekService() does not fully describe the conditions required to get an IBinder. As Dianne Hackborn (Google Android engineer) explains in this post: "Calling startService() is not enough -- you need to have called bindService() for the same intent, so the system had retrieved the IBinder for it".

Bob Snyder
  • 37,759
  • 6
  • 111
  • 158