0
當處於充電狀態時,我無法更新小部件。電池電量保持不變。我的代碼有什麼問題?爲什麼小部件不更新?
public class BatteryStatusWidgetActivity extends AppWidgetProvider {
/** Called when the activity is first created. */
private String batteryLevel = "init";
private String temperatura = "init";
private int widgetImageFrame = R.drawable.full;
@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) {
if (intent.getAction().contentEquals(
"com.sec.android.widgetapp.APPWIDGET_RESIZE")
|| intent.getAction().equals(
"android.appwidget.action.APPWIDGET_UPDATE_OPTIONS")) {
} else {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
level = (rawlevel * 100)/scale;
batteryLevel = level + "%";
// temperatura
int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,
-1)/10;
temperatura = temperature + "°C";
widgetImageFrame = R.drawable.full;
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.widget_text, batteryLevel + " | "
+ temperatura);
thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);
ComponentName thisWidget = new ComponentName(context,
BatteryStatusWidgetActivity.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,
thisViews);
}
}
這是最主要的部件
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/widget_layout" android:minWidth="40dp" android:minHeight="40dp" android:updatePeriodMillis="3000" />
那麼是什麼問題呢? android:updatePeriodMillis="3000"
?
are sure?我寫了一個項目使用你的代碼,它工作正常... –
許多人告訴我,小部件不會更新。例如,在我的情況下,它工作正常..我不知道爲什麼。也許做一個服務更好。 –