Android AsyncTasks 并行执行

androidmobile developmentapps/applications更新于 2026/2/2 5:07:17

在开始示例之前,我们应该了解什么是 asyncTask。AsyncTask 会在后台线程执行操作/动作,并在主线程进行更新。以下是 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" />
   <ImageView
      android:id = "@+id/image2"
      android:layout_width = "300dp"
      android:layout_height = "300dp" />
</LinearLayout>

在上面的代码中,我们声明了两个 ImageView 和一个按钮。当用户点击按钮时,它会从不同的网络来源下载两张图片并附加到 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;
   ImageView imageView2 = null;
   AsyncTaskExample asyncTask = null;
   AsyncTaskExample2 asyncTask2 = 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);
      imageView2 = findViewById(R.id.image2);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            asyncTask2 = new AsyncTaskExample2();
               asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://www.tutorialspoint.com/cprogramming/images/logo.png");
            asyncTask = new AsyncTaskExample();
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://www.tutorialspoint.com/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(true);
         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();
         }
      }
   }
   private class AsyncTaskExample2 extends AsyncTask<String, String, Bitmap> {
      @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 (imageView2 ! = null) {
            imageView2.setImageBitmap(bitmap);
         } else {
         }
      }
   }
}

在上面的代码中,我们指定了 excuteOnExcutor() 来运行两个或两个以上的异步任务。Android 最多支持五个异步任务并行运行。

步骤 4− 将以下代码添加到 manifest.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>

在上面的代码中,我们授予了从互联网来源下载图片的权限。

让我们尝试运行您的应用程序。假设您已将实际的 Android 移动设备连接到电脑。要从 Android Studio 运行该应用程序,请打开项目的某个活动文件,然后点击工具栏上的"运行 Eclipse 运行"图标。选择您的移动设备作为选项,然后检查您的移动设备是否显示您的默认屏幕 −

当用户点击按钮时,它将使用进度条从互联网源下载图像,如下所示 -

它将并行下载两张图片并显示如下 -

点击此处下载项目代码


相关文章