5 Oct 2015

Add application shortcut to the home screen

In this post, I will be discussing about how to create shortcut for Android applications programmatically.
What is Android Shortcut?
Android allows you to create app shortcuts, but you can also create special shortcuts that link directly to screens within an app. For example, shortcuts could link to the Navigation screen in Maps or any screen in the Settings app.
To Create Shortcut
It is very simple to create shortcut programmatically, all you need to do is broadcast the intent with necessary information.
Below code snippet will create the shortcut.
//create shortcuts of app
        Intent HomeScreenShortCut= new Intent(getApplicationContext(),
                MainActivity.class);
        HomeScreenShortCut.setAction(Intent.ACTION_MAIN);
        HomeScreenShortCut.putExtra("duplicate", false);
        //shortcutIntent is added with addIntent
        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, HomeScreenShortCut);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Matrialtest");
        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);

Add add this permission to your manifest

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
That’s all. It’s time to test our code.
Run the application using emulator or device by right clicking on the project >> Run as >> Android application >> Choose emulator or device.

No comments:

Post a Comment