Search code examples
androidandroid-intentintentfilterandroid-package-managers

Load another app from current application


Hi I am developing an android app where I am displaying all the installed apps on a list view . On click of the list item, I am trying to open that particular app.

This is the code i am trying

    mListView.setOnItemClickListener(new OnItemClickListener() 
    {
        private Intent intent;

        public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) 
        {

                String packName = (String) listOfapps.get(position).get("packagename");

                intent = getPackageManager().getLaunchIntentForPackage(packName);

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivity(intent);
        }
    });

This works fine for some apps. But on click of Contacts and few apps, I am getting force close as

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.contacts/com.android.internal.app.ResolverActivity}; have you declared this activity in your AndroidManifest.xml?

Not sure where I am going wrong. Please Help. Thanks


Solution

  • It is possible that there are packages that don't provide a launcher Intent that you can use. To prevent your app from crashing, you should be able to test if your launcher Intent will actually work by doing this:

    String packName = (String) listOfapps.get(position).get("packagename");
    intent = getPackageManager().getLaunchIntentForPackage(packName);
    // See how the package manager will resolve this Intent
    ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
    // Only start the activity if the package manager can resolve the Intent
    if (resolveInfo != null) {
        startActivity(intent);
    } else {
        // Tell the user he can't launch this app or whatever
    }
    

    You also don't need to set Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED on the Intent because those flags should already be set for you by the call to getLaunchIntentForPackage().