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?
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:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With