Search code examples
androidandroid-5.0-lollipopandroid-4.4-kitkat

How to pick Activity to start from the launcher based on SDK version?


I have an Android application which has multiple entry points in the launcher. Some of these requires a higher SDK version than others, and I want to disable or hide these if the device has a lower SDK version than what they require.

Basically my Manifest looks like this:

<application
    ...
    <activity
        android:name=".Activity1"
        ...
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Activity2"
        ...
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    ... // more launcher activities follows
</application>

Activity1 requires SDK version 19, but Activity2 requires SDK version 21. My minimum SDK version is 19. I want Activity2 hidden to be when installing the application on devices with SDK version < 21.

I know I can do a check in the onCreate method of Activity2 like so:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        finish();
        return;
    }
    ...
}

But the activity will obviously still show up in the launcher.

I'm also aware that this is a rather unique problem, and for most people with the same issue, the simplest and probably best solution is to just not have multiple activities as launcher activities, but this will not work so well in my use case.


Solution

  • Please don't do this in code, the only correct way to do this is to use the android:enabled="true/false" property which can be set on components in the AndroidManifest.xml file like an Activity or BroadcastReceiver. Instead of hard-coding the boolean value, use a boolean resource that changes per API level:

    values/bools.xml: Both activities are disabled by default

    <bool name="activity_1_enabled">false</bool>
    <bool name="activity_2_enabled">false</bool>
    

    values-v19/bools.xml: On SDK 19 up to 20 activity 1 is enabled and 2 disabled

    <bool name="activity_1_enabled">true</bool>
    <bool name="activity_2_enabled">false</bool>
    

    values-v21/bools.xml: On SDK 21+ both the activities are enabled

    <bool name="activity_1_enabled">true</bool>
    <bool name="activity_2_enabled">true</bool>
    

    AndroidManifest.xml

    <activity
        android:name=".Activity1"
        android:enabled="@bool/activity_1_enabled" />
    
    <activity
        android:name=".Activity2"
        android:enabled="@bool/activity_2_enabled" />