How to add a widget to the Android home screen from my app?

Looks like Dalvik Droid's links are updated again, the newest link is at requestPinAppWidget

Example: in MainActivity.java:

private void requestToPinWidget(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AppWidgetManager appWidgetManager =
                    getSystemService(AppWidgetManager.class);
            ComponentName myProvider =
                    new ComponentName(this, AppWidget.class);
            assert appWidgetManager != null;
            if (appWidgetManager.isRequestPinAppWidgetSupported()) {
                Intent pinnedWidgetCallbackIntent = new Intent(this, MainActivity.class);
                PendingIntent successCallback = PendingIntent.getBroadcast(this, 0,
                        pinnedWidgetCallbackIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                appWidgetManager.requestPinAppWidget(myProvider, null, successCallback);
            }
        }
    }

Any anywhere in you code you have call requestToPinWidget() to prompt to see if the user wants to add it to the desktop.

Only thing is that this will not add to user's home screen, it will be appended to the page where you see all the apps:

Demo for Android Widget Prompt


It is not possible from a app to place a widget in the home screen. Only the home screen can add app widgets to the home screen.

similar links link1, link2, link3

But you can offer user to pick widget from widgetpicker.

    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetID);
    startActivityForResult(pickIntent, KEY_CODE);

This was answered a long time ago, but in case anyone stumbles upon this question I thought I should provide an up-to-date answer.

As of Android O (API 26), you can now pin widgets to the user's launcher from your app!

Simply create the widget in your app's AndroidManifest file and use AppWidgetManager to request that the widget be pinned to the launcher. Note that it is up to the launcher to support this feature, so you must call AppWidgetManager's isRequestPinAppWidgetSupported() method before requesting to pin it.

Here's some documentation from Google that goes into more detail: https://developer.android.com/preview/features/pinning-shortcuts-widgets.html#widgets

Hope this helps!

Edit: It looks like the documentation pages have changed since I posted this answer. Here is a more helpful link that gives a code example of how to pin a widget to a launcher: https://developer.android.com/guide/topics/appwidgets/#Pinning