我正在制作一个小部件,我知道我的一些代码,例如 broadcastReceiver 目前是错误的,但它甚至不会更新为硬编码setTextViewText
。
我的问题是我不知道为什么会发生这种情况,而且我的小部件不会更新。
这是我的代码,我希望有人能找出我哪里出错了:
public class Widget extends AppWidgetProvider {
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
views = new RemoteViews(context.getPackageName(), R.layout.widget);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(batteryChangedReceiver, batteryLevelFliter);
String alarm = Settings.System.getString(context.getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
views.setTextViewText(R.id.tvAlarm, alarm);
views.setTextViewText(R.id.tvNextAlarm, "qwertyuiop");
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
@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;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean charging = status == BatteryManager.BATTERY_STATUS_CHARGING;
if (charging) {
views.setTextViewText(R.id.tvBattery, "Charging: " + level + "%");
if (level == 100) {
views.setTextViewText(R.id.tvBattery, "Battery Full");
}
} else {
views.setTextViewText(R.id.tvBattery, "Battery: " + level + "%");
}
}
};
}