android - startForeground() 不显示任何通知
问题描述
我想启动一个后台服务,即使应用程序关闭它仍然运行,
为此,我使服务开始变得有粘性,并使其成为一个过程。问题仍然存在,所以我做了一些研究,发现在最近的 Android 设备中,我们必须在前台启动此类服务:-通过使用 startForegroundService 启动服务,-并在服务的 onStartCommand 中 startForeground,-显示具有恒定通道的通知.
我这样做了,但同样的问题,前台服务的通知没有显示,
我的服务的 onStartCommand :
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
Intent intent2 = new Intent(this, RDVSearchService.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent2, 0);
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setContentTitle("Pratikk")
.setContentText("Subject")
.setSmallIcon(R.drawable.ok_done)
.setContentIntent(pendingIntent);
Notification notif;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notif = builder.build();
}else{
notif = builder.getNotification();
}
startForeground(1234, notif);
return START_STICKY;
}
我如何启动服务:
Intent intent = new Intent(context, RDVSearchService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
}else{
context.startService(intent);
}
我在 Manifest 中的服务声明:
<service
android:name=".services.RDVSearchService"
android:exported="false"
android:process=":rdv_search" />
解决方案
从 android 8.0 开始,必须创建频道。
String channelId = "channelId";
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setContentTitle("Pratikk")
.setContentText("Subject")
.setSmallIcon(R.drawable.ok_done)
.setContentIntent(pendingIntent);
startForeground(1234, builder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"name", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("description");
channel.enableLights(false); // light
channel.enableVibration(false); // vibration
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
推荐阅读
- python - statmodels OLS 在 python 中给出 TypeError
- javascript - Webpack 失败:“ENOTDIR:不是目录,stat 'node_modules/.cache/hard-source/.DS_Store/stamp'”
- sql-server - Visual Studio:将 ReportViewer 与用户生成的数据库文件(数据源)一起使用
- reactjs - Atom 中的 Eslint 在有效的 JSX 语法上出错
- python - 包含 3 个数组的数组只会打印一个(python)
- javascript - 传单折线箭头
- java - 如何在 Java 中设置一系列可能的值?
- regex - 从 VBA Excel 中的字符串中检索非常具体的值
- ms-access - MS Access 拆分表格数据表总计
- javascript - 如何重用 GraphQL 单个查询 API 来获取列表?