应用程序在后台时的 BroadcastReceiver

BroadcastReceiver when app is in background

我正在尝试编写一个应用程序,在其中根据我使用 gcm 推送通知发送的消息对 UI 进行更改,我设法通过使用 BroadcastReceiver onReceive 函数来实现它,但它只是如果应用程序在前台工作,但如果它在后台或关闭时没有任何反应,那么有什么办法吗?

编辑1: 在清单文件中,如果我理解你的问题

<receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="info.androidhive.gcm" />
            </intent-filter>
        </receiver>

        <service
            android:name="info.droiders.gcm.gcm.MyGcmPushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <service
            android:name="info.droiders.gcm.gcm.GcmIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>

   myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                // notification received
                handleChanges(intent);
            }
        }
    };

如果您将广播接收器声明为您的 activity 或应用内其他 class 的成员,则它不会 运行 除非您的应用是 运行宁。相反,您应该创建一个独立的 class 来扩展广播接收器。所以改变这个:

   myBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
};

将其放入自己的文件中:

public class GcmReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
}

现在 Android 可以找到 class 并实例化它,即使您的应用不是 运行ning。

编辑: 更正 class 名称以匹配 OP 中显示的清单文件中声明的接收者名称。