How to launch an Activity from another Application in Android

后端 未结 12 1428
春和景丽
春和景丽 2020-11-21 06:02

I want to launch an installed package from my Android application. I assume that it is possible using intents, but I didn\'t find a way of doing it. Is there a link, where t

12条回答
  •  别那么骄傲
    2020-11-21 06:42

    Edit depending on comment

    In some versions - as suggested in comments - the exception thrown may be different.

    Thus the solution below is slightly modified

    Intent launchIntent = null;
    try{
       launchIntent = getPackageManager().getLaunchIntentForPackage("applicationId");
    } catch (Exception ignored) {}
    
    if(launchIntent == null){
        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
    } else {
        startActivity(launchIntent);
    }
    

    Original Answer

    Although answered well, there is a pretty simple implementation that handles if the app is not installed. I do it like this

    try{
        startActivity(getPackageManager().getLaunchIntentForPackage("applicationId"));
    } catch (PackageManager.NameNotFoundException e) {
        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
    }
    

    Replace "applicationId" with the package that you want to open such as com.google.maps, etc.

提交回复
热议问题