我正在尝试使用aService中的androidBroadcastReceiverServiceBroadcastReceiver位于不同的应用程序中。我的理解是,正确的方法是先调用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

最佳答案

peekService()的文档没有完全描述获取ibinder所需的条件。正如dianne hackborn(google android engineer)在this post中所解释的:“仅仅调用startService()是不够的——您需要为相同的目的调用bindService(),所以系统已经为它检索了IBinder。”

关于android - 即使startService不执行,peekService仍返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27612646/

10-10 22:36