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); } };
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30