Android 异步加载解决方案(循环,多任务)

Android 异步加载解决方案

您的评价:
         
不错
  收藏该经验    

AndroidLazy Load主要体现在网络数据(图片)异步加载、数据库查询、复杂业务逻辑处理以及费时任务操作导致的异步处理等方面。在介绍Android开发过程中,异步处理这个常见的技术问题之前,我们简单回顾下Android开发过程中需要注意的几个地方。
Android应用开发过程中必须遵循单线程模型(Single Thread Model)的原则。因为AndroidUI操作并不是线程安全的,所以涉及UI的操作必须在UI线程中完成。但是并非所有的操作都能在主线程中进行,Google工程师在设计上约定,Android应用在5s内无响应的话会导致ANR(Application Not Response),这就要求开发者必须遵循两条法则:1、不能阻塞UI线程,2、确保只在UI线程中访问Android UI工具包。于是,开启子线程进行异步处理的技术方案应运而生。

本文以自定义ListView,异步加载网络图片示例,总结了Android开发过程中,常用的三种异步加载的技术方案。

相关资源:

AndroidManifest.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
     package = "com.doodle.asycntasksample"
     android:versionCode= "1"
     android:versionName= "1.0" >
 
     <uses-sdk
         android:minSdkVersion= "8"
         android:targetSdkVersion= "15" />
 
     <uses-permission android:name= "android.permission.INTERNET" />
 
     <application
         android:icon= "@drawable/ic_launcher"
         android:label= "@string/app_name"
         android:theme= "@style/AppTheme" >
         <activity
             android:name= "com.doodle.asynctasksample.ThreadHandlerPostActivity" >
         </activity>
         <activity android:name= "com.doodle.asynctasksample.AsyncTastActivity" >
         </activity>
         <activity android:name= "com.doodle.asynctasksample.ThreadHandlerActivity" >
         </activity>
         <activity
             android:name= "com.doodle.asynctasksample.BootActivity"
             android:label= "@string/title_activity_boot" >
             <intent-filter>
                 <action android:name= "android.intent.action.MAIN" />
                 <category android:name= "android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
     </application>
 
</manifest>

list_item.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     xmlns:tools = "http://schemas.android.com/tools"
     android:layout_width = "match_parent"
     android:layout_height = "match_parent" >
 
     < LinearLayout
         android:layout_width = "match_parent"
         android:layout_height = "150dp"
         android:layout_alignParentLeft = "true"
         android:layout_alignParentRight = "true"
         android:layout_alignParentTop = "true" >
 
         < ImageView
             android:id = "@+id/imageView"
             android:layout_width = "match_parent"
             android:layout_height = "match_parent"
             android:src = "@android :drawable/alert_dark_frame" />
 
     </ LinearLayout >
 
</ RelativeLayout >

ImageAdapter.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
  * Create a customized data structure for each item of ListView.
  * An ImageAdapter inherited from BaseAdapter must overwrites
  * getView method to show every image in specified style.In this
  * instance only a ImageView will put and fill in each item of
  * ListView.
  *
  * @author Jie.Geng Aug 01, 2012.
  *
  */
public class ImageAdapter  extends BaseAdapter {
     private Context context;
     private List<HashMap<String, Object>> listItems;
     private LayoutInflater listContainer;
     
     public ImageView imageView;
     
     public ImageAdapter(Context context, List<HashMap<String, Object>> listItems) {
         super ();
         this .context = context;
         this .listContainer = LayoutInflater.from(context);
         this .listItems = listItems;
     }
 
     @Override
     public int getCount() {
         return listItems.size();
     }
 
     @Override
     public Object getItem( int position) {
         return null ;
     }
 
     @Override
     public long getItemId( int position) {
         return 0 ;
     }
 
     @Override
     public View getView( int position, View convertView, ViewGroup parent) {
         if (convertView ==  null ) {
             convertView = listContainer.inflate(R.layout.list_item,  null );
             imageView = (ImageView) convertView.findViewById(R.id.imageView);
             convertView.setTag(imageView);
         else {
             imageView = (ImageView) convertView.getTag();
         }
         imageView.setImageDrawable((Drawable) listItems.get(position).get( "ItemImage" ));
         return convertView;
     }

一、采用AsyncTask

AsyncTask简介 AsyncTask的特点是任务在主线程之外运行,而回调方法是在主线程中执行,这就有效地避免了使用Handler带来的麻烦。阅读 AsyncTask的源码可知,AsyncTask是使用java.util.concurrent 框架来管理线程以及任务的执行的,concurrent框架是一个非常 成熟,高效的框架,经过了严格的测试。这说明AsyncTask的设计很好的解决了匿名线程存在的问题。 AsyncTask是抽象类,其结构图如下图所示: AsyncTask定义了三种泛型类型 Params,Progress和Result。 Params 启动任务执行的输入参数,比如HTTP请求的URL。 Progress 后台任务执行的百分比。 Result 后台执行任务最终返回的结果,比如String。 子类必须实现抽象方法doInBackground(Params… p) ,在此方法中实现任务的执行工作,比如连接网络获取数据等。通常还应 该实现onPostExecute(Result r)方法,因为应用程序关心的结果在此方法中返回。需要注意的是AsyncTask一定要在主线程中创 建实例。 AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,需要注意的是这些方法不应该由应用程序调用,开发者需要做的 就是实现这些方法。在任务的执行过程中,这些方法被自动调用,运行过程,如下图所示: onPreExecute() 当任务执行之前开始调用此方法,可以在这里显示进度对话框。 doInBackground(Params…) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用 publicProgress(Progress…)来更新任务的进度。 onProgressUpdate(Progress…) 此方法在主线程执行,用于显示任务执行的进度。 onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回
There are a few threading rules that must be followed for this class to work properly: The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN. The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
AsyncTastActivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class AsyncTastActivity  extends Activity {
 
     private List<String> urlList;
     private ImageAdapter listItemAdapter;
     private ArrayList<HashMap<String, Object>> listItem;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         urlList =  new ArrayList<String>();
         urlList.add( "http://www.baidu.com/img/baidu_sylogo1.gif" );
         urlList.add( "http://y2.ifengimg.com/2012/06/24/23063562.gif" );
         urlList.add( "http://himg2.huanqiu.com/statics/images/index/logo.png" );
 
         listItem =  new ArrayList<HashMap<String, Object>>();
 
         listItemAdapter =  new ImageAdapter( this , listItem);
         ListView listView = (ListView)  this .findViewById(R.id.listView1);
         listView.setAdapter(listItemAdapter);
 
         AsyncTask<List<String>, Integer, Hashtable<String, SoftReference<Drawable>>> task =  new AsyncTask<List<String>, Integer, Hashtable<String, SoftReference<Drawable>>>() {
 
             @Override
             protected void onPreExecute() {
                 super .onPreExecute();
             }
 
             @Override
             protected Hashtable<String, SoftReference<Drawable>> doInBackground(
                     List<String>... params) {
                 Hashtable<String, SoftReference<Drawable>> table =  new Hashtable<String, SoftReference<Drawable>>();
                 List<String> imageUriList = params[ 0 ];
                 for (String urlStr : imageUriList) {
                     try {
                         URL url =  new URL(urlStr);
                         Drawable drawable = Drawable.createFromStream(
                                 url.openStream(),  "src" );
                         table.put(urlStr,  new SoftReference<Drawable>(drawable));
                     catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
                 return table;
             }
 
             @Override
             protected void onPostExecute(
                     Hashtable<String, SoftReference<Drawable>> result) {
                 super .onPostExecute(result);
                 Collection<SoftReference<Drawable>> col = result.values();
                 for (SoftReference<Drawable> ref : col) {
                     HashMap<String, Object> map =  new HashMap<String, Object>();
                     map.put( "ItemImage" , ref.get());
                     listItem.add(map);
                 }
                 listItemAdapter.notifyDataSetChanged();
 
             }
         };
 
         task.execute(urlList);
     }
 
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.activity_main, menu);
         return true ;
     }
}

二、采用Thread + Handler + Message 
Handler简介 Handler为Android提供了一种异步消息处理机制,它包含两个队列,一个是线程列队,另一个是消息列队。使用post方法将线 程对象添加到线程队列中,使用sendMessage(Message message)将消息放入消息队列中。当向消息队列中发送消息后就立 即返回,而从消息队列中读取消息对象时会阻塞,继而回调Handler中public void handleMessage(Message msg)方法。因此 在创建Handler时应该使用匿名内部类重写该方法。如果想要这个流程一直执行的话,可以再run方法内部执行postDelay或者 post方法,再将该线程对象添加到消息队列中重复执行。想要停止线程,调用Handler对象的removeCallbacks(Runnable r)从 线程队列中移除线程对象,使线程停止执行。

ThreadHandlerActivity.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class ThreadHandlerActivity  extends Activity {
 
     private List<String> urlList;
     private ImageAdapter listItemAdapter;
     private LinkedList<HashMap<String, Object>> listItem;
     private Handler handler;
     private ExecutorService executorService = Executors.newFixedThreadPool( 10 );
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         urlList =  new ArrayList<String>();
         urlList.add( "http://www.baidu.com/img/baidu_sylogo1.gif" );
         urlList.add( "http://y2.ifengimg.com/2012/06/24/23063562.gif" );
         urlList.add( "http://himg2.huanqiu.com/statics/images/index/logo.png" );
 
         listItem =  new LinkedList<HashMap<String, Object>>();
 
         listItemAdapter =  new ImageAdapter( this , listItem);
         ListView listView = (ListView)  this .findViewById(R.id.listView1);
         listView.setAdapter(listItemAdapter);
         
         handler =  new Handler(){
             @Override
             public void handleMessage(Message msg) {
                 HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                 listItem.add(map);
                 listItemAdapter.notifyDataSetChanged();
             }
         };
         for ( final String urlStr : urlList) {
             executorService.submit( new Runnable() {
                 @Override
                 public void run() {
                     try {
                         URL url =  new URL(urlStr);
                         Drawable drawable = Drawable.createFromStream(
                                 url.openStream(),  "src" );
                         HashMap<String, Object> table =  new HashMap<String, Object>();
                         table.put( "ItemImage" , drawable);
                         Message msg =  new Message();
                         msg.obj = table;
                         msg.setTarget(handler);
                         handler.sendMessage(msg);
                     catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
             });
         }
     }
 
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.activity_main, menu);
         return true ;
     }
}

三、采用Thread + Handler + post方法

使用post方法将Runnable对象放到Handler的线程队列中,该Runnable的执行其实并未单独开启线程,而是仍然在当前Activity的UI线程中执行,Handler只是调用了Runnable对象的run方法。
ThreadHandlerPostActivity.java  
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class ThreadHandlerPostActivity  extends Activity {
 
     private List<String> urlList;
     private ImageAdapter listItemAdapter;
     private LinkedList<HashMap<String, Object>> listItem;
     private Handler handler =  new Handler();
     private ExecutorService executorService = Executors.newFixedThreadPool( 10 );
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         urlList =  new ArrayList<String>();
         urlList.add( "http://www.baidu.com/img/baidu_sylogo1.gif" );
         urlList.add( "http://y2.ifengimg.com/2012/06/24/23063562.gif" );
         urlList.add( "http://himg2.huanqiu.com/statics/images/index/logo.png" );
 
         listItem =  new LinkedList<HashMap<String, Object>>();
 
         listItemAdapter =  new ImageAdapter( this , listItem);
         ListView listView = (ListView)  this .findViewById(R.id.listView1);
         listView.setAdapter(listItemAdapter);
         
         for ( final String urlStr : urlList) {
             executorService.submit( new Runnable() {
                 @Override
                 public void run() {
                     try {
                         URL url =  new URL(urlStr);
                         Drawable drawable = Drawable.createFromStream(
                                 url.openStream(),  "src" );
                         final HashMap<String, Object> table =  new HashMap<String, Object>();
                         table.put( "ItemImage" , drawable);
                         handler.post( new Runnable(){
 
                             @Override
                             public void run() {
                                 listItem.add(table);
                                 listItemAdapter.notifyDataSetChanged();
                             }
                             
                         });
                     catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
             });
         }
     }
 
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.activity_main, menu);
         return true ;
     }
}

综上所述,我们可以看出,Android API中AsyncTask对于异步处理不是万能的,对于需要循环、多次的任务处理,我们任然需要采用传统的Thread线程机制。我们可以根据需要,灵活取舍。

你可能感兴趣的:(Android 异步加载解决方案(循环,多任务))