以编程方式检查省电模式

2022-01-08 00:00:00 api sdk android java

我已经编写了一个应用程序 (AutoWifiSwitch),并且我计划添加的功能之一是如果启用了省电模式,则自动禁用我的应用程序中的 wifi 扫描服务.

I have written an app (AutoWifiSwitch) and one of the features I plan to add is automatically disabling the wifi scanning service in my app if power saving mode is enabled.

我知道 Android L 应该实现了省电功能(以前 HTC 和三星会将这些功能自己添加到软件中).现在大概这意味着谷歌将为其添加某种 API.理想情况下,会添加一个新动作,以便我可以听.

I know Android L is supposed to have Battery Saving implemented (previously HTC and Samsung would add the features themselves to the software). Presumably this now means Google will have added some sort of API for it. Ideally there would be a new action added so I could listen for that.

我还想知道 HTC/Samsung API 是否可以实现上述操作,如果可以,我该如何使用它们.

I would also like to know if the above is possible with HTC/Samsung APIs and if so, how do I use them.

我一直在到处寻找上述问题,但绝对没有运气,应用程序 SecureSettings(Tasker 的插件)能够连接到 HTC/Samsung API 以启用省电模式,我不太懂确定他们是如何做到的.

I've been searching everywhere for the above questions but had absolutely no luck, the app SecureSettings (an addon for Tasker) is able to hook into the HTC/Samsung APIs to enable the power saver anyway, I'm not quite sure how they do it.

编辑:节电值可以从Android L中的PowerManager获取,但不确定是否有Action.

Edit: The power saver value can be gotten from the PowerManager in Android L, not sure if there is an Action for it though.

推荐答案

我最终想出了如何用 HTC 和三星设备做到这一点.两者都将其电源管理器设置存储在 Settings.System 中.

I've eventually figured out how to do this with HTC and Samsung devices. Both store their power manager settings in Settings.System.

HTC (Sense) 使用密钥 user_powersaver_enable.三星 (Touchwiz) 使用 psm_switch 键.

HTC (Sense) uses the key user_powersaver_enable. Samsung (Touchwiz) uses the key psm_switch.

两者都将布尔值存储为字符串,0"为假,1"为真.然后,您可以像这样使用 ContentObserver 监听更改(需要 API 级别 16 或更高):

Both store the boolean as a String, "0" being false and "1" being true. You can then listen for changes using a ContentObserver like so (requires API level 16 or higher):

getContentResolver().registerContentObserver(Settings.System.CONTENT_URI, true, new ContentObserver(){
  @Override
  public void onChange(boolean selfChange, Uri uri){
    super.onChange(selfChange, uri);
    String key = uri.getPath();
    key = key.substring(key.lastIndexOf("/") + 1, key.length());

    if (key.equals("user_powersaver_enable") || key.equals("psm_switch")){
      boolean batterySaverEnabled = Settings.System.getString(getContentResolver(), key).equals("1");
      // do something
    }
  }
});

但这仅适用于 Android L 发布之前,当 L 发布时,HTC 和三星可能会转移到 AOSP 省电模式,这意味着您将能够在 L 中使用新的省电模式 api.

However this will only be applicable until Android L is release, when L is released HTC and Samsung will likely move over to the AOSP battery saver which means you will be able to use the new battery saver api in L.

相关文章