peekService返回null,即使startService没有

时间:2014-12-23 00:48:36

标签: android broadcastreceiver

我正在尝试使用Service中的Android BroadcastReceiverService生活在与BroadcastReceiver不同的应用程序中。我的理解是,正确的方法是先拨打Context#startService,然后拨打BroadcastReceiver#peekService。对startService的调用似乎正常,因为它返回了预期的ComponentName。但是,当我拨打peekService时,会返回null。对我做错了什么的想法?

谢谢!这是一个包含相关部分的代码清单。

// 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);
  }
}

Log语句打印以下内容:

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

1 个答案:

答案 0 :(得分:3)

peekService()的文档未完全描述获取IBinder所需的条件。正如Dianne Hackborn(Google Android工程师)在this post中解释的那样:“调用startService()是不够的 - 您需要为同一意图调用bindService(),因此系统已检索到{ {1}}为它“。