gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:55 25 4
gpt4 key购买 nike

每当我重新启动手机或升级应用程序(在我的测试设备和 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,事实上,它首先负责调用 onUpdate()。 (例如,当系统启动时,它需要绘制您的初始小部件,它会向您的应用发送一个 APPWIDGET_UPDATE,该消息会传递给 onReceive())。因此,在您的情况下,我不能 100% 确定 onUpdate() 是如何被调用的,但我假设您在其他地方有一些代码调用 updateAppWidget(),这就是您的小部件甚至暂时可以工作的唯一原因。

关于java - 重新启动或升级应用程序后,我的 Android 小部件停止更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52193688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com