android 在onReciver裡面使用定時器 定時更新UI的例子在定時器線程裡面是不能直接更新UI的,需要使用Handle,使用Handle可以註冊個廣播,在定時到時且條件符合情況下發送一個廣播Handler收到廣播後處理更新UI相關操作,這裡還示範了下傳送Context變數作為定時器的建構函式值的方法(如果需要在run方法使用到Context可以用)
下面代碼是工程裡面的,需要參考的人把無關的代碼刪除了 留下骨架改成自己的就可以了
1 private final BroadcastReceiver mConn_Receiver = new BroadcastReceiver() {
2 @Override
3 public void onReceive(Context context, Intent intent) {
4 String action = intent.getAction();
5 if (BluetoothGatt.ACTION_GATT_CONNECTED.equals(action)) {
6 //啟動定時器
7 proximityAlarm(2,context);
8 }
9 }
10 }
11
12 private final static String PROXIMITY_ALARM_ACTION = "com.cyberblue.iitag.proximityalarm";
13 private ProximityAlarmRecevier pReceiver;
14 //延遲警示
15 public void proximityAlarm(int second,Context context){
16 Log.i(TAG,"Enter proximityAlarm second=" + second);
17
18 if(pReceiver == null){
19 pReceiver = new ProximityAlarmRecevier();
20 registerReceiver(pReceiver, new IntentFilter(PROXIMITY_ALARM_ACTION));
21 }
22
23 Timer time = new Timer();
24 ProximityAlarmTimerTask task = new ProximityAlarmTimerTask(context);
25 //dalay/1000秒後執行task.只執行一次
26 time.schedule(task, second*1000);
27 }
28
29 public class ProximityAlarmTimerTask extends TimerTask {
30 private Context context;
31 public ProximityAlarmTimerTask(Context mcontext){
32 context = mcontext;
33 }
34 public void run(){
35 Log.i(TAG,"Enter ProximityAlarmTimerTask");
36 if(mLeState == CONNECTED){
37 return ;
38 }else{
39 Intent intent = new Intent(PROXIMITY_ALARM_ACTION);
40 sendBroadcast(intent);
41 }
42 }
43 }
44
45 public class ProximityAlarmRecevier extends BroadcastReceiver {
46 @Override
47 public void onReceive(Context context, Intent intent) {
48 Log.i(TAG,"Enter ProximityAlarmRecevier");
49 pHandler.sendEmptyMessage(0);
50 }
51 }
52
53 //處理重連
54 Handler pHandler = new Handler() {
55 public void handleMessage(Message msg) {
56 Log.i(TAG,"Enter pHandler");
57 switch (msg.what) {
58 case 0:
59 //停止上一次的音樂
60 stopMusic();
61 //停止震動
62 cancelVibrator();
63 //點亮螢幕
64 final PowerManager.WakeLock wl = wekelock();
65 vibrator();
66 playMusic();
67 //只保留最後一個警示視窗
68 if(view != null){
69 wm.removeView(view);
70 }
71 view = inflater.inflate(R.layout.proximity_result, null);
72 wm.addView(view, wmParams);
73 Button proximitytagBtn = (Button) view.findViewById(R.id.proximitytagBtn);
74 proximitytagBtn.setOnClickListener(new OnClickListener() {
75 @Override
76 public void onClick(View v) {
77 //移除WindowManager
78 wm.removeView(view);
79 view = null;
80 //停止音樂
81 stopMusic();
82 //停止震動
83 cancelVibrator();
84 if(wl != null && wl.isHeld()){
85 wl.release();
86 }
87 }
88 });
89 closeWakeLock(120,wl);
90
91 break;
92 }
93 super.handleMessage(msg);
94 }
95 };