我正在尝试使用来自 BroadcastReceiver
的 Android Service
。 Service
位于与 BroadcastReceiver
不同的应用程序中。我的理解是,执行此操作的正确方法是首先调用 Context#startService
,然后调用 BroadcastReceiver#peekService
。对 startService
的调用似乎工作正常,因为它返回了预期的 ComponentName
。但是,当我调用 peekService
时,返回了 null
。对我做错了什么有什么想法吗?
谢谢!这是包含相关部分的代码 list 。
// 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 工程师)在 this post 中解释的那样:“调用 startService()
是不够的——您需要为相同的 Intent 调用 bindService()
,因此系统已检索到 IBinder
”。
关于android - peekService 返回 null,即使 startService 不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612646/