来自BroadcastReceiver

时间:2016-01-27 17:34:23

标签: android broadcastreceiver settings brightness

我有一个安装在系统分区上的应用程序(Android 4.4.1和4.1.2)。我需要它根据电池电量设置屏幕的亮度。所以,我在Application上注册BroadcastReceiver,听取Intent.ACTION_BATTERY_CHANGED意图检查电池状态。

我已经看到很多关于如何在Activity甚至Service上使用假Activity执行此操作的答案。我可以使用Service - Activity方法,但我不想仅仅将亮度设置应用于WindowManager来启动活动。

这就是我目前所拥有的:

    ContentResolver contentResolver = context.getContentResolver();
    int currentBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, -1);
    int newBrightness = -1;

    // Set brightness according to the battery level
    if (batteryPercentage > BatteryUtils.BATTERY_SAFE_LEVEL
            && currentBrightness != BRIGHTNESS_HIGH) {
        newBrightness = BRIGHTNESS_HIGH;
    } else if (batteryPercentage <= BatteryUtils.BATTERY_SAFE_LEVEL
            && batteryPercentage > BatteryUtils.BATTERY_LOW_LEVEL
            && currentBrightness != BRIGHTNESS_NORMAL) {
        newBrightness = BRIGHTNESS_NORMAL;
    } else if (batteryPercentage <= BatteryUtils.BATTERY_LOW_LEVEL
            && currentBrightness != BRIGHTNESS_LOW) {
        newBrightness = BRIGHTNESS_LOW;
    }

    if (newBrightness != -1) {
        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, newBrightness);
        Log.v(context.getString(R.string.app_name), "BatteryReceiver: setting brightness to " + newBrightness + "("+ batteryPercentage+ "%, " + plugged +")");
    }

正如您可能想象的那样,亮度设置已正确更改 - 如果我重新启动设备,则下次设备重新启动时将应用新的亮度设置 - 但它不会立即应用。

是否有其他方式可以立即应用设置而无需启动活动?也许我的系统应用可以使用的API?

0 个答案:

没有答案