首页 > 代码库 > 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)