diff --git a/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java b/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java new file mode 100644 index 0000000..ff3412f --- /dev/null +++ b/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java @@ -0,0 +1,91 @@ +package cn.hugh.bz.gk2.utils; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.Build; +import android.util.Log; + +import cn.hugh.bz.gk2.receiver.WallpaperChangeReceiver; + +public class AlarmScheduler { + private static final String TAG = "AlarmScheduler"; + private static final int REQUEST_CODE = 1000; + + private final Context context; + private final AlarmManager alarmManager; + + public AlarmScheduler(Context context) { + this.context = context; + this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + } + + public void scheduleWallpaperChange(long intervalMinutes) { + // Cancel existing alarm + cancelSchedule(); + + // Calculate interval in milliseconds + long intervalMillis = intervalMinutes * 60 * 1000; + long triggerAtMillis = System.currentTimeMillis() + intervalMillis; + + // Create pending intent + Intent intent = new Intent(context, WallpaperChangeReceiver.class); + intent.setAction(WallpaperChangeReceiver.ACTION_CHANGE_WALLPAPER); + + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, + REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + + // Schedule alarm + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // Android 12+ needs exact alarm permission + if (alarmManager.canScheduleExactAlarms()) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } else { + // Fallback to inexact alarm + alarmManager.setAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } else { + alarmManager.setExact( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } + + Log.i(TAG, "Scheduled wallpaper change every " + intervalMinutes + " minutes"); + } + + public void cancelSchedule() { + Intent intent = new Intent(context, WallpaperChangeReceiver.class); + intent.setAction(WallpaperChangeReceiver.ACTION_CHANGE_WALLPAPER); + + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, + REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + + alarmManager.cancel(pendingIntent); + Log.i(TAG, "Cancelled wallpaper change schedule"); + } +}