Android Firebase уведомления не имеют звука - PullRequest
0 голосов
/ 04 февраля 2020

Я получаю звук уведомления Firebase во время работы приложения и не слышу звук уведомления, когда приложение находится в фоновом режиме. Я не знаю, почему это происходит.

Это то, что я пытался

Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
            // To Configure the notification channel.
            notificationChannel.setDescription("Sample Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.drawable.gj512x512)
                .setContentText(message)
                .setSound(sound)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);
        notificationManager.notify(1, noBuilder.build());
}

Пожалуйста, помогите мне с этим.

Ответы [ 3 ]

1 голос
/ 04 февраля 2020

Просто сделайте одно: скажем, ваш бэкэнд-разработчик просто отправит данные полезную нагрузку в уведомлении, попросит его ограничить и удалить уведомление полезную нагрузку,

Потому что, когда вы в это время вы получаете уведомление, если ваше приложение в фоновом режиме и вы получаете полезную нагрузку для уведомлений в это время, система обрабатывает уведомление с их стороны, и поэтому возникает проблема,

Так что просто удалите уведомление полезная нагрузка со стороны сервера, и она будет работать нормально.

Добавьте ваш php код, как показано ниже для данных

$title = 'Whatever';
$message = 'Lorem ipsum';
$fields = array
(
    'registration_ids'  => ['deviceID'],
    'priority' => 'high',
    'data' => array(
        'body' => $message,
        'title' => $title,
        'sound' => 'default',
        'icon' => 'icon'
    )
);
0 голосов
/ 04 февраля 2020

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

FCM Класс:

public class FcmMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    showNotification(Objects.requireNonNull(remoteMessage.getNotification()).getTitle(), remoteMessage.getNotification().getBody());
}

private void showNotification(String title, String body) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "net.Test.id";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.setDescription("Description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.BLUE);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableLights(true);
        assert notificationManager != null;
        notificationManager.createNotificationChannel(notificationChannel);
    }
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    notificationBuilder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_launcher_foreground).setContentTitle(title).setContentText(body).setContentInfo("Info");
    assert notificationManager != null;
    notificationManager.notify(new Random().nextInt(), notificationBuilder.build());
}

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.d("TOKEN", s);
}
}

манифест fl ie:

<service
        android:name="arbn.rahyab.rahpayadmin.data.network.fcm.MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/googleg_standard_color_18" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="001" />

, если вы хотите настроить его, напишите коды внутри класса FCN.

0 голосов
/ 04 февраля 2020
 notificationChannel.setSound(null,null);  // remove this line 



.setSound(sound) //replace this line with this 

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