首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在sendBroadcast中使用活动上下文和使用应用程序上下文有什么区别吗?

在sendBroadcast中使用活动上下文和使用应用程序上下文有什么区别吗?
EN

Stack Overflow用户
提问于 2017-09-18 17:14:55
回答 1查看 888关注 0票数 0

sendBroadcast可以在活动上下文或应用程序上下文中调用,有什么区别吗?

另一个问题是,如果上下文已经是应用程序上下文,我猜执行context.getApplicationContext()只会返回自己,对吗?

一种情况可能是将活动上下文传递给接收对象,后者稍后使用此上下文绑定或午餐其他服务。此接收器在几个不同的活动中被本地实例化。上下文在接收方内部引用如下,

如果没有区别的话,也许它可以把applicationConext传递给接收者,

或者更好的是,它可以在上下文中在

代码语言:javascript
复制
onReceive(Context context, Intent intent), 

context.getApplicationContext在那里吗?

代码语言:javascript
复制
// 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);

接收者就像:

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-19 12:25:30

我的案例使用上下文从applicationContext ()获得onReceive()工作,

代码语言:javascript
复制
onReceive(Context context, Intent intent) {  
var appContext = context.applicationContext

  ...
mContext.bindService(new Intent(appContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE);

}

无法使用将获得

代码语言:javascript
复制
 android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to bind to services
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46284877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档