即使应用程序关闭(滑动/滑掉),也能收到GCM通知

6
这是我在MainActivity中使用作为广播接收器的代码。
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        //When the broadcast received
        //We are sending the broadcast from GCMRegistrationIntentService

        @Override
        public void onReceive(Context context, Intent intent) {
            //If the broadcast has received with success
            //that means device is registered successfully
            if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){
                //Getting the registration token from the intent
                String token = intent.getStringExtra("token");
                //Displaying the token as toast
                Toast.makeText(getApplicationContext(), "Registration token:" + token, Toast.LENGTH_LONG).show();

                //if the intent is not with success then displaying error messages
            } else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){
                Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
            }
        }
    };

我跟随了这个关于GCM的教程。 https://www.simplifiedcoding.net/android-push-notification-using-gcm-tutorial/

我认为通过滑动关闭应用程序是强制关闭应用程序,因此除非用户再次启动应用程序,否则它将无法接收到GCM消息。请参阅我在之前的SO问题中的答案。 - Android Enthusiast
1
我通过使用WakefulBroadcastReceiver来完成它。 - Renz Manacmol
1
您可以在应用程序打开或关闭时接收 GCM(现在是 FCM)消息。我建议不要编写自己的 WakefulBroadcastReceiver,请使用提供的 GcmListenerService 或更易于使用的 FirebaseMessagingService。请参阅示例:https://github.com/firebase/quickstart-android/tree/master/messaging - Arthur Thompson
@acer 你是怎么解决的? - natsumiyu
2个回答

14
通过滑动关闭应用程序(更常被称为swiping it away),并不能完全终止应用程序。在Android爱好者社区中,请查看此答案以获取更详细的描述。您可以在那里看到提到了以下内容:

..它不会直接导致服务停止..

由于GCM通知的侦听器是Services,因此这实际上意味着仍然有可能在应用程序被“swiped away”之后继续接收它们。
尽管滑动应用程序的结果也可能取决于其运行的设备,一个可能会强制停止/杀死它,而另一个则会停止后台进程,正如上面提到的那样。
如果结果是应用程序被杀死或强制停止,正如上面链接中的答案所述:

对于stop来说,它是应用程序的完全kill -- 所有进程都被kill掉,所有服务被停止,所有通知都被删除,所有闹钟都被删除等。

这将导致应用程序根本不再接收任何类型的通知,因为自Android 3.1版本以来就是为Android设计的,正如这个答案中所述:

处于停止状态的应用程序不会接收广播意图。

停止状态是:

当应用程序最初安装后(用户在应用程序中运行任何内容之前)或 经过强制停止。 您可以在此处了解更多信息:http://developer.android.com/about/versions/android-3.1.html#launchcontrols

希望这能在某种程度上帮助澄清一些事情。干杯! :D

1
你可以尝试使用 GcmListenerService。当你通过滑动关闭应用程序时,服务仍然在后台激活,你可以接收推送通知。除非用户从设置中手动强制停止应用程序,否则此服务会对你有所帮助。

有一些设备是这样设计的,当你滑动关闭应用程序时,它就相当于强制停止它们(请参见我在这里的答案)。 - Cecil Paul
还有一些设备,即使应用程序仍然被简单地滑动关闭,尽管它没有被强制关闭,但设备本身也会阻止其接收消息。其他人说这不可能是这种情况,因为WhatsApp等应用程序能够做到这一点。我目前所了解的原因是因为设备制造商已经将大多数知名应用程序列入白名单,以便实现这一点。这并没有在任何地方记录,因为(在我看来),这是一个取决于设备的主题,FCM对此没有完全控制。 - Cecil Paul

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