小部件不更新

时间:2013-04-20 17:43:19

标签: android android-widget android-appwidget

我正在尝试创建一个电池小部件,但应该显示电池状态的textView没有更新。它仅在手机重新启动时才会更改。代码中缺少什么?

AndroidManifest:

    <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>

的AppWidgetProvider:

    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>

1 个答案:

答案 0 :(得分:0)

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

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

您还可以将一个变量用于控制哪个小部件引用并设置其级别。