MainActivity获取多个数据是采用多线程进行处理和优化

按不考虑性能和执行效率、只按照正常基本的开发流程是如下代码

public class MainActivity extends Activity {
	private ListView listView;
	private File cacheDir;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**  检查SD卡的缓存目录是否存在      */
        File sdCardDir = Environment.getExternalStorageDirectory();
        cacheDir = new File(sdCardDir, "cache");
        if(!cacheDir.exists()) cacheDir.mkdirs();   
        
        try {
        	/**正常的处理逻辑: 获取数据传递给Adapter,为ListView设置Adapter**/
			listView = (ListView)findViewById(R.id.listView);
			List<Topic> topicList = TopicService.getContacts();
			BaseAdapter adapter = new TopicAdapter(this, topicList, 
					R.layout.listview_item, cacheDir );
			listView.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }    
}

 现在考虑到获取业务数据需要的时间可能比较长,所以需要用Handler作为Activity的属性,结合多线程来处理。

让子线程负责获获取数据,将取到的数据通过Hander的sendMessage()的方法回传给Handler,

再由handler的handleMessage()从Message中取出数据,转换为对应的数据类型,最后设置回ListView的适配器中。

/**正常的处理逻辑: 获取数据传递给Adapter,为ListView设置Adapter**/
/*List<Topic> topicList = TopicService.getContacts();
BaseAdapter adapter = new TopicAdapter(this, topicList, 
		R.layout.listview_item, cacheDir );
listView.setAdapter(adapter);*/

Runnable runnable = new Runnable(){
	@Override
	public void run() {
		try {
			List<Topic> topicList = TopicService.getContacts();
			handler.sendMessage(handler.obtainMessage(100, topicList));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}				
};
new Thread(runnable).start();
Handler handler = new Handler(){
	@Override
	public void handleMessage(Message msg) {
		/**这里负责处理 子线程做完后的工作**/
		List<Topic> topicList = (List<Topic>)msg.obj;
		BaseAdapter adapter = new TopicAdapter(MainActivity.this, topicList, 
				R.layout.listview_item, cacheDir );
		listView.setAdapter(adapter);
	}		
};

相关推荐