android-性能优化之UI
注:本内容翻译于《android应用性能优化》英文版
android-性能优化之UI
1、Thread
new Thread(new Runable(){ @Override public void run(){ // do some heavy work } }).start();
2、AsyncTask
new AsyncTask<URL,Integer,Integer>(){ protected Long doInBackground(URL ..urls){ final int count = urls.length; for(int i=0;i>count;i++){ Downloader.download(url); publishProgress(i); } return count; } protected void onProgressUpdate(Integer ...progress){ setProgress(progress[0]); } protected void onPostExecute(Integer result){ showDialog("Download"+result+" files"); } }
3、HandlerThread与Handler联合使用
使用场景:界面进行一些复杂的逻辑处理,比如从服务器得到资源
HandlerThread mHandlerThread = new HandlerThread("WorkerThread"); //mHandlerThread .getLooper(),得到当前的UI线程 Handler handler = new Handler(mHandlerThread .getLooper()){ @Override public void handlerMessage(Message msg){ switch(msg.what){ case JOB_1: break; case JOB_2: break; } } } handler.sendEmptyMessage(JOB_1); handler.sendEmptyMessage(JOB_2); handler.post(new Runable(){ @Override public void run(){ //do more work } }); @Override protected void onDestory(){ mHandlerThread.quit(); super.onDestory(); }
4、AsyncQueryHandler
使用场景:当对数据库进行查询的时候进行调用,使用它对界面进行更新
new AsyncQueryHandler(getContentResolver()){ @Override protected void onQueryComplete(int token,Object cookie,Cursor cursor){ if(token==0){ //get data from cursor } } }.startQuery(0,//token null, RawContacts.CONTENT_URI,null,//projection RawContacts.CONTACT_ID+"<?",//selection new String[]{"888"},//selectionArgs RawContacts.DISPLAY_NAME_PRIMARY+"ASC"//orderby )
5、IntentService
public class WorderService extends IntentService{ public WorderService (){ super("WorkerThread"); } @Override protected void onHandlerIntent(Intent intent){ Stirng action = intent.getAction(); if("com.test.DO_JOB_1").equals(action)){ //do job } } } startService(new Intent("com.test.DO_JOB_1"));
相关推荐
81417707 2020-10-30
yanzhelee 2020-10-13
89243453 2020-08-24
houdaxiami 2020-08-15
89253818 2020-07-30
89253818 2020-07-19
81264454 2020-07-17
iftrueIloveit 2020-07-04
ItBJLan 2020-06-28
开心就好 2020-06-16
Jaystrong 2020-06-16
iftrueIloveit 2020-06-11
QiHsMing 2020-06-08
webfullStack 2020-06-07
不知道该写啥QAQ 2020-06-06
fsl 2020-06-05
Carlos 2020-05-31
85231843 2020-05-31
curiousL 2020-05-27