Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Broadcast Recceiver for all Activities in app

I am using BroadCast Receiver in my app. I have many activities in my app. Used broadcard receiver in MainActivity.java as below :

private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};

I am notifying when message is coming and MyActivity is in focus. Now When my other activites are in focus i am not getting notified. Is there a common way to use BroadCast thing as global way ??? for all activities ???

like image 314
AskingToStack Avatar asked Feb 04 '23 17:02

AskingToStack


1 Answers

Broadcast receiver always be their util you unregister broadcast receiver.

For solving your problem you have to register broadcast on application level.

Eg :

public MyApplication extends Application 
{
    onCreate() {
        // register broadcast receiver here
    }

    private BroadcastReceiver smsReceiver = new BroadcastReceiver() 
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Retrieves a map of extended data from the intent.
            final Bundle bundle = intent.getExtras();
            try {
                if (bundle != null) {
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

After that you can perform any action at any time as now broadcast receiver on application level. Also you will not face any memory leak inside activity.

like image 120
Jitesh Mohite Avatar answered Feb 07 '23 11:02

Jitesh Mohite