Programmatically add widget to home screen in Android

I developed an application for the Android widget and its work is excellent. Now my client asks that when the user installed this application, it should automatically be placed on the top desktop. How to do it? please help me.

+4
source share
2 answers

Starting with Android O, in your application you can create a request for the system to bind the widget to a supported launcher.

  • Create a widget in the application manifest file
  • Call requestPinAddWidget () method

. : https://developer.android.com/preview/features/pinning-shortcuts-widgets.html

+1

http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/:

Android com.android.launcher.action.INSTALL_SHORTCUT, . MainActivity HelloWorldShortcut.

INSTALL_SHORTCUT android manifest xml.

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

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, "HelloWorldShortcut");
    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);
}

, shortcutIntent, . EXTRA_SHORTCUT_INTENT. . , EXTRA_SHORTCUT_NAME , EXTRA_SHORTCUT_ICON_RESOURCE. . , , , android: exported = "true" .

:

, Android Intent (UNINSTALL_SHORTCUT) . , .

. Android manifest xml.

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

removeShortcut() addShortcut(). , removeShortcut UNINSTALL_SHORTCUT.

private void removeShortcut() {

    //Deleting 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, "HelloWorldShortcut");

    addIntent
            .setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}

-1

Source: https://habr.com/ru/post/1534762/


All Articles