Android 应用程序关闭时推送通知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24313539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:01:19  来源:igfitidea点击:

Push Notifications when app is closed

androidnotificationspush

提问by user3757628

Do you know if is it possible to receive notifications from google cloud message when the application is fully closed?

您知道应用程序完全关闭时是否可以收到来自谷歌云消息的通知?

I know if it's open or in background yes, but can it be programmed any way in order to receive them?

我知道它是打开的还是在后台是的,但是可以通过任何方式对其进行编程以接收它们吗?

EDIT:

编辑:

I continue without receiving notifications when the app is closed.

当应用程序关闭时,我继续没有收到通知。

I attached the code in case I have an error and I am not watching it.

我附上了代码,以防我有错误而我没有在看它。

MANIFEST

显现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.frab"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.frab.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="com.frab.permission.C2D_MESSAGE"
android:protectionLevel="signature" />

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.frab.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver
android:name=".GGMBroadcastReceiver"
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.REGISTRATION" />
<category android:name="com.something" />
</intent-filter>
</receiver>

<service android:name=".GCMIntentService" />
</application>

</manifest>

BROADCAST RECEIVER

广播接收器

package com.something;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.activities.SignIn;
import com.google.android.gcm.GCMBaseIntentService;
import com.objects.Globals;

public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GGM <-----> FRAB";
private Bundle extras;

public GCMIntentService() {
super(Globals.SENDER_ID);
}

@Override
public void onDestroy() {
Log.d(TAG, "terminando servicio");
}

@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}

@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId = " + registrationId);
}
@Override
protected void onMessage(Context context, Intent data) {
extras = data.getExtras();
String message = extras.getString("msg");
Log.d("******", message);
sendNotification(message);
}

@Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId = " + errorId);
}    
}

package com.something;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GGMBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}

When the app is open : OK

当应用程序打开时:OK

When the app is in background : Ok

当应用程序在后台时:好的

When the app is closed forcefully by the user : notifications don't arrive

当应用程序被用户强行关闭时:通知没有到达

What is the problem?

问题是什么?

Thank you very much.

非常感谢。

回答by Sahil Bajaj

Yes, it is possible 'to receive notifications from google cloud message when the application is fully closed'.

是的,可以“在应用程序完全关闭时接收来自谷歌云消息的通知”。

Infact, A broadcast receiver is the mechanism GCM uses to deliver messages. You need to have implement a BroadcastReceiverand declare it in the AndroidManifest.xml.

事实上,广播接收器是 GCM 用来传递消息的机制。您需要实现一个BroadcastReceiver并在 AndroidManifest.xml 中声明它。

Please refer to the following code snippet.

请参考以下代码片段。

AndroidManifest.xml

AndroidManifest.xml

<receiver
    android:name=".GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <!-- Receives the actual messages. -->
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.google.android.gcm.demo.app" />
    </intent-filter>
</receiver>
<service android:name=".GcmIntentService" />

Java code

Java代码

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

When GCM delivers a message to your device, BroadcastReceiverwill receive the message and call the onReceive()function, wherein you may start a service to actually perform the intended task for you.

当 GCM 向您的设备发送消息时,BroadcastReceiver将接收该消息并调用该onReceive()函数,您可以在其中启动服务以实际为您执行预期任务。

The above Code example uses a specialized BroadcastReceivercalled WakefulBroadcastReceiver, which makes sure that the device doesn't go to sleep, while the service is doing its work.

上面的代码示例使用了专门的BroadcastReceiver称为WakefulBroadcastReceiver,它确保设备不会进入睡眠状态,而服务正在执行其工作。

Refer to the Official Android Page for the same: https://developer.android.com/google/gcm/client.html

相同的参考官方Android页面:https: //developer.android.com/google/gcm/client.html

回答by laalto

When the app is closed forcelly by the user : notifications don't arrive

当应用程序被用户强制关闭时:通知没有到达

It's a feature of the Android platform. Force stopping an application by the user puts the application in a stopped state and none of its code is run, including any broadcast receivers declared in manifest. Only when the user explicitly launches the app it is put in a state where the receivers get fired.

这是Android平台的一个特性。用户强制停止应用程序会将应用程序置于停止状态,并且不会运行其任何代码,包括清单中声明的​​任何广播接收器。只有当用户明确启动应用程序时,它才会处于接收器被触发的状态。

For further reading: http://www.doubleencore.com/2014/06/effects-android-application-termination/

进一步阅读:http: //www.doubleencore.com/2014/06/effects-android-application-termination/

回答by berserk

It will not work on killing the app from task manager, but work if you just slide it away from recent. I tried doing on whatsapp by killing it and ask someone to send a msg to me, and I haven't got any notification. Then I started the app, and I got notification.

它无法从任务管理器中杀死应用程序,但如果您将其从最近的位置滑开,则可以工作。我尝试通过杀死它并要求某人向我发送消息来对 whatsapp 进行操作,但我没有收到任何通知。然后我启动了该应用程序,并收到了通知。

回答by Dhaval Jivani

Firebase API has two types of messages, they call them:

Firebase API 有两种类型的消息,他们称之为:

  • notification
  • data
  • 通知
  • 数据

find more information from here

这里找到更多信息

IMPORTANT :You can't send data payload messages from Firebase Console, Console only delivers notification message. So I have mentioned how to send push notification using postman please follow below steps for that.

重要提示:您不能从Firebase 控制台发送数据有效负载消息,控制台仅提供通知消息。所以我已经提到了如何使用邮递员发送推送通知,请按照以下步骤操作。

You must send push messages with data payload because of data payload - Doesn't matter whether your application is in the foreground or background or killed, these messages will always be delivered to onMessageReceived()method.

由于数据负载,您必须发送带有数据负载的推送消息 - 无论您的应用程序是在前台还是后台或被终止,这些消息都将始终传递到onMessageReceived()方法。

In Android 8.0 Oreoif the application is closed, then notification is not received It is because of DOZE mode and battery optimization,you just have to turn off battery optimization for all apps or particular app.

Android 8.0 Oreo 中,如果应用程序关闭,则不会收到通知 这是因为 DOZE 模式和电池优化,您只需关闭所有应用程序或特定应用程序的电池优化。

Turn off battery optimization for your app by below step:

按照以下步骤关闭应用的电池优化:

Settings>> Battery >> battery Optimization >> find your app >> select >> if optimized click on don't optimize >> try pushing notification

设置>>电池>>电池优化>>找到你的应用>>选择>>如果优化点击不优化>>尝试推送通知

Send push notification using postman

使用邮递员发送推送通知

Step 1: https://fcm.googleapis.com/fcm/send

第 1 步:https: //fcm.googleapis.com/fcm/send

Step 2: Set this two into Header

第2步:将这两个设置为Header

Authorization: key=AIzaSyBuRl1Ikz3VXFvU7xW9mmg51lJ3uDSH

授权:密钥=AIzaSyBuRl1Ikz3VXFvU7xW9mmg51lJ3uDSH

Content-Type: application/json

内容类型:应用程序/json

Step 3: Send this json

第 3 步:发送此 json

{
 "to" : "eb9HgFulyzU:APA91bFMLReWWwilNFfJ1fnXZ0A2PhJAYsabg-UcK_dHgHQcstTzcxLs4_mqgOmZtUiyLMne4JaOG7f8KH7pWxB7JugOGCCYgjd4fUynRBKZvNUgjaj2UdJB2Ux8VocszuUydCX",
 "data" : {
     "message" : "First Notification",
     "title": "Push Notification",
     "key_1" : "Key 1 value",
     "key_2" : "Hello"
 }
}

Hope this helps..

希望这可以帮助..

Enjoy :) :)

享受 :) :)

回答by Zez3

After some testing I did on this issue, I found out that it behaves differently on how the app is closed. If you close the app while the cable is connected to the device, it then blocks every notification when the app is closed. However, if you take the cable off the device and close the app, when you send the notification, everything works again, as it should!

在对此问题进行了一些测试后,我发现它在应用程序关闭方式上的行为有所不同。如果您在电缆连接到设备时关闭应用程序,它会在应用程序关闭时阻止每个通知。但是,如果您从设备上取下电缆并关闭应用程序,当您发送通知时,一切都会恢复正常!

In case you get a "Waiting for the Debugger" popup message, just restart the device and then send a test notification!

如果您收到“等待调试器”弹出消息,只需重新启动设备,然后发送测试通知!

回答by SandyQi

I just finished a GCM app. It still works well if you close the app. The thing is you should have already opened the app for once. create two class to achieve this goal: GcmBroadcastReceiverand GcnIntentService. Find more information http://developer.android.com/google/gcm/index.html

我刚刚完成了一个 GCM 应用程序。如果您关闭应用程序,它仍然可以正常工作。问题是你应该已经打开了一次应用程序。创建两个类来实现这个目标:GcmBroadcastReceiverGcnIntentService。查找更多信息 http://developer.android.com/google/gcm/index.html

Here is the trick

这是诀窍

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);

}
}

the class being extended is WakeFulBroadcastReceiver. There is a WAKE_LOCK permission in your Manifest.xml. This allows using PowerManagerWakeLocksto keep processor from sleeping or screen from dimming. However, if you extend BroadcastReceiver, it will not work after the app is closed.

正在扩展的类是WakeFulBroadcastReceiver. 您的 Manifest.xml 中有 WAKE_LOCK 权限。这允许使用PowerManagerWakeLocks防止处理器休眠或屏幕变暗。但是,如果您扩展BroadcastReceiver,它将在应用程序关闭后不起作用。

<uses-permission android:name="android.permission.WAKE_LOCK" />

回答by user3757628

I've been trying another phone and the second worked perfectly, even when the phone was off. The first had a room that did not allow to be notified when the app was closed ... Thanks to all

我一直在尝试另一部手机,第二部工作得很好,即使手机关机。第一个房间不允许在应用程序关闭时收到通知......感谢所有人

回答by Paresh

I was having the same issue on Oneplus phone. As mentioned by many people above, the issue was forceful app termination. In my case, it was done due to "Recent App management" setting as shown below. Once I changed it to "Normal clear" setting everything started working fine.

我在 Oneplus 手机上遇到了同样的问题。正如上面许多人所提到的,问题是强行终止应用程序。就我而言,这是由于“最近的应用程序管理”设置而完成的,如下所示。一旦我将其更改为“正常清除”设置,一切都开始正常工作。

enter image description here

在此处输入图片说明