115定时器(TimerTask+Timer+Handler)
Posted 大米稀饭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了115定时器(TimerTask+Timer+Handler)相关的知识,希望对你有一定的参考价值。
public class TimerUtils {
public static Activity act;
public static List<MaiDianModels> listMaiAll = new ArrayList<MaiDianModels>();
public TimerUtils(Activity act) {
this.act = act;
}
public static Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 3199:
if (listMaiAll.size() > 0) {
// Gson gson = new Gson();
String str = new Gson().toJson(listMaiAll);
// String类型 进行Base64编码
String encoded = Base64.encode(str);
Log.i("maidian", "encoded[编码]......" + encoded);
// String类型 进行Base64解码
String decoded = Base64.decode(encoded);
Log.i("maidian", "decoded[解码]......" + decoded);
}
break;
default:
break;
}
}
};
public static Timer timer = null;
public static MyTask myTask = null;
static class MyTask extends TimerTask { //
@Override
public void run() {
//do something
Message msg = Message.obtain();
msg.what = 3199;
myHandler.sendMessage(msg);
}
}
;
public static void start() {
stop();
timer = new Timer();
myTask = new MyTask();
timer.schedule(myTask, 2000, 2000); // 2s后执行task,经过2s再次执行 20000
}
public static void stop() {
if (myTask != null) {
myTask.cancel();
}
if (timer != null) {
timer.cancel();
timer.purge();
timer = null; // (可选)
}
}
}
new TimerUtils(TwoActivity.this).start();
以上是关于115定时器(TimerTask+Timer+Handler)的主要内容,如果未能解决你的问题,请参考以下文章