在Oreo后台中自定义推送通知声音无法工作

4
我有以下负载推送通知,是从我的服务器发送的。该通知在所有版本中都可以工作,但声音仅在Android Oreo上不起作用,其他Android版本都正常工作。
{
  "to" : "d4DLcrilLbs...",
   "notification" : {
   "body" : "This is an FCM notification message!",
   "title" : "FCM Message",
   "sound" : "new_sound.wav"
  }
}
3个回答

2
在Oreo中,您需要设置通道声音。
请使用以下代码更改:

在Oreo中,您需要设置通道声音。

请使用以下代码进行更改:

 if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
    {
        final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + this.getPackageName() + "/raw/notification");
        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();
        NotificationChannel channel = new NotificationChannel("MyNotification","MyNotification", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setSound(alarmSound,attributes);
        NotificationManager mgr =getSystemService(NotificationManager.class);
        mgr.createNotificationChannel(channel);

    }

无论您的应用程序是在后台还是前台运行,它都可以正常工作。

Original Answer翻译成"最初的回答"


我们要把这段代码写在哪里?当应用程序处于后台时,onMessageReceived不起作用。 - Olkunmustafa
1
我已经在我的启动器活动(主活动的创建方法)中添加了这个。 - Kamleshwer Purohit
答案是正确的,但还需要添加注释。在通知中应添加“android_channel_id”:“MyNotification”参数。 - Olkunmustafa

0

在Android Oreo中,通知需要在通道下注册,否则您将无法生成通知。

查看以下文章可能会对您有所帮助

点击这里


0
package com.example.notification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import android.util.Log;

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


public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    NotificationManager  mNotificationManager;
    NotificationCompat.Builder  mBuilder;
    Context mContext;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());


        }

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

    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        sendRegistrationToServer(token);
    }

    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }


    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }


    private void sendNotification(String message) {
        Intent resultIntent=new Intent(getApplicationContext(),MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(),
                0 /* Request code */, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

//        Uri uri = Uri.parse("android.resource://" + getApplicationContext()
//                .getPackageName() + "/" + R.raw.mix);
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

        mBuilder = new NotificationCompat.Builder(getApplicationContext());
        mBuilder.setSmallIcon(R.drawable.ic_launcher_background);
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher_background));
        mBuilder.setContentTitle(message)
                .setContentText(message)
                .setSound(soundUri)
                .setLights(100,200,300)
                .setAutoCancel(false)
                .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                .setColor(Color.GREEN)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setContentIntent(resultPendingIntent)
                .setOnlyAlertOnce(true);

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel("541201134433333", "MYGET", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setShowBadge(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//            notificationChannel.s

            if (soundUri != null) {
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();
                notificationChannel.setSound(soundUri, audioAttributes);
            }

            assert mNotificationManager != null;
            mBuilder.setChannelId("541201134433333");
            mNotificationManager.createNotificationChannel(notificationChannel);

        }

        assert mNotificationManager != null;
        mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
    }
}

1
你能在这里加一点解释吗?哪些调用是关键的?什么是关键? - mate00
应用程序在后台时无法正常工作。如何使 onMessageReceived 能够正常工作? - Olkunmustafa
完全从您的服务器请求中删除通知字段。仅发送数据并在onMessageReceived()中处理它,否则当应用程序在后台或被杀死时,将不会触发onMessageReceived()。"data":{ "id": 1, "missedRequests": 5 "addAnyDataHere": 123 }, "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......", "priority": "high" } - Vibhu Vikram Singh
在你的通知请求中不要忘记包含 "priority": "high" 字段。 - Vibhu Vikram Singh

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