【发布时间】:2018-12-03 16:20:42
【问题描述】:
最近我开始编写我的第一个 android 项目,其中包括 Firebase Cloud Messaging。我使用 Android SDK 21 (Android 5)。
我的目的是让用户选择,应该播放哪种铃声以及设备是否应该振动。为此,我创建了一个帮助类 SettingsHandler,它可以像这样访问用户设置:
public synchronized static Uri getRingtoneUri(Context context) {
Sharedpreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return Uri.parse(prefs.getString("ringtone_key"), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString());
}
public synchronized static boolean shouldVibrateOnPush(Context context) {
SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return prefs.getBoolean("vibration_flag", true);
}
因此,当我收到来自 Firebase 的通知时,我想设置用户可以使用上述方法设置的声音和振动模式。
为了得到这个,我覆盖了 MyFirebaseMessagingService 中的 onMessageReceived 方法,它扩展了 - 谁期望这个 - FirebaseMessagingService:
public void onMessageReceived(RemoteMessage msg) {
super.onMessageReceived(msg);
if (msg.getNotification() != null) {
Intent activityIntent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, activityIntent, PendingIntent.FLAG_ONE_SHOT);
Notification note = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.mipmap.icon)
.setContentTitle(msg.getNotification().getTitle())
.setContentText(msg.getNotification().getBody())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setSound(SettingsHandler.getRingtoneUri(this))
.setVibrate(SettingsHandler.shouldVibrateOnPush ? new long[] {500, 500, 500, 500, 500} : new long[] {0, 0, 0, 0, 0})
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//create notification channels
}
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(1, note);
}
}
但是,当我发送通知时,总是播放默认声音,所以我开始问自己,我的思维方式是否有错误。任何方式如何正确地做到这一点?提前致谢。
【问题讨论】:
标签: android firebase firebase-cloud-messaging android-notifications