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

2013年5月15日 星期三

今天我學到 - 如何讓Google map view (v2),在滾動頁面時不會產生殘影

使用Google map api v2時,發生了一個大問題,程式中的map view不是佔據整個頁面,只是其中的一部分。這樣問題就來了,當滾動(Scrolling)時原本map view的位置就會產生殘影,整個畫面就被破壞掉了。(後來發現如果將Google Map View放在ViewPager,也會有類似的問題)  

2013年5月7日 星期二

今天我學到 - Hardware acceleration和WebView

程式裡因為改用Google Map api V2時,就忘了將Hardware acceleration設成off,就在測試時發現WebView會不定時的crash,google了一下找到這篇,說WebView使用硬體加速會有很多問題,建議取消。但是,因為程式中的Google Map api v2用到openGL,所以如果Hardware acceleration設成on的話是會讓整個速度提升不少的。所以就花了一點時間查詢如何在外部和程式中設定是否使用硬體加速的功能。

在AndroidManifest.xml中設定

a.整個application設定
<application android:hardwareAccelerated="true" ...>
b.對activity
<activity android:hardwareAccelerated="false" />
您可以在application中設定整體是否要加速,然後在activity中對分別activity來設定。但是,如果您想要在程式中設定,或者只針對某一個View來設定呢的話,可以參考下面程式碼:
// 在window中只能設定硬體加速,不能取消哦。
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

// 在view中可以取消硬體加速
myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

2013年5月6日 星期一

2013年5月2日 星期四

今天我學到 - Google Map API v2如何Zoom到指定位置和指定區塊

將程式裡的Google Map從原本的v1,移植到v2的版本上面來,發現還不是非常容易哩。原本v1裡面的一些程式碼都不能用了,全部都的改成v2的思維才行。