Social Icons

2013年5月22日 星期三

今天我學到 - Service onStart程序內不要做loading太重的事

在我的計劃裡面,主程式起來前會呼叫一個service來完成一些上傳的動作,但是常常會讓我的主程式跑出UI freeze的對話框。用Google查了一下,Service的程序是會影響主程序的,如果要操作比較耗時的工作,還是要再另外起一個Thread會比較好啊。

原本的程式:
 @Override
 public void 
 onStart(Intent intent, int startId) {
  super.onCreate();
  showNotification();
  
  trainingId = -1;
  while (isConnect()==true &&          // still connect with internet 
    _error_occurred == false &&        // no error occurred.
    (trainingId=providerUtils.getLastTrainingId())>0) {  // can get any training record.
   
   if (_bg_h!=null) {
    _is_upload = true;
    _start_upload_time = System.currentTimeMillis();
    _bg_h.post(do_uploadTraingRecord);
    while (_is_upload==true && 
     _error_occurred==false) {
     if ((System.currentTimeMillis()-_start_upload_time) > max_waiting_time) {
      _is_upload = false;
      _error_occurred = true;
     }
     else {
      try {
       Thread.sleep(1000);
      } 
      catch (InterruptedException e) {
       e.printStackTrace();
       _error_occurred = true;
      }      
     }
    }
   }
   else {
    // no background handler.
    break;
   }
  }
  stopService();
 }
會發現有一個while迴圈,這就是造成UI凍結的兇手,只要把它搬到thread去就好了。

更改過後:
 @Override
 public void 
 onStart(Intent intent, int startId) {
  super.onCreate();
  showNotification();
  
  if (isConnect()==false || providerUtils.getLastTrainingId() <=0 || _bg_h==null) {
   stopService();
  }
  else {
   _bg_h.post(run_uploadAll);
  }
 }

沒有留言:

張貼留言