简体   繁体   English

从其他线程更新UI

[英]Updating UI from different thread

Can anyone explain when I put the thread to sleep for 30 milliseconds it updates the UI from the background thread. 任何人都可以解释一下,当我使线程休眠30毫秒时,它将从后台线程更新UI。 but when I put the sleep for 300 milliseconds it crashes saying that you cannot touch view from another thread. 但是当我将睡眠时间设置为300毫秒时,它崩溃了,提示您无法触摸其他线程的视图。 I expect it to crash in both cases but somehow it is working in 30 milliseconds. 我预计它在两种情况下都会崩溃,但是某种程度上它会在30毫秒内工作。 Needs some clarification on this issue. 需要对此问题进行一些澄清。

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;
    }
}
runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // do what you want
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM