android 桌面小组件小记

记录自己在开发小组件时的几个问题:
1.数据已经更新,但是页面加载的还是旧数据;
2.小组件的点击事件;
3.4个小组件同时刷新;
4.小组件数据列表的item点击事件

1.小组件的页面刷新依赖一下代码

MyRemoteViews myRemoteViews = new MyRemoteViews(App.getApp());
        myRemoteViews.notifyAppWidgetViewDataChanged();

如果你的数据是从网路请求过来的,需要花费时间,请把这段代码置于数据下载完成之后,不然页面会加载旧的数据
2.小组件的点击事件机制是先声明:

public void setOnRefreshClickPendingIntent() {
		Intent intent = getProviderIntent();
		intent.setAction(MyAppWidgetProvider.ACTION_REFRESH_MANUAL);
		PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
		setOnClickPendingIntent(R.id.button_refresh, refreshPendingIntent);
	}

然后在AppWidgetProvider广播中接收action : MyAppWidgetProvider.ACTION_REFRESH_MANUAL,当然,在此之前,你还需要在AppWidgetProvider的onUpdate方法中注册:

 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        if (android.os.Build.VERSION.SDK_INT < 14) {
            return;
        }
        MyRemoteViews newsRemoteViews = new MyRemoteViews(context);
        newsRemoteViews.setOnRefreshClickPendingIntent();
        // 更新所有的widget
        appWidgetManager.updateAppWidget(appWidgetIds, newsRemoteViews);
        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }

3.我的桌面小组件有4个,所以需要4个同时刷新,所以我并没有采用广播的方式,而是采用接口回调的方式实现
4.数据列表的item点击事件获取代码:

Intent fillInIntent = new Intent();
		if(note != null){
	fillInIntent.setAction(MyAppWidgetProvider.ACTION_JUMP_LISTITEM + note.getClientClassId());
		}
		// 设置 第position位的"视图"对应的响应事件, api 11
		rv.setOnClickFillInIntent(R.id.rl_item_bg, fillInIntent);

小组件的点击事件回调方法里边并不能传其他的参数,只有控件id和intent,所以如果你想获取item的具体数据,我采用的是把数据加入到action中,当然这会产生很多不同的action,但是由于我的数据比较少(最多显示7个),所以这种方法还是可行的

猜你喜欢

转载自blog.csdn.net/weixin_42582102/article/details/86537384