我正在尝试一些非常简单的代码来让 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() 之后被杀死了吗?所以要做到这一点,我必须使用某种持久存储?
此外,如果我当前添加另一个小部件,即使我只是触摸一个,两者都会显示相同的值并增加。有没有办法让每个小部件都有自己的计数器?
谢谢!