Bry*_*n W 9 java android android-widget android-activity android-studio
每当我重新启动手机或升级应用程序(在我的测试设备和Android模拟器上)时,小部件就会停止更新,直到我创建小部件的新实例。然后小部件的两个实例将再次开始更新。我认为这是与调用onUpdate()旧的东西有关WidgetIds,但我无法弄清楚。这是我的代码的一小部分。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
}
编辑:这是我的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>
Run Code Online (Sandbox Code Playgroud)
将呼叫添加到super.onReceive()您的onReceive().
解释
如果您查看基类的源代码onReceive(),您可以看到它实现了管理 Widget 生命周期的部分框架逻辑。(文档也暗示)。事实上,它首先APPWIDGET_UPDATE负责处理调用。onUpdate()(例如,当系统启动时,它需要绘制您的初始小部件,它会向您的应用程序发送一个APPWIDGET_UPDATE,该值被传递到onReceive())。所以,在你的情况下,我不能 100% 确定如何被onUpdate()调用,但我假设你在其他地方有一些代码调用,这就是你的小部件似乎暂时工作的唯一原因。updateAppWidget()
| 归档时间: |
|
| 查看次数: |
2406 次 |
| 最近记录: |