【问题标题】:Background service stops in battery saver mode in android R后台服务在android R中以省电模式停止
【发布时间】:2020-08-17 21:50:52
【问题描述】:

我编写了一个安卓应用程序,它通过改变电量来检查电池电量,并在电量达到一定值时发出警报。 我在我的应用程序中使用了广播接收器和后台服务。 它在所有 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;
  }
}

【问题讨论】:

    标签: android battery background-service battery-saver


    【解决方案1】:

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

    为清单添加权限:

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

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

    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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多