Android startForegroundService与startForeground

server/2024/10/18 2:29:40/

启动service

service启动有四种形式。

1.显示启动(如直接按service的全路径启动)

2.隐示启动(如通过intent-filter的action标签启动)

3.通过bindservice显示启动。

4.通过bindservice隐示启动。

Demo

创建一个service的子类,如

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;public class ForceGroundServer extends Service {private static final String TAG = "ForceGroundServer";@Nullable@Overridepublic IBinder onBind(Intent intent) {Log.d(TAG, "onBind: ");return null;}@Overridepublic boolean onUnbind(Intent intent) {Log.d(TAG, "onUnbind: ");return super.onUnbind(intent);}@Overridepublic void onCreate() {super.onCreate();Log.d(TAG, "onCreate: ");if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {sendNotification();}}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d(TAG, "onStartCommand: ");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.d(TAG, "onDestroy: ");}private final String CHANNEL_ID = "TestID";@RequiresApi(api = Build.VERSION_CODES.O)private void sendNotification() {NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "TEstName", NotificationManager.IMPORTANCE_HIGH);channel.enableLights(true);//设置提示灯channel.setLightColor(Color.BLUE);//设置提示灯颜色channel.setShowBadge(true);//显示logochannel.setDescription("test");//设置描述channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);//锁屏可见manager.createNotificationChannel(channel);Notification testNotification = new Notification.Builder(this).setChannelId(CHANNEL_ID).setContentText("服务已经至于前台了").setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).build();//id 不能是0startForeground(1, testNotification);}
}

显示启动

    private final static String TARGET_APP_PACKAGE = "com.example.mycolorpicker";private final static String TARGET_SERVICE_NAME = TARGET_APP_PACKAGE + ".ForceGroundServer";private final static String TARGET_SERVICE_ACTION = TARGET_SERVICE_NAME + ".action";private void startServerVisible() {Intent intent = new Intent();intent.setComponent(new ComponentName(TARGET_APP_PACKAGE,  TARGET_SERVICE_NAME));if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {startForegroundService(intent);Log.d(TAG, "startForegroundService");} else {startService(intent);Log.d(TAG, "startService");}}

隐示启动

    private void startServerHide() {Intent intent = new Intent();intent.setPackage(TARGET_APP_PACKAGE);intent.setAction(TARGET_SERVICE_ACTION);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {startForegroundService(intent);} else {startService(intent);}}

设置前台服务

首先需要在Manifest中声明权限需求。

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

若无此权限声明,系统会抛SecurityException异常

                                                                                                    java.lang.RuntimeException: Unable to create service com.example.mycolorpicker.ForceGroundServer: java.lang.SecurityException: Permission Denial: startForeground from pid=12931, uid=10247 requires android.permission.FOREGROUND_SERVICE

上面通过startForegroundService启动了servervice,会执行Service的Oncreate和OnStartCommand,service需要在5秒内调用startForeground,否则系统就会报TimeExceptio异常,app闪退。

ndroid.app.ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{263b8f7 u0 com.example.mycolorpicker/.ForceGroundServer}at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2046)at android.app.ActivityThread.access$2900(ActivityThread.java:275)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2271)at android.os.Handler.dispatchMessage(Handler.java:106)at android.os.Looper.loopOnce(Looper.java:211)at android.os.Looper.loop(Looper.java:300)at android.app.ActivityThread.main(ActivityThread.java:8291)at java.lang.reflect.Method.invoke(Native Method)


http://www.ppmy.cn/server/7524.html

相关文章

力扣HOT100 - 25. K 个一组翻转链表

解题思路&#xff1a; class Solution {public ListNode reverseKGroup(ListNode head, int k) {ListNode dum new ListNode(0, head);ListNode pre dum;ListNode end dum;while (end.next ! null) {for (int i 0; i < k && end ! null; i) {end end.next;}if …

Vue模版语法(初学Vue之v-指令语法)

目录 一、介绍 1.概念 2.常见指令语法及用法 1.v-bind: 2.v-model: 3.v-if / v-else-if / v-else: 4.v-for: 5.v-on: 6.v-show: 7.v-pre: 8.v-cloak: 二、使用 1.Mustache插值语法 2.v-once指令使用 3.v-text指令使用 4.v-html指令使用 5.v-pre指令使用 6.v-…

springboot 从mysql 迁移人大金仓 -kingbase

一、配置方法修改 1、添加maven依赖 <!-- 人大金仓 --><dependency><groupId>cn.com.kingbase</groupId><artifactId>kingbase8</artifactId><version>8.6.0</version></dependency> 2、连接配置&#xff0c;修改 .y…

安全开发实战(3)--存活探测与端口扫描

目录 安全开发专栏 前言 存活探测 端口扫描 方式一: 1.3.1 One 1.3.2 Two 1.3.3 批量监测 方式二: 1.3.1 One 1.3.2 Two 1.3.3 Three 1.3.4 扫描ip地址,提取出开放端口和协议 ​编辑 1.3.5 批量扫描(最终完成版) 总结 安全开发专栏 安全开发实战​http://t.csd…

electron项目打包慢、打包报错

项目使用了electron框架&#xff0c;在第一次打包或者网络条件不好的环境下进行打包时熟速度慢的出奇&#xff0c;甚至经常出现打包失败的情况&#xff08;如上面图片的报错&#xff09;。 这是因为&#xff0c;在electron打包的过程中&#xff0c;需要去官方源https://github.…

[MoeCTF 2022]Hex

看提示要用010&#xff0c;拖进010查看&#xff0c;查找ctf找到flag&#xff0c; moectf{Hello_Hex}

vscode 搭建stm32开发环境记录(eide+cortex-debug+jlink)

前言 clion使用的快过期了&#xff0c;所以就准备使用vscode 来代替clion作为代码开发环境 vscode 插件安装 创建个空白工程 添加项目相关的源文件&#xff0c;和配置宏定义和头文件目录 编译和烧录(ok) 结合cortex-debug 结果(测试ok)