1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings.fuelgauge.anomaly.action;
18
19import android.app.AppOpsManager;
20import android.content.Context;
21import android.os.Build;
22import android.support.annotation.VisibleForTesting;
23
24import com.android.internal.logging.nano.MetricsProto;
25import com.android.settings.fuelgauge.BatteryUtils;
26import com.android.settings.fuelgauge.anomaly.Anomaly;
27
28/**
29 * Background check action for anomaly app, which means to stop app running in the background
30 */
31public class BackgroundCheckAction extends AnomalyAction {
32
33    private AppOpsManager mAppOpsManager;
34    @VisibleForTesting
35    BatteryUtils mBatteryUtils;
36
37    public BackgroundCheckAction(Context context) {
38        super(context);
39        mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
40        mActionMetricKey = MetricsProto.MetricsEvent.ACTION_APP_BACKGROUND_CHECK;
41        mBatteryUtils = BatteryUtils.getInstance(context);
42    }
43
44    @Override
45    public void handlePositiveAction(Anomaly anomaly, int contextMetricsKey) {
46        super.handlePositiveAction(anomaly, contextMetricsKey);
47        if (anomaly.targetSdkVersion < Build.VERSION_CODES.O) {
48            mAppOpsManager.setMode(AppOpsManager.OP_RUN_IN_BACKGROUND, anomaly.uid,
49                    anomaly.packageName,
50                    AppOpsManager.MODE_IGNORED);
51        }
52    }
53
54    @Override
55    public boolean isActionActive(Anomaly anomaly) {
56        return !mBatteryUtils.isBackgroundRestrictionEnabled(anomaly.targetSdkVersion, anomaly.uid,
57                anomaly.packageName);
58    }
59
60    @Override
61    public int getActionType() {
62        return Anomaly.AnomalyActionType.BACKGROUND_CHECK;
63    }
64}
65