android 开发 之 AsyncTask机制


AsyncTask

是一个异步执行任务框架,内部结合线程池和handler机制进行处理和回调;

1.params--->WorkerRunable--->FutureTask--->Sync 中的callable;

2.线程池调用了 FutureTask的run----》Sync的innerRun----》mWorker的call方法----》doInBackgroud方法----》结果返回给Sync----》返给FurtureTask通过handler发送消息到主线程的onPostExecute方法中;

这个机制体现了数据的层层封装和传递,实现逻辑分层和数据封装分层;如果对数据进行处理或者拦截的话只需找对应的数据封装层即可;便于项目的维护和拓展;

        new AsyncTask<String ,Integer,Long>()
        {
            //在主线程  准备工作
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            //进度更新
            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }

            //执行结果回调,在主线程中
            @Override
            protected void onPostExecute(Long aLong) {
                super.onPostExecute(aLong);
            }

            //在子线程,异步执行任务
            @Override
            protected Long doInBackground(String... params) {
                return null;
            }
        }.execute("url");
    }


原理:

 

1.先看execute方法,先执行了onPreExecute方法准备工作;然后将参数params传给了mWorker;

 

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
	        ...
	
	        mStatus = Status.RUNNING;
			// 在主线程中执行准备操作
	        onPreExecute();
			// 把params参数赋值给mWorker
	        mWorker.mParams = params;
			// 用线程池执行mFuture
	        sExecutor.execute(mFuture);
}

mWorker是一个WorkerRunable任务类;在AsyncTask的构造方法中创建的;FurtureTask也实现了runable接口,在asyncTask的构造中实现的;最后将mWorker传给了fureture;

 

 

// 在AsyncTask构造方法中创建了mWorker
	    mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
               ...
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                ...
            }
        };


在FutureTask的构造中的callable就是传进来的mWorker,然后在传给Sync中的callable;

 

 

		// 把mWorker传递给FutureTask,callable指的就是mWorker
		public FutureTask(Callable<V> callable) {
		        if (callable == null)
		            throw new NullPointerException();
		        sync = new Sync(callable);
		    }
		// 把mWorker传递给Sync,callable指的是mWorker
		Sync(Callable<V> callable) {
		            this.callable = callable;
		        }


这一步将params--->WorkerRunable--->FutureTask--->Sync 中的callable;

 

 

2.使用线程池指向FutureTask;FutureTask的run方法中调用了Sync.innerRun();

 

		public void run() {
				// 转调
		        sync.innerRun();
		    }
		void innerRun() {
		            if (!compareAndSetState(READY, RUNNING))
		                return;
		
		            runner = Thread.currentThread();
		            if (getState() == RUNNING) { // recheck after setting thread
		                V result;
		                try {
							// 就是调用了mWorker.call方法
							// 把耗时操作得到的结果赋值给result
		                    result = callable.call();
		                } catch (Throwable ex) {
		                    setException(ex);
		                    return;
		                }
						// 转调了sync.innerSet(v);
		                set(result);
		            } else {
		                releaseShared(0); // cancel
		            }
		        }

Sync.innerRun()方法中执行了callable.call();最终执行了doInBackground();

		mWorker = new WorkerRunnable<Params, Result>() {
		            public Result call() throws Exception {
		                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
						// 执行耗时操作 在子线程中执行
		                return doInBackground(mParams);
		            }
		        };

Sync.innerRun()方法中执行了callable.call()完后返回了一个result,再调用了set(result);转调了innerSet();返回结果最后调用了FutureTask的done()方法;

		protected void set(V v) {
				// 转调
		        sync.innerSet(v);
		    }

		void innerSet(V v) {
		            for (;;) {
		                int s = getState();
		                if (s == RAN)
		                    return;
		                if (s == CANCELLED) {
		                    // aggressively release to set runner to null,
		                    // in case we are racing with a cancel request
		                    // that will try to interrupt runner
		                    releaseShared(0);
		                    return;
		                }
		                if (compareAndSetState(s, RAN)) {
		                    result = v;
		                    releaseShared(0);
							// 调用了FutureTask的抽象方法
		                    done();
		                    return;
		                }
		            }
		        }

 

 

可以看到通过get()方法获得result,,然后以后hander发送消息;

		mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                Message message;
                Result result = null;

                try {
					// 转调了sync.innerGet()
                    result = get();
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occured while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
                            new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
                    message.sendToTarget();
                    return;
                } catch (Throwable t) {
                    throw new RuntimeException("An error occured while executing "
                            + "doInBackground()", t);
                }
				// 发送了一个Message
                message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                        new AsyncTaskResult<Result>(AsyncTask.this, result));
                message.sendToTarget();
            }
        };

 

		public V get() throws InterruptedException, ExecutionException {
				// 转调
		        return sync.innerGet();
		    }

		V innerGet() throws InterruptedException, ExecutionException {
		            acquireSharedInterruptibly(0);
		            if (getState() == CANCELLED)
		                throw new CancellationException();
		            if (exception != null)
		                throw new ExecutionException(exception);
					// 把之前doinBackground方法的结果返回
		            return result;
		        }

 

这个InernalHandler是AsyncTask的成员变量;

 

    private static class InternalHandler extends Handler {
        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
					// 结束耗时操作完成后的消息
					// 调用了AsyncTask的finish方法传递的result.mData[0]就是之前
					// 耗时操作返回来的结果
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
                case MESSAGE_POST_CANCEL:
                    result.mTask.onCancelled();
                    break;
            }
        }
    }

    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;
		// data 是返回的结果
        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }

    private void finish(Result result) {
        if (isCancelled()) result = null;
		// 耗时操作完成,更新UI,执行在主线程
        onPostExecute(result);
        mStatus = Status.FINISHED;
    }

 


这步的流程:线程池调用了 FutureTask的run----》Sync的innerRun----》mWorker的call方法----》doInBackgroud方法----》结果返回给Sync----》返给FurtureTask通过handler发送消息到主线程的onPostExecute方法中;

 

总结:这个机制体现了数据的层层封装和传递,实现逻辑分层和数据封装分层;如果对数据进行处理或者拦截的话只需找对应的数据封装层即可;便于项目的维护和拓展;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值