从不同的线程更新UI

时间:2015-12-10 11:02:40

标签: java android multithreading

任何人都可以解释当我让线程休眠30毫秒时它会从后台线程更新UI。但是当我把睡眠放置300毫秒时,它会崩溃,说你不能从另一个线程触摸视图。我希望它在两种情况下崩溃但不知何故它在30毫秒内工作。需要对这个问题做一些澄清。

public class HandlerDemo extends Activity implements Handler.Callback{

private static final String TAG = "FFFF";
private Handler mHandler = null;
private Handler mUIHandler = null;
private HandlerThread backgroundThread = null;

public static final int BACKGROUND_OPERATION = 10;
public static final int MAIN_THREAD_OPERATION = 20;

private TextView asd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    HandlerThread backgroundThread = new HandlerThread("BACKGROUND_THREAD");
    backgroundThread.start();
    mHandler = new Handler(backgroundThread.getLooper(), this);
    mHandler.sendEmptyMessage(BACKGROUND_OPERATION);

    //        mUIHandler = new Handler(Looper.getMainLooper(), this);
    //        mUIHandler.sendEmptyMessage(MAIN_THREAD_OPERATION);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mHandler.getLooper().quit();
}

@Override
public boolean handleMessage(Message message) {
    Log.d(TAG, Thread.currentThread() + "");
    switch (message.what) {
        case MAIN_THREAD_OPERATION:
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ((TextView) findViewById(R.id.textview)).setText("Updating from UI Handler");
            findViewById(R.id.textview).invalidate();
            break;
        case BACKGROUND_OPERATION:
            try {
                **Thread.sleep(300);**
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ((TextView) findViewById(R.id.textview)).setText("Updating from background Handler");
            findViewById(R.id.textview).invalidate();
            break;
        default:
            break;
    }

    //        message.recycle();
    return true;
    }
}

1 个答案:

答案 0 :(得分:-2)

runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // do what you want
        }
    });