# # 前台服务(android foreground services) ## # 用户可以解除前台通知 在安卓13(API level 33)开始,用户可以通过右滑来强行关闭前台通知(但是前台服务并没有关闭), 如果不想要用户手动关闭前台通知,使用Notification.Builder创建自定义通知的时候将true传入到setOngoing()方法中。 ## # 服务将会立即显示 如果前台服务包含以下至少一个特征,系统将会立即展示与其相关联的通知: 提醒中包含了操作按钮 服务包含了一个媒体播放,媒体投影或者电话 建立通知的时候,调用了setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE) ## # 显示紧急消息 响铃警报这类需要高时效性的事件,可以使用全屏Intent与通知关联。根据设备的锁定状态,用户会看到以下情况之一: 如果用户设备被锁定,会显示全屏 Activity,覆盖锁屏。 如果用户设备处于解锁状态,通知以展开形式显示,其中包含用于处理或关闭通知的选项。 > **注意** > 全屏Intent需要USE_FULL_SCREEN_INTENT权限 ```{lang} Intent fullScreenIntent = new Intent(this, ImportantActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setFullScreenIntent(fullScreenPendingIntent, true); ``` ## # 申请前台服务权限 安卓9以上使用前台服务需要获取FOREGROUND_SERVICE许可。 ```{lang} ... ``` ## # 开始一个前台服务 在请求系统将一个服务作为前台服务运行之前,需要先启动这个服务本身 ```{lang} Context context = getApplicationContext(); Intent intent = new Intent(...); // Build the intent for the service context.startForegroundService(intent); ``` Loading... # # 前台服务(android foreground services) ## # 用户可以解除前台通知 在安卓13(API level 33)开始,用户可以通过右滑来强行关闭前台通知(但是前台服务并没有关闭), 如果不想要用户手动关闭前台通知,使用Notification.Builder创建自定义通知的时候将true传入到setOngoing()方法中。 ## # 服务将会立即显示 如果前台服务包含以下至少一个特征,系统将会立即展示与其相关联的通知: 提醒中包含了操作按钮 服务包含了一个媒体播放,媒体投影或者电话 建立通知的时候,调用了setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE) ## # 显示紧急消息 响铃警报这类需要高时效性的事件,可以使用全屏Intent与通知关联。根据设备的锁定状态,用户会看到以下情况之一: 如果用户设备被锁定,会显示全屏 Activity,覆盖锁屏。 如果用户设备处于解锁状态,通知以展开形式显示,其中包含用于处理或关闭通知的选项。 > **注意** > 全屏Intent需要<code>USE_FULL_SCREEN_INTENT</code>权限 ```{lang} Intent fullScreenIntent = new Intent(this, ImportantActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setFullScreenIntent(fullScreenPendingIntent, true); ``` ## # 申请前台服务权限 安卓9以上使用前台服务需要获取FOREGROUND_SERVICE许可。 ```{lang} <manifest xmlns:android="http://schemas.android.com/apk/res/android" ...> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <application ...> ... </application> </manifest> ``` ## # 开始一个前台服务 在请求系统将一个服务作为前台服务运行之前,需要先启动这个服务本身 ```{lang} Context context = getApplicationContext(); Intent intent = new Intent(...); // Build the intent for the service context.startForegroundService(intent); ``` 最后修改:2025 年 07 月 14 日 © 允许规范转载 赞 别打赏,我怕忍不住购买辣条与续命水