android 申请忽略电池节电

 1      fun checkBattery(){
 2         var main = activity as MainActivity
 3         if(main.isIgnoringBatteryOptimizations()){
 4             Log.e("SplashFrgmt","在白名单")
 5         }else{
 6             Log.e("SplashFrgmt","不在白名单")
 7             main.requestIgnoreBatteryOptimizations()
 8         }
 9     }
10 
11     fun requestIgnoreBatteryOptimizations(){
12         try {
13             var intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
14             intent.setData(Uri.parse("package:" + getPackageName()))
15             val battery = 3032
16             startActivityForResult(intent,battery)
17         } catch ( e : Exception) {
18             e.printStackTrace()
19         }
20     }
21 
22  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
23         super.onActivityResult(requestCode, resultCode, data)
24         val NOTIFY_PER = 10293
25         val BATTERY = 3032
26 
27         when(requestCode){
28             NOTIFY_PER-> {
29                 ...
30             }
31             BATTERY->{
32                 var ret = isIgnoringBatteryOptimizations()
33                 Log.e("requestCode","requestCode = $resultCode ,ret = $ret")
34                 if(!ret){
35                     Toast.makeText(baseContext,"申请忽略电池节电失败,锁屏后应用可能被杀!",Toast.LENGTH_LONG).show()
36                 }
37             }
38         }
39     }

 

fun checkBattery(){
var main = activity as MainActivity
if(main.isIgnoringBatteryOptimizations()){
Log.e("SplashFrgmt","在白名单")
}else{
Log.e("SplashFrgmt","不在白名单")
main.requestIgnoreBatteryOptimizations()
}
}
posted @ 2020-05-06 11:54  f9q  阅读(491)  评论(0编辑  收藏  举报