android - 防止触发 WidgetProvider 的 onUpdate

标签 android android-widget appwidgetprovider

我正在实现一个具有 ConfigurationActivity 的小部件,并且必须与 Eclair(2.1) 保持兼容。

documentation关于 AppWidgetProviders onUpdate 方法明确指出:

... .However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequent updates. It is the responsibility of the configuration Activity to perform the first update when configuration is done. (See Creating an App Widget Configuration Activity below.)

不幸的是,这不是真的(至少对于我的带 JellyBean 的 Nexus S 而言)。事实上,onUpdate 在我的 ConfigurationActivity 触发器的 onCreate 之前被调用。我想知道,如果其他手机上也有类似的行为,是否有可能阻止我的提供商内部的 onUpdate 调用?

我的解决方法是在我的 WidgetConfigurationActivity 内的 SharedPreferences 中存储一个带有特定 AppWidgetId 的标志。如果它不存在,我可以假设没有首先调用 ConfigurationActivity。这行得通,但在我看来真的很难看。如果无法阻止onUpdate的触发,有没有更好的解决方案?

最佳答案

是的,当您在主屏幕上添加小部件时会调用 onUpdate()。 看这里:

http://developer.android.com/reference/android/appwidget/AppWidgetProvider.html

http://developer.android.com/reference/android/appwidget/AppWidgetManager.html#ACTION_APPWIDGET_UPDATE

我不确定是否有办法在创建小部件时不触发它。但是您可以通过将 Widget Info XML 文件中的“updatePeriodMillis”字段设置为 0 或将其保留为空白 来阻止它再次触发。

另一种方法是将小部件 ID 存储在某处。现在,每当添加一个新的小部件时,在您的 Receiver 类中,检查该 ID 是否已经存在。如果它不存在(意味着一个新的小部件),那么不要执行任何代码。此外,每当删除小部件时,从您的记录中删除小部件 ID。由于有可能您删除了一个小部件,然后又添加了一个与旧小部件具有相同 ID 的新小部件。

希望对您有所帮助!

编辑: 在 Receiver 类的 onReceive() 方法中,执行以下操作:

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    if( appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID )
    {
        super.onReceive(context, intent);
    }

}

当第一次从 Widgets 列表中选择一个 widget 时,它的 appWidgetId 将等于 INVALID_APPWIDGET_ID,直到它被添加到主屏幕上。由于“super.onReceive()”在选择一个小部件时会调用 onUpdate() 方法,因此不会在第一次调用 onUpdate()。

关于android - 防止触发 WidgetProvider 的 onUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781415/

相关文章:

android - 有什么办法可以响应Android用户的强制关闭消息吗?

java - 从 Activity 向 Intent 传递附加值会抛出 NullPointerException

Android - ListView - 按需调用 getView()

android - Marshmallow 升级后 appwidget listview 行未更新或加载

java - Android 10 - 文件提供程序 - 权限拒绝 : reading android. support.v4.content.FileProvider uri

Android - 应用程序之间的共享变量

android - 小部件的多个实例仅更新最后一个小部件

java - 在全屏中显示选定的网格图像,其代码需要在 MainActivity 类中,如下所示

Android应用程序小部件背景形状以编程方式更改颜色不透明度

android - 如何在服务中获取我的应用程序的 widgetID 和 ComponentName