2016年1月27日 星期三

android.os.Debug.waitForDebugger 造成沒有連接usb才出錯

在開發APP的時候發生一個狀況
當手機拍完照返回主要的Activity時,APP掛掉了
偏偏這個奇怪的情況,在連接usb除錯時,不會發生
拿掉usb連線,直接操作手機時才會發生
沒辦法使用電腦debug,這樣到底要如何除錯呢?

最後發現是Service裡其中一段造成的

 @Override
 public void onConfigurationChanged(Configuration newConfig) {
  android.os.Debug.waitForDebugger();
  super.onConfigurationChanged(newConfig);
 }

因為在Service下中斷點,需要特別加這句才能讓中斷點產生作用
android.os.Debug.waitForDebugger();

手機本身沒有"Debugger",所以會造成錯誤
連接usb時,電腦就是Debugger


onConfigurationChanged 這個是在旋轉畫面或鍵盤收起等事件呼叫的
在測試的手機中,有兩台Sony在拍照的時候,會旋轉畫面
一台ASUS,在拍照的時候,不會旋轉畫面
所以,這個APP在有些手機可以正常執行,有些不行,就是這個原因




------------------------------------
 onConfigurationChanged可以偵測的事件
waitForDebugger
How to debug a Service?

ADT

  • ADT now attempts to connect a debugger to any application that shows up in the wait-for-debugger state, even if this application was not launched from Eclipse.

    The connection is actually established only if there exists a project in the Eclipse workspace that contains an AndroidManifest.xml declaring a package matching the name of the process. To force this connection from your code, use Debug.waitForDebugger(). Activities declaring that they require their own process through the "process" attribute with a value like ":someProcess" will be recognized and a debugger will be connected accordingly. This should make it easier to debug intent receivers, services, providers, and other activities not launched from the standard app launcher.
  • ADT has launch modes for device target selection. Automatic mode will: 1) launch an emulator if no device is present, 2) automatically target the device if only one is connected, and 3) prompt the user if 2 or more are connected. Manual mode will always prompt the user.