我正在创建一个小部件,我知道我的一些代码,例如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 + "%");
}
}
};
}
答案 0 :(得分:0)
AppWidgetProvider扩展了android.content.BroadcastReceiver,因此您无法将新的BroadcastReceiver注册到AppWidget的上下文中。在您的代码中,您不会从BroadcastReceiver接收电池事件。请参考以前的问题。 :)
Android Broadcast Receiver in Widget
Register BroadcastReceiver to Widget (Difference of Context object)