首页 > 代码库 > 115、定时器(TimerTask+Timer+Handler)
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。