我正在为Android实现新闻小部件。在onUpdate中,我正在获取所有数据(大约50篇文章,其中包含一些文本和url)。我希望实现左右按钮在新闻之间循环。但是onReceive我只能调用onUpdate,并且onUpdate将再次获取所有项目。如何实现左键和右键单击而又不使用现有数据又重新获取所有数据。还有另一个问题,如果我在AppWidgetProvider中定义了全局变量,它是不是在某个时候被垃圾收集器收集了,或者它永远与小部件“共存”?
代码:
public class MyWidgetProvider extends AppWidgetProvider {
private static final String RIGHT_CLICKED = "RIGHT_CLICKED";
private static final String LEFT_CLICKED = "LEF_CLICKED";
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (RIGHT_CLICKED.equals(intent.getAction())) {
//Get next content on list
}
if (LEFT_CLICKED.equals(intent.getAction())) {
//Get prev content on list
}
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//Fetching all stories from RSS
RSSFetchCallback rssFetchCallback = new RSSFetchCallback() {
@Override
public void onComplete(ArrayList<Story> stories) {
ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);
remoteViews.setTextViewText(R.id.textViewContent, stories.get(0).getContent()); //Setting 0 story for example
remoteViews.setTextViewText(R.id.textViewHeadline, stories.get(0).getTitle()); //Setting 0 story for example
remoteViews.setOnClickPendingIntent(R.id.buttonRight, getPendingSelfIntent(context, RIGHT_CLICKED));
remoteViews.setOnClickPendingIntent(R.id.buttonLeft, getPendingSelfIntent(context, LEFT_CLICKED));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
//Loading R.id.imageView with Glide
AppWidgetTarget awt = new AppWidgetTarget(context, R.id.imageView, remoteViews, widgetId) {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
super.onResourceReady(resource, transition);
}
};
RequestOptions options = new RequestOptions().override(300, 300).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher);
Glide.with(context.getApplicationContext())
.asBitmap()
.load(stories.get(0).getImgUrl())//Setting 0 story image for example
.apply(options)
.into(awt);
//End Loading R.id.imageView with Glide
}
}
};
RSSFetcher.getData(rssFetchCallback);
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}