Search code examples
androidandroid-intentbroadcastreceiveradb

Static BroadcastReceiver not Working after Installation from ADB


I working on a project that need to launch an app by broadcasting a customized intent "com.example.demo.action.LAUNCH" via adb.

My plan is to statically register a broadcast receiver "LaunchAppReceiver" that will launch the app when receiving the customized intent.

I installed the .apk by calling

adb install -r <pakcageName>

then I sent the intent by calling

adb shell am broadcast -a com.example.demo.action.LAUNCH

However, nothing happened after the intent was sent. It seemed the broadcast receiver didn't receive the intent at all. Do I need to somehow instantiate the receiver before it can receive the intent?

Note: Since the android device is remote, I have to use adb to handle the installation and the launch.

Thanks!!


I declared the broadcast receiver as follow

public class LaunchAppReceiver extends BroadcastReceiver{

    public LaunchAppReceiver () {}

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent newIntent = new Intent(context, MainActivity.class);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(newIntent);
    }
}

and statically registered it in the AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demo" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:enabled="true">
        <receiver
            android:name="com.example.demo.LaunchAppReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.demo.action.LAUNCH"/>
            </intent-filter>
        </receiver>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Solution

  • Finally got this fixed.

    Since Honeycomb, all the freshly installed apps will get into a STOP stage until they are launched for at least one time. Android adds a flag "FLAG_EXCLUDE_STOPPED_PACKAGES" for all broadcast intents, which stops them from reaching the stopped apps. http://droidyue.com/blog/2014/01/04/package-stop-state-since-android-3-dot-1/

    To solve this issue, just simply add the flag "FLAG_INCLUDE_STOPPED_PACKAGES" to the intents we send. In my case, I modify the adb command as

    adb shell am broadcast -a com.example.demo.action.LAUNCH --include-stopped-packages