android - Android R 中的后台服务在省电模式下停止

标签 android battery background-service battery-saver

我编写了一个 Android 应用程序,它通过更改电量来检查电池电量,并在电量达到特定值时发出警报。 我在我的应用程序中使用了广播接收器和后台服务。 它在所有 Android 版本中都能正常工作,但在 Android R 中,当打开省电模式时,服务会停止。 我在多个模拟器和具有不同 Android 版本的真实设备上测试了我的应用程序,并且工作正常,但在 Android R 中出现问题。 有没有办法防止服务停止?

我的服务类别:

public class BatService extends Service {

  private BatReceiver receiver = new BatReceiver();

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    BatteryLevelAsync async = new BatteryLevelAsync();
    async.execute();

    return START_STICKY;
  }

  @Override
  public void onDestroy() {
    unregisterReceiver(receiver);

    super.onDestroy();
  }

  private class BatteryLevelAsync extends AsyncTask<Void,Void,Void>
  {
    @Override
    protected Void doInBackground(Void... voids) {
      registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      return null;
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}

最佳答案

Google 对 Android 8 施加了限制以优化电池。 即使在使用服务时,这也会限制后台工作。 我找到了解决这个问题的方法:使用 PowerManager。

向 list 添加权限:

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

并将以下代码添加到您的 Activity 中:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  String packageName = context.getPackageName();
  PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
  if (!pm.isIgnoringBatteryOptimizations(packageName)) {
    Intent intent = new Intent();
    intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setData(Uri.parse("package:" + packageName));
    context.startActivity(intent);
  }
}

关于android - Android R 中的后台服务在省电模式下停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63459111/

相关文章:

java - 比较 2 个 ArrayList<HashMap<String, String>> 之间的字符串

Javascript Battery API 返回无限放电时间

android - 作为业务需求,我必须让我的后台服务在我的 android 应用程序中始终运行

Android 无法解析主机

android - 为什么 iOS 模拟器比 Android 快得多?

android - 构造函数中的默认值显示Kotlin中的错误

excel - 检索计算机的充电状态和当前电池电量

iphone - 最小化 iOS 上应用程序的电池使用量(当手机被锁定时等)

android - 应用程序关闭后,WorkManager 停止调度周期性 Worker

android - 我在后台的 IntentService 如何始终监听设备的震动?