手动设置上
- 电池优化:不同手机路径不同,可直接搜索“电池”,找到带有“优化”的选项
以上可通过代码操作:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d("TINA", "isIgnoringBatteryOptimizations(): " + isIgnoringBatteryOptimizations());
if (!isIgnoringBatteryOptimizations()) {
requestIgnoreBatteryOptimizations();
Log.d("TINA", "requestIgnoreBatteryOptimizations(): ");
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isIgnoringBatteryOptimizations() {
boolean isIgnoring = false;
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
if(powerManager != null) {
isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
}
return isIgnoring;
}
private static int RESULT = 20;
@RequiresApi(api = Build.VERSION_CODES.M)
public void requestIgnoreBatteryOptimizations() {
try{
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:"+ getPackageName()));
startActivityForResult(intent, RESULT);
} catch(Exception e) {
e.printStackTrace();
}
}
- “电池与性能-设置-应用智能省电-无限制” 或者 “应用设置-应用管理-选择应用-省电策略-无限制”
代码上
增加前台服务
private void startNotification(Context context) {
Notification notification;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setTicker("Advertising测试")
.setContentTitle("Advertising测试标题")
.setContentText("Advertising测试内容")
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel();
builder.setChannelId("AdvertisingChannelId");
}
notification = builder.build();
startForeground(100, notification);
}
public void createNotificationChannel() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("AdvertisingChannelId", "AdvertisingChannelName", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
}
参考连接: 2020年了,Android后台保活还有戏吗?看我如何优雅的实现!
|