Push-уведомления без звука на MIUI - PullRequest
1 голос
/ 05 ноября 2019

Основная функция моего приложения - отправка push-уведомлений с удаленного сервера. Я использую FCM в качестве службы доставки сообщений. Моя проблема в том, что на Xiaomi Mi 9 Lite приходят уведомления без звука (Android 9 / MIUI 11). Однако на Xiaomi Redmi Note 5 (Android 9 / MIUI 10) звук работает нормально, а также на Samsung Galaxy S7 Edge (Android 8). Я создал MessagingService, который расширяет FirebaseMessagingService и канал уведомлений, как написано в документации. Вот мой код:

public class MessagingService extends FirebaseMessagingService {

    private static String channelId;
    private NotificationManager notificationManager;
    private NotificationChannel notificationChannel;
    private NotificationCompat.Builder notificationBuilder;

    private MessagesViewModel viewModel;

    public MessagingService() { }

    @Override
    public void onCreate() {
        super.onCreate();
        channelId = getResources().getString(R.string.default_notification_channel_id);
        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        final Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        notificationBuilder = new NotificationCompat.Builder(this, channelId);
        notificationBuilder.setSmallIcon(R.raw.metrial_message_icon);
        notificationBuilder.setAutoCancel(false);
        notificationBuilder.setSound(soundUri);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            final AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            String name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            notificationChannel = new NotificationChannel(channelId, name, importance);
            notificationChannel.setDescription(description);
            notificationChannel.enableLights(true);
            notificationChannel.setShowBadge(true);
            notificationChannel.setSound(soundUri, audioAttributes);
            notificationManager.createNotificationChannel(notificationChannel);
            notificationBuilder.setChannelId(channelId);
        }
        else {
            notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
            notificationBuilder.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);
            notificationBuilder.setLights(Color.WHITE, 500, 5000);
        }

        viewModel = new MessagesViewModel(getApplication());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        logger.info("onNewToken()");
        ConnectionParameters.getInstance().setToken(s);
        MyPrefs.getInstance(getApplicationContext()).putString(Constants.TOKEN, s);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        final String messageId = remoteMessage.getData().get("message_id");
        final String title = remoteMessage.getData().get("title");
        final String body = remoteMessage.getData().get("body");

        if (messageId != null && title != null && body != null) {

            final Message message = new Message();
            message.setMessageId(messageId);
            message.setTitle(title);
            message.setContent(body);
            message.setTimestamp(new Date());

            try {
                message.setNotificationId((int)viewModel.insert(message));
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }

            logger.info("onMessageReceived(): notificationId=" + message);

            if (MyPrefs.getInstance(getApplicationContext()).getBoolean(Constants.ENABLE_PUSH)) {
                notificationBuilder.setContentTitle(title);
                notificationBuilder.setContentText(body);

                final Intent notifyIntent = new Intent(this, MessageInfoActivity.class);
                notifyIntent.putExtra(Constants.ARG_MESSAGE_OBJECT, message);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addNextIntentWithParentStack(notifyIntent);
                PendingIntent pendingActivityIntent =
                        stackBuilder.getPendingIntent(message.getNotificationId(), PendingIntent.FLAG_UPDATE_CURRENT);
                notificationBuilder.setContentIntent(pendingActivityIntent);

                final Notification notification = notificationBuilder.build();
                notification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS;
                notificationManager.notify(message.getNotificationId(), notification);
            }
        }
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());
}

И в Настройки-> Уведомления Я получил следующие параметры: enter image description here

И внутри моегоЗвук push-notifications-channel звук включен, но всякий раз, когда приходит сообщение, похоже, что настройки уведомлений приложения переопределяют параметры в канале уведомлений. enter image description here

Должно быть какое-то решение, потому что в популярных приложениях, таких как WhatsApp, Telegram и т. Д., Эти переключатели включаются после установки (по умолчанию). Надеюсь, кто-то поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...