[英]After rebooting or upgrading the app, my Android widget stops updating
每當我重啟手機或升級應用程序(在測試設備和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()
。
說明
如果查看基類onReceive()
的源代碼,您會發現它實現了用於管理Widget生命周期的框架邏輯的一部分。 (也由docs提示 )。 它處理APPWIDGET_UPDATE
,實際上,它APPWIDGET_UPDATE
負責調用onUpdate()
。 (例如,當系統啟動時,它需要繪制您的初始小部件,它將向您的應用程序發送APPWIDGET_UPDATE
,並將其傳遞給onReceive()
)。 因此,對於您的情況,我不確定100%如何onUpdate()
過 onUpdate()
,但是我假設您在其他地方有一些代碼調用了updateAppWidget()
,這是您的小部件似乎可以瞬間工作的唯一原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.