如何利用AsyncTask在安卓中高效实现异步任务?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1848个文字,预计阅读时间需要8分钟。
在Android中实现异步任务(2)——使用AsyncTask、问题背景及实现方式概述
Android开发中,异步任务处理是常见的需求,以避免UI界面在耗时操作时出现卡顿。本文将介绍使用AsyncTask实现异步任务,并简要概述其他几种实现异步任务的方法。
AsyncTask是一种轻量级的后台线程处理工具,允许在后台线程中执行耗时操作,并在操作完成后更新UI。以下是使用AsyncTask实现异步任务的步骤:
1. 创建一个继承自AsyncTask的类,重写doInBackground()和onPostExecute()方法。
2.在主线程中,创建AsyncTask的实例,并调用execute()方法启动异步任务。
问题背景:
- 异步任务处理是Android开发中的常见需求,如网络请求、文件读写等。- 如果在主线程中直接执行耗时操作,会导致应用界面卡顿,影响用户体验。实现方式概述:
1.使用AsyncTask:
- 异步任务在后台线程执行,不会阻塞主线程。 - 通过回调机制,可以在操作完成后更新UI。2. 使用Handler和Looper: - 通过Handler将任务提交到主线程的消息队列。 - 在主线程的消息队列中执行任务。
3. 使用线程池(ThreadPoolExecutor): - 创建一个线程池,提交任务到线程池执行。 - 线程池可以复用线程,提高效率。
4. 使用RxJava: - 使用RxJava的异步编程模型,实现复杂的异步任务。 - 支持链式调用,代码简洁。
本文简要介绍了使用AsyncTask实现异步任务的方法,以及其他几种常见的异步任务实现方式。后续文章将详细介绍每种方法的具体实现和优缺点。
安卓中实现异步任务(2)——使用AsyncTask实现
问题背景
上次的文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于asyncTask实现,持续更新。
实现demo
(1)实现我们的AsyncTask子类
import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class MyAsyncTask extends AsyncTask<Integer,Integer,Integer> { private final String TAG = "AsyncTask"; private TextView textView; private ProgressBar progressBar; private Context context; public MyAsyncTask(TextView textView, ProgressBar progressBar, Context context) { this.textView = textView; this.progressBar = progressBar; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG,"onPreExecute(): " + Thread.currentThread().getName()); } @Override protected Integer doInBackground(Integer... ints) { Integer count = ints[0]; while (count < 10 && !isCancelled()){ // isCancelled()表示判断当前任务是否被取消,防止在取消异步任务的时候循环不能及时停下 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.d(TAG,"doInBackground(): "+ Thread.currentThread().getName() +" "+count); publishProgress(count); } return count; } @Override protected void onPostExecute(Integer i) { Log.d(TAG,"onPostExecute(): "+ Thread.currentThread().getName()); textView.setText(i + ""); } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG,"onProgressUpdate(): " + Thread.currentThread().getName()); textView.setText(values[0]+""); progressBar.setProgress(values[0]); } @Override protected void onCancelled() { Log.d(TAG,"nCancelled(): "+Thread.currentThread().getName()); super.onCancelled(); Toast.makeText(context,"任务取消成功", Toast.LENGTH_LONG).show(); } }(2)新建我们的activity,对应layout布局如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".thread.AsyncTaskActivity"> <TextView android:id="@+id/textView" android:hint="0" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:id="@+id/progressBar" android:progress="0" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:text="启动任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:onClick="doTaskClick" /> <Button android:text="取消任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:onClick="cancelTaskClick" /> </RelativeLayout> </LinearLayout>(3)对应我们activity的代码如下:
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskActivity extends AppCompatActivity { private TextView textView; private ProgressBar progressBar; private MyAsyncTask myAsyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_task); textView= findViewById(R.id.textView); progressBar= findViewById(R.id.progressBar); } public void doTaskClick(View view){ myAsyncTask = new MyAsyncTask(textView, progressBar,this); // 执行异步任务,传入初始参数 myAsyncTask.execute(1); } public void cancelTaskClick(View view){ // 取消异步任务 myAsyncTask.cancel(true); } }执行结果如下:
安卓中实现异步任务(2)——使用AsyncTask实现
问题背景
上篇文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于asyncTask实现,持续更新。
实现demo
import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class MyAsyncTask extends AsyncTask<Integer,Integer,Integer> { private final String TAG = "AsyncTask"; private TextView textView; private ProgressBar progressBar; private Context context; public MyAsyncTask(TextView textView, ProgressBar progressBar, Context context) { this.textView = textView; this.progressBar = progressBar; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG,"onPreExecute(): " + Thread.currentThread().getName()); } @Override protected Integer doInBackground(Integer... ints) { Integer count = ints[0]; while (count < 10 && !isCancelled()){ // isCancelled()表示判断当前任务是否被取消,防止在取消异步任务的时候循环不能及时停下 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.d(TAG,"doInBackground(): "+ Thread.currentThread().getName() +" "+count); publishProgress(count); } return count; } @Override protected void onPostExecute(Integer i) { Log.d(TAG,"onPostExecute(): "+ Thread.currentThread().getName()); textView.setText(i + ""); } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG,"onProgressUpdate(): " + Thread.currentThread().getName()); textView.setText(values[0]+""); progressBar.setProgress(values[0]); } @Override protected void onCancelled() { Log.d(TAG,"nCancelled(): "+Thread.currentThread().getName()); super.onCancelled(); Toast.makeText(context,"任务取消成功", Toast.LENGTH_LONG).show(); } } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".thread.AsyncTaskActivity"> <TextView android:id="@+id/textView" android:hint="0" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:id="@+id/progressBar" android:progress="0" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:text="启动任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:onClick="doTaskClick" /> <Button android:text="取消任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:onClick="cancelTaskClick" /> </RelativeLayout> </LinearLayout> import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskActivity extends AppCompatActivity { private TextView textView; private ProgressBar progressBar; private MyAsyncTask myAsyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_task); textView= findViewById(R.id.textView); progressBar= findViewById(R.id.progressBar); } public void doTaskClick(View view){ myAsyncTask = new MyAsyncTask(textView, progressBar,this); // 执行异步任务,传入初始参数 myAsyncTask.execute(1); } public void cancelTaskClick(View view){ // 取消异步任务 myAsyncTask.cancel(true); } }执行结果如下:
根据log,我们可以很清楚的看到asyncTask对应各方法所在的线程以及执行时机;
关键代码分析
持续更新。。。
本文共计1848个文字,预计阅读时间需要8分钟。
在Android中实现异步任务(2)——使用AsyncTask、问题背景及实现方式概述
Android开发中,异步任务处理是常见的需求,以避免UI界面在耗时操作时出现卡顿。本文将介绍使用AsyncTask实现异步任务,并简要概述其他几种实现异步任务的方法。
AsyncTask是一种轻量级的后台线程处理工具,允许在后台线程中执行耗时操作,并在操作完成后更新UI。以下是使用AsyncTask实现异步任务的步骤:
1. 创建一个继承自AsyncTask的类,重写doInBackground()和onPostExecute()方法。
2.在主线程中,创建AsyncTask的实例,并调用execute()方法启动异步任务。
问题背景:
- 异步任务处理是Android开发中的常见需求,如网络请求、文件读写等。- 如果在主线程中直接执行耗时操作,会导致应用界面卡顿,影响用户体验。实现方式概述:
1.使用AsyncTask:
- 异步任务在后台线程执行,不会阻塞主线程。 - 通过回调机制,可以在操作完成后更新UI。2. 使用Handler和Looper: - 通过Handler将任务提交到主线程的消息队列。 - 在主线程的消息队列中执行任务。
3. 使用线程池(ThreadPoolExecutor): - 创建一个线程池,提交任务到线程池执行。 - 线程池可以复用线程,提高效率。
4. 使用RxJava: - 使用RxJava的异步编程模型,实现复杂的异步任务。 - 支持链式调用,代码简洁。
本文简要介绍了使用AsyncTask实现异步任务的方法,以及其他几种常见的异步任务实现方式。后续文章将详细介绍每种方法的具体实现和优缺点。
安卓中实现异步任务(2)——使用AsyncTask实现
问题背景
上次的文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于asyncTask实现,持续更新。
实现demo
(1)实现我们的AsyncTask子类
import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class MyAsyncTask extends AsyncTask<Integer,Integer,Integer> { private final String TAG = "AsyncTask"; private TextView textView; private ProgressBar progressBar; private Context context; public MyAsyncTask(TextView textView, ProgressBar progressBar, Context context) { this.textView = textView; this.progressBar = progressBar; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG,"onPreExecute(): " + Thread.currentThread().getName()); } @Override protected Integer doInBackground(Integer... ints) { Integer count = ints[0]; while (count < 10 && !isCancelled()){ // isCancelled()表示判断当前任务是否被取消,防止在取消异步任务的时候循环不能及时停下 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.d(TAG,"doInBackground(): "+ Thread.currentThread().getName() +" "+count); publishProgress(count); } return count; } @Override protected void onPostExecute(Integer i) { Log.d(TAG,"onPostExecute(): "+ Thread.currentThread().getName()); textView.setText(i + ""); } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG,"onProgressUpdate(): " + Thread.currentThread().getName()); textView.setText(values[0]+""); progressBar.setProgress(values[0]); } @Override protected void onCancelled() { Log.d(TAG,"nCancelled(): "+Thread.currentThread().getName()); super.onCancelled(); Toast.makeText(context,"任务取消成功", Toast.LENGTH_LONG).show(); } }(2)新建我们的activity,对应layout布局如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".thread.AsyncTaskActivity"> <TextView android:id="@+id/textView" android:hint="0" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:id="@+id/progressBar" android:progress="0" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:text="启动任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:onClick="doTaskClick" /> <Button android:text="取消任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:onClick="cancelTaskClick" /> </RelativeLayout> </LinearLayout>(3)对应我们activity的代码如下:
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskActivity extends AppCompatActivity { private TextView textView; private ProgressBar progressBar; private MyAsyncTask myAsyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_task); textView= findViewById(R.id.textView); progressBar= findViewById(R.id.progressBar); } public void doTaskClick(View view){ myAsyncTask = new MyAsyncTask(textView, progressBar,this); // 执行异步任务,传入初始参数 myAsyncTask.execute(1); } public void cancelTaskClick(View view){ // 取消异步任务 myAsyncTask.cancel(true); } }执行结果如下:
安卓中实现异步任务(2)——使用AsyncTask实现
问题背景
上篇文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于asyncTask实现,持续更新。
实现demo
import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class MyAsyncTask extends AsyncTask<Integer,Integer,Integer> { private final String TAG = "AsyncTask"; private TextView textView; private ProgressBar progressBar; private Context context; public MyAsyncTask(TextView textView, ProgressBar progressBar, Context context) { this.textView = textView; this.progressBar = progressBar; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG,"onPreExecute(): " + Thread.currentThread().getName()); } @Override protected Integer doInBackground(Integer... ints) { Integer count = ints[0]; while (count < 10 && !isCancelled()){ // isCancelled()表示判断当前任务是否被取消,防止在取消异步任务的时候循环不能及时停下 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.d(TAG,"doInBackground(): "+ Thread.currentThread().getName() +" "+count); publishProgress(count); } return count; } @Override protected void onPostExecute(Integer i) { Log.d(TAG,"onPostExecute(): "+ Thread.currentThread().getName()); textView.setText(i + ""); } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG,"onProgressUpdate(): " + Thread.currentThread().getName()); textView.setText(values[0]+""); progressBar.setProgress(values[0]); } @Override protected void onCancelled() { Log.d(TAG,"nCancelled(): "+Thread.currentThread().getName()); super.onCancelled(); Toast.makeText(context,"任务取消成功", Toast.LENGTH_LONG).show(); } } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".thread.AsyncTaskActivity"> <TextView android:id="@+id/textView" android:hint="0" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:id="@+id/progressBar" android:progress="0" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:text="启动任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:onClick="doTaskClick" /> <Button android:text="取消任务" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:onClick="cancelTaskClick" /> </RelativeLayout> </LinearLayout> import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskActivity extends AppCompatActivity { private TextView textView; private ProgressBar progressBar; private MyAsyncTask myAsyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_task); textView= findViewById(R.id.textView); progressBar= findViewById(R.id.progressBar); } public void doTaskClick(View view){ myAsyncTask = new MyAsyncTask(textView, progressBar,this); // 执行异步任务,传入初始参数 myAsyncTask.execute(1); } public void cancelTaskClick(View view){ // 取消异步任务 myAsyncTask.cancel(true); } }执行结果如下:
根据log,我们可以很清楚的看到asyncTask对应各方法所在的线程以及执行时机;
关键代码分析
持续更新。。。

