android - 持久通知android
问题描述
我需要创建一个持久通知 - 即使在新的 Android 版本上也是如此。我使用带有 (START_STICKY) 的前台服务来显示通知。通知是在 onCreate() 方法中创建的,并且我不时重新启动前台服务 - 以防万一它被杀死。
这就是我创建通知的方式:
String CHANNEL_ID = MainActivity.packageName+".notification";// The id of the channel.
CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setSound(null, null);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, MainActivity.packageName+".notification");
Intent main = new Intent(this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
// set intent so it does not start a new activity
Notification notification = nBuilder
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.icon)
.setWhen( System.currentTimeMillis())
.setContentTitle("my app")
.setContentText("my msg")
.setOngoing(true)
.setChannelId(MainActivity.packageName+".notification")
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notificationManager.notify(StaticMembers.notifId, notification);
startForeground(StaticMembers.notifId+1, notification);
通知会显示,但在某些手机型号上,几天后通知不再显示,即使服务仍在运行。
我应该怎么办?我创建通知的方式有问题吗?如果显示通知,我应该检查服务何时运行,如果不重新创建它?
谢谢
解决方案
推荐阅读
- javascript - Javascript - addEventListener 只能工作一次
- typescript - 用打字稿表达错误
- html - PostgreSQL 中的 HTML 数据类型
- react-native - 具有自定义文本子样式的 React-native TextInput
- nestjs - Loopback vs. NestJS - 开箱即用的 Loopback 类似 GraphQL 的带有 REST 支持的查询非常好。NestJS 也可以实现类似的功能吗?
- android - Pepper 机器人 QiSDK-改变眼睛的颜色 Leds
- python - 如何在python中使用内部类?
- python - 如何合并上下三角形,还添加1s的对角线
- java - 如何在 Intellij IDEA 中为资源包属性设置 UTF-8?
- mongodb - 模型和填充模型的猫鼬搜索关键字