Note: This content is translated from the English version of "Android Application Performance Optimization"
android-performance optimization 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. Combined use of HandlerThread and Handler
Usage scenario: The interface performs some complex logic processing, such as getting resources from the server
HandlerThread mHandlerThread = new HandlerThread("WorkerThread"); //mHandlerThread .getLooper(), get the current UI thread 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
Usage scenario: call when querying the database, use it to update the interface
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"));