栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Android AsyncTask示例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android AsyncTask示例

好的,您正在尝试通过另一个线程访问GUI。基本上,这不是一个好习惯。

AsyncTask
doInBackground()
另一个线程内部执行所有操作,该线程无法访问您的视图所在的GUI。

preExecute()
postExecute()
在此新线程发生繁重之前和之后为您提供访问GUI的权限,甚至可以将long操作的结果传递给
postExecute()
,然后显示任何处理结果。

请在以后更新TextView的地方查看这些行:

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

把它们放进去

onPostExecute()

doInBackground
完成后,您将看到更新的TextView文本。

我注意到您的onClick侦听器不会检查是否已选择哪个视图。我发现最简单的方法是通过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        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/365566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号