在Android Oreo版本中没有收到FCM通知消息?

Sri*_*n M 21 android firebase firebase-cloud-messaging

我已经从服务器向用户发送FCM通知.它工作正常(直到api 25),但在奥利奥,当应用程序没有在后台(服务已关闭)(或)完全关闭.我没有得到任何FCM通知在这种情况但在Whatsapp工作正常.这里我附上了FCM代码

的Manifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_ic_notification" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="fcm"/>

        <meta-data android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />

        <meta-data android:name="firebase_analytics_collection_enabled"
            android:value="false" />

    </application>

</manifest>
Run Code Online (Sandbox Code Playgroud)

应用程序/ gradle这个

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.fcm"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-messaging:17.1.0'
}

apply plugin: 'com.google.gms.google-services'
Run Code Online (Sandbox Code Playgroud)

MyFirebaseMessagingService.java

package com.fcm;

import android.app.Service;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService
{

    @Override
    public void onNewToken(String s) 
    {
    super.onNewToken(s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Log.e("FCM Message Received","You Have FCM Message");
    }
}
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

package com.nexge.fcm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this,  new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                String newToken = instanceIdResult.getToken();
                Log.e("newToken",newToken);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Vis*_*kar 7

当您定位到Android 8.0(API级别26)时,您必须实现一个或多个通知渠道.如果您的targetSdkVersion设置为25或更低,当您的应用在Android 8.0(API级别26)或更高版本上运行时,其行为与运行Android 7.1(API级别25)或更低版本的设备上的行为相同.

注意: 如果您定位Android 8.0(API级别26)并在未指定通知通道的情况下发布通知,则不会显示通知,系统会记录错误.

注意:您可以在Android 8.0(API级别26)中启用新设置,以显示屏幕警告,当针对Android 8.0(API级别26)的应用尝试在没有通知渠道的情况下发布时,该警告会显示为吐司.要打开运行Android 8.0(API级别26)的开发设备的设置,请导航到"设置">"开发人员选项"启用"显示通知通道警告".

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
   String id = "id_product";
   // The user-visible name of the channel.
   CharSequence name = "Product";
   // The user-visible description of the channel.
   String description = "Notifications regarding our products";
   int importance = NotificationManager.IMPORTANCE_MAX;
   NotificationChannel mChannel = new NotificationChannel(id, name, importance);
   // Configure the notification channel.
   mChannel.setDescription(description);
   mChannel.enableLights(true);
   // Sets the notification light color for notifications posted to this
   // channel, if the device supports this feature.
   mChannel.setLightColor(Color.RED);
   notificationManager.createNotificationChannel(mChannel);
}
Run Code Online (Sandbox Code Playgroud)

在Android Oreo上创建推送通知

要创建通知,您将使用NotificationCompat.Builder类.之前使用过的构造函数只将Context作为参数,但在Android O中,构造函数看起来像这样 -

NotificationCompat.Builder(Context context, String channelId)
Run Code Online (Sandbox Code Playgroud)

以下代码段将向您展示如何创建通知 -

Intent intent1 = new Intent(getApplicationContext(), Ma

inActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 123, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),"id_product")
       .setSmallIcon(R.drawable.flatpnicon) //your app icon
       .setBadgeIconType(R.drawable.flatpnicon) //your app icon
       .setChannelId(id)
       .setContentTitle(extras.get("nt").toString())
       .setAutoCancel(true).setContentIntent(pendingIntent)
       .setNumber(1)
       .setColor(255)
       .setContentText(extras.get("nm").toString())
       .setWhen(System.currentTimeMillis());
notificationManager.notify(1, notificationBuilder.build());
Run Code Online (Sandbox Code Playgroud)

Android O为您提供了一些自定义通知的功能 -

setNumber() - 允许您设置长按菜单中显示的数字 setChannelId() - 允许您在使用旧构造函数setColor()时显式设置通道ID - 允许RGB值为您设置颜色主题notification setBadgeIconType() - 允许您设置要在长按菜单中显示的图标

有关详细信息,请查看示例


aan*_*shu 6

"从Android 8.0(API级别26)开始,所有通知都必须分配给频道,否则不会出现."

现在必须将个别通知放入特定频道.(参考)

选项1 [简单] 更改目标Android版本Android 7.1(API级别25)或更低.

compileSdkVersion 25
    defaultConfig {
        applicationId "com.fcm"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
Run Code Online (Sandbox Code Playgroud)

选项2 如果您不想更改目标版本,请按照以下方法操作

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
     NotificationChannel nc = new NotificationChannel(“[enter your product id]”, “[Name]”,NotificationManager.IMPORTANCE_MAX);
     nc.setDescription(“[your description for the notification]”);
     nc.enableLights(true);
     nc.setLightColor(Color.GREEN);
     nm.createNotificationChannel(nc);
  }
Run Code Online (Sandbox Code Playgroud)

使用以下Builder构造函数

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(appContext, [id you mentioned above in constructor of NotificationChannel])
Run Code Online (Sandbox Code Playgroud)

从Builder创建通知

nm.notify("0", notificationBuilder.build())
Run Code Online (Sandbox Code Playgroud)