Android Thread学习笔记。。。

There are simply two rules to Android's single thread model:

1.  Do not block the UI thread
2.  Do not access the Android UI toolkit from outside the UI thread


Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
1.  Activity.runOnUiThread(Runnable)
2.  View.post(Runnable)
3.  View.postDelayed(Runnable, long)
PS:这里的Activity和View都需要指明对象,通过new一个Runnable对象并且在其中的run方法中修改UI界面,这样就能在别的线程修改UI线程的界面。
   
   当然还有第四种方法就是在新的线程中通过UI线程的handler发送消息,这样就会调用UI线程handler的handleMessage()方法,这样来修改UI界面。
   Google Dev Guide中推荐的方法也是比较方便的方法是通过继承AsyncTask类来完成多线程操作并且在修改UI界面。
具体的方法如下:
private class MyTask extends AsyncTask<Params, Progress, Result> { ... }

1.  Params, the type of the parameters sent to the task upon execution.
2.  Progress, the type of the progress units published during the background computation.
3.  Result, the type of the result of the background computation.

When an asynchronous task is executed, the task goes through 4 steps:

1.onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will MyTaskbe passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
简单的说就是先执行onPreExecute()方法,然后执行主体部分doInBackground(Params...),这里就是我们处理一些比较耗时的操作的地方,在一个新的线程上(不同于UI线程),Params就是我们刚刚在写class的时候写的那个类型,这个方法里可以调用publishProgress(Progress...)方法来同步更新UI界面,比如执行下载操作时更新进度条。然后doInBackground(Params...)返回一个参数这个参数传递给onPostExecute(Result)做更新UI的界面类似的操作。

调用通过new MyTask().execute(url1, url2, url3);来实现,MyTask就是刚刚自己写的类,execute()中的参数是用来传递给doInBackground(Params...)的,个数可以自己定,最后会是以数组的形式存在。

以上是我看了Dev Guide中Processes and Threads部分后的理解,有不正确的地方还请多多指教。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值