0

我正在制作一个小部件,我知道我的一些代码,例如 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 + "%");
        }
    }
};

}
4

1 回答 1

0

AppWidgetProvider扩展了 android.content.BroadcastReceiver,因此您不能将新的 BroadcastReceiver 注册到您的 AppWidget 的上下文中。在您的代码中,您不会收到来自 BroadcastReceiver 的电池事件。参考这些以前的问题。:)

小部件中的 Android 广播接收器

将 BroadcastReceiver 注册到 Widget(Context 对象的区别)

于 2013-06-07T05:42:20.530 回答