在我的应用程序中,我必须使用 HomeScreenWidget。并且每 2 分钟它应该更新它的内容。所以我尝试了以下步骤
i) 创建 AppWidgetProvider 类
public class MainWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.i("onUpdate","called");
this.context=context;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
remoteViews.setOnClickPendingIntent(R.id.widget_button,getServerData(context));
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("onreceive","called");
this.context=context;
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName thisWidget = new ComponentName(context, MainWidget.class);
remoteViews.setTextViewText(R.id.widget_tv1,aaa);
remoteViews.setTextViewText(R.id.widget_tv2,bbb);
manager.updateAppWidget(thisWidget, remoteViews);
super.onReceive(context, intent);
}
二)创建widget_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_layout"
android:minHeight="72dp"
android:minWidth="294dp"
android:updatePeriodMillis="120000">
</appwidget-provider>
iii) 在 Manifest 中添加小部件类
<receiver android:name=".MainWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
我的小部件每 30 分钟更新一次。我想每 2 分钟更新一次小部件。请给我最好的方法