Androidのアプリで違うアプリから自分のアプリがkickされることって良くあると思います。
で、その時の動作を確認する為に、スタブアプリを作ってーみたいな事を今までやっていたのですが、実はCLIでインテントの送信やブロードキャストの送信も出来る事が分かり、とても便利なのでそのメモ。
参考
前提
- テストするアプリのパッケージ名はcom.example.toshihirock.myapplicationとしています。適宜自分の環境に置き換えて読んでください。
 - MyActivityというActivityが存在するものとします。
 - adb devicesで端末が認識出来る状態にしておきます。
 
明示的インテント
$adb shell am start -n 'com.example.toshihirock.myapplication/.MyActivity'
com.example.toshihirock.myapplicationというパッケージ名のMyActivityを起動させます。
アプリ終了
$adb shell am force-stop com.example.toshihirock.myapplication
パッケージ名を指定します。
暗黙的インテント
$adb shell am start -a 'android.intent.action.VIEW' -d 'http://google.co.jp'
-dではDATA_URIを指定しています。
ブロードキャストの送信
今回はom.example.toshihirock.testというアクションでtestという文字列の変数を送る事を確認してみます。
以下のようなクラスがあったとしてます。
MyBroadCastReceiver.java
package com.example.toshihirock.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
 * Created by toshihirock on 7/2/14.
 */
public class MyBroadCastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        String str = intent.getExtras().getString("test");
        Log.i("tag",str);
    }
}
また、AndroidManifest.xmlでreceiverに上記クラスを設定します。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.toshihirock.myapplication" >
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyBroadCastReceiver">
            <intent-filter>
                <action android:name="com.example.toshihirock.test"></action>
            </intent-filter>
        </receiver>
    </application>
</manifest>
上記作成後、以下のコマンドで該当のクラスへのBroadcastが確認出来ます。
$adb shell am broadcast -a 'com.example.toshihirock.test' -e 'test' 'aaaa'
Logcatには以下のように出力されるはずです。
07-01 11:40:37.621 3144-3144/com.example.toshihirock.myapplication I/tag﹕ aaaa
なお、文字列に"などを指定したい場合には、以下のようにエスケープする事で正しく内容が送信出来ます。
$adb shell am broadcast -a 'com.example.toshihirock.test' -e 'test' '\"aaaa\"'
Logcatで確認出来ます。
07-01 12:02:30.007 3144-3144/com.example.toshihirock.myapplication I/tag﹕ "aaaa"
その他
以下のコマンドでヘルプが見れるので詳細はこちらを見ると良いかと思います。
$adb shell am
他にも色々出来るっぽいです。
0 件のコメント:
コメントを投稿