I'm trying to create such a widget for my app that when it is clicked, it will open the app and send id of the clicked widget to the app.
The following code works with a single widget. But if I create several widgets, say with id:s 2, 3 and 4 - then clicking any widget always sends id of the latest created widget (i.e. 4 in this case) instead of the id of the widget which was clicked.
Widget code:
class NewAppWidget : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
}
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
val views = RemoteViews(context.packageName, R.layout.new_app_widget)
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(Intent.EXTRA_UID, appWidgetId.toString())
val pendingIntent: PendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
views.setOnClickPendingIntent(R.id.root_layout, pendingIntent)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
Widget XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/light_blue_50">
<TextView
android:id="@+id/appwidget_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="24sp" />
</RelativeLayout>
Problem is told by this snippet from PendingIntent documentation:
A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen.
Removing PendingIntent.FLAG_UPDATE_CURRENT
from the code doesn't fix this, it just changes which id is used by all widgets (seems to be id of first widget instead of last).
The solution is to make PendingIntent
:s different, for example by giving different requestCode
for each:
val pendingIntent: PendingIntent = PendingIntent.getActivity(
context,
appWidgetId, // <- different code for each
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)