【问题标题】:Android app is not receiving FCM notification when closedAndroid 应用在关闭时未收到 FCM 通知
【发布时间】:2016-10-17 19:53:42
【问题描述】:

我正在检查Firebase Cloud Messaging 以发送通知。已经实现它并在应用程序处于打开状态时接收通知。但如果我关闭应用程序,它不再提供通知。有什么解决办法吗?

代码:

WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";

Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;

Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

WebResponse wResponse = wRequest.GetResponse();

消息服务-

public class MessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String>  data = remoteMessage.getData();
        sendNotification(data);
    }

    public void showMessage(Map<String, String>  serverData) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
    }

    private void sendNotification(Map<String, String>  serverData) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
    }

}

主要活动-

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();
    }
}

清单-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.com.firebasenotify">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service android:name=".MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

</manifest>

【问题讨论】:

  • 显示 fcm 监听器类,并显示您对 fcm 发出的 POST 请求
  • 更新消息服务、FCM 帖子和主要活动代码
  • 你至少在onreceive中收到消息吗?
  • 当应用程序未运行(或后台运行)时,不会调用onMessageReceived 进行通知。在这种情况下,Android 应该在收到通知时显示系统通知(在顶部的栏中)。
  • @Frank 如果 POST 有效负载中没有 notification 键,则会调用它

标签: android notifications firebase firebase-cloud-messaging firebase-notifications


【解决方案1】:

代码没有问题。我正在使用 Mi note 4,但不知何故,当应用程序关闭时,它不会在 Mi4 中显示通知。我用其他安卓设备测试过,它工作正常。

感谢 Tim Castelijns 和 Frank van Puffelen 参与对话。

【讨论】:

  • 对于 MI,您需要在安全中将应用置于自动启动模式,以便在应用关闭时收到通知
  • 谢谢大佬,redmi prime2 也遇到了同样的问题。您在 MI 设备中找到解决此问题的方法了吗?
  • vivo,opp也遇到同样的问题,请给个解决办法
【解决方案2】:

关于这个问题here 有很好的解决方案和解释。您需要为通知设置高优先级以告诉android立即做出反应,否则需要几分钟才能显示收到的通知。

【讨论】:

    【解决方案3】:

    我使用 Legacy Server Key 而不是 Server Key 它对我有用。

    【讨论】:

      【解决方案4】:

      在您的 POST Payload 中添加 time_to_live 键将解决此问题。此参数的值必须是 0 到 2,419,200 秒的持续时间,它对应于 FCM 存储的最长时间并尝试传递消息。 "time_to_live" : 3 Refer Firebase Docs

      【讨论】:

      • 这可能仅在用户返回应用程序时才有效。
      【解决方案5】:

      根据 FCM 文档 onMessageReceived() 不会在应用处于 后台 时被调用。您应该发送一个 notification 对象,以便将其显示在系统托盘中,当用户单击它时,启动器活动将打开,其中数据作为 extras 具有意图。对于有效负载,您应该使用 data 对象。 see docsReceive Messages in an Android App

      【讨论】:

      • 如果您看到没有通知对象的代码。他只是发送数据对象
      • 你也需要发送通知对象。
      • 但是如果我们发送通知对象,那么它不会点击 onMessageReceived 并且通知将由 android 本身处理并显示在通知托盘中(没有您的客户端应用程序)。如果我们在没有通知对象的情况下发送但有数据对象,那么它总是会点击 onMessageReceived。
      猜你喜欢
      • 1970-01-01
      • 2017-04-11
      • 2019-06-19
      • 1970-01-01
      • 2021-06-10
      • 2018-04-01
      • 2021-10-30
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多