137

I know how to update my own programs, and I know how to open programs using the a predefined Uri (for sms or email for example)

I need to know how I can create an Intent to open MyTracks or any other application that I don't know what intents they listen to.

I got this info from DDMS, but I havn't been succesful in turning this to an Intent I can use. This is taken from when opening MyTracks manually.

Thanks for your help

05-06 11:22:24.945: INFO/ActivityManager(76): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.google.android.maps.mytracks/com.google.android.apps.mytracks.MyTracks bnds=[243,338][317,417] }
05-06 11:22:25.005: INFO/ActivityManager(76): Start proc com.google.android.maps.mytracks for activity com.google.android.maps.mytracks/com.google.android.apps.mytracks.MyTracks: pid=1176 uid=10063 gids={3003, 1015}
05-06 11:22:26.995: INFO/ActivityManager(76): Displayed activity com.google.android.maps.mytracks/com.google.android.apps.mytracks.MyTracks: 1996 ms (total 1996 ms)
Steve Haley
  • 53,826
  • 17
  • 73
  • 84
AndersWid
  • 1,373
  • 2
  • 9
  • 4

20 Answers20

237

I have work it like this,

/** Open another app.
 * @param context current Context, like Activity, App, or Service
 * @param packageName the full package name of the app to open
 * @return true if likely successful, false if unsuccessful
 */
public static boolean openApp(Context context, String packageName) {
    PackageManager manager = context.getPackageManager();
    try {
        Intent i = manager.getLaunchIntentForPackage(packageName);
        if (i == null) {
            return false;
            //throw new ActivityNotFoundException();
        }
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
        return true;
    } catch (ActivityNotFoundException e) {
        return false;
    }
}

Example usage:

openApp(this, "com.google.android.maps.mytracks");

Hope it helps someone.

Benny
  • 1,392
  • 1
  • 15
  • 23
Christopher
  • 25
  • 1
  • 2
  • 9
  • 5
    because getLaunchIntentForPackage("app package name") may cause exception. – xtr Jan 16 '12 at 03:49
  • This is a great answer, simple catch the exception and do what you need, notify user etc – IT-Dan Nov 29 '12 at 05:56
  • 5
    Not to be a stickler, but there's no reason to allocate a new Intent on the first line given you use the result of the `getLaunchIntentForPackage` call. – Chris Lacy Apr 28 '13 at 11:12
  • 2
    `getLaunchIntentForPackage()`already adds the category, see source: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/ApplicationPackageManager.java#L150 – jrub Mar 06 '15 at 11:40
  • The only problem for me is `Context` object where/how to get/create it?And what packages to import. New in Java for Android development. – Aleksey Kontsevich Aug 08 '20 at 00:54
141

Firstly, the concept of "application" in Android is slightly an extended one.

An application - technically a process - can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running (the process).

So, what you have to identify is how do you want to "start the application".

Ok... here's what you can try out:

  1. Create an intent with action=MAIN and category=LAUNCHER
  2. Get the PackageManager from the current context using context.getPackageManager
  3. packageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcher
  4. Get theActivityInfo you're interested in
  5. From the ActivityInfo, get the packageName and name
  6. Finally, create another intent with with category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  7. Finally, context.startActivity(newIntent)
Dunes Buggy
  • 1,669
  • 1
  • 21
  • 39
Gaurav Vaish
  • 9,140
  • 3
  • 35
  • 43
  • What If i wanted to open three separate apps? – Si8 Aug 15 '13 at 20:12
  • 7
    The community wiki answer below is better, if you know the package name http://stackoverflow.com/a/7596063/379115 – Martin Belcher - AtWrk Oct 10 '13 at 13:03
  • How can you pass data between the calling app and the launched app? I've found 'Intent.putExtra()' but I don't know how to retrieve the extra data in the launched app. – Bram Nov 17 '13 at 04:20
  • `onCreate` => `Bundle extras = getIntent().getExtras()` => `if(extras != null) { extras.getString("blah") }` etc – Gaurav Vaish Nov 19 '13 at 01:24
  • 2
    `getPackageManager().getLaunchIntentForPackage()` already does all that for you https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/ApplicationPackageManager.java#L137 – jrub Mar 06 '15 at 11:38
  • what about if you wanna resume this app from background not launch it again – Menna-Allah Sami May 06 '15 at 09:25
  • That's not under your control. That's defined by the activity's manifest - singleTop, singleInstance etc. – Gaurav Vaish May 07 '15 at 06:57
  • You saved my life! It's worked on android 4.x, 5, 7. Thank you so much! – hungtdo Jul 20 '17 at 15:34
97
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setComponent(ComponentName.unflattenFromString("com.google.android.maps.mytracks/com.google.android.apps.mytracks.MyTracks"));
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(intent);

EDIT :

as suggested in comments, add one line before startActivity(intent);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
jox
  • 1,777
  • 19
  • 28
zawhtut
  • 7,841
  • 5
  • 46
  • 72
  • 18
    but it requires to know the name of the activity – njzk2 Oct 18 '11 at 13:43
  • I tried this and got an error recommending to use the FLAG_ACTIVITY_NEW_TASK flag. I added this line before startActivity and it worked: intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); – david-hoze Aug 21 '13 at 10:08
  • 1
    @njzk2 finding the package name for something on Google Play is easy; it is right there in the URL. For example: https://play.google.com/store/apps/details?id=com.google.zxing.client.android&hl=en – Da-Jin Feb 05 '14 at 00:21
  • @iceybobby yes the package name is easy to find, but how do you find the class name of the activity to launch? – phreakhead Jun 18 '15 at 03:42
  • @phreakhead You're right. I think I used the solution in this answer:http://stackoverflow.com/a/8944286/1224186 so the activity name wasn't needed, and so I think that makes my reply to njzk2 unhelpful here. – Da-Jin Jun 19 '15 at 00:52
39

If you already have the package name you wish to activate, you can use the following code which is a bit more generic:

PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
    context.startActivity(appStartIntent);
}

I found that it works better for cases where the main activity was not found by the regular method of start the MAIN activity.

Muzikant
  • 7,834
  • 5
  • 50
  • 85
13

This is the code of my solution base on MasterGaurav solution:

private void  launchComponent(String packageName, String name){
    Intent launch_intent = new Intent("android.intent.action.MAIN");
    launch_intent.addCategory("android.intent.category.LAUNCHER");
    launch_intent.setComponent(new ComponentName(packageName, name));
    launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    activity.startActivity(launch_intent);
}

public void startApplication(String application_name){
    try{
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        List<ResolveInfo> resolveinfo_list = activity.getPackageManager().queryIntentActivities(intent, 0);

        for(ResolveInfo info:resolveinfo_list){
            if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
                launchComponent(info.activityInfo.packageName, info.activityInfo.name);
                break;
            }
        }
    }
    catch (ActivityNotFoundException e) {
        Toast.makeText(activity.getApplicationContext(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
    }
}
inversus
  • 1,229
  • 2
  • 15
  • 27
10

Using the solution from inversus, I expanded the snippet with a function, that will be called when the desired application is not installed at the moment. So it works like: Run application by package name. If not found, open Android market - Google play for this package.

public void startApplication(String packageName)
{
    try
    {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);

        for(ResolveInfo info : resolveInfoList)
            if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
            {
                launchComponent(info.activityInfo.packageName, info.activityInfo.name);
                return;
            }

        // No match, so application is not installed
        showInMarket(packageName);
    }
    catch (Exception e) 
    {
        showInMarket(packageName);
    }
}

private void launchComponent(String packageName, String name)
{
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    intent.setComponent(new ComponentName(packageName, name));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);
}

private void showInMarket(String packageName)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

And it is used like this:

startApplication("org.teepee.bazant");
peter.bartos
  • 10,745
  • 2
  • 46
  • 60
6

Use this :

    PackageManager pm = getPackageManager();
    Intent intent = pm.getLaunchIntentForPackage("com.package.name");
    startActivity(intent);
Swetha
  • 716
  • 10
  • 17
  • Have any idea ? open an test.apk instead of installed in device store in inside existing application. hints when click a button lunch test.apk apps that was stored in existing project. thanks in advanced. – Selim Raza Jul 27 '15 at 04:22
6

Open application if it is exist, or open Play Store application for install it:

private void open() {
    openApplication(getActivity(), "com.app.package.here");
}

public void openApplication(Context context, String packageN) {
    Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
    if (i != null) {
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
        }
    }
}
Martin Marconcini
  • 23,346
  • 18
  • 98
  • 135
Flinbor
  • 3,097
  • 1
  • 20
  • 25
4

To Start another application activity from my application Activity. It is working fine for me.

Below code will work if the another application already installed in your phone otherwise it is not possible to redirect form one app to another app.So make sure your app launched or not

Intent intent = new Intent();
intent.setClassName("com.xyz.myapplication", "com.xyz.myapplication.SplashScreenActivity");
startActivity(intent);
KCN
  • 474
  • 6
  • 19
  • Please do not write multiple answers that are almost identical to the same question. Use the "edit" link below the answer and change the original. – AdrianHHH Nov 23 '15 at 09:25
3

// This works on Android Lollipop 5.0.2

public static boolean launchApp(Context context, String packageName) {

    final PackageManager manager = context.getPackageManager();
    final Intent appLauncherIntent = new Intent(Intent.ACTION_MAIN);
    appLauncherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = manager.queryIntentActivities(appLauncherIntent, 0);
    if ((null != resolveInfos) && (!resolveInfos.isEmpty())) {
        for (ResolveInfo rInfo : resolveInfos) {
            String className = rInfo.activityInfo.name.trim();
            String targetPackageName = rInfo.activityInfo.packageName.trim();
            Log.d("AppsLauncher", "Class Name = " + className + " Target Package Name = " + targetPackageName + " Package Name = " + packageName);
            if (packageName.trim().equals(targetPackageName)) {
                Intent intent = new Intent();
                intent.setClassName(targetPackageName, className);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                Log.d("AppsLauncher", "Launching Package '" + packageName + "' with Activity '" + className + "'");
                return true;
            }
        }
    }
    return false;
}
gsamaras
  • 66,800
  • 33
  • 152
  • 256
2

For API level 3+, nothing more then one line of code:

Intent intent = context.getPackageManager().getLaunchIntentForPackage("name.of.package");

Return a CATEGORY_INFO launch Intent (apps with no launcher activity, wallpapers for example, often use this to provide some information about app) and, if no find it, returns the CATEGORY_LAUNCH of package, if exists.

Renascienza
  • 1,627
  • 1
  • 12
  • 14
2

If you're attempting to start a SERVICE rather than activity, this worked for me:

Intent intent = new Intent();
intent.setClassName("com.example.otherapplication", "com.example.otherapplication.ServiceName");
context.startService(intent);

If you use the intent.setComponent(...) method as mentioned in other answers, you may get an "Implicit intents with startService are not safe" warning.

Dunc
  • 16,506
  • 6
  • 74
  • 95
2

Alternatively you can also open the intent from your app in the other app with:

Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

where uri is the deeplink to the other app

electrobabe
  • 961
  • 9
  • 14
2

Use following:

String packagename = "com.example.app";
startActivity(getPackageManager().getLaunchIntentForPackage(packagename));
larsaars
  • 837
  • 1
  • 12
  • 25
2

Launch an application from another application on Android

  Intent launchIntent = getActivity.getPackageManager().getLaunchIntentForPackage("com.ionicframework.uengage");
        startActivity(launchIntent);
2

If you want to open another application and it is not installed you can send it to the Google App Store to download

  1. First create the openOtherApp method for example

    public static boolean openOtherApp(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
         try {
            Intent intent = manager.getLaunchIntentForPackage(packageName);
            if (intent == null) {
                //the app is not installed
                try {
                    intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setData(Uri.parse("market://details?id=" + packageName));
                    context.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    //throw new ActivityNotFoundException();
                    return false;
                }
    
             }
             intent.addCategory(Intent.CATEGORY_LAUNCHER);
             context.startActivity(intent);
             return true;
        } catch (ActivityNotFoundException e) {
            return false;
        }
    
    }
    

2.- Usage

openOtherApp(getApplicationContext(), "com.packageappname");
Vladimir Salguero
  • 4,156
  • 2
  • 30
  • 39
2

Since applications aren't allowed to change many of the phone settings, you can open a settings activity just like another application.

Look at you LogCat output after you actually modified the setting manually:

INFO/ActivityManager(1306): Starting activity: Intent { act=android.intent.action.MAIN cmp=com.android.settings/.DevelopmentSettings } from pid 1924

Then use this to display the settings page from your app:

String SettingsPage = "com.android.settings/.DevelopmentSettings";

try
{
Intent intent = new Intent(Intent.ACTION_MAIN);             
intent.setComponent(ComponentName.unflattenFromString(SettingsPage));             
intent.addCategory(Intent.CATEGORY_LAUNCHER );             
startActivity(intent); 
}
catch (ActivityNotFoundException e)
{
 log it
}
TNR
  • 6,014
  • 3
  • 30
  • 61
Tary
  • 951
  • 1
  • 9
  • 12
0

Try this code, Hope this will help you. If this package is available then this will open the app or else open the play store for downloads

    String  packageN = "aman4india.com.pincodedirectory";

            Intent i = getPackageManager().getLaunchIntentForPackage(packageN);
            if (i != null) {
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                startActivity(i);
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
                }
                catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
                }
            }
AMAN SINGH
  • 3,091
  • 5
  • 23
  • 44
0

You can use this command to find the package names installed on a device:

adb shell pm list packages -3 -f

Reference: http://www.aftvnews.com/how-to-determine-the-package-name-of-an-android-app/

JPritchard9518
  • 142
  • 1
  • 4
  • 11
-3
Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("package_name","package_name.class_name"));
        intent.putExtra("grace", "Hi");
        startActivity(intent);
Sicco
  • 5,759
  • 3
  • 41
  • 58
Manzer
  • 15
  • 2