val appWidgetManager = AppWidgetManager.getInstance(requireContext())
val provider = ComponentName(requireContext(), SimpleNotesWidget::class.java)
if (!appWidgetManager.isRequestPinAppWidgetSupported) {
showToast("Pin app widget is not supported")
return
}
val pendingIntent = WidgetReceiver.getPendingIntent(requireContext(), listId)
appWidgetManager.requestPinAppWidget(provider, Bundle(), pendingIntent)
接收方:
class WidgetReceiver : BroadcastReceiver() {
companion object {
const val WIDGET_NAME = "WIDGET_NAME"
fun getPendingIntent(context: Context, checkListId: String): PendingIntent {
val callbackIntent = Intent(context, WidgetReceiver::class.java)
val bundle = Bundle()
bundle.putString(WIDGET_NAME, checkListId)
callbackIntent.putExtras(bundle)
return PendingIntent.getBroadcast(
context,
checkListId.hashCode(),
callbackIntent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE
else PendingIntent.FLAG_UPDATE_CURRENT
)
}
}
override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) {
return
}
val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
if (widgetId == -1) {
return
}
val listId = intent.getStringExtra(WIDGET_NAME)
val widgetPreferences = WidgetPreferences(context)
widgetPreferences.setWidgetValues(widgetId, listId!!)
context.updateWidgets()
}
}
1条答案
按热度按时间bfhwhh0e1#
我没有找到自己的解决办法,这样我就设法解决了。
接收方:
配置活动: