How can I listen to Intent.ACTION

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.

链接地址: http://www.djcxy.com/p/50586.html

上一篇: 小部件导致“应用程序未安装”错误

下一篇: 我如何收听Intent.ACTION