java - 如何在android中自定义通知
问题描述
我刚刚使用主题消息实现了 Firebase 云消息推送通知。收到通知,但 MyFirebaseMessagingService 无法正常工作。它与从云消息传递一样传递消息。
完成云消息功能。创建一个服务名称 MyFirebaseMessagingService 并使用 FirebaseMessagingService 进行扩展。将服务添加到清单。
这是我的 FirebaseMessagingService 类。
@Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String clickAction = remoteMessage.getNotification().getClickAction();
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.hollow);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("New Notification")
.setSound(soundUri)
.setContentText(messageTitle);
Intent resultIntent = new Intent(clickAction);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) builder.setVibrate(new long[0]);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, builder.build());
}
我的清单文件:-
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
解决方案
在发送云消息时,您还必须订阅要接收通知的主题,例如。
FirebaseMessaging.getInstance().subscribeToTopic("general")
.addOnCompleteListener(task -> {
if (task.isSuccessful())
Toast.makeText(this, "Subs-Successful", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Subs NOT Successful", Toast.LENGTH_SHORT).show();
});
在此,我订阅了一般主题,并且只会收到有关此主题的消息,例如此主题。
希望这有帮助....为我工作!
推荐阅读
- apache-spark - 客户端模式下的 Spark 作业抛出错误
- java - H2 中用于单元测试的现有索引
- vtiger - 在 Vtiger7 中,vtigercrm/index.php?module=Leads&view=Edit 的 edit.js 文件的位置是什么
- selenium-webdriver - 如果不执行其他操作(例如清除字段),如果表值等于预期值,则想要执行操作
- mongoengine - 烧瓶棉花糖自定义字段
- rest - 当我在 Java 中使用 @jsonPropretyorder 时,属性显示 2 次
- arrays - Powershell Group-对象数组列表
- c# - 是否可以在 C# 中动态启用和禁用 CORS?
- javascript - URL 链接到 # 页面位置和 Owl Carousel 滑块位置
- android - Couchbase Mobile 2.0 在 MutableDocument 中设置数组