2

我在我的应用程序中使用 DefaultSharedPreferences。我想创建一个小部件来切换我的偏好之一。我做了小部件。它正在做我想做的事,但是如果我从其他活动中更改此偏好,小部件不会更新。

public class WidgetReceiver extends AppWidgetProvider {
    public static String ACTION_WIDGET_TOGGLE = "ActionToggle";

    public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ) {
        RemoteViews remoteViews = new RemoteViews( context.getPackageName(), R.layout.widget_on_off );

        boolean state = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( "serviceOn", true );
        if( state )
            remoteViews.setImageViewResource( R.id.widgetImage, R.drawable.ic_widget );
        else
            remoteViews.setImageViewResource( R.id.widgetImage, R.drawable.ic_widget_dark );

        Intent intent = new Intent( context, WidgetReceiver.class );
        intent.setAction( ACTION_WIDGET_TOGGLE );
        PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, intent, 0 );
        remoteViews.setOnClickPendingIntent( R.id.widgetImage, pendingIntent );

        appWidgetManager.updateAppWidget( appWidgetIds, remoteViews );
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if( AppWidgetManager.ACTION_APPWIDGET_DELETED.equals( action )) {
            final int appWidgetId = intent.getExtras().getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID );
            if ( appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID ) {
                this.onDeleted( context, new int[] { appWidgetId });
            }
        } else {
            if( intent.getAction().equals( ACTION_WIDGET_TOGGLE )) {
                boolean state = !PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( "serviceOn", true );
                Editor editor = PreferenceManager.getDefaultSharedPreferences( context ).edit();
                editor.putBoolean( "serviceOn", state );
                editor.commit();
                ComponentName thisAppWidget = new ComponentName( context.getPackageName(), WidgetReceiver.class.getName());
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance( context );
                int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);
                onUpdate( context, appWidgetManager, appWidgetIds);
            }
            super.onReceive(context, intent);
        }
    }
}

怎么样,让它发挥作用?谢谢。

4

1 回答 1

1

如果您更改某些活动的偏好,则小部件没有理由更新(因为它的 onUpdate() 函数被调用)。您应该做的是从更改偏好的活动发送意图,该意图将触发您的小部件以显示新数据。此处解释了发送此类意图。

于 2012-07-13T14:28:17.407 回答