Last active
July 16, 2024 09:20
-
-
Save Ayush783/edb36365343b2fa58c92b4c8c944a633 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListViewAppWidgetProvider : HomeWidgetProvider() { | |
... | |
/// Capture the intent, replace current view with a loader and trigger WorkRequest | |
override fun onReceive(context: Context?, intent: Intent?) { | |
super.onReceive(context, intent) | |
val action = intent?.action | |
if (action == "com.example.listview_app_widget.refresh") { | |
val appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) | |
val loader = RemoteViews(context!!.packageName, R.layout.listview_widget_loader) | |
val appWidgetManager = AppWidgetManager.getInstance(context) | |
appWidgetManager.updateAppWidget(appWidgetId, loader) | |
initiateWorkRequest(context!!, appWidgetId) | |
} | |
} | |
private fun initiateWorkRequest(context: Context, id: Int) { | |
... | |
} | |
companion object { | |
fun createListView(context: Context, widgetId: Int, data: String): RemoteViews { | |
... | |
// set pending intent for refresh button, this intent will be fired whenever user taps on the button | |
views.setOnClickPendingIntent(R.id.refresh_button, getRefreshPendingIntent(context, widgetId)) | |
return views | |
} | |
... | |
/// Generate refresh pending intent | |
private fun getRefreshPendingIntent(context: Context, widgetId: Int): PendingIntent { | |
// set target receiver class as your Provider class | |
val refreshIntent = Intent(context, ListViewAppWidgetProvider::class.java) | |
// specify your custom action | |
refreshIntent.action = "com.example.listview_app_widget.refresh" | |
// Add widget id to intent | |
refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) | |
var flags = PendingIntent.FLAG_UPDATE_CURRENT | |
if (Build.VERSION.SDK_INT >= 23) { | |
flags = flags or PendingIntent.FLAG_IMMUTABLE | |
} | |
return PendingIntent.getBroadcast(context, 0, refreshIntent, flags) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment