5

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 ???

AskingToStack
  • 59
  • 1
  • 5

2 Answers2

2

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.

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
1

Is there a common way to use BroadCast thing as global way ?

You should register your in BroadcastReceiver instead of specific Activity

<receiver
        android:name="com.example.android.NotificationReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.android" />
        </intent-filter>
    </receiver>

Second way: Make independent custom class of BroadcastReceiver and register/unregister in Base of all Activity

Kishore Jethava
  • 6,666
  • 5
  • 35
  • 51