Android activity-alias is your friend

Updated

This is the second post in my Android snippet series, where I write about useful tips on how to make your app smarter and your development process easier. In this post I’m going to show you how to use activity-alias tag to your advantage.

Android activity-alias tag is one of the most unused tags in AndroidManifest.xml file. It’s so unknown that I’d guess most of the Android developers don’t even know why it’s there and what benefits it can bring to your app.

The whole concept behind activity-alias is very simple. As the name implies, the tag is an alias for an activity. But why would you need an alias for an activity? One of the common use cases for an activity-alias is to alias the main activity. For example, normally without an alias, your AndroidManifest should have the startup activity set like this:

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

If for some reason you need to change the startup activity to another one, you would normally add a new activity to AndroidManifest and move the intent-filter tag with the MAIN intent to this new activity. The downside of this is that if a user has created a shortcut to your app, the shortcut will be removed automatically by Android when the startup Activity changes.

But you can prevent the shortcut deletion by using the activity-alias tag like this:

<activity android:name=".MainActivity" />
<activity android:name=".NewMainActivity" />

<activity-alias
    android:name=".MainActivity"
    android:targetActivity=".NewMainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

In the above listing new activity called NewMainActivity has been added to the manifest. Also there’s now an activity-alias which contains the intent-filter tag that used to be attached to the MainActivity.

Now when the app starts, the activity-alias is the one being called (because of the MAIN intent) and it forwards the call to NewMainActivity since it’s set in the targetActivity attribute.

Also previously created shortcuts will remain in place, because the activity-alias has the same name attribute (.MainActivity) as the previous startup activity.

With this setup you can change the startup activity just by changing the targetActivity attribute in the activity-alias and users' shortcuts will stay in place.

Activity-alias has additional use cases like adding extra startup icons to specific parts of the app. More info about the tag can be found in the Android documentation. There’s also a nice blog post in the Android developer blog which dives into the things that cannot change in the app.