我正在尝试创建一个电池小部件,但应该显示电池状态的 textView 没有更新。仅当手机重新启动时才会更改。代码中缺少什么?
安卓清单:
<uses-permission android:name="android.permission.BATTERY_STATS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".WidgetConfigurationActivity"
android:excludeFromRecents="true"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<receiver android:name=".MAppWidgetProvider" >
<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>
</application>
应用小部件提供者:
public class MAppWidgetProvider extends AppWidgetProvider
{
private String batteryLevel="init";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds)
{
context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateView(context);
}
@Override
public void onReceive(Context context, Intent intent)
{
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
level = (rawlevel * 100) / scale;
batteryLevel = Integer.toString(level);
updateView(context);
super.onReceive(context, intent);
}
public void updateView(Context context)
{
RemoteViews thisViews = new RemoteViews(context.getApplicationContext()
.getPackageName(), R.layout.widget_layout);
thisViews.setTextViewText(R.id.textView1, batteryLevel);
ComponentName thisWidget = new ComponentName(context,
AnalogClockWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,
thisViews);
}
}
信息:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="40dp"
android:minHeight="40dp"
android:initialLayout="@layout/widget_layout"
android:updatePeriodMillis="10000"
android:configure="in.wptrafficanalyzer.appwidgetclockconfiguration.WidgetConfigurationActivity"
android:resizeMode="horizontal|vertical">
</appwidget-provider>