Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

透過 adb am 指令啟動 Android 應用程式

編輯:進階開發

Android 基於 Linux,對各種應用程式與系統服務的支持是其最大特色,也是開發者最該摸清的部分。除了寫程式,直接從 shell 用 am 指令啟動元件,是除錯與自動化測試時非常 handy 的技巧。

進入 shell 並查看說明

C:\Documents and Settings\mawenjian>adb shell

進入後執行 am -help,會看到用法提示(注意參數寫錯時也會印出同一段 usage):

usage: am [start|instrument]
am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
         [-c <CATEGORY> [-c <CATEGORY>] ...]
         [-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
         [-n <COMPONENT>] [-D] [<URI>]
am instrument [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>]
              [-w] <COMPONENT>

參數其實就是 Intent 的組成要素:-a 對應 action、-d 對應 data URI、-t 對應 MIME type、-c 對應 category、-n 對應 component(格式為「套件名/類別全名」)、-e 則用來傳 extra。

用 component 直接啟動

最直接的方式是指定要啟動的元件,例如開啟瀏覽器:

# am start -n com.google.android.browser/com.google.android.browser.BrowserActivity
Starting: Intent { comp={com.google.android.browser/com.google.android.browser.BrowserActivity} }

看到 Starting: Intent 就代表啟動成功。

用 action 與 data 間接啟動

不指定元件、改由系統挑選能處理該 Intent 的程式,可以試試這幾條:

# 開啟瀏覽器並載入網址
am start -a android.intent.action.VIEW -d https://mwjian.Javaeye.com

# 撥打電話
am start -a android.intent.action.CALL -d tel:88888888

# 開啟應用程式清單
am start -a android.intent.action.ALL_APPS

# 開啟地圖並搜尋地點
am start -a android.intent.action.VIEW -geo:0,0?q=shanghai

每條指令執行後都會回顯對應的 Intent 內容,例如:

Starting: Intent { action=android.intent.action.VIEW data=https://mwjian.Javaeye.com }
Starting: Intent { action=android.intent.action.CALL data=tel:88888888 }
Starting: Intent { action=android.intent.action.ALL_APPS }
Starting: Intent { action=android.intent.action.VIEW data=geo:0,0?q=shanghai }

這對開發有什麼幫助

第一,可以在不部署測試程式的情況下快速驗證自己的 Activity 是否已在 AndroidManifest 中正確註冊、intent-filter 是否寫對,省下反覆重新編譯的時間。

第二,am instrument 能直接觸發 instrumentation 測試,是串接自動化測試流程的入口。

第三,搭配 adb shell 就能寫成腳本批次操作,例如每次安裝新版本後自動開啟指定頁面確認沒有閃退。要注意 tel: 這類需要權限的 action,若用 CALL 直接撥號會受權限限制,改用 DIAL 只叫出撥號程式則不受影響,除錯時差別不小。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved