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

时间:2018-03-27 22:02:24

标签: java android react-native widget android-widget

我有以下代码: 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

1 个答案:

答案 0 :(得分:0)

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

在Oreo设备上,我们有一个新的固定小部件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

的文档