MainActivityが複数のデータを取得するのはマルチスレッドによる処理と最適化である

2351 ワード

パフォーマンスと実行効率を考慮せず、通常の基本的な開発プロセスのみに従うコードは次のとおりです.
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();
		}
    }    
}

ビジネスデータを取得するのに時間がかかる可能性があることを考慮すると,Activityの属性としてHandlerを用い,マルチスレッドと組み合わせて処理する必要がある.
サブスレッドにデータの取得を担当させ、取得したデータを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);
	}		
};