React-native 添加一个小部件到 android 主屏幕

React-native add a widget to the android home screen

我有以下代码: https://github.com/lucas-kejan/React-Widget/blob/master/android/app/src/main/java/com/androidwidgetpoc/BackgroundTaskBridge.java#L26

当调用该方法时,应该将小部件添加到 android 主屏幕,但它不起作用。

它给我以下错误:

lenght = 0; index = 0.
BackgroundTaskBridge.java:31

好吧,让我们来看看您想做的事情 - 让用户选择小部件并在启动器中占据一席之地。如果你想让它成为 pre Oreo 设备,这里没有 api 用于后续操作。因此,为了 运行 PICK_APPWIDGET 意图,您需要 appWidgetId。自己获取appWidgetId的唯一方法就是将id绑定到appWidgetInfo上,但是这个东西需要BIND_APPWIDGET权限,只有system可以使用。所以在 Oreo 之前的设备上不可能做出你想要的东西(当然如果你不是系统应用程序)。

在 Oreo 设备上,我们有一个新的 pinning 小部件 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());
}

不要忘记它需要 api 版本 26+。您可以查看以下 api here

的文档