我正在尝试使用Service
中的Android BroadcastReceiver
。 Service
生活在与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
答案 0 :(得分:3)
peekService()的文档未完全描述获取IBinder所需的条件。正如Dianne Hackborn(Google Android工程师)在this post中解释的那样:“调用startService()
是不够的 - 您需要为同一意图调用bindService()
,因此系统已检索到{ {1}}为它“。