Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start MAIN activity of the current application without knowing it's name

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?

like image 881
alex2k8 Avatar asked Jul 26 '11 18:07

alex2k8


2 Answers

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);
}
like image 84
alex2k8 Avatar answered Oct 17 '22 08:10

alex2k8


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);
    }
}
like image 28
L. G. Avatar answered Oct 17 '22 10:10

L. G.