【问题标题】:FCM never delivers when app is in background当应用程序处于后台时,FCM 从不交付
【发布时间】:2019-06-17 17:53:47
【问题描述】:

我在我的应用中集成了 FCM。每当应用程序处于后台时,都不会收到 fcm 消息。我已经尝试过通知类型和数据类型消息。甚至通知消息也不会显示在通知托盘中。他们只是迷路了!

请帮我找出哪里出错了。我已经按照文档跟踪了所有内容,并且已经研究了整整一周。

我的清单:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ....>    
<service
        android:name=".MyFirebaseMessagingService"
        android:exported="true"
        android:enabled="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

我的 Firebase 消息服务:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    SharedPreferences sharedPref;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        }


        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    @Override
    public void onNewToken(String token) {
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
    //Sending handled here
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(this, UserHomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("title", title);
        intent.putExtra("message", messageBody);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 273, intent,
                PendingIntent.FLAG_ONE_SHOT);

        //String channelId = getString(R.string.default_notification_channel_id);
        String channelId = "Sandeep123";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setContentTitle(title)
                        .setSmallIcon(R.mipmap.ic_launcher_foreground_new)
                        .setColorized(true)
                        .setColor(Color.BLUE)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setVisibility(VISIBILITY_PUBLIC)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    getString(R.string.channel_name),
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(createID(), notificationBuilder.build());
    }

    public int createID() {
        Date now = new Date();
        int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
        return id;
    }
}

我在 firebase 控制台中添加了我的调试和发布 SHA-1。我不知道我还能在哪里出错。当应用程序处于活动状态时,它适用于所有设备。但是当应用程序在后台时它根本不起作用。

*------------更新-服务器端代码

function sendGcmNotification($amountAdded, $tok,$des){
    define( 'API_ACCESS_KEY', '***' );
     $title = "Rs.".$amountAdded." added as credit";
     $notificationMsg = "***";
    //$token = array();
    //$token[] = $tok;
     $msg =
 [
    'message'   => $notificationMsg,
    'title'   => $title
 ];

 $android = ["priority"=>"high"];
 $fields = 
 [
    'to'  => $tok,
    'data'      => $msg,
    'time_to_live' => 900,
    'priority' => 10,
    'android' => $android
 ];

 $headers = 
 [
   'Authorization: key=' . API_ACCESS_KEY,
   'Content-Type: application/json'
 ];

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
 curl_setopt( $ch,CURLOPT_POST, true );
 curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
 curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
 curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
 curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
 $result = curl_exec($ch );
  curl_close( $ch );
 echo $result;

}

Log猫日志如下:

2019-01-24 11:14:08.310 1541-1578/? W/ActivityManager: Background start not allowed: service Intent { act=com.google.firebase.MESSAGING_EVENT pkg=in.dailydelivery.dailydelivery cmp=in.dailydelivery.dailydelivery/.MyFirebaseMessagingService (has extras) } to in.dailydelivery.dailydelivery/.MyFirebaseMessagingService from pid=26445 uid=10210 pkg=in.dailydelivery.dailydelivery 2019-01-24 11:14:08.311 26445-26445/? 
E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found

请帮帮我。 桑迪普。

【问题讨论】:

  • 收到通知后能否查看logcat?
  • 2019-01-24 11:14:08.310 1541-1578/? W/ActivityManager:不允许后台启动:服务 Intent { act=com.google.firebase.MESSAGING_EVENT pkg=in.dailydelivery.dailydelivery cmp=in.dailydelivery.dailydelivery/.MyFirebaseMessagingService(有附加功能)} 到 in.dailydelivery.dailydelivery/ .MyFirebaseMessagingService 来自 pid=26445 uid=10210 pkg=in.dailydelivery.dailydelivery 2019-01-24 11:14:08.311 26445-26445/? E/FirebaseInstanceId:传递消息时出错:未找到 ServiceIntent。

标签: android firebase firebase-cloud-messaging


【解决方案1】:

FCM 在前台/后台将消息传递到应用程序以在通知栏上创建通知,从应用程序服务器发送的消息格式应符合以下格式,请注意通知消息不会收到应用后台时的任何回调,只会收到数据消息

通知消息格式:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

数据信息:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

更多详情请参考以下链接 https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message

为了让 fcm 在设备锁定或后台发送推送通知,来自应用服务器的消息应具有以下标签

{
   ....
   "android": {"priority":"high"},
   "priority": 10,
   ....
}

请参阅下文了解更多详情 https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message

【讨论】:

  • 请查看我在我的 cmets 中附加的日志猫日志。当应用程序最近关闭时传递消息。但在一段时间不活动后,观察到上述日志。请帮帮我
【解决方案2】:

您需要在您的 Manifest 的应用程序标签中声明服务

see this sample code.

要了解更多,请查看guide

【讨论】:

  • 嗨...该服务仅在应用程序标签中...我只剪切了所需的部分并将其放在这里...谢谢...我已经更新了相关问题。当应用程序处于活动状态时,我会收到通知。我没有在后台收到.. 这就是问题。
  • 也许你错过了一些在 MessagingService 上的实现,尝试在 Firebase 示例项目 github.com/firebase/quickstart-android/tree/master/messaging 上交叉检查你的实现
【解决方案3】:

在后台接收时带有通知和数据负载的消息。在这种情况下,通知会被传递到设备的系统托盘,而数据负载会在启动器 Activity 的 Intent 的附加部分中传递。

Handling Messages: Receive messages in an Android app

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 2017-06-25
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多