我覺得大部分程序員不會太在意電池優化這件事兒。因爲耗電和產品需求或者設計有衝突的時候,99%的時候都是犧牲耗電量。所以我覺得電池優化最大的關鍵在於——溝通!你能說服產品改需求,或者是設計改設計稿,那你優化成功了。代碼上的修改遠不如他們需求與設計上的修改。
我就列舉下android5.0以來對電池方面做得優化以及,哪些API被改動了。
這上面比較重點的就是,請注意7.0以後隱式廣播被移除了,意思就是你靜態註冊的廣播,很多都收不到了,你需要動態註冊。
不過有辦法修改發送廣播的地方,讓靜態廣播能收到,但是註冊的系統靜態廣播就收不到了。
以及6.0引入的低電耗模式,在這個模式下,你有的API可能會沒法返回正確的值給你。我待會兒會舉出幾個。
這個是獲取充電方式的方法,在低電耗模式會拿不到值。
//獲取充電方式
public static boolean isPlugged(Context context){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
Intent intent=context.registerReceiver(null,intentFilter);
int state=intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);
boolean ac_power=state==BatteryManager.BATTERY_PLUGGED_AC;
boolean usb_power=state==BatteryManager.BATTERY_PLUGGED_USB;
boolean wire_power=state==BatteryManager.BATTERY_PLUGGED_WIRELESS;
return ac_power||usb_power||wire_power;
}
這個是獲取充電狀態值,可以在低電耗模式下拿到,所以我推薦用下面這個判斷
//獲取是否充滿/正在充電
public static boolean isPowerState(Context context){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
Intent intent=context.registerReceiver(null,intentFilter);
int state=intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
boolean full_power=state==BatteryManager.BATTERY_STATUS_FULL;
boolean charging_power=state==BatteryManager.BATTERY_STATUS_CHARGING;
return full_power||charging_power;
}
這個是申請添加應用到白名單的方法
//添加應用到白名單
public static void addWhiteList(Activity activity){
PowerManager powerManager= (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
if(!powerManager.isIgnoringBatteryOptimizations(activity.getPackageName())){
Intent intent=new Intent( Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS );
intent.setData(Uri.parse("package:"+activity.getPackageName()));
activity.startActivity(intent);
}
}
上面是低功耗那次修改推薦使用的方法,下面那個實測,不會準時啓動。
//6.0以後用這個很準
alarmManager.setExactAndAllowWhileIdle();
//6.0以後用這個不知道什麼時候會觸發
alarmManager.setRepeating();
今天既然講電量優化,總結我都寫在開頭了,代碼上能做到的真的很有限。產品少來幾個奇怪的需求,設計少來幾個狂拽酷炫叼的動畫,電量很經用的。我們又不是有病要讓用戶多耗電,我們也只是在做我們的工作。