在 Android O 中,如何以编程方式固定小部件快捷方式时对成功回调意图执行任何操作?

0 android

我正在尝试 android O 中给出的 API 来固定小部件快捷方式,如

https://developer.android.com/guide/topics/appwidgets/index.html#Pinning

给出的示例代码是:

AppWidgetManager mAppWidgetManager = context.getSystemService(AppWidgetManager.class);
ComponentName myProvider = new ComponentName(context, MyAppWidgetProvider.class);

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);
}
Run Code Online (Sandbox Code Playgroud)

在上面,如果我尝试通过成功回调意图获取任何活动,即该活动应在固定快捷方式后立即打开,我不会得到它。有人可以帮忙吗?

sig*_*ute 6

我也遇到过这个。您传入的意图应该是为了实现 BroadcastReceiver。

val callbackIntent = Intent(context, DemoWidgetPinnedReceiver::class.java)
val successCallback = PendingIntent.getBroadcast(
       context, 0, callbackIntent, PendingIntent.FLAG_UPDATE_CURRENT)
appWidgetManager.requestPinAppWidget(provider, null, successCallback)
Run Code Online (Sandbox Code Playgroud)

添加成功后,您将在BroadcastReceiver的onReceive方法中获得EXTRA_APPWIDGET_ID,然后您可以保存该ID。您不需要在固定小部件后启动配置活动,因为您可以将要为小部件保存的任何值传递到回调意图中。

我写了一篇关于此的博客文章,还创建了一个演示应用程序,希望这会有所帮助! https://medium.com/wearebase/android-oreo-widget-pinning-in-kotlin-398d529eab28 https://github.com/sigute/WidgetsDemo