您的位置:首页 > 产品设计 > UI/UE

android 在onReciver里面使用定时器 定时更新UI的例子

2012-08-08 09:30 435 查看
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 }
}

private final static String PROXIMITY_ALARM_ACTION = "com.cyberblue.iitag.proximityalarm";
private ProximityAlarmRecevier pReceiver;
//延迟报警
public void proximityAlarm(int second,Context context){
Log.i(TAG,"Enter proximityAlarm second=" + second);

if(pReceiver == null){
pReceiver = new ProximityAlarmRecevier();
registerReceiver(pReceiver, new IntentFilter(PROXIMITY_ALARM_ACTION));
}

Timer time = new Timer();
ProximityAlarmTimerTask task = new ProximityAlarmTimerTask(context);
//dalay/1000秒后执行task.只执行一次
time.schedule(task, second*1000);
}

public class ProximityAlarmTimerTask extends TimerTask {
private Context context;
public ProximityAlarmTimerTask(Context mcontext){
context = mcontext;
}
public void run(){
Log.i(TAG,"Enter ProximityAlarmTimerTask");
if(mLeState == CONNECTED){
return ;
}else{
Intent intent = new Intent(PROXIMITY_ALARM_ACTION);
sendBroadcast(intent);
}
}
}

public class ProximityAlarmRecevier extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"Enter ProximityAlarmRecevier");
pHandler.sendEmptyMessage(0);
}
}

//处理重连
Handler pHandler = new Handler() {
public void handleMessage(Message msg) {
Log.i(TAG,"Enter pHandler");
switch (msg.what) {
case 0:
//停止上一次的音乐
stopMusic();
//停止振动
cancelVibrator();
//点亮屏幕
final PowerManager.WakeLock wl = wekelock();
vibrator();
playMusic();
//只保留最后一个报警窗口
if(view != null){
wm.removeView(view);
}
view = inflater.inflate(R.layout.proximity_result, null);
wm.addView(view, wmParams);
Button proximitytagBtn = (Button) view.findViewById(R.id.proximitytagBtn);
proximitytagBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//移除WindowManager
wm.removeView(view);
view = null;
//停止音乐
stopMusic();
//停止振动
cancelVibrator();
if(wl != null && wl.isHeld()){
wl.release();
}
}
});
closeWakeLock(120,wl);

break;
}
super.handleMessage(msg);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: