Abra otra aplicación desde la suya (intent)


Sé cómo actualizar mis propios programas, y sé cómo abrir programas usando el Uri predefinido (para sms o correo electrónico, por ejemplo)

Necesito saber cómo puedo crear una Intent para abrir MyTracks o cualquier otra aplicación que no sepa qué intents escuchan.

Obtuve esta información de DDMS, pero no he tenido éxito en convertir esto en una Intención que pueda usar. Esto se toma al abrir MyTracks manualmente.

Gracias por tu ayuda

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)
Author: Steve Haley, 2010-05-06

20 answers

En primer lugar, el concepto de "aplicación" en Android es un poco extendido.

Una aplicación - técnicamente un proceso - puede tener múltiples actividades, servicios, proveedores de contenido y/o oyentes de difusión. Si al menos uno de ellos se está ejecutando, la aplicación está funcionando (el proceso).

Entonces, lo que tienes que identificar es cómo quieres "iniciar la aplicación".

Ok... esto es lo que puedes probar:

  1. Crear una intent con action=MAIN y category=LAUNCHER
  2. Obtenga el PackageManager del contexto actual usando context.getPackageManager
  3. packageManager.queryIntentActivity(<intent>, 0) donde la intención tiene category=LAUNCHER, action=MAIN o packageManager.resolveActivity(<intent>, 0) para obtener la primera actividad con main / launcher
  4. Obtenga el ActivityInfo que le interesa
  5. Desde el ActivityInfo, obtener el packageName y name
  6. Finalmente, crear otra intención con con category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) y setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  7. Finalmente, context.startActivity(newIntent)
 140
Author: Gaurav Vaish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-13 21:39:38

Tengo trabajo como este,

/** 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;
    }
}

Ejemplo de uso:

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

Espero que ayude a alguien.

 224
Author: Anonsage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 15:21:26
    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);

EDITAR:

Como se sugiere en los comentarios, añádase una línea antes de startActivity(intent);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 95
Author: zawhtut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 21:32:40

Si ya tiene el nombre del paquete que desea activar, puede usar el siguiente código que es un poco más genérico:

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

Encontré que funciona mejor para los casos en los que la actividad principal no se encontró por el método regular de iniciar la actividad PRINCIPAL.

 38
Author: Muzikant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-20 16:05:12

Este es el código de mi base de solución en la solución MasterGaurav:

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();
    }
}
 13
Author: inversus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-25 09:18:42

Usando la solución de inversus, expandí el fragmento con una función, que se llamará cuando la aplicación deseada no esté instalada en este momento. Así que funciona como: Ejecutar la aplicación por nombre de paquete. Si no lo encuentra, abra Android market-Google play para este paquete .

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);
}

Y se usa así:

startApplication("org.teepee.bazant");
 10
Author: peter.bartos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-27 15:13:40

Abra la aplicación si existe, o abra la aplicación Play Store para instalarla:

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)));
        }
    }
}
 6
Author: Flinbor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-07 17:23:16

Usa esto:

    PackageManager pm = getPackageManager();
    Intent intent = pm.getLaunchIntentForPackage("com.package.name");
    startActivity(intent);
 5
Author: Swetha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-02 06:18:39

Para iniciar otra actividad de aplicación desde mi actividad de aplicación. Está funcionando bien para mí.

El siguiente código funcionará si la otra aplicación ya está instalada en su teléfono, de lo contrario, no es posible redirigir una aplicación a otra app.So asegúrese de que su aplicación se haya iniciado o no

Intent intent = new Intent();
intent.setClassName("com.xyz.myapplication", "com.xyz.myapplication.SplashScreenActivity");
startActivity(intent);
 4
Author: KCN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-13 07:49:04

/ / Esto funciona en 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;
}
 3
Author: Anil Kongovi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-28 11:41:27

Dado que las aplicaciones no pueden cambiar muchas de las configuraciones del teléfono, puede abrir una actividad de configuración al igual que otra aplicación.

Mire la salida de LogCat después de modificar la configuración manualmente:

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

Luego use esto para mostrar la página de configuración de su aplicación:

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
}
 2
Author: Tary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-18 14:40:17

Para el nivel de API 3+, nada más que una línea de código:

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

Devuelve un intento de lanzamiento de CATEGORY_INFO (aplicaciones sin actividad de lanzador, fondos de pantalla, por ejemplo, a menudo usan esto para proporcionar información sobre la aplicación) y, si no lo encuentra, devuelve el CATEGORY_LAUNCH del paquete, si existe.

 2
Author: Renascienza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-26 13:09:45

Si está intentando iniciar un SERVICIO en lugar de una actividad, esto funcionó para mí:

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

Si usas la intent.setComponent(... como se mencionó en otras respuestas, puede obtener una advertencia de "Intenciones implícitas con startService no son seguras".

 2
Author: Dunc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-01 10:29:31

Alternativamente, también puede abrir la intent desde su aplicación en la otra aplicación con:

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

Donde uri es el vínculo profundo con la otra aplicación

 2
Author: electrobabe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-10 07:08:52

Utilice lo siguiente:

String packagename = "com.example.app";
startActivity(getPackageManager().getLaunchIntentForPackage(packagename));
 2
Author: user6765242,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-01 09:06:19

Iniciar una aplicación desde otra aplicación en Android

  Intent launchIntent = getActivity.getPackageManager().getLaunchIntentForPackage("com.ionicframework.uengage");
        startActivity(launchIntent);
 2
Author: Ashutosh Srivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 12:19:23

Si quieres abrir otra aplicación y no está instalada puedes enviarla a Google App Store para descargarla

  1. Primero cree el método openOtherApp por ejemplo

    public static boolean openApp(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.- Uso

openOtherApp(getApplicationContext(), "com.packageappname");
 1
Author: Vladimir Salguero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-23 22:34:44

Pruebe este código, espero que esto le ayude. Si este paquete está disponible, se abrirá la aplicación o bien se abrirá play store para descargas

    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)));
                }
            }
 0
Author: AMAN SINGH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-20 18:09:59

Puede usar este comando para encontrar los nombres de paquetes instalados en un dispositivo:

adb shell pm list packages -3 -f

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

 0
Author: JDPMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-02 19:31:07
Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("package_name","package_name.class_name"));
        intent.putExtra("grace", "Hi");
        startActivity(intent);
 -3
Author: Manzer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-16 14:46:01