So I have a home screen widget in my app and clicking this widget opens a single instance activity, this activity opens a dialog box consisting of a few radio options. The user selects a radio option and the activity closes. I want to send the option which the user selected back to the home screen widget, and I can't figure out a way to do this. Things I have thought of:
- using startActivityForResult: This won't work cause I am using a pending intent and setOnClickPendingIntent method to set an on click listener to trigger that pending intent
- saving the new radio choice using sharedPreferences, accessing the value in the widget: This won't work cause the onUpdate method of this widget isn't called when the dialog box activity ends, so there is no way for me to fetch the latest value stored in sharedPreferences when the activity ends.
The code for the widget:
class WidgetProvider : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
appWidgetIds.forEach { widgetId ->
val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
val pendingIntent = PendingIntent.getActivity(context, 0, Intent(context, TimeTypeDialog::class.java) , PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
setOnClickPendingIntent(R.id.timeType, pendingIntent)
}
appWidgetManager.updateAppWidget(widgetId, views)
}
}
}
The code pertaining to the activity started by the widget:
class TimeTypeDialog : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("debugging", "alert triggered")
val alertDialog = AlertDialog.Builder(this)
// title of the alert dialog
alertDialog.setTitle("Choose an Item")
val listItems = arrayOf("Android Development", "Web Development", "Machine Learning")
alertDialog.setSingleChoiceItems(listItems, -1
) { _, which ->
Log.d("debugging", listItems[which])
finish()
}
alertDialog.setOnCancelListener { dialogInterface -> finish() }
alertDialog.create()
alertDialog.show()
super.onCreate(savedInstanceState)
}
}
How am I supposed to send the selected data back to the widget?