android - 务实地启用我的后台服务通知
问题描述
我有 android 应用程序,我必须使用 android o 及更高版本的服务在后台运行我知道后台服务被系统杀死,所以我正在使用startForground
适当的通知,但有时这些通知不会出现,这可能是因为移动设置
所以如果我们从
设置->应用->我的应用名称->通知->我的后台服务和服务
因此我的问题是我如何务实地启动或检查这些我的后台服务和服务。
解决方案
从Android O,
我们需要为到达后台的每个通知设置频道 ID。
在清单中需要添加
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="default_channel_id"/>
在您的消息服务类中,
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());//Considering you have message in your body.
}
和
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
推荐阅读
- php - 自动装配如何知道要通过什么类?
- java - 有没有将字符串中的整数转换为 JAVA 中的 ASCII 字符的解决方案?
- ios - 第二次实例化 ARSCNView 时崩溃
- mongodb - mongodb成员卡在startup2中
- python - 如何覆盖python脚本文件中的一些分配?
- javascript - 将内容写入新窗口
- dns - 如何使用 nslookup 查找规范名称
- python-3.x - 使用 docx 模块在 docx 文档中按索引查找字符串
- php - 按 Polylang 语言过滤 WooCommerce 相关产品
- reactjs - 强制反应功能组件触发重新渲染