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"));

相关推荐