我正在尝试一些非常简单的代码来运行 Android 小部件,但没有成功。我环顾四周,但没有找到好的答案。
我现在想要的只是在触摸小部件时增加计数器并显示当前值。
这是我的 AppWidgetProvider:
public class WordWidget extends AppWidgetProvider
{
Integer touchCounter = 0;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
//This is run when a new widget is added or when the update period expires.
Log.v("wotd", "Updating " + appWidgetIds.length + " widgets");
for(int x = 0; x < appWidgetIds.length; x++)
{
Integer thisWidgetId = appWidgetIds[x];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
remoteViews.setTextViewText(R.id.mainText, touchCounter.toString());
Intent widgetIntent = new Intent(context, WordWidget.class);
widgetIntent.setAction("UPDATE_NUMBER");
PendingIntent widgetPendingIntent = PendingIntent.getBroadcast(context, 0, widgetIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widgetLinearLayout, widgetPendingIntent);
appWidgetManager.updateAppWidget(thisWidgetId, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent)
{
Log.v("wotd", "In onReceive with intent=" + intent.toString());
if (intent.getAction().equals("UPDATE_NUMBER"))
{
Log.v("wotd", "In UPDATE_NUMBER");
touchCounter++;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
remoteViews.setTextViewText(R.id.mainText, touchCounter.toString());
} else
{
Log.v("wotd", "In ELSE... going on to super.onReceive()");
super.onReceive(context, intent);
}
}
}
这是我的清单的一部分:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver
android:icon="@drawable/ic_launcher"
android:name="com.example.mywidget.WordWidget"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="UPDATE_NUMBER" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widgetinfo" />
</receiver>
</application>
日志显示 onReceive() 在放置到主屏幕后以及被触摸后立即被调用,但数量从未增加。我不完全理解小部件是如何工作的,但是它们在 onUpdate() 之后会被杀死吗?那么为此我必须使用某种持久存储吗?
另外,如果我当前添加另一个小部件,即使我只触摸一个小部件,它们也会显示相同的值和增量。有没有办法让每个小部件都有自己的计数器?
Thanks!