创建 BatteryOptimizationUtil.java
parent
2363429491
commit
cfbca44456
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.nbee.echolink.utils;
|
||||||
|
|
||||||
|
import static android.content.Context.POWER_SERVICE;
|
||||||
|
import static androidx.core.content.ContextCompat.getSystemService;
|
||||||
|
import static androidx.core.content.ContextCompat.startActivity;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.os.PowerManager;
|
||||||
|
import android.provider.Settings;
|
||||||
|
|
||||||
|
import timber.log.Timber;
|
||||||
|
|
||||||
|
public class BatteryOptimizationUtil {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查应用是否在电池优化白名单中。
|
||||||
|
*/
|
||||||
|
public static boolean isAppIgnoringBatteryOptimizations(Context context) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
|
||||||
|
if (pm != null) {
|
||||||
|
return pm.isIgnoringBatteryOptimizations(context.getPackageName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true; // 在低于Android 6.0的设备上,默认为true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求将应用加入电池优化白名单。
|
||||||
|
*/
|
||||||
|
public static void requestIgnoreBatteryOptimization(Context context) {
|
||||||
|
Timber.d("请求电池优化白名单");
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
String packageName = context.getPackageName();
|
||||||
|
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||||
|
if (pm != null && !pm.isIgnoringBatteryOptimizations(packageName)) {
|
||||||
|
Intent intent = new Intent();
|
||||||
|
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
|
||||||
|
intent.setData(Uri.parse("package:" + packageName));
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 添加FLAG_ACTIVITY_NEW_TASK标志
|
||||||
|
context.startActivity(intent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue