sendBroadcast可以在活动上下文或应用程序上下文中调用,有什么区别吗?
另一方面问题,如果上下文已经是应用程序上下文,我想做context.getApplicationContext()只会返回自己,对吗?
一个场景可能是将活动上下文传递给接收者对象,后者使用此上下文来绑定或午餐其他服务。该接收器在几个不同的活动中进行本地实例化。上下文在接收器内部被引用如下,
如果没有差异,可能只是将applicationConext传递给接收者,
或者更好,它可以在
中获得传递的上下文onReceive(Context context, Intent intent),
并在那里做context.getApplicationContext吗?
// inside the receiver it will the following with the context:
mContext.bindService(new Intent(mContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE);
mContext.unbindService(mInitServiceConnection);
Intent newStartIntent = new Intent(mContext, InitService.class);
mContext.startService(newStartIntent);
接收器就像:
class LocalBroadcastReceiver extends BroadcastReceiver {
private final Context mContext;
public LocalBroadcastReceiver(@NonNull Context context) {
mAppContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
// could it here use the context to get application context, like:
mContext = context.getApplicationContext()
//then do something like:
Intent newStartIntent = new Intent(mContext, InitService.class);
mContext.startService(startMailAccountInitIntent);
}
}
答案 0 :(得分:0)
我的情况是使用上下文从onReceive()获取applicationContext,
onReceive(Context context, Intent intent) {
var appContext = context.applicationContext
...
mContext.bindService(new Intent(appContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE);
}
无法使用将获得的上下文
android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to bind to services