FCM推送通知在一加6手机上无法正常工作。

7

FCM推送通知在以下设备中,当设备在后台、前台以及通过从托盘滑动关闭应用程序时都能正常工作。

品牌 Android版本
Micromax 5.1
Motorola 7.1.1
Nokia 8.1.0
Samsung 8.0.0
Nexus 8.1.0
xiaomi 7.1.2

但是,在OnePlus设备上,当应用程序通过从托盘滑动关闭时,FCM通知无法正常工作,但当应用程序在前台和后台时可以正常工作。

设备 版本
OnePlus 8.1.0

但是,当我手动关闭我的应用程序的电池优化选项时,所有情况下FCM推送通知都能在OnePlus设备上正常工作。

我的androidManifest.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.Notification"
    android:installLocation="auto">

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

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <!-- [START fcm_default_icon] -->
        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_launcher" />
        <!-- [END fcm_default_icon] -->
        <!-- [START fcm_default_channel] -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>
        <!-- [END fcm_default_channel] -->

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

        <activity
            android:name="com.demo.Notification.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

我是MyFirebaseMessagingService.java

package com.demo.Notification;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONObject;

public class MyFirebaseMessagingService extends FirebaseMessagingService
{
    private static final String NOTIFICATION_MESSAGE_KEY = "MESSAGE";
    private NotificationManager notificationManager;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {

        sendNotification(remoteMessage.getData().get(NOTIFICATION_MESSAGE_KEY));
    }

    private void sendNotification(String msg)
    {
        String notification_message_title = "";
        String notification_message_text = "";
        int notification_id = 1;
        String channel_id = getString(R.string.default_notification_channel_id);

        try
        {
            JSONObject jsonObject = new JSONObject(msg);

            if(jsonObject.has("notification_message_title"))
            {
                notification_message_title = jsonObject.getString("notification_message_title");
                notification_message_title = (notification_message_title != null) ? notification_message_title.trim() : "";
            }

            if(jsonObject.has("notification_message_text"))
            {
                notification_message_text = jsonObject.getString("notification_message_text");
                notification_message_text = (notification_message_text != null) ? notification_message_text.trim() : "";
            }

            if("".equals(notification_message_title))
            {
                return;
            }

            if("".equals(notification_message_text))
            {
                return;
            }

        }
        catch(Exception e)
        {
            return;
        }

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            setupChannels();
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,channel_id);
        mBuilder.setAutoCancel(true);
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        mBuilder.setContentTitle(notification_message_title);
        mBuilder.setContentText(notification_message_text);
        mBuilder.setColor(Color.BLUE);
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);

        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        mBuilder.setLargeIcon(largeIcon);

        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(notificationSound);


        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        notification_id,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            mBuilder.setChannelId(channel_id);
        }

        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
        notificationManagerCompat.notify(notification_id, mBuilder.build());

        //SEND Notification END
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setupChannels(){
        String channel_id = getString(R.string.default_notification_channel_id);
        CharSequence channelName = getString(R.string.default_notification_channel_name);

        NotificationChannel channel = new NotificationChannel(channel_id, channelName, NotificationManager.IMPORTANCE_MAX);
        channel.enableLights(true);
        channel.setLightColor(Color.BLUE);
        channel.enableVibration(true);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}

我的应用级别的build.gradle文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.3"
    defaultConfig {
        applicationId "com.demo.Notification"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:27.1.1'    
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.google.firebase:firebase-messaging:17.3.0'
}
apply plugin: 'com.google.gms.google-services'

我的项目级 build.gradle 文件

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

我是这样向服务器发送令牌的。

public void registerDevice()
{
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task)
                {
                    String registrationId = task.getResult().getToken();
                    sendTokenToServer(registrationId);
                }
            });
}

任何小的帮助都将不胜感激


manifest文件中的FirebaseMessagingService中尝试测试用例 android:stopWithTask="false" - AskNilesh
谢谢您的回复,但是问题仍然存在,即使使用了您的解决方案。 - ashish pandey
检查这个 https://dev59.com/71UK5IYBdhLWcg3w4jQv#51129304 - AskNilesh
我仔细查看了你的代码并尝试了一下,但是问题依旧存在。 - ashish pandey
我曾经遇到过同样的问题。以下链接对我有所帮助:https://dev59.com/0VYN5IYBdhLWcg3wuaNx - Yesha
@Yesha感谢您提供的链接,但是问题仍然存在。同时我也发现,即使像Flipkart、Fasoos、Myntra等大型组织的应用(印度电子商务公司)也存在同样的问题。我只从亚马逊应用程序中收到通知,因为它在一加6中被列入白名单。 - ashish pandey
3个回答

2

这是由于Doze模式引起的。您可以通过在后端设置推送通知消息优先级为高消息优先级来克服这个问题。请查看文档


即使更改了优先级,仍然存在相同的问题,在应用程序在前台和后台时它可以工作,但在从OnePlus6手机的最近标签中滑动应用程序时无法工作。 - ashish pandey

1
在这些设备中(如OnePlus,Huawei,OPPO),它们使用基于Android操作系统的定制版操作系统,当其处于电池优化模式时,可能会强制关闭FCM的后台服务,因此我们无法收到任何通知。

2
但是像亚马逊和WhatsApp这样的应用程序,即使启用电池优化,我也能正常收到通知。 - ashish pandey
这些应用程序,如亚马逊、WhatsApp、Flipkart,默认情况下已被设备供应商列入白名单。 - Akash Kumar
@ashishpandey。你解决了这个问题吗?我还在寻找答案。请回复。 - Akash Kumar
抱歉,仍然无法解决这个问题。 - ashish pandey

-1

试试这段代码

Uri defaultSoundUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
 NotificationCompat.Builder notificationBuilder = new 
NotificationCompat.Builder(this)
 .setSmallIcon(R.drawable.ic_notif_icon)
  .setContentTitle("testTitle")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setChannelId("testChannelId") // set channel id
.setContentIntent(pendingIntent);

1
仍然存在相同的问题。 - ashish pandey

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