使用AlarmManager实现APP保活(2)

Alarm_Receiver的代码如下:

public class Alarm_Receiver extends BroadcastReceiver {
    private boolean is_local_service_running;
    private boolean is_remote_service_running;
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        try {
            do_something();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 设置下一次唤醒
        schedule_alarm(context);
    }

    private void do_something() throws ClassNotFoundException {
    ...
    }
}

Alarm_Receiver继承自BroadcastReceiver,在onReceive()方法中,调用要执行的任务,然后用schedule_alarm()方法设置下一次唤醒.

在Application类的onCreate()方法里面,调用Alarm_Receiver类的schedule_alarm()方法,开始第一次调用:

Alarm_Scheduler.schedule_alarm(this);

这样,就可以循环调用下去.

posted @ 2025-04-02 18:01  MSTK  阅读(35)  评论(0)    收藏  举报