我编写了一个 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;
}
}
谷歌对 Android 8 进行了限制以优化电池。
即使在使用服务时,这也会限制后台工作。
我找到了解决这个问题的方法:使用PowerManager。
添加清单权限:
<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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)