2013-04-20 70 views
1

我正在嘗試創建電池控件,但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> 

回答

0

所有你需要使用一個服務,因爲活動是在onPause狀態,當你在室外應用程序來更新你的部件首先。

其次服務註冊一個意圖過濾器接收電池狀態的變化。當它更新時,通知appwidget。

您還可以在服務中保留一個變量,以便小部件參考並設置其級別。