当应用程序被强制停止时,如何接收推送通知?(安卓)

4
我正在开发一款应用程序,使用Push Notification(GCM)。当应用程序运行时,它会接收到推送通知,但是当我从“设置->应用程序->MyApp”中强制停止它后,它就不能接收到推送通知了。我已经测试了同样的问题,WhatsApp在我强制停止它时可以接收到推送通知。那么我该如何实现我的应用程序也能做到这一点呢? 注意:在代码中,我在WakefulBroadcastReceiver的子类中接收推送通知,并在清单中静态注册它,即使应用程序被强制停止,它也不会被调用。
public class GCM_Receiver extends WakefulBroadcastReceiver {
    //Processes Gcm message .
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "GCM_Receiver", Toast.LENGTH_LONG).show();
        ComponentName comp = new ComponentName(context.getPackageName(),GCMIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

编辑: 我已经以静态方式注册了GCM_Receiver:

<receiver
        android:name="com.myApp.GCM_Receiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.RETRY" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.myApp" />
        </intent-filter>
    </receiver>

编辑: 以下是我的GCMIntentService代码:

public class GCMIntentService extends IntentService{
//Constructor with super().
public GCMIntentService () {
    super("GcmIntentService");
}
//Processes gcm messages .
@Override
protected void onHandleIntent(Intent intent) {
    Log.d("GCMIntentService ", "GCMIntentService Started");
    Toast.makeText(getApplicationContext(), "GCMIntentService Started", Toast.LENGTH_LONG).show();
    GCM_Receiver.completeWakefulIntent(intent);
}}

您提供的代码没问题,但请展示一下您在清单文件中如何注册接收器以及GCMIntentService中包含了什么? - Viktor Yakunin
可能是当我杀死我的应用程序时BroadcastReceiver不起作用的重复问题。 - Viktor Yakunin
@ViktorYakunin:我已经编辑了问题,请纠正我是否有做错什么。 - Shishupal Shakya
@ViktorYakunin 这篇帖子中有一些重复的内容,但并没有解决我的问题。 - Shishupal Shakya
1个回答

1
只有通过com.google.android.c2dm.permission.SEND权限,Google Play服务才能调用那个特定的广播接收器。由于我假设Play服务在发送广播时不包括FLAG_INCLUDE_STOPPED_PACKAGES标志,因此您停止运行的应用程序将无法接收到消息。
有趣的是,在强制停止WhatsApp应用程序后,我不会收到任何WhatsApp消息。但是,无论应用程序如何,如果它可以在强制停止时接收消息,则肯定会从带有FLAG_INCLUDE_STOPPED_PACKAGES标志的意图中接收广播。

在我的情况下,即使强制停止了WhatsApp,它仍然可以接收GCM推送通知,我已经尝试过多个设备(三星,摩托罗拉,华为)。 - Shishupal Shakya
那么在我的情况下,我该如何设置这个标志呢? - Shishupal Shakya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接