我读了大约AsyncTask篇文章,我try 了下面的简单程序.但它似乎不起作用.我该怎么做?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

我只是想在后台处理5秒钟后更改标签.

这是我的main.xml分:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

推荐答案

好的,您正在try 通过另一个线程访问GUI.这基本上不是好的做法.

AsyncTask在另一个线程中执行doInBackground()中的所有操作,该线程无权访问视图所在的GUI.

preExecute()postExecute()允许您在这个新线程中进行繁重的提升之前和之后访问GUI,您甚至可以将长操作的结果传递给postExecute(),然后显示任何处理结果.

查看以下几行,稍后更新TextView:

TextView txt = findViewById(R.id.output);
txt.setText("Executed");

把他们放进onPostExecute()号房.

然后,您将看到文本视图文本在doInBackground完成后更新.

我注意到你的onClick监听器没有判断 Select 了哪个视图.我发现最简单的方法是通过switch语句.我有一个完整的课堂,下面是所有的建议,以避免混淆.

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;
    AsyncTask<?, ?, ?> runningTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = findViewById(R.id.button1);

        // Because we implement OnClickListener, we only
        // have to pass "this" (much easier)
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // Detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            if (runningTask != null)
                runningTask.cancel(true);
            runningTask = new LongOperation();
            runningTask.execute();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Cancel running task(s) to avoid memory leaks
        if (runningTask != null)
            runningTask.cancel(true);
    }

    private final class LongOperation extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // We were cancelled; stop sleeping!
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // You might want to change "executed" for the returned string
            // passed into onPostExecute(), but that is up to you
        }
    }
}

Android相关问答推荐

Android Kotlin DSL Gradle找不到自定义存储库中的依赖项

如何处理穿戴构图上的长点击事件?

Jetpack Compose-如何使用值动画直接控制其他动画

如何在Android Studio中将我的Java-库&库设置为Kotlin库

无法将Kotlin序列化添加到Android项目

Android App Google AdMob";广告加载失败:3;带有测试ID,&q;广告加载失败:1 for My Gahad

OverridePendingTransition已弃用,我该怎么办?

在Jetpack Compose中实现焦点突出的最佳方式?

如何防止在Android Studio中设置kotlin断点时优化变量

Android v31 及更低版本中 ImageView 中的圆角

ComposeView 抢走了 AndroidTV 内容的焦点

来自位图的 WearOS 图标不显示 colored颜色

如何将一个 Composable 作为其参数传递给另一个 Composable 并在 Jetpack Compose 中显示/运行它

PayUCheckoutPro Android SDK 实现问题

Android Transitions API - 在 24-48 小时后停止接收任何更新

喷气背包组成影子奇怪的行为

重命名列失败的房间自动迁移(NOT NULL 约束失败,生成错误的迁移类)

在 jetpack compose 中使用 viewmodel 的最佳实践

Firebase Crashlytics 缩小 R8 Android

如何让用户与任意应用程序共享文件?