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

网站建设功能清单网页设计案例欣赏

网站建设功能清单,网页设计案例欣赏,深圳网站建设制作设计,黄石论坛AsyncTask AsyncTask用于处理耗时任务#xff0c;可以即时通知进度#xff0c;最终返回结果。可以用于下载等处理。 使用 实现类继承三个方法 1. doInBackground后台执行#xff0c;在此方法中进行延时操作 /*** Override this method to perform a computation on a back…AsyncTask AsyncTask用于处理耗时任务可以即时通知进度最终返回结果。可以用于下载等处理。 使用 实现类继承三个方法 1. doInBackground后台执行在此方法中进行延时操作 /*** Override this method to perform a computation on a background thread. The* specified parameters are the parameters passed to {link #execute}* by the caller of this task.** This method can call {link #publishProgress} to publish updates* on the UI thread.** param params The parameters of the task.** return A result, defined by the subclass of this task.** see #onPreExecute()* see #onPostExecute* see #publishProgress*/WorkerThreadprotected abstract Result doInBackground(Params... params);2. onProgressUpdate刷新UI /*** Runs on the UI thread after {link #publishProgress} is invoked.* The specified values are the values passed to {link #publishProgress}.** param values The values indicating progress.** see #publishProgress* see #doInBackground*/SuppressWarnings({UnusedDeclaration})MainThreadprotected void onProgressUpdate(Progress... values){}3. onPostExecute结果返回此结果即为后台执行方法返回的结果。 /*** pRuns on the UI thread after {link #doInBackground}. The* specified result is the value returned by {link #doInBackground}./p* * pThis method wont be invoked if the task was cancelled./p** param result The result of the operation computed by {link #doInBackground}.** see #onPreExecute* see #doInBackground* see #onCancelled(Object) */SuppressWarnings({UnusedDeclaration})MainThreadprotected void onPostExecute(Result result) {}Result,Progress,Params三者是AsyncTask的泛型从代码可以看出Result为返回结果类型Progress是刷新进度的类型Params是处理耗时任务时需要传入的类型。 public abstract class AsyncTaskParams, Progress, Result4. execute启动方法 /*** Executes the task with the specified parameters. The task returns* itself (this) so that the caller can keep a reference to it.* * pNote: this function schedules the task on a queue for a single background* thread or pool of threads depending on the platform version. When first* introduced, AsyncTasks were executed serially on a single background thread.* Starting with {link android.os.Build.VERSION_CODES#DONUT}, this was changed* to a pool of threads allowing multiple tasks to operate in parallel. Starting* {link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being* executed on a single thread to avoid common application errors caused* by parallel execution. If you truly want parallel execution, you can use* the {link #executeOnExecutor} version of this method* with {link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings* on its use.** pThis method must be invoked on the UI thread.** param params The parameters of the task.** return This instance of AsyncTask.** throws IllegalStateException If {link #getStatus()} returns either* {link AsyncTask.Status#RUNNING} or {link AsyncTask.Status#FINISHED}.** see #executeOnExecutor(java.util.concurrent.Executor, Object[])* see #execute(Runnable)*/MainThreadpublic final AsyncTaskParams, Progress, Result execute(Params... params) {return executeOnExecutor(sDefaultExecutor, params);}分析 相关知识点 线程池Android Handler 1. 构造器 /*** Creates a new asynchronous task. This constructor must be invoked on the UI thread.*/public AsyncTask() {this((Looper) null);}/*** Creates a new asynchronous task. This constructor must be invoked on the UI thread.** hide*/public AsyncTask(Nullable Handler handler) {this(handler ! null ? handler.getLooper() : null);}/*** Creates a new asynchronous task. This constructor must be invoked on the UI thread.** hide*/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);}}};}1.1 Handler 使用getMainHandler()返回的Handler。消息处理部分可以看到完成处理与进度更新。 private static Handler getMainHandler() {synchronized (AsyncTask.class) {if (sHandler null) {sHandler new InternalHandler(Looper.getMainLooper());}return sHandler;}}private static class InternalHandler extends Handler {public InternalHandler(Looper looper) {super(looper);}SuppressWarnings({unchecked, RawUseOfParameterizedType})Overridepublic void handleMessage(Message msg) {AsyncTaskResult? result (AsyncTaskResult?) msg.obj;switch (msg.what) {case MESSAGE_POST_RESULT:// There is only one resultresult.mTask.finish(result.mData[0]);break;case MESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate(result.mData);break;}}}private void finish(Result result) {if (isCancelled()) {onCancelled(result);} else {onPostExecute(result);}mStatus Status.FINISHED;}SuppressWarnings({UnusedDeclaration})MainThreadprotected void onProgressUpdate(Progress... values) {}1.2 WorkerRunnable实现对象mWorker 使用Callable接口。 private static abstract class WorkerRunnableParams, Result implements CallableResult {Params[] mParams;} 1.3 FutureTask实现对象 mFuture FutureTask其中保存了Callable接口。 public FutureTask(CallableV var1) {if (var1 null) {throw new NullPointerException();} else {this.callable var1;this.state 0;}}2. exectue执行操作开始 MainThreadpublic final AsyncTaskParams, Progress, Result execute(Params... params) {return executeOnExecutor(sDefaultExecutor, params);}/*** Executes the task with the specified parameters. The task returns* itself (this) so that the caller can keep a reference to it.* * pThis method is typically used with {link #THREAD_POOL_EXECUTOR} to* allow multiple tasks to run in parallel on a pool of threads managed by* AsyncTask, however you can also use your own {link Executor} for custom* behavior.* * pemWarning:/em Allowing multiple tasks to run in parallel from* a thread pool is generally emnot/em what one wants, because the order* of their operation is not defined. For example, if these tasks are used* to modify any state in common (such as writing a file due to a button click),* there are no guarantees on the order of the modifications.* Without careful work it is possible in rare cases for the newer version* of the data to be over-written by an older one, leading to obscure data* loss and stability issues. Such changes are best* executed in serial; to guarantee such work is serialized regardless of* platform version you can use this function with {link #SERIAL_EXECUTOR}.** pThis method must be invoked on the UI thread.** param exec The executor to use. {link #THREAD_POOL_EXECUTOR} is available as a* convenient process-wide thread pool for tasks that are loosely coupled.* param params The parameters of the task.** return This instance of AsyncTask.** throws IllegalStateException If {link #getStatus()} returns either* {link AsyncTask.Status#RUNNING} or {link AsyncTask.Status#FINISHED}.** see #execute(Object[])*/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;}2.1 进行status判断 正在运行的对象调用此方法会抛出异常正在运行的设置在此方法中。已经完成的对象调用此方法会抛出异常已经完成的设置在InternalHandler中调用。 private void finish(Result result) {if (isCancelled()) {onCancelled(result);} else {onPostExecute(result);}mStatus Status.FINISHED;}2.2 调用onPreExecte()方法 子类实现此方法会在耗时操作前执行一些操作。 /*** Runs on the UI thread before {link #doInBackground}.** see #onPostExecute* see #doInBackground*/MainThreadprotected void onPreExecute() {}2.3 执行exec.execute(mFuture) 2.3.1 exec是什么 通过调用链可看出是sDefaultExecutor。在代码中可以看到是SerialExecutor静态内部类对象。 public static final Executor SERIAL_EXECUTOR new SerialExecutor();private static final int MESSAGE_POST_RESULT 0x1;private static final int MESSAGE_POST_PROGRESS 0x2;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);}}}2.3.2 execute(final Runnable r)传是mFuture这里是Runnable public class FutureTaskV implements RunnableFutureV{} public interface RunnableFutureV extends Runnable, FutureV {void run(); }2.3.3 调用mFuture的run方法 刚才1.3futuretask实现对象-mfuture可以看出 this.callable var1;即此处调用了mWorker的call()方法 public void run() {if (this.state 0 UNSAFE.compareAndSwapObject(this, runnerOffset, (Object)null, Thread.currentThread())) {boolean var9 false;try {var9 true;Callable var1 this.callable;if (var1 ! null) {if (this.state 0) {Object var2;boolean var3;try {var2 var1.call();var3 true;}....}....}....}....}}2.3.4 mWorker调用doInBackground 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;}};2.3.5 doInBackground返回result调用postResult(result) 这里发送了结果见1.1处理 private Result postResult(Result result) {SuppressWarnings(unchecked)Message message getHandler().obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskResultResult(this, result));message.sendToTarget();return result;}3. 进度刷新 进度刷新可以调用如下方法。大多在doInBackground中使用。 /*** This method can be invoked from {link #doInBackground} to* publish updates on the UI thread while the background computation is* still running. Each call to this method will trigger the execution of* {link #onProgressUpdate} on the UI thread.** {link #onProgressUpdate} will not be called if the task has been* canceled.** param values The progress values to update the UI with.** see #onProgressUpdate* see #doInBackground*/WorkerThreadprotected final void publishProgress(Progress... values) {if (!isCancelled()) {getHandler().obtainMessage(MESSAGE_POST_PROGRESS,new AsyncTaskResultProgress(this, values)).sendToTarget();}}4. 如何暂停/取消 直接在doInBackground方法中返回Result即可Result是泛型可以自定义各种类型的返回值。
http://www.dnsts.com.cn/news/150906.html

相关文章:

  • 网站开发花费网店营销策划书
  • 免费网站后台模板做网站现在要多少钱
  • 长春网站建设网站上海工商网查询企业信息查询系统
  • 响应式网站检测工具世界上做的最后的网站
  • 一般做兼职在哪个网站网站服务器租赁你的知识宝库
  • 纪检网站建设方案做一百度网站吗
  • 去哪个网站找建筑图纸国家高新技术企业是国企吗?
  • 网站用什么程序做的大望路做网站的公司
  • 网站建设展示型是什么邯郸网站开发公司电话
  • 网站排名方法摄影作品网站app十大排名
  • 黑色网站模版wnmp搭建wordpress
  • 企业网站推广的策略有哪些哪些网站可以注册邮箱
  • 网站备案成功后怎么弄河南省建设工程中标信息网
  • 在阿里云做视频网站需要什么重庆建设工程公司网站
  • 泸州建设网站云虚拟主机可以做多少个网站
  • 网站策划怎么样中企动力网站报价
  • 网站首页设计布局图文广告店最佳名字
  • 衡阳市建设网站制作图片的免费网站
  • 东莞网站建设aj工作室WordPress安装Redis
  • 商业门户网站制作wordpress 边框大小
  • 网站打开速度规定多长时间南昌地宝网
  • 网站上可以做文字链接么万户网络有限责任公司
  • 建设企业网站的好处是什么seo优化流程
  • 访问网站错误代码为137php网站后台管理系统
  • 成都网站制作计划负责网站建设推广
  • 企业网站 带后台长宁深圳网站建设公司
  • 用帝国cms做网站wordpress ie9
  • 找个人制作网页的网站焦作网站制作公司
  • 推几个学习网站网站备案号被注销
  • vue 大型网站开发石龙网站建设