Android 实现app1定时开启关闭app2
一、实现步骤
令app1一直运行在后台------->添加定时机制-------> App1在后台开启App2-----------> App1在后台关闭App2
1、令app1一直运行在后台
方法一:将服务设置为前台服务:
在清单中声明前台服务
提示:安卓14必须要声明 android:foregroundServiceType 属性
android:foregroundServiceType
<service
android:name=".ForegroundService" // 服务名称
android:enabled="true"
android:exported="true" />
API 级别 29 或更高级别:必须使用 location 服务类型声明所有使用位置信息的前台服务。
API 级别 30 或更高级别:必须分别使用 camera 或 microphone 服务类型声明所有使用摄像头或麦克风的前台服务。
API 级别 34 或更高级别:必须声明所有前台服务及其服务类型。
请求前台服务权限
提示:每种前台服务类型都有对应的权限类型。API28以上需要申请FOREGROUND_SERVICE权限,API34以上要根据要执行的工作类型请求适当的权限类型
API [28,34)之间
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
创建前台服务
1、检查对应权限是否成功获取
2、创建通知(前台任务需要与通知相关联)
(1)创建通知渠道(API 26以上需要)
(2)动态申请通知权限(API 33以上)
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
// 获取系统通知服务
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// 获取 PendingIntent 对象
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
Notification notification = null;
NotificationChannel channel