0

我是 Android 新手,我在配置 Activity 的帮助下更新了 Widget 上的 TextView。它工作正常。需要更新相同的文本视图以刷新按钮单击。为此,我通过 Intent 传递小部件 ID,但在接收方无法接收小部件 ID,因此无法更新文本视图。

在 Widget_Provider 中设置 Intent

Intent refreshIntent = new Intent(context, refreshWidgetActivity.class);
refreshIntent.setAction(ACTION_WIDGET_REFRESH);
PendingIntent refreshPendingIntent = PendingIntent.getActivity(context, 0, 
refreshIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.button3, refreshPendingIntent);
refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetIds[0]);

在收到活动结束时,

Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID, 
AppWidgetManager.INVALID_APPWIDGET_ID);
}

if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}

这里 0 在 extras 而不是 Widget ID 中找到,请帮助。

4

2 回答 2

0

Have you tried calling putExtra before you create the PendingIntent?

Like this:

Intent refreshIntent = new Intent(context, refreshWidgetActivity.class);
refreshIntent.setAction(ACTION_WIDGET_REFRESH);
refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetIds[0]);
PendingIntent refreshPendingIntent = PendingIntent.getActivity(context, 0, 
refreshIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.button3, refreshPendingIntent);
于 2012-07-31T08:54:55.300 回答
0

I think you have to manage some flags.

If I correctly understood your problem, you're trying to update data in your Activity passing it extras.

You don't set any FLAG for your Intent. Also, I don't really know where is your Intent and how it is launched. However, for a same kind of problem in my own application, I use this solution :

I set my Intent with two flags :

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

In this way, my Intent will launch a new task (FLAG_ACTIVITY_NEW_TASK), then it will clear it to its root state (FLAG_ACTIVITY_CLEAR_TOP) (see Sources to understand why).

Then, my PendingIntent was set to cancel the current, to be sure there is only one instance launched (no need more I think)

PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

In this way, the new Intent will launch a new task, clear all previous data and take the new ones. The PendingIntent is not uselessly duplicated.

It works for my case, and I think it should work for yours. If any enhancements can be added, please tell me.

Sources : http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

于 2012-07-31T08:55:56.357 回答