1

我正在尝试创建一个电池小部件,但应该显示电池状态的 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>
4

1 回答 1

0

首先,您需要使用服务来更新您的小部件,因为当您在应用程序之外时,活动处于 onPause 状态。

其次,在服务中注册一个意图过滤器,用于接收电池状态的变化。当它更新时,通知appwidget。

您还可以在服务中保留一个变量,小部件将引用该变量并设置其级别。

于 2013-04-20T17:55:54.467 回答