Question

I have developed a widget that has an ImageButton that toggles the Auto-Rotate setting. Everything works fine and the setting toggles when the button is pressed. The problem is that I do not know how to listed to Intent.ACTION_CONFIGURATION_CHANGED in order for the button to change it's state if the setting is enabled/disabled from other sources than my widget.

I have gone through the documentation and I know that I can't register the intent-filter action android.intent.action.CONFIGURATION_CHANGED in the Manifest and this intent-filter must be registered dynamically using Context.registerReceiver (BroadcastReceiver receiver, IntentFilter filter).

I have tried creating a new class that extends BroadcastReceiver and then registering the receiver in the onUpdate() method, but it does not work.

Here is the code I've tried:

The BroadcastReceiver class:

public class ConfigurationIntentReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
    if(intent.getAction().equals("android.intent.action.CONFIGURATION_CHANGED")){
        if  (android.provider.Settings.System.getInt(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
            remoteViews.setImageViewResource(R.id.widget_autorotate, R.drawable.ic_widget_autorotate_on);
        } else {
            remoteViews.setImageViewResource(R.id.widget_autorotate, R.drawable.ic_widget_autorotate_off);
        }   
        WidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews);

    }
}
}

And here is the AppWidgetProvider class:

public class WidgetProvider extends AppWidgetProvider {



@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    context.getApplicationContext().registerReceiver(new ConfigurationIntentReceiver(), new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    pushWidgetUpdate(context, remoteViews);
}

The ConfigurationIntentReceiver component has not been declared in the Manifest as per Android's documentation.

If anyone can point me in the right direction, I would really appreciate it.

No correct solution

OTHER TIPS

You can only register to such an intent, so you will have to do it via a foreground service (or Activity, but those die, and you don't want to have the widget to stop getting it).

https://developer.android.com/reference/android/content/Intent.html#ACTION_CONFIGURATION_CHANGED

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top