Kuv*_*bov 9 service notifications android foreground
前台服务通知在 Android 12 上显示太慢。使用过ContextCompat.startForegroundService(...)
和mContext.startForegroundService(...)
。5-10 秒后仍会显示。
这是我的代码的示例:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Counting steps", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableVibration(false);
channel.setSound(null, null);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
}
Run Code Online (Sandbox Code Playgroud)
onStartCommand方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("numberOfSteps");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_directions_walk_24)
.setContentIntent(pendingIntent);
startForeground(FOREGROUND_ID, notificationBuilder.build());
}
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)
如何快速启动或显示前台服务通知?
如果前台服务至少具有以下特征之一,系统将在服务启动后立即显示关联的通知,即使在运行 Android 12 或更高版本的设备上也是如此:
该服务与包含操作按钮的通知相关联。 该服务的foregroundServiceType 为mediaPlayback、mediaProjection 或phoneCall。 该服务提供与电话呼叫、导航或媒体播放相关的用例,如通知的类别属性中所定义。 在设置通知时,服务已通过将 FOREGROUND_SERVICE_IMMEDIATE 传递到 setForegroundServiceBehavior() 来选择退出行为更改。 在 Android 13(API 级别 33)或更高版本上,如果用户拒绝通知权限,他们仍然会在前台服务 (FGS) 任务管理器中看到与前台服务相关的通知,但不会在通知抽屉中看到它们。
请参阅:立即显示通知的服务
Java示例代码:
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(message)
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
}
Run Code Online (Sandbox Code Playgroud)
科特林示例:
val notificationBuilder: Notification.Builder =
Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Notification title")
.setContentText("Content title")
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3160 次 |
最近记录: |