【发布时间】:2019-03-07 13:27:17
【问题描述】:
我使用startForeground 使我的服务持久化。因此,我必须构建一个通知以将其传递给startForeground 函数。
我想在不让通知发出警报的情况下启动该前台服务(即通过振动或声音)。
对于 android 8 设备,我在调用 startForeground 之前创建了一个通知通道。我将重要性设置为NotificationManager.IMPORTANCE_NONE 以避免通知警报(只是为了使图标出现在状态栏上)。
但是,在某些设备上,我仍然有通知提醒(对于三星 Galaxy S8 和 Honor View 10)。
所以,我测试了这个批准的答案https://stackoverflow.com/a/24008765/10069542。
这适用于三星 Galaxy S8。尽管如此,当我启动前台服务时,Honor View 10 仍然会发出警报。
这是创建我的通知通道并构建要传递给 startForeground 的通知的代码
通知渠道
@RequiresApi(api = Build.VERSION_CODES.O)
private String createNotificationChannel() {
String channelId = NOTIFICATION_CHANNEL_ID;
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (service != null) {
service.createNotificationChannel(chan);
} else {
Log.e(TAG, "Error creating notification channel");
return null;
}
return channelId;
}
通知
private Notification getNotification() {
Intent startIntent = new Intent(getApplicationContext(), RangoActivity.class);
startIntent.setAction(Intent.ACTION_MAIN);
startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
this, REQ_CODE_REQUEST_RANGO_SERVICE, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);
} else {
builder = new Notification.Builder(this);
}
builder.setSmallIcon(R.drawable.rango_notification_icon)
.setContentTitle(getString(R.string.notification_content_title))
.setContentText(getString(R.string.notification_content_text))
.setTicker(getString(R.string.notification_ticker))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L})
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(contentIntent);
Notification notification = builder.build();
return notification;
}
【问题讨论】:
-
您在通知生成器上尝试过
setSound(null,null)方法吗? -
是的,我刚刚添加了这一行,仍然得到同样的结果。
-
卸载并重新安装应用程序并检查它是否仍然无法运行
-
我从一个刚导出的apk开始
标签: android notifications android-service android-notifications foreground-service