LoginSignup
48
42

More than 5 years have passed since last update.

Intent の中身を覗きたくていつもやるアレ

Posted at

Intent の中身を見たい

Intent を受け取った時、中に何が入っているか気になることがあります。
自分のアプリ内から飛んでくる Intent なら大したことはありませんが、よそから Intent が飛んできた時、中に何が入っているかがとても気になります。

toString() の罠

世の中便利なもので、どんなオブジェクトもObject#toString()によって文字列化することで、オブジェクトを人間に読めるようにすることができます(ただし本当に読み取れるようになるかどうかは実装に依存する)。

便利なので、Intent#toString()とか、文字列リテラルで結合して自動で文字列化してもらったりとかするんですが、以下のような文字列が生成されます。

Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.drivemode.intentlog.app/.MainActivity }

Action, Categories, Flag, Component が表示されます。

Action, Categories, Component は、これ以上はないほど親切に表示されますが、Flags は 16 進数になっていて、自分で頑張って計算しないと何がセットされていたのかよく分かりません。

Intent には Extras という、よそから引数みたいなものを渡す仕組みがあります。Intent に Extras が入っている場合、以下のようになります。

Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10100000 cmp=com.drivemode.intentlog.app/.MainActivity bnds=[481,810][1312,1641] }

bnds という謎の項目が増えました。これはロリポップからこうなったようです。OS のバージョンによっては、(has Extras) しか表示されないこともあります。いずれにしても何のことだかさっぱり分かりません。

取り出して、確認

Flags の場合、ビット演算でどんなフラグがセットされているか見ることができます。


Intent intent = getIntent();
int flags = intent.getFlags();

if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & flags) != 0) {
    // FLAG_ACTIVITY_CLEAR_TOP が入っている
}

Extras の場合、Bundle の keySet を使ってイテレーションしながら、対応する値を取り出すことで中身を見ることができます。


Bundle extras = intent.getExtras();
for (String key : extras.keySet()) {
    Object obj = extras.get(key);
}

ユーティリティへ

ここに置いておきます。そのうち maven central にも置きます。

ちなみに出力結果はだいたいこんなかんじです。

com.drivemode.intentlog.app V/test﹕ Intent[@172e5d96] content:
com.drivemode.intentlog.app V/test﹕ Action   : android.intent.action.MAIN
com.drivemode.intentlog.app V/test﹕ Category : {android.intent.category.LAUNCHER}
com.drivemode.intentlog.app V/test﹕ Data     : null
com.drivemode.intentlog.app V/test﹕ Component: com.drivemode.intentlog.app/com.drivemode.intentlog.app.MainActivity
com.drivemode.intentlog.app V/test﹕ Flags    : 10000001100000000000000000000
com.drivemode.intentlog.app V/test﹕ Flag     : FLAG_RECEIVER_FOREGROUND
com.drivemode.intentlog.app V/test﹕ Flag     : FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
com.drivemode.intentlog.app V/test﹕ Flag     : FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
com.drivemode.intentlog.app V/test﹕ HasExtras: true
com.drivemode.intentlog.app V/test﹕ Extra[profile] :0

やったねたえちゃん!Intent の中身全部丸見えだよ!

48
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
42