Android 应用程序处于后台时广播接收器

Android 应用程序处于后台时广播接收器,android,push-notification,google-cloud-messaging,Android,Push Notification,Google Cloud Messaging,我正在尝试编写一个应用程序,根据我发送的带有gcm推送通知的MSG对UI进行更改,我尝试使用BroadcastReceiver onReceive函数来实现它,但它仅在应用程序位于前台时有效,但如果它位于后台或关闭,则不会发生任何情况 编辑1: 在清单文件中如果我理解你的问题对吗 <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="

我正在尝试编写一个应用程序,根据我发送的带有gcm推送通知的MSG对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);
        }
    }
};
并将其放在自己的文件中:

public class GcmReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
}
现在Android可以找到类并实例化它,即使你的应用程序没有运行


编辑:更正类名,使之与OP中所示清单文件中声明的接收者名称相匹配。

您是如何注册此接收者的?如果您正在对UI进行更改,当您的应用程序不在前台时,您希望看到什么?您知道我哪里出错了吗?:)我的意思是当我打开它时@rothloupi在我的handleChanges函数中使用GetSharedReferences,它的红色现在还没有定义
public class GcmReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
}