Reputation:
I have the following code: https://github.com/lucas-kejan/React-Widget/blob/master/android/app/src/main/java/com/androidwidgetpoc/BackgroundTaskBridge.java#L26
That should add the widget to the android home screen, when the method is called, but it does not work.
It gives me the following error:
lenght = 0; index = 0.
BackgroundTaskBridge.java:31
Upvotes: 2
Views: 2827
Reputation: 1746
Well, let's take a look on things that you want to do - let user to pick widget and take a place in launcher. If you want to make it pre Oreo devices, where is no api for following action. So to run PICK_APPWIDGET intent you need appWidgetId. The only way to get appWidgetId by yourself is to bind id to appWidgetInfo, but this thing requires BIND_APPWIDGET permission, which is only available to system. So on pre Oreo device it's impossible to make a thing that you want (of course if you're not a system app).
On Oreo devices we have a new pinning widget api.
AppWidgetManager mAppWidgetManager =
context.getSystemService(AppWidgetManager.class);
AppWidgetProviderInfo myWidgetProviderInfo = new AppWidgetProviderInfo();
ComponentName myProvider = myWidgetProviderInfo.provider;
if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
// Create the PendingIntent object only if your app needs to be notified
// that the user allowed the widget to be pinned. Note that, if the pinning
// operation fails, your app isn't notified.
Intent pinnedWidgetCallbackIntent = new Intent( ... );
// Configure the intent so that your app's broadcast receiver gets
// the callback successfully. This callback receives the ID of the
// newly-pinned widget (EXTRA_APPWIDGET_ID).
PendingIntent successCallback = PendingIntent.createBroadcast(context, 0,
pinnedWidgetCallbackIntent);
mAppWidgetManager.requestPinAppWidget(myProvider, null,
successCallback.getIntentSender());
}
Don't forget that it requires api version 26+. You can check documentation of following api here
Upvotes: 1