Create an application shortcut in an onLogClickListener?

0

The code below creates a shortcut on the device's home screen, but by clicking this shortcut, it returns me an error "The app is not installed" How to solve? I would like this mainactivity to be opened with a specific parameter, to trigger an event when opened by this created shortcut.

Here is the code used:

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

fabEmergencia.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        createShortCut();
        return true;
    }
});


private void createShortCut() {
    Intent shortcutIntent = new Intent(activity,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, "YourAppName");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(activity, R.drawable.ic_launcher));
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    activity.sendBroadcast(addIntent);
}
    
asked by anonymous 05.07.2017 / 22:51

1 answer

1

Usually when I use it, I do it this way:

public void criarAtalho(){
    // cria intent para criar atalho
    Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    // nega atalho repetido
    shortcutintent.putExtra("duplicate", false);
    // define um nome para o atalho
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Nome do atalho");
    // define do icone do atalho
    Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher);
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
    // define atividade que será iniciada ao clicar no atalho
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , MainActivity.class));
    // envia broadcast
    sendBroadcast(shortcutintent);
}

Then in the setOnLongClickListener method, you do this below:

fabEmergencia.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        criarAtalho();
        return true;
    }
});

And as you mentioned before, you should give permission on AndroidManifest . See:

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

Below is how your <activity> is in AndroidManifest :

<activity 
    android:name=".MainActivity" 
    android:label="@string/title"
    .
    .
    .
    >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />    
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
    
06.07.2017 / 03:08