对应用程序中的所有活动使用广播接收器

Using Broadcast Recceiver for all Activities in app

我在我的应用程序中使用 BroadCast Receiver。我的应用程序中有很多活动。在 MainActivity.java 中使用的广播接收器如下:

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

当消息到来并且 MyActivity 处于焦点时我会通知。 现在,当我的其他活动成为焦点时,我不会收到通知。 有没有一种通用的方法可以将 BroadCast 用作全局方式???对于所有活动 ???

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

您应该在 BroadcastReceiver 中注册您的,而不是特定的 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>

第二种方式: 在 Base of all Activity

中独立自定义 BroadcastReceiver 和 register/unregister class

创建一个名为 AbstractActivity 的摘要 activity。使所有其他活动扩展此抽象 Activity 并在该抽象 activity 中声明 broadCastReceiver。

public AbstractActivity extends Activity{....}

public SubActivity extends AbstractActivity{...}

或者您可以使用 EventBus:

阅读全文 getting started guide

广播接收器始终是他们的 util 你注销广播接收器。

为了解决您的问题,您必须在应用程序级别注册广播。

例如:

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

之后,您可以随时执行任何操作,就像应用程序级别的广播接收器一样。此外,您不会在 activity.

中面临任何内存泄漏