安卓 AsyncTask 示例教程

今天,我们将研究Android AsyncTask。我们将开发一个在后台执行抽象AsyncTask的Android示例应用程序。

Android AsyncTask

Android AsyncTask是Android提供的一个抽象类,它允许我们自由地在后台执行繁重的任务,并使UI线程保持轻量级,从而使应用程序更具响应性。启动时,Android应用程序在单线程上运行。由于这种单线程模型,获取响应所需的时间较长的任务可能会使应用程序无响应。为了避免这种情况,我们使用Android AsyncTask在后台的专用线程上执行繁重的任务,并将结果传递回UI线程。因此,在Android应用程序中使用AsyncTask使UI线程始终保持响应。Android AsyncTask类中使用的基本方法定义如下:

  • doInBackround() :该方法包含需要在后台执行的代码。在此方法中,我们可以通过PublishProgress()方法将结果多次发送到UI线程。要通知后台处理已经完成,我们只需使用Return语句
  • onPreExecute() :该方法包含后台处理开始前执行的代码
  • onPostExecute() :在doInBackround方法完成处理后调用该方法。来自doInBackround的结果被传递给此方法
  • onProgressUpdate() :该方法接收doInBackround方法的进度更新,该方法通过PublishProgress方法发布,该方法可以使用该进度更新来更新UI线程

在android AsyncTask类中使用的三种泛型类型如下所示:

  • parms :执行时发送给任务的参数类型
  • 进度 :后台计算时发布的进度单位类型
  • 结果 :后台计算结果类型

Android异步任务示例

若要启动AsyncTask,MainActivity类中必须存在以下代码段:

1MyTask myTask = new MyTask();
2myTask.execute();

在上面的代码片段中,我们使用了扩展AsyncTask的示例类名,并使用Execute方法启动后台线程。注:

  • 必须在UI线程中创建和调用AsyncTask实例。
  • 永远不应调用在AsyncTask类中被覆盖的方法。它们是自动调用的
  • AsyncTask只能调用一次。再次执行它将引发异常

在本教程中,我们将实现一个AsyncTask,它使进程在用户设置的给定时间段内进入睡眠状态。

Android异步任务项目结构

安卓异步任务,安卓异步任务example

Android AsyncTask示例代码

XML布局在active_main.xml中定义,其给定如下:active_main.xml

 1<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 2    xmlns:tools="https://schemas.android.com/tools"
 3    android:layout_width="match_parent"
 4    android:layout_height="match_parent"
 5    tools:context=".MainActivity" >
 6
 7    <TextView
 8        android:id="@+id/tv_time"
 9        android:layout_width="wrap_content"
10        android:layout_height="wrap_content"
11        android:textSize="10pt"
12        android:textColor="#444444"
13        android:layout_alignParentLeft="true"
14        android:layout_marginRight="9dip"
15        android:layout_marginTop="20dip"
16        android:layout_marginLeft="10dip"
17        android:text="Sleep time in Seconds:"/>
18    <EditText
19        android:id="@+id/in_time"
20        android:layout_width="150dip"
21        android:layout_height="wrap_content"
22        android:background="@android:drawable/editbox_background"
23        android:layout_toRightOf="@id/tv_time"
24        android:layout_alignTop="@id/tv_time"
25        android:inputType="number"
26        />
27    <Button
28        android:id="@+id/btn_run"
29        android:layout_width="wrap_content"
30        android:layout_height="wrap_content"
31        android:text="Run Async task"
32        android:layout_below="@+id/in_time"
33        android:layout_centerHorizontal="true"
34        android:layout_marginTop="64dp" />
35    <TextView
36        android:id="@+id/tv_result"
37        android:layout_width="wrap_content"
38        android:layout_height="wrap_content"
39        android:textSize="7pt"
40        android:layout_below="@+id/btn_run"
41        android:layout_centerHorizontal="true" />
42</RelativeLayout>

在上面的布局中,我们使用一个预定义的可绘制对象作为EditText的边框。MainActivity.java的定义如下:

 1package com.journaldev.asynctask;
 2
 3import android.app.ProgressDialog;
 4import android.os.AsyncTask;
 5import android.os.Bundle;
 6import android.support.v7.app.AppCompatActivity;
 7import android.view.View;
 8import android.widget.Button;
 9import android.widget.EditText;
10import android.widget.TextView;
11
12public class MainActivity extends AppCompatActivity {
13    private Button button;
14    private EditText time;
15    private TextView finalResult;
16
17    @Override
18    protected void onCreate(Bundle savedInstanceState) {
19        super.onCreate(savedInstanceState);
20        setContentView(R.layout.activity_main);
21        time = (EditText) findViewById(R.id.in_time);
22        button = (Button) findViewById(R.id.btn_run);
23        finalResult = (TextView) findViewById(R.id.tv_result);
24        button.setOnClickListener(new View.OnClickListener() {
25            @Override
26            public void onClick(View v) {
27                AsyncTaskRunner runner = new AsyncTaskRunner();
28                String sleepTime = time.getText().toString();
29                runner.execute(sleepTime);
30            }
31        });
32    }
33
34    private class AsyncTaskRunner extends AsyncTask<String, String, String> {
35
36        private String resp;
37        ProgressDialog progressDialog;
38
39        @Override
40        protected String doInBackground(String... params) {
41            publishProgress("Sleeping..."); // Calls onProgressUpdate()
42            try {
43                int time = Integer.parseInt(params[0])*1000;
44
45                Thread.sleep(time);
46                resp = "Slept for " + params[0] + " seconds";
47            } catch (InterruptedException e) {
48                e.printStackTrace();
49                resp = e.getMessage();
50            } catch (Exception e) {
51                e.printStackTrace();
52                resp = e.getMessage();
53            }
54            return resp;
55        }
56
57        @Override
58        protected void onPostExecute(String result) {
59            // execution of result of Long time consuming operation
60            progressDialog.dismiss();
61            finalResult.setText(result);
62        }
63
64        @Override
65        protected void onPreExecute() {
66            progressDialog = ProgressDialog.show(MainActivity.this,
67                    "ProgressDialog",
68                    "Wait for "+time.getText().toString()+ " seconds");
69        }
70
71        @Override
72        protected void onProgressUpdate(String... text) {
73            finalResult.setText(text[0]);
74
75        }
76    }
77}

在上面的代码中,我们使用AsyncTaskRunner类来执行AsyncTask操作。以秒为单位的时间将作为参数传递给类,并在给定的时间量内显示ProgressDialog。下面给出的图像是由用户设置的时间为5秒的项目产生的输出。Android异步任务示例,AsyncTask这将结束本教程。你可以从下面的链接下载最终的Android AsyncTask项目。

下载Android异步任务示例Project

Published At
Categories with 技术
Tagged with
comments powered by Disqus