Domanda

Quello che voglio fare è:

1) Sono dentro un'attività, ci sono 2 pulsanti. Se faccio clic sul primo, viene creata una scorciatoia nella mia schermata principale. La scorciatoia aperta un html Pagina che è stata precedentemente scaricata, quindi voglio che usi il browser predefinito ma non voglio usare Internet perché ho già la pagina.

2) Il secondo pulsante crea un altro collegamento che avvia un'attività. E voglio passare all'attività alcuni argomenti extra (come stringhe per esempio) ...........

Quelle cose sono possibili? Ho trovato qualche link e alcune domande simili come Android: esiste un modo di programmazione per creare un collegamento Web nella schermata principale

Sembrano essere la risposta alla mia domanda, ma qualcuno mi ha detto che questo codice non funzionerà su tutti i dispositivi e questo è deprecato e che ciò che voglio fare non è possibile .......

Questa tecnica non è raccomandata. Questa è un'implementazione interna, non parte dell'SDK Android. Non funzionerà su tutte le implementazioni della schermata domestica. Potrebbe non funzionare su tutte le versioni passate di Android. Potrebbe non funzionare nelle versioni future di Android, poiché Google non è obbligato a mantenere interfacce non documentate interne. Si prega di non usarlo

Cosa significa implementazione interna? È quel codice affidabile o no ..... aiutami pls .....

È stato utile?

Soluzione

Il codice di esempio utilizza interfacce non documentate (autorizzazione e intento) per installare un collegamento. Come ti ha detto "qualcuno", questo potrebbe non funzionare su tutti i telefoni e potrebbe rompere le future versioni di Android. Non farlo.

Il modo corretto è ascoltare una richiesta di scelta rapida dalla schermata principale, con un filtro intento come così nel tuo manifest:

<activity android:name=".ShortCutActivity" android:label="@string/shortcut_label">
  <intent-filter>
    <action android:name="android.intent.action.CREATE_SHORTCUT" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

Quindi nell'attività che riceve l'intento, si crea un intento per il tuo collegamento e lo restituisci come risultato dell'attività.

// create shortcut if requested
ShortcutIconResource icon =
    Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

Intent intent = new Intent();

Intent launchIntent = new Intent(this,ActivityToLaunch.class);

intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, someNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

setResult(RESULT_OK, intent);

Altri suggerimenti

Ho sviluppato un metodo di seguito per la creazione dell'icona di scelta rapida su Android Homesreen [testato sulla mia app]. Chiamalo solo.

private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}

Non dimenticare di modificare il nome dell'attività, la risorsa icona e l'autorizzazione.

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

Codice felice !!!

Modificare:

Per un problema duplicato, la prima opzione è quella di aggiungere la riga sotto nel codice, altrimenti ne crea una nuova ogni volta.

addIntent.putExtra("duplicate", false);

La seconda opzione è prima disinstallare l'icona di collegamento dell'app e quindi installarla se la prima opzione non ha funzionato.

The com.android.launcher.action.INSTALL_SHORTCUT broadcast no longer has any effect since android oreo. LINK

If you want to support all android versions, especially android 8.0 or oreo and newer, use the code below to create shortcut:

public static void addShortcutToHomeScreen(Context context)
{
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context))
    {
        ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                .setIntent(new Intent(context, YourActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
                .setShortLabel("Test")
                .setIcon(IconCompat.createWithResource(context, R.drawable.ic_launcher))
                .build();
        ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
    }
    else
    {
        // Shortcut is not supported by your launcher
    }
}

Add permission in manifest file:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

I improved a little bit a solution above. Now it saves in preferences whether a shortcut was already added and doesn't add it in new launches of an app if user deleted it. This also saves a little bit time, since the code to add an existing shortcut doesn't run anymore.

final static public String PREFS_NAME = "PREFS_NAME";
final static private String PREF_KEY_SHORTCUT_ADDED = "PREF_KEY_SHORTCUT_ADDED";


// Creates shortcut on Android widget screen
private void createShortcutIcon(){

    // Checking if ShortCut was already added
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    boolean shortCutWasAlreadyAdded = sharedPreferences.getBoolean(PREF_KEY_SHORTCUT_ADDED, false);
    if (shortCutWasAlreadyAdded) return;

    Intent shortcutIntent = new Intent(getApplicationContext(), IntroActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "YourAppName");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);

    // Remembering that ShortCut was already added
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(PREF_KEY_SHORTCUT_ADDED, true);
    editor.commit();
}

Starting from Android O, this is the way to create a shortcut:

            if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
                final ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

                ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder(context, shortcutId)
                        .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
                        .setShortLabel(label)
                        .setIntent(new Intent(context, MainActivity.class).setAction(Intent.ACTION_MAIN))
                        .build();
                shortcutManager.requestPinShortcut(pinShortcutInfo, null);
            }

It has a lot of limitations, sadly:

  1. Requires the user to accept adding it.
  2. Can't be added/removed in the background.
  3. You are supposed to be able to update it, but to me it didn't work.
  4. Won't be removed if the targeted app is removed. Only the one which created it.
  5. Can't create the icon based on a resource of the targeted app, except if it's of the current app. You can do it from a bitmap though.

For pre-Android O, you can use ShortcutManagerCompat to create new shortcuts too, without any of those limitations.

Since API level 26, using com.android.launcher.action.INSTALL_SHORTCUT is deprecated. The new way of creating shortcuts are using ShortcutManager.

It mentions that there are 3 kinds of shortcuts, static, dynamic and pinned. Based on your requirements, you can choose to create them.

@Siddiq Abu Bakkar Answer works. But in order to prevent creating shortcut every time app launches use shared Preferences.

final String PREF_FIRST_START = "AppFirstLaunch";
 SharedPreferences settings = getSharedPreferences(PREF_FIRST_START, 0);
    if(settings.getBoolean("AppFirstLaunch", true)){

        // record the fact that the app has been started at least once
        settings.edit().putBoolean("AppFirstLaunch", false).commit();
        ShortcutIcon();

    }
final Intent shortcutIntent = new Intent(this, SomeActivity.class);

final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// Sets the custom shortcut's title
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// Set the custom shortcut icon
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
// add the shortcut
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);
public static void addShortcutToHomeScreen(Context context)
{
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context))
    {
        ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                .setIntent(new Intent(context, YourActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
                .setShortLabel("Test")
                .setIcon(IconCompat.createWithResource(context, R.drawable.ic_launcher))
                .build();
        ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
    }
    else
    {
        // Shortcut is not supported by your launcher
    }
}

I've used it, but some devices on the home screen adds 2 icons. I did not understand??

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top