java - AsyncTask 不是异步的吗?

标签 java android user-interface android-asynctask

不知何故,在 AsyncTask 完成之前我无法使用 GUI。我没有意识到在“onCreate”或“onCreateOptionsMenu”方法中发布execute()有什么区别。 你知道出了什么问题吗? 感谢您的帮助。

package com.test11;

import java.util.concurrent.ExecutionException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class TestActitivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_actitivity);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_test_actitivity, menu);

        try
        {
            int t = new TestTask().execute().get();
        }

        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        return true;
    }

    class TestTask extends AsyncTask<Void, Void, Integer>
    {
        public Integer doInBackground(Void...voids)
        {
            try
            {
                Thread.sleep(10000);
            }

            catch(Exception e)
            {
                e.printStackTrace();
            }

            return 1;
        }
    }
}

最佳答案

您可以这样执行任务:

new TestTask().execute().get();

你在这里具体做什么?您创建一个新的任务实例。然后你运行它。然后您在任务上调用 get(),即 waits until the computation of this task is completed返回它的值。这意味着 onCreate()onCreateOptionsMenu() 将被阻塞,直到第二个线程完成。如果您删除 get(),您的任务将不会阻塞 UI。

如果您想使用结果,您应该覆盖 onPostExecute()在您的 AsyncTask 中,而不是使用 get()onPostExecute() 在 UI 线程中运行,允许您使用结果轻松操作 UI。例如,如果您想在 TextView 中显示结果,您可以使用如下实现:

@Override
public void onPostExecute(Integer result) {
    TextView tv = (TextView) findViewById(R.id.sampletext);
    tv.setText("Result was " + result);
}

关于java - AsyncTask 不是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11428585/

相关文章:

android - 管理 fragment 到 fragment 的导航

java - Java中如何避免类和包之间的名称冲突?

java - 奇怪的 'out' 变量,System.out.println()

android - Jetpack 撰写弹出菜单

python - Python TUI 后端有哪些选项?

javascript - 以编程方式更改 EditorGrid 的单元格值

java - 'for' 和 'switch' 之间有冲突吗?

java - 覆盖默认接口(interface)方法

android - 什么情况下需要在realm中使用gson反序列化?

java - 为什么我从 Firebase 得到 NULL 结果