【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
今天在犯了一个愚蠢的错误,TimerTask中更新UI界面了,难怪半天没反应。
在网上搜了一篇Timer更新UI的帖子转过来。
错误写法:
- package com.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class TestTimer_Wrong extends Activity {
- Timer timer = new Timer();
- TimerTask task = new TimerTask(){
- public void run() {
- setTitle("hear me?");
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
TimerTask 里面直接做UI更新,没有在UIThread里面。与Java的EDT线程,是同一概念。
正确写法一 : 交由UI Thread处理
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class TestTimer extends Activity {
- Timer timer = new Timer();
- TimerTask task = new TimerTask(){
- public void run() {
- runOnUiThread(new Runnable(){
- @Override
- public void run() {
- setTitle("hear me?");
- }});
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
正确写法二 :由Handler处理UI 更新。
- package com.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- public class TestTimer extends Activity {
- Timer timer = new Timer();
- Handler handler = new Handler(){
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- setTitle("hear me?");
- break;
- }
- super.handleMessage(msg);
- }
- };
- TimerTask task = new TimerTask(){
- public void run() {
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
来源:oschina
链接:https://my.oschina.net/u/1463230/blog/278780