简体   繁体   English

即使在使用工作线程时,Android也可以在UI线程上运行

[英]Android running on UI thread even when using worker thread

I am using a worker thread, as described here but still the code is blocking the UI. 我使用的是工作线程,如此处所述但代码仍然阻止UI。 If I sleep at the beginning of the run() method, it doesn't block the UI. 如果我在run()方法的开头睡觉,它不会阻塞UI。 The thing is, it's a heavy code that runs from the onCreate method, but no matter what I do, I can't make it not block the UI. 事实是,这是一个繁重的代码,它从onCreate方法运行,但是无论我做什么,我都不能使它不阻塞UI。 What am I doing wrong? 我究竟做错了什么?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                Log.d("asdf", "asdf");
            }
        }
    }).start();
}

You are not using an AsyncTask - which is the control Android uses to do long running processes off the UI thread. 您没有使用AsyncTask-Android用来在UI线程之外执行长时间运行的进程的控件。

Bottom line, use this and you will have much more success. 最重要的是,使用它,您将获得更大的成功。

AsyncTask Android example Android AsyncTask示例

Use Handler to or .runOnUiThread(runnable) to call your UI thread. 使用Handler.runOnUiThread(runnable)来调用您的UI线程。 You can execute your thread without the Runnable as well, like this: 您也可以在没有Runnable的情况下执行线程,如下所示:

new Thread(){
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                Log.d("asdf", "asdf");
            }
        }
    }).start();

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

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