Почему не воспроизводятся настройки уведомлений?Android Studio - PullRequest
0 голосов
/ 27 августа 2018

Я получаю уведомления от службы сообщений Firebase.Все работает хорошо, когда приложение работает на главном экране, но когда я использую другое приложение или экран заблокирован, уведомления запускаются по умолчанию (мелодия по умолчанию, без вибрации и т. Д.).В этих случаях он не использует конфигурацию, которую я сделал для настройки активности.

Это класс FirebaseMessagingService

public class MyFirebaseMessaggingService extends FirebaseMessagingService {

    public static final String TAG = "Noticias";

    public boolean notification, vibrate;
    public String ringTone;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        // Obteniendo token
        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
                new OnSuccessListener<InstanceIdResult>() {
                    @Override
                    public void onSuccess(InstanceIdResult instanceIdResult) {
                        final String token = instanceIdResult.getToken();
                        Log.i(TAG, "Token: " + token);
                    }
                });
    }

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

        String from = remoteMessage.getFrom();
        Log.i(TAG, "Mensaje recibido de: " + from);

        SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        notification = preferencias.getBoolean("notifications_on_off", true);
        ringTone = preferencias.getString("notifications_tono", "DEFAULT_SOUND");
        vibrate = preferencias.getBoolean("vibrate_on_off",false);

        Log.i("Tono de notificacion ", ringTone);

        if (remoteMessage.getNotification() != null) {
            Log.i(TAG, "Notificación: " + remoteMessage.getNotification().getBody());

            if(notification){
                mostrarNotificacion(remoteMessage.getNotification().getTitle(),
                        remoteMessage.getNotification().getBody(), ringTone, vibrate);
            }
        }

        if (remoteMessage.getData().size() > 0) {
            Log.i(TAG, "data" + remoteMessage.getData());
        }
    }

    private void mostrarNotificacion(String title, String body,
                                     String ringtone, boolean vibrate) {

        Intent intent = new Intent(this, NavigationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri tonoNotificacion = Uri.parse(ringtone);// Parseo del sonido de la notificación a URI
        //Ringtone ringtoneNotification = RingtoneManager.getRingtone(getApplicationContext(), tonoNotificacion);
        //ringtoneNotification.play();

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String ID = FirebaseInstanceId.getInstance().getId();
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ID)
                .setSmallIcon(R.drawable.ic_notifications_white_24dp)
                .setContentTitle(title)
                .setContentText(body)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
                .setAutoCancel(true)
                .setShowWhen(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(pendingIntent)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(ID,
                    "Mensaje Recibido", NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription(body);
            channel.setShowBadge(true);
            channel.enableVibration(vibrate);
            channel.setVibrationPattern(new long[]{500, 500});

            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .build();

            channel.setSound(tonoNotificacion, audioAttributes);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }else{
            if(vibrate){
                notificationBuilder.setVibrate(new long[]{500, 500});
            }
            notificationBuilder.setSound(tonoNotificacion);
            notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
            notificationBuilder.setFullScreenIntent(pendingIntent,true);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

Мне нужно воспроизвести все настройки уведомлений, сохраненные в preferenceActivity, когда яс помощью другого приложения или мой экран заблокирован.Буду признателен за все ваши рекомендации.

1 Ответ

0 голосов
/ 27 августа 2018

Используйте Notification.Builder не NotificationCompat.Builder для Oreo и более поздней версии

И вам нужно позвонить Notification.Builder.setChannelId(), чтобы установить канал уведомлений

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