【问题标题】:Firebase Notification : Should always ring even if the phone is in silent/DND/vibrate modeFirebase 通知:即使手机处于静音/免打扰/振动模式,也应始终响铃
【发布时间】:2021-02-03 07:28:41
【问题描述】:

我创建了一个 android 应用程序并希望使用 firebase 进行通知。但我想让电话一直响,即使它处于静音/振动/dnd 模式。

我编写的以下代码在某些情况下不起作用,例如有人确实降低了警报音量/以及在某些手机中无法使用静音模式。

这是我的 FirebaseMessageReceiver.java 文件

public class FirebaseMessageReceiver extends FirebaseMessagingService {
    private static final String TAG = "";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        RemoteMessage.Notification notification = remoteMessage.getNotification();
        Map<String, String> data = remoteMessage.getData();
        Log.d(TAG, "myFirebaseMessagingService - onMessageReceived - message: " + remoteMessage);
        Intent dialogIntent = new Intent(this, NotificationReceiver.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        dialogIntent.putExtra("msg", remoteMessage);
        startActivity(dialogIntent);

    }

    private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
        String channel_id = getString(default_notification_channel_id);
        String channel_name = getString(default_notification_channel_name);
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Uri notification_sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.alert);

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
        intent.putExtra("message", notification.getBody());
        intent.putExtra("title", notification.getTitle());
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Log.d(TAG, "Alert Sound  Value" + notification_sound);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id)
                .setContentTitle(notification.getTitle())
                .setContentText(notification.getBody())
                .setAutoCancel(true)
                .setSound(notification_sound)
                .setContentIntent(pendingIntent)
                .setContentInfo(notification.getTitle())
                .setLargeIcon(icon)
                .setColor(Color.RED)
                .setLights(Color.RED, 1000, 300)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_ALARM)
                .setShowWhen(true)
//                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setSmallIcon(R.mipmap.ic_launcher);


        try {
            String picture_url = data.get("picture_url");
            if (picture_url != null && !"".equals(picture_url)) {
                URL url = new URL(picture_url);
                Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                notificationBuilder.setStyle(
                        new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setupChannels(notificationManager);
        }
            notificationManager.notify(1, notificationBuilder.build());
            startActivity(intent);

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setupChannels(NotificationManager notificationManager) {
        String adminChannelName = getString(default_notification_channel_name);
        String adminChannelDescription = getString(default_notification_channel_name);
        String channelid = getString(default_notification_channel_id);
        AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        Uri notification_sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.i_phone_mix);

        NotificationChannel adminChannel;
        adminChannel = new NotificationChannel(channelid, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
        adminChannel.setDescription(adminChannelDescription);
        adminChannel.enableLights(true);
        adminChannel.setLightColor(Color.RED);
        adminChannel.enableVibration(true);
        adminChannel.canBypassDnd();
        Log.d(TAG, "Alert Sound  Value" + notification_sound);
        AudioAttributes audio_attribute = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM,
                audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM),
                0);
        adminChannel.setSound(notification_sound, audio_attribute);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(adminChannel);
        }


    }
}

【问题讨论】:

    标签: android firebase push-notification firebase-cloud-messaging android-notifications


    【解决方案1】:

    如果您想在设备上响铃。任何情况下,如果手机处于静音模式 Dns 模式/振动模式并且移动显示已关闭,因此您可以按照此代码进行操作。

    public class MyFirebaseMessagingService extends FirebaseMessagingService {
        public static final String FCM_PARAM = "picture";
        private static final String CHANNEL_NAME = "FCM";
        private static final String CHANNEL_DESC = "Firebase Cloud Messaging";
        private int numMessages = 0;
    
    
    
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            RemoteMessage.Notification notification = remoteMessage.getNotification();
            final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.notification_speech);
            mediaPlayer.start();
            Map<String, String> data = remoteMessage.getData();
            sendNotification(notification, data);
    
        }
    
        @RequiresApi(api = Build.VERSION_CODES.O)
        private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
    
            Log.d("notification_", String.valueOf(notification));
            Bundle bundle = new Bundle();
            // bundle.putString(FCM_PARAM, data.get(FCM_PARAM));
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("notificationValue", String.valueOf(data));
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("EXIT", true);
            intent.putExtras(bundle);
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getString(R.string.app_name))
                    .setContentTitle(notification.getTitle())
                    .setContentText(notification.getBody())
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setContentInfo("Hello").setSound(null)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.nofi_icon))
                    .setLights(Color.RED, 1000, 300)
                    .setNumber(++numMessages).setSound(null)
                    .setSmallIcon(R.drawable.nofi_icon);
    
            try {
                String picture = data.get(FCM_PARAM);
                if (picture != null && !"".equals(picture)) {
                    URL url = new URL(picture);
                    Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                    notificationBuilder.setStyle(
                            new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
                    );
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        getString(R.string.app_name), CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW
                );
    
                channel.setDescription(CHANNEL_DESC);
                channel.setShowBadge(true);
                channel.canShowBadge();
                channel.enableLights(true);
                channel.setLightColor(Color.RED);
                channel.setSound(null, null);
    
                AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                manager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
    
                channel.enableVibration(true);
                //channel.setSound(soundUri, audioAttributes);
                channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
    
    
                assert notificationManager != null;
                notificationManager.createNotificationChannel(channel);
            }
            assert notificationManager != null;
            notificationManager.notify(0, notificationBuilder.build());
        }
    }
    

    【讨论】:

    • 嗨,Prem,非常感谢,但该代码是否仅在应用程序处于后台时才能使用?
    • 当你在 manifest 中定义适当的服务时,应用程序后台运行良好,如下所示:过滤器> 服务>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多