Android AsyncTasks 并行执行
在进入示例之前,我们应该知道什么是 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 和一个 Button,当用户点击按钮时,它将从不同的互联网源下载两个图像并附加到 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://tutorialspoint.com/cprogramming/images/logo.png"); asyncTask = new AsyncTaskExample(); asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://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 { } } } }
在上面的代码中,我们使用 executeOnExecutor() 来运行两个或多个 AsyncTask。Android 最多支持五个 AsyncTask 并行运行。
步骤 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 运行 图标 从工具栏中。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -
当用户点击按钮时,它将使用进度条从互联网源下载图像,如下所示 -
它将并行下载两张图片并显示如下 -
点击 这里 下载项目代码
广告