代码之家  ›  专栏  ›  技术社区  ›  lannyf

使用活动上下文和使用应用程序上下文发送广播之间有区别吗

  •  0
  • lannyf  · 技术社区  · 7 年前

    另一个附带的问题是,如果上下文已经是应用程序上下文,我想是做上下文。getApplicationContext()只会返回自身,对吗?

    如果没有区别,它可能只会传入接收器旁边的应用程序,

    或者更好的是,它可以在

    onReceive(Context context, Intent intent), 
    

    然后做上下文。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);
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   lannyf    7 年前

    我的案例使用上下文从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