1.利用timertask传递消息
TimerTask task = new TimerTask() { @Override public void run() { if (isOnEvent)//flag { Message msg = LocationHandler.obtainMessage(1,""); LxxHandler.sendMessage(msg); isOnEvent=false; if (dialog!=null && dialog.isShowing()) { dialog.dismiss(); } } } }; Timer timer = new Timer(); timer.schedule(task, 10000);//延迟1秒执行 Handler LxxHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if (msg.obj != null) { if (msg.what == 1) { Toast.makeText(m_Activity, "xx失败,请稍后重试!", Toast.LENGTH_LONG).show(); } } } };
2、利用timerTask在指定时间执行指定任务(如后退键退出程序)
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (isQuit == false) { isQuit = true; Toast.makeText(getBaseContext(), "再按一次返回键退出程序", Toast.LENGTH_SHORT).show(); TimerTask task = new TimerTask() { @Override public void run() { isQuit = false; } }; timer.schedule(task, 2000);//******超过2秒,isQuit变为false } else { SysApplication.getInstance().exit();//2秒内连续按两次以上,退出程序 } } return false; }