2016-08-31 54 views
4

Android 6和7具有某些功率優化(打盹模式),用於在未使用設備時限制應用程序聯網。檢查電池優化是否已啓用或不適用於應用程序

用戶可以在電池的設置來禁用任何應用優化模式:

android settings screenshot

是否可以檢查是否優化我的應用程序啓用與否?我需要問用戶禁用優化更好的應用程序功能,但我不知道如何以編程方式檢查它。

回答

1

科特林

/** 
* return false if in settings "Not optimized" and true if "Optimizing battery use" 
*/ 
fun checkBatteryOptimized(): Boolean { 
    val pwrm = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager 
    val name = applicationContext.packageName 
    if (VERSION.SDK_INT >= VERSION_CODES.M) { 
     return !pwrm.isIgnoringBatteryOptimizations(name) 
    } 
    return false 
} 

,這表明優化活動

fun checkBattery() { 
    if (isBatteryOptimized() && VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { 
     val name = resources.getString(R.string.app_name) 
     Toast.makeText(applicationContext, "Battery optimization -> All apps -> $name -> Don't optimize", Toast.LENGTH_LONG).show() 

     val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) 
     startActivity(intent) 
    } 
} 
相關問題