getlaunchintentforpackage returning null

Viewed 3922

Can someone tell me please why this gives me null on the variable intent?

public class MainActivity extends AppCompatActivity {
    private static String action = "com.google.android.youtube";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume() {
        super.onResume();
        this.launch();
    }

    public void launch() {
        PackageManager pm = getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(action);
        System.out.println("debug: " + intent);
        //startActivity(intent);
    }
}

i test this on a pixel 4 and i never do uninstall youtube. also, sidequest list the app and gives me the package com.google.android.youtube

3 Answers

Add below code in manifiest at below level hope it will work with you.

<manifest
    <application
            >
        </application>

        <queries>
        <intent>
         <action android:name="com.google.android.youtube.api.service.START"/>
        </intent>
        </queries>
    </manifest>

If you know the package name of the app you want to launch at build-time, then see CommonsWare's answer, as this will work on Android 11+. For my case I don't know the package name at build-time because we get it from a server call, so I can't put that in my manifest. I had to take a different approach.

If you know the activity name of the package you are trying to launch, you don't need to call getLaunchIntentForPackage, as you can replicate its behaviour yourself. If you look at the source for getLaunchIntentForPackage, the PackageManager is used only to get the activity class name for the package being launched.

So here's my re-implementation which works on Android 11+ if you already know the activity class name:

// you have String variables packageName and className (fully-qualified)
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(packageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(packageName, className);
startActivity(intent);

PS: If you do know the app package name, but don't know the activity name, probably the best way to get the activity name is just to run getLaunchIntentForPackage on an earlier version of Android (version 10 or below) where that app is installed, and get the activity name from the resulting intent (intent.getComponent().getClassName()).

For example, for YouTube the values would be:

  • packageName = "com.google.android.youtube"
  • className = "com.google.android.youtube.app.honeycomb.Shell$HomeActivity"
Related