线程实现数字递减问题!!
我要在AlertDialog上面的TextView数字每秒递减一,但是每隔几秒减4,可能是线程原因但找到原因,求大神指导。。下面是我的代码
public class MainActivity extends Activity {
TextView tv = null;
int i = 60;
UIUpdateThread ui = null;
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what < 0) {
aDialog.dismiss();
timer.cancel();
}
}
};
AlertDialog aDialog = null;
Timer timer = new Timer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater mInflater = (LayoutInflater) MainActivity.this
.getSystemService(LAYOUT_INFLATER_SERVICE);
ui = new UIUpdateThread();
View view = mInflater.inflate(R.layout.activity_main, null);
RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.back);
tv = new TextView(getApplicationContext());
layout.addView(tv);
aDialog = new AlertDialog.Builder(MainActivity.this).setMessage("")
.create();
aDialog.setTitle("时间倒计时:");
aDialog.setView(view);
new Thread(new UIUpdateThread()).start();
aDialog.show();
timer.schedule(new TimerTask() {
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.what = i;
msg.obj = ui;
handler.sendEmptyMessage(msg.what);
handler.post(ui);
i = i - 1;
}
}, 1000, 1000);
}
class UIUpdateThread implements Runnable {
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
concreteUpdateUI();
tv.invalidate();
}
};
public void run() {
// delay some minutes you desire.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(mUpdateResults);
}
}
protected void concreteUpdateUI() {
// Add concrete movement for UI updates.
i--;
tv.setText(String.valueOf(i));
}