8

我有一个小部件,我必须在操作android.media.RINGER_MODE_CHANGED发生时更新小部件。我有以下广播接收器:

public void onReceive(Context context, Intent intent) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
        ComponentName thisWidget = new ComponentName(context.getApplicationContext(), ExampleAppWidgetProvider.class);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        if (appWidgetIds != null && appWidgetIds.length > 0) {
            for (int widgetId : appWidgetIds) {
                RemoteViews remoteViews = new RemoteViews(context
                        .getApplicationContext().getPackageName(),
                        R.layout.widget1);
                appWidgetManager.updateAppWidget(widgetId, remoteViews);
            }
        }
    }

和我的小部件的这个 si 代码

public class ExampleAppWidgetProvider extends AppWidgetProvider {
    DateFormat df = new SimpleDateFormat("hh:mm:ss");

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            //my pudate widget code
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

<receiver android:name=".ExampleAppWidgetProvider" android:label="demo widget">
  <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  </intent-filter>
  <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget1_info" />
</receiver>

所以我的问题是,即使appWidgetManager.updateAppWidget(widgetId, remoteViews);我的广播接收器的指令被执行,小部件内的更新方法也不会被执行。有人知道为什么吗?

4

1 回答 1

19

似乎 AppWidgetProvider 扩展了 BroadcastReceiver 所以这是我的代码:

public class ExampleAppWidgetProvider extends AppWidgetProvider {
    DateFormat df = new SimpleDateFormat("hh:mm:ss");

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        //my update code here
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
        ComponentName thisWidget = new ComponentName(context.getApplicationContext(), ExampleAppWidgetProvider.class);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        if (appWidgetIds != null && appWidgetIds.length > 0) {
            onUpdate(context, appWidgetManager, appWidgetIds);
        }
    }
}

<receiver android:name=".ExampleAppWidgetProvider" android:label="demo widget">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
    </intent-filter>
    <intent-filter>
        <action android:name="android.media.RINGER_MODE_CHANGED"/>
    </intent-filter>
    <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget1_info"/>
</receiver>
于 2013-08-31T16:16:19.407 回答