问题是,无论何时将主窗口添加到主屏幕,窗口小部件会尝试在启动/完成配置活动之前自己更新,这可能会导致长时间的延迟(几秒钟).配置活动应该在widget添加之前尝试更新自己的任何东西.
以下是在添加小部件时在LogCat中看到的事件序列:
> Widget.onRecive:action = APPWIDGET_ENABLED
> Widget.onEnabled
> Widget.onReceive:action = APPWIDGET_UPDATE
> Widget.onUpdate:启动Widget服务.
> WidgetService.onStartCommand:潜在的长时间运行的工作,将延迟配置活动立即显示.
> WidgetConfiguration.on创建
> Widget.onReceive:action = APPWIDGET_UPDATE
> Widget.onUpdate:Widget服务再次启动
> WidgetService.onStartCommand:可能长时间运行的工作再次执行.
发生的情况是,当添加窗口小部件时,服务将在配置视图显示之前启动.
的Manifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="xxx.xxx.xxxwidget" android:versionCode="1" android:versionName="@string/app_version" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:debuggable="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <receiver android:name="xxxWidget" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <Meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_info" /> </receiver> <activity android:name="xxxWidgetConfigure" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="xxxWidgetService" /> </application> </manifest>
解决方法
http://developer.android.com/guide/topics/appwidgets/index.html#Configuring
The onUpdate() method will not be called when the App Widget is created (the system will not send the ACTION_APPWIDGET_UPDATE broadcast when a configuration Activity is launched). It is the responsibility of the configuration Activity to request an update from the AppWidgetManager when the App Widget is first created. However,onUpdate() will be called for subsequent updates—it is only skipped the first time.
不过,这似乎并不正确!
我做了什么是向SharedPreferences添加一个布尔值,告诉我这个widgetId是否已经通过配置.如果不跳过此更新.在你的AppWidgetProvider类’onUpdate方法中实现这一点.