Send an Android broadcast to a device using adb

How to trigger a BroadcastReceiver from the command line

This is another of those posts that’s really a reminder to myself about how to do something, something that I do so infrequently that I forget it in between times (a bit like my post on setting up Charles proxy). But hopefully others will find it useful too.

I was recently working on a project where we wanted to monitor how our users were managing the battery on their device – when they plugged it in to a charger, when they unplugged it, what type of charger (USB/AC/Wireless), and what the state of the battery was at all these events. (This was a controlled group of test users by the way, not the general public.)

This is fairly easy to do on Android, just set a BroadcastReceiver for the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED actions as described here on the Android developer site. Each time the broadcast was fired we saved the data to a SQLite database, and I’m your uncle.

But debugging it is not so simple. Set a breakpoint on the receiver, pull the USB cable out to fire the disconnected event, and…oh, wait, no breakpoint. There’s an easy way around this though – while the cable is still plugged in fire the event manually using adb:

adb shell am broadcast -a android.intent.action.ACTION_POWER_DISCONNECTED

The breakpoint is hit and you can debug as normal.

You can also pass extras with the intent by using --es (for string extras) and --ei for integer extras. For example:

adb shell am broadcast -a android.intent.action.ACTION_POWER_DISCONNECTED --es extra_test "this\ is\ a\ string"

This is using terminal on a mac, note the backslashes to escape the spaces in the string extra.

This guy has a few more examples.

Leave a Reply

Your email address will not be published. Required fields are marked *