Roshan
Roshan

Reputation: 290

Android: Can I check if a shortcut already exists?

In Android, is it possible to check whether an application shortcut already exists?

Thanks, Roshan

Upvotes: 0

Views: 5045

Answers (2)

Chirag Gandhi
Chirag Gandhi

Reputation: 27

// 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(), MainActivity.class);
        shortcutIntent.setAction(Intent.ACTION_MAIN);

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

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

Upvotes: 2

Manitoba
Manitoba

Reputation: 8702

You cannot detect that kind of things.

But if you need to add a shortcut on the Home screen, you could probably do something like that:

  • Uninstall existing shortcut (if any)

    intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(intent);
    
  • Install a new shortcut

    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(intent);
    

Just don't forget to add this permission in your Manifest:

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

Upvotes: 4

Related Questions