Power save mode android
переношу вопрос в эту ветку — по просьбе модераторов
Друзья, у каждого в телефоне Wi-Fi модуль и в нем для экономии батареи предусмотрен «щадящий режим», для экономии аккумулятора.
Я так понял есть классическая схема Wifi power saving mode
Когда мобильное устройство сообщает роутеру, что он будет работать экономно и тогда телефон слушает уже не все beacon пакеты роутера, а определенные, к примеру каждый 10-й (то есть слушает эфир не каждый 100 мс, а каждую секунду). И только если есть нужные пакеты у роутера, он сообщает в пакете что есть данные для устройства и услышав это — устройство отзывается (включает передатчик) и сообщает о том что готово принять пакеты.
(иными словами — принцип абсолютно схож с работой мобильного телефона в сетях 2G/3G/4G, когда телефон «отзывается» только когда сеть ему по пейджигновому каналу сеть даст команду отозваться).
И еще одна технология WMM Power Save
где устройство само периодически опрашивает точку доступа на предмет, а есть ли что то для него. Вроде бы это как бы более новая технология, но с другой стороны в чем же экономия, если устройство периодически включает передатчик, которые потребляет куда больше чем приемник? Теоретически — экономия может достигаться за счет более длительной паузы между опросами . но без мониторинга — не проверить. Может кто либо изучал эти вещи?
Пока так и не понял, что и за счет чего происходит экономия и какие порядки при потреблении тока (может кто либо измерял?):
— режим ожидания Wi-Fi (приема данных нету);
— режим приема Wi-Fi (происходит прием данных — передатчик отключен);
— режим передачи Wi-Fi (телефон отправляет АСК пакеты подтверждения, либо отправляет данные)
— режим поиска сети, который периодически телефон производит, когда находится за пределами сетей, сохраненных в списке «доверенных».
п.с. К примеру у меня в роутере (прошивка DD-WRT) есть контроль уровня сигнала от клиента, так вот, даже когда телефон в ожидании — поднося его ближе к роутеру — уровень меняется.
Однако почему создал тему, потому что интересно — ведь режим передачи самый затратный для аккумулятора телефона, а по другому как тогда точка доступа определит уровень сигнала?
Сообщение отредактировал Andrey_A&S — 28.10.17, 23:33
Источник
Режим энергосбережения на смартфоне — что это и зачем нужно?
Современный смартфон является настоящим коммуникационным центром и помощником, выполняющим множество полезных функций.
Наша жизнь теперь всецело привязана к телефону. Когда мы находимся в движении и видим небольшой остаток заряда батареи, который быстро уменьшается, стараемся поддержать его всеми доступными способами.
Операционная система Android дает пользователю массу возможностей посредством своих сервисов и приложений, а смартфон с достойными характеристиками обеспечивает быструю работу программ и высокую производительность. Расплачиваться за это приходится значительным энергопотреблением. При активном использовании гаджета мало кому хватает полного заряда аккумулятора на весь день — он быстро разряжается . К счастью, существует масса способов, позволяющих не остаться с выключенным смартфоном в самый неподходящий момент.
Любое устройство на Android позволяет включить режим энергосбережения. При переходе в данный режим происходит ограничение работы или отключение основных потребителей энергии в операционной системе.
Дисплей . Именно он расходует большую часть заряда аккумулятора. От степени яркости, таймаута подсветки и разрешения экрана напрямую зависит срок работы батареи.
Фоновые процессы . Установленные приложения незаметно, но регулярно обновляют свой контент для пользователя, а мессенджеры и почтовые клиенты уведомляют нас о новых сообщениях и письмах, используя интернет-трафик и заряд аккумулятора.
Производительность процессора . Этот показатель определяет то, как устройство справляется с многозадачностью, и с какой скоростью работают приложения. Высокая производительность требует значительных энергоресурсов. При переходе в режим энергосбережения и уменьшения скорости процессора при выполнения стандартных задач можно заметить ухудшения работы смартфона.
Режим энергосбережения в Android может активироваться как автоматически (при достижении небольшого остатка заряда аккумулятора) и вручную — через настройки устройства. После этого смартфон сообщит, на сколько часов без подзарядки пользователь может рассчитывать. Разумеется, это оценочные данные.
Некоторые производители смартфонов добавляют еще один режим — «экстремальное/максимально энергосбережение». В этом случае пользователю становятся недоступны многие приложения за исключением SMS, телефонных звонков и каких-то основных функций.
Для более экономного использования заряда батареи можно воспользоваться не только стандартными режимами смартфона, но и самостоятельно проанализировать некоторые параметры его работы. Часто в устройстве активированы функции, которые на данный момент не используются, но продолжают потреблять заряд аккумулятора:
- автоповорот экрана, датчик положения которого находится в постоянно работающем режиме;
- живые обои и многочисленные виджеты;
- активная синхронизация аккаунтов и контактов;
- запущенные беспроводные соединения: Bluetooth, Wi-Fi, GPS и мобильный интернет (особенно 4G).
Важно обращать внимание за количеством одновременно работающих приложений. При активной работе со смартфоном запускается много программ, которые остаются открытыми длительное время, быстро уменьшая заряд аккумулятора. Особо прожорливые процессы рекомендуется закрывать вручную.
Источник
Programming VIP
Very Interesting Programming
Power saving mode for Android 9.0 power management
On Android’s platform, the issue of power consumption has been criticized.Since Lollipop, Google has also attached great importance to transforming its power-saving model.This article will be based on the latest Android Pie code to analyze the current power saving mode process for Android, and give some suggestions for some points that can continue to be optimized.This article will start with SystemUI.
This picture is believed to impress everyone who uses an android phone, QuickSettings belonging to SystemUI.
Battery SaverTile’s handleCllick responds to a click on power saving mode.
mBatteryController is an instantiated object of the BatteryController class, so setPowerSaveMode is implemented in BatteryControllerImpl.
BatterySaverUtils is a class in frameworks/base/packages/SettingsLib whose methods are of type static, making it easy for other classes to make method calls.
When we click on the power saving mode button to start the power saving mode, the parameter powerSave here will be set to true, and the needFirstTimeWarning will also be true.
Within this class, the main method implemented is context.getSystemService(PowerManager.class).setPowerSaveMode(enable).
GettSystemService takes the PowerManager object and calls the function setPowerSaveMode to set it up.
PowerManager is one of Android’s core service s, and its code is located in frameworks/base/core/java/android/os/PowerManager.java
PowerManager is the framework exposed interface, the real implementation is the PowerManager Service.
Here are a few things to note:
- enforceCallingOrSelfPermission is a secure memory of the Android framework, primarily to check if the UID of the current calling process has privileges to operate on a system.For example, in power-saving mode, because it operates inside the SystemUI, the AndroidManifest.xml inside the SystemUI must declare the rights of DEVICE_POWER, otherwise it will be thrown as an exception.
- When the SystemUI calls PowerManager and checks permissions, Binder.clearCallingIdentity clears the UID,PID information of the SystemUI Process and replaces it with the UID,PID content of the process PowerManager is in.Because this involves binder communication, we will discuss it later in the Binder section.
- In try<>finally<>, Binder.restoreCallingIdentity() is called.
This is used to restore uid and pid information on the remote caller side, which is the inverse of clearCallingIdentity. - Next, there is the core call, setLowPowerModeInternal (enable), where the parameter, enable = true, is clicked on the power saving mode.
The operation of setLowPowerModel Internal is really simple, using the object mBatterySaverStateMachine of BatterySaverStateMachine to call setBatterySaverEnabledManual.
Because enabled came in before it was true, it can be translated as
public static final int REASON_MANUAL_ON = 2;
The next enableBatterySaverLocked function updates the content to the global setting s.
- wasEnabled first determines if it was enable d before and, if so, return s.
- isPowered also returns directly if true.
- MLastChangedIntReason, the value of mLastChangedStrReason is saved as the previously passed in value, that is, mLastChangedIntReason=2, mLastChangedStrReason=»Manual ON».
- Both manual and enable s are true states, so upateSnoozingLocked. This function simply sets the value of mBatterySaverSnoozing to true.We will encounter this value later.
- PutGlobalSetting (Global.LOW_POWER_MODE, enable? 1: 0); set the LOW_POWER_MODE value to 1 in the database.
- PutGlobalSetting (Global.LOW_POWER_MODE_STICKY, enable? 1:0); Set the LOW_POWER_MODE_STICKY value to 1 in the database.
- mBatterySaverController.enableBatterySaver(enable, intReason); this function will be called for real operation after the corresponding database has been saved.
In the enableBatterySaver function that calls the controller, the main point is that mEnable is set to true.And pass the actual reason ing to the Handler.
The purpose of this function is to populate the message and sendToTarget.
- Because MSG_STATE_CHANGED is a previously populated and sent message, it is processed in the case of MSG_STATE_CHANGED.
- handleBatterySaverStateChanged(msg.arg1 == ARG_SEND_BROADCAST, msg.arg2); in the function, the first parameter is true because it was also passed ARG_SEND_BROADCAST; the second parameter is the previously populated reason, so the function of handleBatterySaverStateChanged is very complex, involving information such as jni, native devices, adbrocast, etc., so followHere’s the real big game.
This function is very large, and the operation is broken down as follows:
- final boolean isInteractive = getPowerManager().isInteractive();
Here, get the status of Interactive from PowerManager.
isInteractive is simple:
In fact, it is to determine whether the value of wakefulness is WAKEFULNESS_AWAKE or WAKEFULNESS_DREAMING, so what does this value represent?
WAKEFULNESS_ASLEEP: Indicates that the system is currently dormant and can only be awakened by a wakeUp() call.
WAKEFULNESS_AWAKE: Indicates that the system is currently functioning properly.
WAKEFULNESS_DREAMING: Indicates that the system is currently in the state of an interactive screen saver.
WAKEFULNESS_DOZING: Indicates that the system is in a «doze» state
Since we are analyzing the power saving mode here, we will not expand in detail.
isInteractive returns true when it normally clicks on the power-saving mode button.
- listeners = mListeners.toArray(new LowPowerModeListener[mListeners.size()]);
The mListeners here were actually all service s that added LowPowerModeListener when they were previously registered.Includes VibratorService, NetworkPolicyManagerService, etc.These are saved once for later message distribution. - The call to PowerManager Internal here is complex, but it doesn’t really work.But for each manufacturer, you can focus here because the frequency of subsequent CPUs can be set along this line.
First is the function of powerHint
As before, this side will still check to see if there are any rights to DEVICE_POWER.
The powerHintInternal function is then called for processing.
In this function, the hintId we passed in is 5, and the value of PowerHint.LAUNCH is defined in the class of PowerHint, which is public static final int LAUNCH = 8;.
So native’s method is called directly.
The corresponding files and functions are:
Because it’s a jni call, this side is just a simple encapsulation.
The mobile phone I use is pixel xl, its corresponding devices are marlin, and powerHal is powerHalV1_1 version, so I will walk to it
ret = powerHalV1_1->powerHintAsync(hintId, data);
processPowerHalReturn(ret, «powerHintAsync»);
So the corresponding function is:
powerHintAsync device/google/marlin/power/Power.cpp
The following is the implementation:
It’s a crazy encapsulation again.
For perfd, we are not going to do any analysis here.Because normally, it continues to be power_hint.
Next, the power_hint implements a large code, but it is useless.
This function sets the CPU frequency in different power states, but it does not judge the incoming hint=5, so it has no practical effect.But when we want to set the processing of the low frequency state of the cpu, this is undoubtedly the best choice.
Here’s default break.
- Let’s go back to the main function and do the analysis.
After analyzing the pmi calls, updateBattery SavingStats ();
The core of this function is transitionState, but it is only used to preserve the current state, so we won’t go into it.
- fileValues is empty by default, and we don’t handle analysis either.
- The next Plugin is a bit interesting because it’s a plug-in way to operate.
But for real implementation, aosp only implements one:
onBatterySaverChanged
frameworks/base/services/core/java/com/android/server/power/batterysaver/BatterySaverLocationPlugin.java
Here the specific implementation is:
killer = false; therefore, when setting up the Global Settings database here, set LOCATION_GLOBAL_KILL_SWITCH to zero.
- The next step is to process the broadcast request for each service, package.
There are mainly three broadcasts: ACTION_POWER_SAVE_MODE_CHANGING, ACTION_POWER_SAVE_MODE_CHANGED, ACTION_POWER_SAVE_MODE_CHANGED, and ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL.
Next, we do a one-to-one analysis of the three broadcasts.
- ACTION_POWER_SAVE_MODE_CHANGING
The broadcast first added a flag FLAG_RECEIVER_REGISTERED_ONLY to indicate that only dynamically registered receipts are allowed.
The main places accepted are:
One is in Packages/apps/Settings
One is frameworks/base/packages/SystemUI/
For Battery SaverReceiver, the main update here is the status inside settings.
For sBatteryControllerImpl, the call here is
The state of PowerSave is saved here and implemented by calling the firePowerSaveChanged method.
Here you will iterate through mChangeCallbacks and call back the method of onPowerSaveChanged.
The main ways to implement callbacks are:
BatteryMeterView.java
StatusBar.java
KeyguardStatusBarView.java
LightBarController.java
BatterySaverTile.java
This is where the SystemUI and interface show some of the above actions.
- ACTION_POWER_SAVE_MODE_CHANGED
The broadcast, like before, added a Flag: FLAG_RECEIVER_REGISTERED_ONLY
The main operations of the recipient are:
And what are the six radio stations doing?
class | Effect |
---|---|
BatteryBroadcastReceiver | Notify the change of battery power, enter power save mode |
PowerUI | If in power save mode, ignore the warning that the battery is low |
DeviceStateMonitor | Set modem to power save mode |
SoundTriggerHelper | Turn off voice interaction |
GnssLocationProvider | Limit gps usage, shut down gps after screen goes off |
The final call to DeviceStateMonitor is as follows:
The implementation of SoundTriggerHelper is to change the value of mIsPowerSaveMode for the following purposes:
The call to GnssLocationProvider is implemented as follows and can be easily read from comments.
- Finally, an array callback function that was previously saved:
Listeners mentioned this in our previous article, which summarizes in detail:
class | Effect |
---|---|
VibratorService.java | Cancel the vibration effect of mobile phone |
NetworkPolicyManagerService.java | Update whitelist and apply restrictions on network access |
WindowManagerService.java | Cancel window animation |
The NetworkPolicyManagerService calls as follows:
- Updating temporary whitelist, whitelist, whitelist except idle app will allow network access
- Allow network access if process priority is above foreground service
- isUidValidForBlacklistRules do not allow updates when uid is of type media or drm, or app s previously authorized for INTERNET network access
- If it is a foreground process, access to the network is allowed even in restricted mode
- Other processes, non-whitelist will be set to deny access to RULE_REJECT_ALL
For WindowManagerService, the effect is to cancel the window animation.
Источник