Skip to content

Instantly share code, notes, and snippets.

@achinverma
Forked from zakelfassi/android_shortcut.java
Created January 7, 2017 05:10
Show Gist options
  • Save achinverma/fd1962b51b48c40af5301a0fa64d405e to your computer and use it in GitHub Desktop.
Save achinverma/fd1962b51b48c40af5301a0fa64d405e to your computer and use it in GitHub Desktop.
Create android app shortcut programatically
// Note that a shortcut is created automagically if the app is installed via Play store.
// Change "APP_NAME" by your app name. *MrObvious*
/*Manifest file - add this */
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
/* MainActivity.java */
public class MainActivity ... {
...
private SharedPreferences appSettings;
...
protected void onCreate(Bundle savedInstanceState) {
...
...
appSettings = getSharedPreferences("APP_NAME", MODE_PRIVATE);
// Make sure you only run addShortcut() once, not to create duplicate shortcuts.
if(!appSettings.getBoolean("shortcut", false)) {
addShortcut();
}
}
private void addShortcut() {
//Adding shortcut for MainActivity
//on Home screen
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, "APP_NAME");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent.putExtra("duplicate", false);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
SharedPreferences.Editor prefEditor = appSettings.edit();
prefEditor.putBoolean("shortcut", true);
prefEditor.commit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment