Android AsyncTask 示例與講解


Android AsyncTask 用於在後臺執行緒執行後臺操作並在主執行緒更新UI。在 Android 開發中,我們不能直接從後臺執行緒訪問主執行緒。AsyncTask 幫助我們在後臺執行緒和主執行緒之間進行通訊。

AsyncTask 的方法

  • onPreExecute() − 在執行後臺操作之前,我們應該在螢幕上顯示一些內容,例如進度條或動畫。我們可以直接使用 doInBackground() 方法進行後臺操作,但最佳實踐是呼叫所有 AsyncTask 方法。

  • doInBackground(Params) − 在此方法中,我們必須在後臺執行緒執行後臺操作。此方法中的操作不應訪問任何主執行緒活動或片段。

  • onProgressUpdate(Progress…) − 在執行後臺操作時,如果要更新UI上的某些資訊,可以使用此方法。

  • onPostExecute(Result) − 在此方法中,我們可以更新後臺操作結果的UI。

AsyncTask 中的泛型

  • TypeOfVarArgParams − 它包含有關用於執行的引數型別的資訊。

  • ProgressValue − 它包含有關進度單元的資訊。在執行後臺操作時,我們可以使用 onProgressUpdate() 方法更新UI上的資訊。

  • ResultValue − 它包含有關結果型別的資訊。

此示例演示如何在 Android 中使用 AsyncTask。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,然後填寫所有必需的詳細資訊以建立一個新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:id = "@+id/rootview"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   android:background = "#c1c1c1"
   android:gravity = "center_horizontal"
   tools:context = ".MainActivity">
<Button
   android:id = "@+id/asyncTask"
   android:text = "Download"
   android:layout_width = "wrap_content"
   android:layout_height = "wrap_content" />
<ImageView
   android:id = "@+id/image"
   android:layout_width = "300dp"
   android:layout_height = "300dp" />
</LinearLayout>

在上面的 xml 中,我們建立了一個按鈕,當用戶單擊該按鈕時,它將下載影像並將影像新增到 ImageView。

步驟 3 − 將以下程式碼新增到 src/MainActivity.java

package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
   URL ImageUrl = null;
   InputStream is = null;
   Bitmap bmImg = null;
   ImageView imageView= null;
   ProgressDialog p;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button button=findViewById(R.id.asyncTask);
      imageView=findViewById(R.id.image);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            AsyncTaskExample asyncTask=new AsyncTaskExample();
            asyncTask.execute("https://tutorialspoint.tw/images/tp-logo-diamond.png");
         }
      });
   }
   private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();
         p = new ProgressDialog(MainActivity.this);
         p.setMessage("Please wait...It is downloading");
         p.setIndeterminate(false);
         p.setCancelable(false);
         p.show();
      }
      @Override
      protected Bitmap doInBackground(String... strings) {
         try {
            ImageUrl = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);
         } catch (IOException e) {
            e.printStackTrace();
         }
         return bmImg;
      }
      @Override
      protected void onPostExecute(Bitmap bitmap) {
         super.onPostExecute(bitmap);
         if(imageView!=null) {
            p.hide();
            imageView.setImageBitmap(bitmap);
         }else {
            p.show();
         }
      }
   }
}

在上面的程式碼中,我們使用 AsyncTask 下載影像並將影像新增到 ImageView。

步驟 4 − 將以下程式碼新增到 AndroidManifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

在上面的 AndroidManifest.xml 檔案中,我們添加了 internet 許可權以訪問網際網路以下載影像。

讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行 Eclipse 執行圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。

Download

現在單擊下載按鈕,它將在 UI 上顯示進度並在後臺下載影像,如下所示

Downloading In Progress

下載影像後,它將在 UI 上更新,如下所示

Downloaded

點選這裡下載專案程式碼

更新於:2020年6月25日

13K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.