Search code examples
androidapplicationcontextandroid-broadcastreceiver

is there a difference between using activity context and using application context to sendBroadcast


sendBroadcast can be called on activity context or application context, is there any difference?

another side question if the context is already a application context, I guess doing context.getApplicationContext() would just return itself, right?

one scenario could be passing the activity context to a receiver object which later using this context to bind or lunch other service. This receiver is locally instantiated in a few different activities. The context are referred inside the receiver as below,

If there is no difference maybe it could just pass in the applicationConext to the receiver,

or better could it just get the passed in context in the

onReceive(Context context, Intent intent), 

and do context.getApplicationContext there?

// 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);

the receiver is like:

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);
    }
}

Solution

  • I my case using the context to get applicationContext from onReceive() works,

    onReceive(Context context, Intent intent) {  
    var appContext = context.applicationContext
    
      ...
    mContext.bindService(new Intent(appContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE);
    
    }
    

    cannot use the context which will get

     android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to bind to services