我正在尝试编写一个应用程序,其中我根据使用 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/