You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API 35下notifyAppWidgetViewDataChanged等Widget废弃方法的替代方案

替换API 35中废弃的Widget数据管理方法

1. setRemoteAdapter(Int, Intent!) 的替代方案

API 35开始官方弃用了通过Intent直接绑定RemoteViewsService的写法,转而推荐用**setRemoteAdapter(ComponentName, RemoteViews.RemoteAdapter!)**,通过RemoteViews.RemoteAdapter.Builder构建适配器实例,这种方式更明确,也避免了隐式Intent可能带来的组件匹配问题。

旧代码(废弃写法):

val intent = Intent(context, MyRemoteViewsService::class.java)
remoteViews.setRemoteAdapter(R.id.widget_list, intent)

新代码(API 35+适配):

val remoteAdapter = RemoteViews.RemoteAdapter.Builder(
    context,
    ComponentName(context, MyRemoteViewsService::class.java)
).build()
remoteViews.setRemoteAdapter(R.id.widget_list, remoteAdapter)

要是需要给RemoteViewsService传额外参数,直接在Builder里调用setIntent()就行:

val intent = Intent(context, MyRemoteViewsService::class.java).apply {
    putExtra("EXTRA_FILTER", "today")
}
val remoteAdapter = RemoteViews.RemoteAdapter.Builder(
    context,
    ComponentName(context, MyRemoteViewsService::class.java)
).setIntent(intent)
.build()
remoteViews.setRemoteAdapter(R.id.widget_list, remoteAdapter)

2. notifyAppWidgetViewDataChanged(Int, Int) 的替代方案

原来的方法只能更新单个Widget指定视图的数据,API 35提供了更灵活的重载方法,分两种场景:

场景1:更新单个/多个指定Widget

用notifyAppWidgetViewDataChanged(IntArray, Int, Bundle?),传入Widget ID数组、目标视图ID,可选的Bundle还能给RemoteViewsService传更新相关的额外信息:

旧代码(废弃写法):

appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list)

新代码(API 35+适配):

// 无额外参数的情况
appWidgetManager.notifyAppWidgetViewDataChanged(intArrayOf(appWidgetId), R.id.widget_list, null)

// 需要传额外参数时
val updateInfo = Bundle().apply {
    putBoolean("FORCE_REFRESH", true)
}
appWidgetManager.notifyAppWidgetViewDataChanged(intArrayOf(appWidgetId), R.id.widget_list, updateInfo)

场景2:更新所有同类型Widget

如果要更新该WidgetProvider下的所有实例,直接传ComponentName就行:

appWidgetManager.notifyAppWidgetViewDataChanged(
    ComponentName(context, MyWidgetProvider::class.java),
    R.id.widget_list,
    null
)

兼容旧版本的小技巧

如果你的App需要兼容API 35以下的版本,直接通过版本判断分支处理即可:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
    appWidgetManager.notifyAppWidgetViewDataChanged(intArrayOf(appWidgetId), R.id.widget_list, null)
} else {
    appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list)
}

内容的提问来源于stack exchange,提问作者m.i.n.a.r.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:13:23