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);
}
}发布于 2017-09-19 12:25:30
我的案例使用上下文从applicationContext ()获得onReceive()工作,
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 serviceshttps://stackoverflow.com/questions/46284877
复制相似问题