当前位置: 首页 > news >正文

无锡市政建设集团网站文创产品设计书籍

无锡市政建设集团网站,文创产品设计书籍,图文生成二维码免费,建设工程公司官网前言#xff1a; 在Android应用程序开发中#xff0c;异步操作是非常常见的需求。比如#xff0c;我们可能需要在后台线程中执行网络请求、数据库操作或者其他耗时的任务#xff0c;而不阻塞UI线程。为了实现这些异步操作#xff0c;Android提供了多种方式#xff0c;其…前言  在Android应用程序开发中异步操作是非常常见的需求。比如我们可能需要在后台线程中执行网络请求、数据库操作或者其他耗时的任务而不阻塞UI线程。为了实现这些异步操作Android提供了多种方式其中之一就是使用AsyncTask类。 1.什么是AsyncTask AsyncTask是一种轻量级的异步任务类它可以在线程池中执行后台任务然后把执行的进度和最终的结果传递给主线程并在主线程中更新UI。两个线程池Handler 2.介绍AsyncTask类的泛型参数和核心方法 AsyncTask是一个抽象的泛型类它提供了ParamsProgress和Result这三个泛型参数。 public abstract class AsyncTaskParams, Progress, Result 其中 Params表示参数的类型Progress表示后台任务的执行进度和类型Result表示后台任务的返回结果 AsyncTask类提供了四个核心方法按照执行顺序介绍 1️⃣onPreExecute():在主线程中执行用于准备工作。 2️⃣doInBackground(Params...params):在线程池中执行用于执行异步任务。在此方法中可以通过publishProgress方法来更新任务的进度publishProgress方法调用onProgressUpdate方法。 3️⃣onProgressUpdate(Progress...values):在主线程中执行当后台任务的执行进程发送变化时此方法会被调用。 4️⃣onPostExecute(Result result):在主线程中执行在异步任务执行之后此方法会被调用。 AsyncTask还提供了onCancelled()方法它同样在主线程中执行当异步任务被取消时onCancelled会被调用这个时候onPostExecute则不会被调用。 3.如何使用AsyncTask 使用AsyncTask的步骤 步骤一继承AsyncTask类并实现它的几个回调方法比如doInBackground()方法用来执行后台任务onPostExecute()方法用来更新UI。 步骤二在UI线程中创建AsyncTask的实例并调用execute()方法来启动异步操作。 示例 在Activity中创建一个子类来继承AsyncTask完成以下任务 1.展示ProgressDialog 2.发送网络请求 3.关闭ProgressDialog 代码如下 public class MainActivity extends AppCompatActivity {Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new AsyncTask_test().execute();} ​public static ProgressDialog dialog;public class AsyncTask_test extends AsyncTaskString,Integer,Long {Overrideprotected void onPreExecute() {dialogProgressDialog.show(MainActivity.this,, 努力加载中);} ​Overrideprotected Long doInBackground(String... strings) {OkHttpClient okHttpClient new OkHttpClient();Request requestnew Request.Builder().url(https://www.httpbin.org/get?a1b2).build();Response response null;try {response okHttpClient.newCall(request).execute();if(!response.isSuccessful()){Log.e(xxx,网络请求失败response);}String responsedataresponse.body().string();if(responsedata!null){Log.e(xxx,输出responsedata);}} catch (IOException e) {Log.e(xxx,报错e);throw new RuntimeException(e);} ​return null;} ​Overrideprotected void onPostExecute(Long aLong) {if(dialog!null){dialog.dismiss();}super.onPostExecute(aLong);}} } AsyncTask在使用时的注意事项 AsyncTask的对象必须在主线程中创建。原因AsyncTask的handler对象是静态的Handler对象要切换到主线程由于静态成员在类加载时就被初始化因此AsyncTask必须在主线程中加载 execute方法必须在UI线程调用。 不要在线程中直接调用onPreExecute()、onPostExecute、doInBackground和onProgressUpdate方法。 一个AsyncTask对象只能执行一次即只能调用一次execute方法否则会报运行时异常。 4.AsyncTask的工作原理 工作原理 ➡️当asyncTask执行execute()方法的时候会先调用onPreExecute()方法。 ➡️然后调用SERIAL_EXECUTOR的execute(mFuture)把任务加入到队列的尾部等待执行。 ➡️执行的时候调用THREAD_POOL_EXECUTOR的execute(mFuture)方法。 ➡️mFuture调用mWorker的call()方法在call()方法中调用了dolnBackground()方法并在最后调用了postResult()方法。 ➡️postResult()方法也就是通过Handler发送消息给主线程在主线程中调用AsyncTask的finish()方法来决定是调用onCancelled()还是onPostExecute()方法。 源码解析 MainThread public final AsyncTaskParams, Progress, Result execute(Params... params) {return executeOnExecutor(sDefaultExecutor, params); }MainThreadpublic final AsyncTaskParams, Progress, Result executeOnExecutor(Executor exec,Params... params) {if (mStatus ! Status.PENDING) {switch (mStatus) {case RUNNING:throw new IllegalStateException(Cannot execute task: the task is already running.);case FINISHED:throw new IllegalStateException(Cannot execute task: the task has already been executed (a task can be executed only once));}} ​mStatus Status.RUNNING; ​onPreExecute(); ​mWorker.mParams params;exec.execute(mFuture); ​return this;} 其中sDefaultExecutor是一个串行的线程池一个进程中所有的AsyncTask全部在这个串行的线程池中排队执行。在executeOnExecutor方法中AsyncTask的onPreExecute方法最先执行然后线程池开始执行下面是线程池的执行过程 public static final Executor SERIAL_EXECUTOR new SerialExecutor();private static volatile Executor sDefaultExecutor SERIAL_EXECUTOR;private static class SerialExecutor implements Executor {final ArrayDequeRunnable mTasks new ArrayDequeRunnable();Runnable mActive; ​public synchronized void execute(final Runnable r) {mTasks.offer(new Runnable() {public void run() {try {r.run();} finally {scheduleNext();}}});if (mActive null) {scheduleNext();}} ​protected synchronized void scheduleNext() {if ((mActive mTasks.poll()) ! null) {THREAD_POOL_EXECUTOR.execute(mActive);}}} 当一个AsyncTask任务执行完后AsyncTask会调用scheduleNext()方法继续执行下一个任务直到所有任务被执行为止总的来说默认情况下AsyncTask是串行执行的。 AsyncTask中有两个线程池SerialExecutor和THREAD_POOL_EXECUTOR和一个Handle SerialExecutor用于任务的排队 THREAD_POOL_EXECUTOR用于真正地执行任务 Handler用于将执行环境从线程池切换到主线程 在AsyncTask的构造方法中有如下一段代码由于FutureTask的run方法会调用mWorker的call方法因此mWorker的call方法最终会在线程池中执行。 public AsyncTask(Nullable Looper callbackLooper) {mHandler callbackLooper null || callbackLooper Looper.getMainLooper()? getMainHandler(): new Handler(callbackLooper); ​mWorker new WorkerRunnableParams, Result() {public Result call() throws Exception {mTaskInvoked.set(true);Result result null;try {Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//noinspection uncheckedresult doInBackground(mParams);Binder.flushPendingCommands();} catch (Throwable tr) {mCancelled.set(true);throw tr;} finally {postResult(result);}return result;}}; ​mFuture new FutureTaskResult(mWorker) {Overrideprotected void done() {try {postResultIfNotInvoked(get());} catch (InterruptedException e) {android.util.Log.w(LOG_TAG, e);} catch (ExecutionException e) {throw new RuntimeException(An error occurred while executing doInBackground(),e.getCause());} catch (CancellationException e) {postResultIfNotInvoked(null);}}};} ​ 在mWorker的call方法中首先将mTaskInvoked设为true表示当前任务已经被调用过了然后执行AsyncTask的doInBackground方法接着将返回值传递给postResult方法它的实现如下 private Result postResult(Result result) {SuppressWarnings(unchecked)Message message getHandler().obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskResultResult(this, result));message.sendToTarget();return result; } 在上面代码中postResult方法会通过Handler对象发送一个MESSAGE_POST_RESULT的消息这个Handler对象的定义如下 getHandler()获取Handler对象 private Handler getHandler() {return mHandler; } 赋值mHandler private final Handler mHandler; public AsyncTask(Nullable Looper callbackLooper) {mHandler callbackLooper null || callbackLooper Looper.getMainLooper()? getMainHandler(): new Handler(callbackLooper);...} 1如果callbackLooper null就getMainHandler() private static Handler getMainHandler() {synchronized (AsyncTask.class) {if (sHandler null) {sHandler new InternalHandler(Looper.getMainLooper());}return sHandler;} } 2如果callbackLooper Looper.getMainLooper()就new Handler(callbackLooper) public Handler(NonNull Looper looper) {this(looper, null, false); } Handler对象收到MESSAGE_POST_RESULT这个消息后会调用AsyncTask的finish方法。 private void finish(Result result) {if (isCancelled()) {onCancelled(result);} else {onPostExecute(result);}mStatus Status.FINISHED; } 如果AsyncTask被取消执行了那么就调用onCancelled方法否则就会调用onPostExecute方法就可以看到doInBackground的返回结果会传递给onPostExecute方法到这里AsyncTask的整个工作过程就分析完毕了。 总结 通过本篇博客我们了解了AsyncTask的工作原理和如何在Android应用程序中使用它来进行异步操作。AsyncTask提供了一种简单而强大的方式来管理异步任务并在UI线程中更新UI是Android开发中不可或缺的工具之一。希望本篇博客能帮助你更好地理解和使用AsyncTask。
http://www.dnsts.com.cn/news/259936.html

相关文章:

  • 偏门网站建设零基础免费学编程
  • 传奇服务器如何做网站云微助力网站建设
  • 提高网站建设水平意见方案旅游网站开发设计报告书
  • 网站建设服务商城劳务公司注册需要什么条件
  • 自助单页网站职业能力建设网网站
  • 动漫做视频在线观看网站网站空间维护
  • wordpress论坛哪个功能全面通化网站优化
  • 网站备案 厦门wordpress 公司展示
  • 南阳做网站推广企业邮箱后缀
  • 网络使用x86架构的通用设备代替昆明百度seo
  • 重庆住房建设部网站wordpress子域名网站
  • 石家庄自助建站软件企业在阿里云做网站
  • 景区官方网站建设学习做网站只学过c
  • 当前业界主流的网站建设网站建设感受
  • 织梦网站上传数据库为什么搜索不到刚做的网站
  • 网站开发包含哪些如何让网站快速收录你
  • 高端品牌网站建设兴田德润实惠游戏工作室
  • 做企业网站费用网站管理和建设工作职责
  • wordpress网站标题自定义重庆有几个区几个县
  • 建立公司网站需要注意什么写作网站大全
  • 子洲网站建设平台wordpress里再建一个网站
  • 龙华建设发展有限公司网站温州网站建设企业
  • 世界顶尖名表瑞士网站不要中国手表网站营销型公司官网建设
  • 电子商务网站规划的原则有哪些火是用什么做的视频网站
  • 大兴企业官网网站建设咨询cms网站开发实验报告
  • 天河网站建设开发页面设计公司会招低学历的人吗
  • 有什么网站是帮别人做设计的展示网站报价
  • 重庆做网站建设的公司哪家好东莞市市场监督管理局
  • 可信网站验证服务中心石家庄网站建设q.479185700棒
  • 陵水专业网站建设dz比wordpress速度快