Search code examples
androidandroid-activitybroadcastreceiver

Calling a Activity method from BroadcastReceiver in Android when BroadcastReceiver app is not started


I have a Broadcastreceiver in my ReceiverApp, which I call from my SenderApp and this works fine. I would like to call a method of the Activity in my ReceiverApp.

How can I do that with the following prerequisites ? :

  • The ReceiverApp was not started and dynamically registering the receiver is not possible.

  • I can't call the Receivers Mainactivity from my Sender, because I would like to prevent showing any ActivityScreen of the Receiver. The Sender should just call an ReceiverActivity method and proceed further, so the Senderscreen should be always on top.

  • I cant do the ReceiverActivity Method "static", because then I loose the context of the Activity. I need for example to fetch the Packagename of the Receiver with : this.getPackageName()

    public class MyBroadcastReceiver extends BroadcastReceiver {
    
    @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            // Extract data included in the Intent
            CharSequence intentData = intent.getCharSequenceExtra("message");  
            Toast.makeText(context, "Say : "+intentData, Toast.LENGTH_LONG).show();
    
            MainActivity.myMethod(); <<<<<--------
    
        }
    

    }

Any hint or help ?


Solution

  • By definition, what you want is impossible. If the activity does not exist, you cannot call methods on it.

    Move your code to some common location that is accessible from both the receiver and the activity, such as a static method.

    I cant do the ReceiverActivity Method "static", because then I loose the context of the Activity.

    Pass a Context as a parameter to the method.

    I need for example to fetch the Packagename of the Receiver with : this.getPackageName()

    Call getPackageName() on the Context that is passed into onReceive().