使用AlarmManager实现APP保活(1)

首先,定义两个类:Alarm_Scheduler和Alarm_Receiver,Alarm_Scheduler的代码如下:

复制代码
public class Alarm_Scheduler {
    public static void schedule_alarm(Context context) {
        AlarmManager alarm_manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, Alarm_Receiver.class);
        PendingIntent pending_intent = PendingIntent.getBroadcast(
                context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 高版本无法setExactAndAllowWhileIdle
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (!alarm_manager.canScheduleExactAlarms()) {
                try {
                    intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                    context.startActivity(intent);
                } catch (ActivityNotFoundException e1) {
                    try {
                        // 跳转到应用详情页备选
                        Intent settingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        settingsIntent.setData(Uri.parse("package:" + context.getPackageName()));
                        context.startActivity(settingsIntent);
                    }
                    catch (ActivityNotFoundException e2) {
                        // 显示手动引导弹窗
                    }
                }
            }
        }

        // 设置精确唤醒(根据系统版本适配)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm_manager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + TraceApplication.alarm_interval,
                    pending_intent);
        }
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm_manager.setExact(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + TraceApplication.alarm_interval,
                    pending_intent);
        }
        else {
            alarm_manager.set(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + TraceApplication.alarm_interval,
                    pending_intent);
        }
}
复制代码

首先获得一个AlarmManager的实例,再定义一个PendingIntent启动Alarm_Receiver.

‌setExactAndAllowWhileIdle是Android中用于设置精确闹钟的方法,它允许在设备处于低功耗模式(如Doze模式)时仍然能够触发闹钟‌.这种方法特别适用于需要确保在特定时间触发闹钟的应用场景.然而,高版本的Android系统(API版本31及以上)禁止使用这个方法,因此要判断Android系统的版本,对于高版本的系统引导用户进行设置,允许使用‌setExactAndAllowWhileIdle方法.

然后根据不同的系统版本设置闹钟,API版本23及以上的使用setExactAndAllowWhileIdle(),19~22使用setExact(),18及以下使用set().

posted @   MSTK  阅读(1)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示