使用 am 命令可以在命令列方式下啟動系統中已經存在的 app.
adb shell 進入命令列。
am 斷行符號,可以看到關於 am 的協助資訊。
關於各個參數的含義,在這裡不再贅述,舉幾個例子即可。
為了說明問題,自己寫一個 app,一個 activity、一個 service:
源碼:
package mark.zhang;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.os.Handler;public class AmActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);IntentFilter mFilter = new IntentFilter();mFilter.addAction("action_finish");registerReceiver(listener, mFilter);}private BroadcastReceiver listener = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if ("action_finish".equals(action)) {new Handler().postDelayed(new Runnable() {@Overridepublic void run() {finish();}}, 5000);}}};protected void onDestroy() {super.onDestroy();unregisterReceiver(listener);};}
package mark.zhang;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {super.onCreate();Log.d("mark", "MyService--- onCreate callbacks");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d("mark", "MyService--- onStartCommand callbacks");return super.onStartCommand(intent, flags, startId);}}
在 AmActivity 裡面接收到廣播就在 5s 後 finish.
將這個工程編譯之後的 apk 安裝到模擬器:
adb install **/Am.apk
1. 啟動 activity
am start -n mark.zhang/mark.zhang.AmActivity
這個時候 activity 被啟動了
2. 發送廣播
am broadcast -a "action_finish"
5s 之後,可以看到 AmActivity 被 finish.
3. 啟動服務
am startservice -n mark.zhang/mark.zhang.MyService
列印資訊
相關源碼
framworks/base/cmds/am/src/com/android/commands/am/Am.java
程式入口
/** * Command-line entry point. * * @param args The command-line arguments */ public static void main(String[] args) { try { (new Am()).run(args); } catch (IllegalArgumentException e) { showUsage(); System.err.println("Error: " + e.getMessage()); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } }