Android 3.0自带的天气预报例子代码
2011-03-19 11:57:21 来源:本站整理}
@Override
public void onEnabled(Context context) { //当appWidget添加到桌面上时
final ContentResolver r = context.getContentResolver();
if (sDataObserver == null) {
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context, WeatherWidgetProvider.class);
sDataObserver = new WeatherDataProviderObserver(mgr, cn, sWorkerQueue);
r.registerContentObserver(WeatherDataProvider.CONTENT_URI, true, sDataObserver); //注册监控数据库变化的回调
}
}
@Override
public void onReceive(Context ctx, Intent intent) {
final String action = intent.getAction();
if (action.equals(REFRESH_ACTION)) { //接收数据库改变的回调广播
final Context context = ctx;
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
final ContentResolver r = context.getContentResolver();
final Cursor c = r.query(WeatherDataProvider.CONTENT_URI, null, null, null,
null);
final int count = c.getCount();
final int maxDegrees = 96;
r.unregisterContentObserver(sDataObserver); //首先取消数据库监控
for (int i = 0; i < count; ++i) {
final Uri uri = ContentUris.withAppendedId(WeatherDataProvider.CONTENT_URI, i);
final ContentValues values = new ContentValues();
values.put(WeatherDataProvider.Columns.TEMPERATURE,
new Random().nextInt(maxDegrees));
r.update(uri, values, null, null); //更新数据库记录层
}
r.registerContentObserver(WeatherDataProvider.CONTENT_URI, true, sDataObserver); //重新设置监视数据库
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context, WeatherWidgetProvider.class);
mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.weather_list); //提示Widget有数据更新并刷新UI
赞助商链接