peekService returns null even though startService does not

老子叫甜甜 提交于 2019-12-22 10:06:57

问题


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:


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".



来源:https://stackoverflow.com/questions/27612646/peekservice-returns-null-even-though-startservice-does-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!