Start MAIN activity of the current application without knowing its name

I am trying to write a utility method that could start an activity (belonging to the current application), marked as "android.intent.action.MAIN". The utility method should not accept any parameters.

Required 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?

+6
source share
3 answers

This works with 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); } 
+13
source

We used the nice alex2k8 solution for a while, until we found that it does not work on all devices on the released version downloaded from Google Play ,

Unfortunately, the system was not:

  • throw any exception
  • write down the reason for the error

We used the following method to solve the problem:

 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); } } 
+1
source

I think you will need to find a list of all the actions declared in your manifest, and then use aimFilter actionsIterator() to iterate over all the actions of each filter, the intent of the activity matches the one that has intent.action.MAIN , and then run this action.

The problem is that I'm not sure how to get a list of all the Activit you declared from the manifest.

0
source

Source: https://habr.com/ru/post/893625/


All Articles