1 year ago

#367888

test-img

Arrowsome

AppWidgetProvider Listen for System Setting Changes

I have a widget that user can see the current status of an accessibility service and by clicking it, the accessibly service setting opens.

class MyAppWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetIds: IntArray?
    ) {
        context ?: return
        appWidgetIds?.forEach { widgetId ->
            val pendingIntent: PendingIntent = PendingIntent.getActivity(
                context,
                0,
                Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS),
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
            )
            val remoteViews = RemoteViews(
                context.packageName,
                R.layout.widget_accessibility_setting
            ).apply {
                setOnClickPendingIntent(R.id.setting_switch, pendingIntent)
                setTextViewText(R.id.setting_switch, getStatusLabel(context))
            }

            appWidgetManager?.updateAppWidget(widgetId, remoteViews)
        }
    }
}

The first time that the widget is on the screen, it shows the right label i.e., ON or OFF But after user navigating to setting by clicking on the widget or through system settings, I have no idea how to update the label on the button.

<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:widgetCategory="home_screen"
    android:minWidth="160dp"
    android:minHeight="40dp"
    android:resizeMode="none"
    android:initialLayout="@layout/widget_accessibility_setting">

</appwidget-provider>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/setting_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/accessibility_status_off"/>

</LinearLayout>
<receiver
    android:name="MyAppWidgetProvider"
    android:exported="true">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/widget_info_provider"/>
</receiver>

My question is, how to listen for updates on Android system setting, in my case Accessibility Service status. I thought about updating the widget every a few seconds, but that doesn't look right for this purpose.

android

android-widget

android-appwidget

appwidgetprovider

0 Answers

Your Answer

Accepted video resources