java - Android前台服务通知未显示在状态栏中
问题描述
我在这里尝试了各种解决方案,但似乎无法让它们中的任何一个工作。通知根本不会显示。谁能指出我的代码中可能存在的问题?
private void startRunningInForeground() {
setupNotificationChannel();
Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_stat_ic_logo);
builder.setContentTitle(getString(R.string.merge_notif_title));
builder.setContentText(getString(R.string.merge_notif_description));
builder.setContentIntent(contentIntent);
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setOngoing(true);
startForeground(NOTIFICATION_ID, builder.build());
}
private void setupNotificationChannel() {
// Only run this on versions of Android that require notification channels.
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager == null) {
return;
}
NotificationChannel cachingChannel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL,
getString(R.string.merge_channel), NotificationManager.IMPORTANCE_HIGH);
cachingChannel.setDescription(getString(R.string.merge_channel_description));
cachingChannel.enableLights(false);
cachingChannel.enableVibration(false);
notificationManager.createNotificationChannel(cachingChannel);
}
没有收到任何错误消息并且正在创建通知通道,因为我在应用程序设置中看到了它。
解决方案
你的 startForeground 做什么?
尝试修改它并确保您的操作系统 > Android 8.0
顺便说一句,频道只需要创建一次。
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
NOTIFICATION_ID, <---
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
startForeground(NOTIFICATION_ID, builder.build());
notificationManager.notify(NOTIFICATION_ID, builder.build()); <--
可能是因为Android O bg服务限制
//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourService.class));
} else {
startService(new Intent(this, YourService.class));
}
推荐阅读
- c++ - c++ 类和范围内的标头
- jupyter-notebook - 如何从 Sagemaker 培训中打印调试信息?
- openvas - 如何使用 Openvas+proxychains 或 Nmap+proxychains(通过 socks5 而不是 socks4)?
- php - 错误!找不到命令“tesseract”。(PHP 蒂亚戈莱西奥)
- firebase-authentication - Firebase 身份验证是否存储散列和加盐密码?
- angular - ngFor Angular 2+ 中未加载索引
- r - 如何编写引用 R 优化中的目标的约束
- javascript - 过滤对象的数组属性而不改变对象本身
- webpack - webpack 正在使用父节点的 node_modules 并且当前目录中有 node_modules
- cmake - 傻瓜的 CMake 3.5.0 详细模式