我在主屏幕小工具中有一个列表视图,我想在点击项目时启动一个待定Intent。我参考了这一点,为每个列表项目设置了一个fillInIntent,然后设置了一个待定Intent模板,该模板触发小工具的广播接收器:
class WidgetProvider : HomeWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
appWidgetIds.forEach { widgetId ->
val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
val todosStr = widgetData.getString("todos", "null")
val todos = ArrayList<HashMap<String, Any>>()
val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()
if(todosStr != "null"){
val jObj = JSONObject(todosStr)
val jsonArry = jObj.getJSONArray("todos")
for (i in 0 until jsonArry.length()) {
val todo = HashMap<String, Any>()
val obj = jsonArry.getJSONObject(i)
todo["id"] = obj.getInt("id")
todos.add(todo)
val view = RemoteViews(context.packageName, R.layout.each_todo).apply {
setTextViewText(R.id.each_todo_container_text, todo["taskName"].toString())
val fillInIntent = Intent().apply {
Bundle().also { extras ->
extras.putInt("todo_id", todo["id"].toString().toInt())//this isn't working for some reason
putExtras(extras)
}
}
Log.d("debugging", "id received is ${todo["id"].toString()}" )
setOnClickFillInIntent(R.id.each_todo_container_text, fillInIntent)
}
todosRemoteView.addItem(todo["id"].toString().toInt().toLong(), view)
}
}
setRemoteAdapter(
R.id.todos_list,
todosRemoteView
.build()
)
val pendingIntentx: PendingIntent = Intent(
context,
WidgetProvider::class.java
).run {
PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE or Intent.FILL_IN_COMPONENT)
}
setPendingIntentTemplate(R.id.todos_list, pendingIntentx)
}
appWidgetManager.updateAppWidget(widgetId, views)
}
}
override fun onReceive(context: Context?, intent: Intent?) {
val viewIndex: Int = intent!!.getIntExtra("todo_id", 0)
Log.d("debugging", "an item is clicked $viewIndex")
//the default value gets used, which means that the receiver isn't receiving the intent data
super.onReceive(context, intent)
}
}
问题是接收方没有接收到放在fillInIntent中的数据,默认值0被最后一条语句打印出来。我也试着将FILL_IN_COMPONENT标志设置为建议的here,但这不起作用。我哪里出错了?
1条答案
按热度按时间bejyjqdl1#
只要把
PendingIntent.FLAG_IMMUTABLE or Intent.FILL_IN_COMPONENT
替换成PendingIntent.FLAG_MUTABLE
就行了,我觉得是IMMUTABLE
让intent不能改,结果就得不到多余的。