An alternative main
Activity could be useful for different purposes: a
brief description or tutorial covering
the main features of your app, or for a setup process for example. Of
course, you want the alternative main Activity to
be started only once (the first time
the user launches the app), while afterwards the regular main
Activity should be used.
To begin with, we
declare the two Activities in the AndroidManifest.xml file, like in
the following example:
<activity
android:name=”.ActivityTutorial”
android:label=”@string/activity_tutorial_label”
android:icon=”@drawable/activity_tutorial_icon”
android:enabled=”true”>
<intent-filter>
<action
android:name=”android.intent.action.MAIN”/>
<category
android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
<activity
android:name=”.ActivityMain”
android:label=”@string/activity_main_label”
android:icon=”@drawable/activity_main_icon”
android:enabled=”false”>
<intent-filter>
<action
android:name=”android.intent.action.MAIN”/>
<category
android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
There are two
things to notice in the previous
example: the enabled attribute is set to true for the tutorial
Activity (this is the Activity that starts when the user launches the
app for the first time) and false for the usual main Activity.
Notice also the
intent filter of the two Activities:
it is the same because both Activities
are used as the main Activity of your app: the ActivityTutorial only
the first time, the ActivityMain from the second time onwards.
In order to toggle
the enabled attribute of the two
Activities (from true to false for ActivityTutorial, from false to
true for ActivityMain) we use the following code within the
ActivityTutorial:
PackageManager
myPackageManager = getPackageManager();
//let’s
disable the ActivityTutorial
myPackageManager.setComponentEnabledSetting(new
ComponentName(this, ActivityTutorial.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
//let’s
enable the ActivityMain
myPackageManager.setComponentEnabledSetting(new
ComponentName(this, ActivityMain.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
We used the
DONT_KILL_APP
flag because we don’t want to kill the app containing the
component.
The class
PackageManager belongs to the following package: android.content.pm.
No comments:
Post a Comment