Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Manifest How to replace Activity by Flavor Activity

How to use the manifest command "replace" to replace an activity from the main package by an activity with the same name but in a flavor package?

com.name.project/main/
-ActivityA

replace by

com.name.project/pro/
-ActivityA
like image 990
XxGoliathusxX Avatar asked Dec 04 '16 22:12

XxGoliathusxX


1 Answers

You can do this by creating an activity alias for each activity you want to override, and then overriding the alias's target_activity in the flavor's manifest.

1) Add an alias for your activity to the main manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.company.app">
    <application>

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

    <activity-alias
        android:name="${applicationId}.aliasMain"
        android:targetActivity=".MainActivity"/>

    </application>
</manifest>

It's important to use ${applicationId} when declaring the alias if your flavors have different package names. This is because you launch an activity alias using the built package name.

2) Change the intents that launch your activity so that they launch it using the alias:

Intent intent = new Intent();
String packageName = context.getPackageName();
ComponentName componentName = new ComponentName(packageName, packageName + ".aliasMain");
intent.setComponent(componenteduName);

3) In the flavor's manifest, declare the replacement activity, override the alias's target activity to point at this new activity, and remove the base activity declaration for good measure:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.company.app">

    <application>

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

        <activity-alias
            tools:replace="android:targetActivity"
            android:name="${applicationId}.aliasMain"
            android:targetActivity=".flavor.MainActivity"/>

        <activity
            tools:node="remove"
            android:name=".MainActivity"
            />

    </application>
</manifest>

Note that the package name in the manifest tag is the base package name "com.company.app". This means that I have to include the package suffix in the activity declaration. I do this intentionally because it is more explicit. It also allows me to use the node:remove on the activity from the base package.

like image 152
Bob Liberatore Avatar answered Oct 26 '22 03:10

Bob Liberatore