CodeByte

Write your code smartly

Monthly Archives: January 2014

Android: Create Shortcut Icon

Here is how you can create a shortcut icon on Android device

try
{
//checking the shortcut icon is created or not
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//repeat to create is forbidden
shortcutintent.putExtra("duplicate", false);
//set the name of shortCut
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "MinhaConexao");
//set icon
Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.shortcut);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//set the application to launch when you click the icon
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , MinhaConexao.class));
//sendBroadcast,done
sendBroadcast(shortcutintent);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}

The shared preferences are in application memory having a life cycle equal to application life cycle. Calling the shortcut creating code every time will popup a system Toast (irritating) which cannot be controlled. Making use of Shared Preferences can help you log the status of shortcut icon. If it is the first time application is launched then shortcut creating code will be executed as according to the code above else create the icon. The icon will appear on the main screen of the Android device.

Don’t forget to add permissions in AndroidManifest.xml

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

Happy Coding !

Design a site like this with WordPress.com
Get started