54 lines
1.9 KiB
Java
54 lines
1.9 KiB
Java
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) {
|
||
if (isAppIgnoringBatteryOptimizations(context)) {
|
||
Timber.d("已在忽略电池优化白名单");
|
||
return;
|
||
}
|
||
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.ACTION_VIEW);
|
||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
|
||
intent.setData(Uri.parse("package:" + packageName));
|
||
context.startActivity(intent);
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|