简体   繁体   English

Android 推送通知声音在 android 上丢失(不工作)背景和前景

[英]Android Push Notification Sound is missing (Not Working ) background and foreground on android

I have implementing FCM for push notification.我已经为推送通知实施了 FCM。 I am calling this OnMessageReceived Method but the sound is not played when the app is in the foreground and background我正在调用这个 OnMessageReceived 方法但是当应用程序在前台和后台时不播放声音

here is my code这是我的代码

public class MyFirebaseMessagingService extends FirebaseMessagingService {

public static  String ChannelID = "";
public static final int NOTIFICATION_ID = 1041;
public static boolean IsDriverBusy = false;
private NotificationManager notificationManager;
private SharedPreferences sharedPreferences;
private NotificationChannel mChannel;
private NotificationCompat.Builder notificationBuilder;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    System.out.println("notificationIntentIs   0000000000000123545 onMessageReceived  " + IsDriverBusy);

    String mTime = getDate(remoteMessage.getSentTime());
    String RiderLOcation = remoteMessage.getData().get("RiderLocation");
    String RiderID = remoteMessage.getData().get("RiderID");
    String Dlat = remoteMessage.getData().get("Dlat");
    String DLong = remoteMessage.getData().get("DLong");
    String Plat = remoteMessage.getData().get("Plat");
    String Plong = remoteMessage.getData().get("Plong");
    String RiderName = remoteMessage.getData().get("RiderName");
    String RiderRating = remoteMessage.getData().get("RiderRating");
    String MainBody = "RiderID:" + RiderID + ";RiderName:" + RiderName + ";RiderLocation:"
            + RiderLOcation + ";PLat:" + Plat + ";PLong:" + Plong + ";DLat:" + Dlat + ";DLong:" + DLong + ";RiderRating:" + RiderRating;
    sharedPreferences = getSharedPreferences("LoginDetail", Context.MODE_PRIVATE);
    if (sharedPreferences.getString("id", "").equals("")) {
        Intent intent1 = new Intent(this, LoginActivity.class);
        startActivity(intent1);

    } else {
        if (!IsDriverBusy) {
            sendNotification(MainBody);
            PreferenceHandler.writeString(this, PreferenceHandler.RIDE_DETAIL, MainBody);
        }
    }

}

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000L);
    String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
    return date;
}

@SuppressLint("WrongConstant")
private void sendNotification(String messageBody) {

    Intent intent = new Intent(this, MainActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("bookingId", messageBody);
    intent.putExtras(bundle);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    startActivity(intent);
    ChannelID=getString(R.string.default_notification_channel_id);

    Uri defaultSoundUri = Uri.parse("android.resource://com.my.package/" + R.raw.windchime);
    long[] VIBRATE_PATTERN = {0, 500};

    notificationBuilder = new NotificationCompat.Builder(this, ChannelID)
            .setSmallIcon(R.drawable.logo)
            .setVibrate(VIBRATE_PATTERN)
            .setPriority(Notification.DEFAULT_ALL)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(getString(R.string.notificationData))
            .setAutoCancel(true)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(pendingIntent);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // Since android Oreo notification channel is needed.
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

        AudioAttributes mAudioAttributes=new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        mChannel = new NotificationChannel(ChannelID, "Qwykr_Channel",
                NotificationManager.IMPORTANCE_HIGH);
        mChannel.setVibrationPattern(VIBRATE_PATTERN);
        mChannel.setImportance(Notification.DEFAULT_ALL);
        mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        mChannel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,mAudioAttributes);
        notificationManager.createNotificationChannel(mChannel);
    }

    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
    clearNotification(NOTIFICATION_ID);
}

public void clearNotification(int ID) {
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {

        }
    };
    Runnable doDisplayError = new Runnable() {
        public void run() {

            notificationManager.cancel(ID);
        }
    };
    handler.postDelayed(doDisplayError, 3000);

}

} }

and I'm using Xiaomi Redmi 7 pro.I'm checking the phone setting app notification channel the only vibration is enabled not a sound and another option is enabled.我正在使用小米红米 7 pro。我正在检查手机设置应用程序通知频道,唯一启用的是振动而不是声音,并且启用了另一个选项。 How can set a channel like Whatsapp and telegram application?如何设置像 Whatsapp 和电报应用程序这样的频道? How can I enable all the fields of the screenshot like Sound, Floating Notification, LockScreen Notifications?如何启用屏幕截图的所有字段,如声音、浮动通知、锁屏通知? Here is my app Channel screenshot:这是我的应用频道截图:

在此处输入图片说明

Please Help me out to solve the problem.请帮我解决问题。 Thanks in andvance万分感谢

This code is working for me这段代码对我有用

First You can uninstall your app then try the channel code.首先您可以卸载您的应用程序,然后尝试频道代码。

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_ONE_SHOT);

    String channelId = CommonUtill.random();
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.logo)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(true)

                    .setSound(defaultSoundUri)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(messageBody).setBigContentTitle(getString(R.string.app_name)))
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notification);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(channelId,
                getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        mChannel.setDescription("desc");
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setSound(sound, attributes); // This is IMPORTANT


        if (notificationManager != null)
            notificationManager.createNotificationChannel(mChannel);

    }
    notificationManager.notify(943/* ID of notification */, notificationBuilder.build());

What type of FCM you are sending?您发送的是什么类型的 FCM? Is it Notification message or Data message?是通知消息还是数据消息? If it is Notification message OnMessageReceived will not be called when app is in the background.如果是通知消息OnMessageReceived在应用程序在后台时不会被调用。 The notification will be taken care of by the ststem tray.通知将由 ststem 托盘处理。 If you want to run OnMessageReceived while in background use FCM Data message.如果您想在后台运行OnMessageReceived ,请使用 FCM 数据消息。

EG:例如:

Notification message:通知讯息:

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

Data message:数据信息:

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

More about it here .更多关于它在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android 仅当应用程序处于前台时才播放推送通知声音,但当应用程序处于后台时不播放声音 - Android Push notification sound is played only when app is in foreground but not playing sound when app is in background Firebase 云消息推送通知无法在前台工作,仅在后台工作,在 Android - Firebase Cloud Messaging push notification not working in foreground, only background, on Android Android Firebase 推送通知自定义声音不起作用 - Android Firebase push notification custom sound is not working Android 推送通知的自定义声音不起作用 (FCM) - Custom sound for Android Push Notification not working (FCM) FCM不工作推送通知声音android - FCM not working push notification sound android android推送通知声音 - android push notification sound Android 接收推送通知并在前台或后台处理它 - Android receiving push notification and handling it either in foreground or background 推送通知未显示在 Android 前台 - Push notification not showing in Android foreground firebase 推送通知声音在 android 工作室中的 android 应用程序上不起作用 - firebase push notification sound not working on android app in android studio Android通知声音不起作用 - Android notification sound is not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM