重新启动或升级应用程序后,我的 Android 小部件停止更新

After rebooting or upgrading the app, my Android widget stops updating

每当我重新启动 phone 或升级应用程序(在我的测试设备和 Android 模拟器上)时,小部件都会停止更新,直到我创建小部件的新实例。然后小部件的两个实例将再次开始更新。我认为这是在旧 WidgetIds 上调用 onUpdate() 的问题,但我无法弄清楚。 这是我的代码的一小段。

 public class NewAppWidget extends AppWidgetProvider {

private static final String refresh = "b_refresh";

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    Intent intent = new Intent(context, NewAppWidget.class);
    intent.setAction(refresh);
    intent.putExtra("appWidgetId", appWidgetId);

    views.setOnClickPendingIntent(R.id.refresh, PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_UPDATE_CURRENT));
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

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

    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

@Override
public void onReceive(Context context, Intent intent) {
    if(refresh.equals(intent.getAction())) {
        Toast.makeText(context, "Clicked2", Toast.LENGTH_LONG).show();
    }
}

}

编辑:这是我的 manifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".NewAppWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="android.appwidget.action.EXTRA_APPWIDGET_IDS"/>
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/new_app_widget_info" />
    </receiver>

    <activity android:name=".NewAppWidgetConfigureActivity">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
        </intent-filter>
    </activity>
</application>

将对 super.onReceive() 的呼叫添加到您的 onReceive()

说明

如果您查看基础 class onReceive() 的源代码,您会发现它实现了用于管理 Widget 生命周期的部分框架逻辑。 (也由 docs 暗示)。它处理 APPWIDGET_UPDATE,事实上,它首先负责调用 onUpdate()。 (例如,当系统启动时,它需要绘制您的初始小部件,它会向您的应用发送一个 APPWIDGET_UPDATE,然后传递给 onReceive())。所以,我不是 100% 确定 onUpdate() 是如何 ever 被调用的,在你的情况下,但我假设你在其他地方有一些代码调用 updateAppWidget() ,这是您的小部件似乎可以暂时工作的唯一原因。