I am trying to write an utility method, that would be able to start activity (belonging to current application) marked as "android.intent.action.MAIN". The utility method should not accept any parameters.
Desired code:
public void startMainActivity(Context context) {
...
}
Manifest:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Any ideas?开发者_StackOverflow
This works since API Level 3 (Android 1.5):
private void startMainActivity(Context context) throws NameNotFoundException {
PackageManager pm = context.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
context.startActivity(intent);
}
We used the nice solution of alex2k8 for a while until discovering it was not working on all devices on released version downloaded from Google Play.
Unfortunately the system didn't:
- throw any exception
- log the cause of the error
We used following workaround to solve it:
protected void startMainActivityWithWorkaround() throws NameNotFoundException, ActivityNotFoundException {
final String packageName = getPackageName();
final Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
if (launchIntent == null) {
Log.e(LOG_TAG, "Launch intent is null");
} else {
final String mainActivity = launchIntent.getComponent().getClassName();
Log.d(LOG_TAG, String.format("Open activity with package name %s / class name %s", packageName, mainActivity));
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(packageName, mainActivity));
// optional: intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
I think you'd have to find a list of all the activities declared in your manifest, and then use the intentFilter's actionsIterator()
to iterate through all the actions of each activity's intent-filter, match the one that has intent.action.MAIN
and then start that Activity.
The problem is I'm not sure how to retrieve a list of all your declared Activites from the manifest.
精彩评论