自定义定时任务实际上是使用封装handler进行定时任务
package com.guosen.kuanggong.common.util;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import java.util.List;
/**
* Created by cgx on 2017-6-6.
* 定时任务
*/
public class TimerHelper {
private Handler mHandler = new Handler();
private int mScheduleTime = 60;//60秒刷一次
private boolean stoped = true;
private Context mContext;
public TimerHelper(Context ctx) {
mContext = ctx;
}
public TimerHelper(Context ctx, int scheduleTime) {
this.mScheduleTime = scheduleTime;
mContext = ctx;
}
private Runnable task = new Runnable() {
public void run() {
if (isForeground(mContext)) {
onSchedule();
}
mHandler.postDelayed(task, mScheduleTime * 1000);
}
};
/**
* 开始轮询统计任务
*/
public final void start() {
if (!stoped) {
return;
}
mHandler.removeCallbacks(task);
mHandler.post(task);
onStart();
stoped = false;
}
/**
* 结束轮询统计任务
*/
public final void stop() {
onStop();
mHandler.removeCallbacks(task);
stoped = true;
}
/**
* 执行定时任务
*/
protected void onSchedule() {
}
/**
* 开始任务的时候需要进行的首次统计任务
*/
protected void onStart() {
}
/**
* 终止任务的时候,执行的任务
*/
protected void onStop() {
}
private boolean isForeground(Context context) {
if (context != null) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
if (processInfo.processName.equals(context.getPackageName())) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE
) {
return true;
}
}
}
}
return false;
}
}
定时任务以activity的生命周期为主,切换到后台或者切换到别的activity都会停止定时任务,同时清空handler。在onResume中调用start,在onPause中调用
对外暴露两个公有方法start和stop,分别是开启定时任务和关闭定时任务,final方法不能被子类重写
使用的时候,需要继承这个类,推荐采用匿名内部类的方式,可以先传递一个参数,如果没有,默认是60s
mTimerHelper = new TimerHelper(this,3){
@Override
protected void onSchedule() {
Log.e("timer"," on timer");
}
};
还有onStart和onStop方法,以便在定时开始或结束的时候执行其他任务,