【发布时间】:2019-02-11 02:30:17
【问题描述】:
每当我重新启动手机或升级应用程序(在我的测试设备和 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>
【问题讨论】:
-
我们可以看到 AndroidManifest.xml 的匹配部分(您注册提供程序的位置)吗?
-
@greeble31 当然,我已经用 .xml 编辑了问题。
-
嗯。
EXTRA_APPWIDGET_IDS真的不应该在那里(b/c 这不是一个动作),但我看不出是什么导致了你的问题。 1.) 你怎么知道小部件没有更新? 2.) 每次都记录对onUpdate()的调用并转储appWidgetIds怎么样? -
我尝试删除该标志,但保留了它,因为我没有注意到这样做有任何变化。因此,当我升级应用程序或重新启动手机时,刷新按钮将停止工作。但是,当我在主应用程序(具有相同的代码)中登录
onUpdate时,不会为现有小部件调用onUpdate。当我创建第二个小部件实例时,旧实例只会再次调用onUpdate。 -
我怀疑
onUpdate()确实在重启后被调用,否则你会说,“小部件在重启时消失。”您的问题听起来更像是Intent没有按照您期望的方式进行活动。您能否仔细解释“主要应用程序”和“相同代码”的含义(也许将其添加到您的问题中)?我们是否正在处理同时安装的两个应用程序?而且,当您说“升级”时,我认为它的意思是“增加android:versionCode并重新安装”。是这个意思吗?
标签: java android android-studio android-activity android-widget