android - 应用程序在后台时的 BroadcastReceiver

标签 android push-notification google-cloud-messaging

我正在尝试编写一个应用程序,其中我根据使用 gcm 推送通知发送的消息对 UI 进行更改,并且我设法通过使用 BroadcastReceiver onReceive 函数来实现它来实现它,但它仅在应用程序处于前景,但如果它在背景中或关闭时没有任何反应,那么有什么办法解决这个问题吗?

编辑1: 在 list 文件中,如果我理解你的问题是对的

<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 或其他类的成员,那么除非您的应用程序正在运行,否则它不会运行。相反,您应该创建一个扩展广播接收器的独立类。所以改变这个:

   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 中显示的 list 文件中声明的接收器名称。

关于android - 应用程序在后台时的 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492582/

相关文章:

java - 如何连接2个onActivityResult?

android - Android GCM 推送通知是如何处理的?

java - App Engine 后端与 Google Cloud Messaging 向 1000 多名用户发送消息

android - flutter : Intent

java - Android 应用程序按钮按下无法正常工作

android - 外部调用/Intent 上的上下文 getFilesDir()

ios - 消息发送成功但未出现在 ios 开发模式下的设备中

push-notification - 推送通知(如 GCM)为何以及如何高效?

ios - 是否可以通过企业配置文件(内部企业)获得推送通知?

android - 为什么 Messenger 应用程序会在应用程序强制停止时收到消息?