Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 6e42055d authored by Lei Yu's avatar Lei Yu Committed by Android (Google) Code Review
Browse files

Merge changes from topics "ww_4_delete_data", "ww_3_checkconfig",...

Merge changes from topics "ww_4_delete_data", "ww_3_checkconfig", "ww_2_uploadIntent", "ww_1_receiver"

* changes:
  Add JobService to delete obsolete anomaly data
  Add code to handle anomaly config update
  Add AnomalyConfigReceiver
  Add AnomalyDetectionReceiver
parents 8443e8f7 338ae2fd
Loading
Loading
Loading
Loading
+15 −0
Original line number Diff line number Diff line
@@ -3294,6 +3294,21 @@
            </intent-filter>
        </receiver>

        <!-- Couldn't be triggered from outside of settings. Statsd can trigger it because we send
             PendingIntent to it-->
        <receiver android:name=".fuelgauge.batterytip.AnomalyDetectionReceiver"
                  android:exported="false" />

        <receiver android:name=".fuelgauge.batterytip.AnomalyConfigReceiver">
            <intent-filter>
                <action android:name="android.app.action.STATSD_STARTED"/>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <service android:name=".fuelgauge.batterytip.AnomalyCleanUpJobService"
                 android:permission="android.permission.BIND_JOB_SERVICE" />

        <!-- This is the longest AndroidManifest.xml ever. -->
    </application>
</manifest>
+1 −0
Original line number Diff line number Diff line
@@ -18,6 +18,7 @@
-->
<resources>
    <item type="id" name="preference_highlighted" />
    <item type="id" name="job_anomaly_clean_up" />

    <item type="id" name="lock_none" />
    <item type="id" name="lock_pin" />
+75 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.fuelgauge.batterytip;

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.VisibleForTesting;
import android.util.Log;

import com.android.settings.R;
import com.android.settingslib.utils.ThreadUtils;

import java.util.concurrent.TimeUnit;

/** A JobService to clean up obsolete data in anomaly database */
public class AnomalyCleanUpJobService extends JobService {
    private static final String TAG = "AnomalyCleanUpJobService";

    @VisibleForTesting
    static final long CLEAN_UP_FREQUENCY_MS = TimeUnit.DAYS.toMillis(1);

    public static void scheduleCleanUp(Context context) {
        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);

        final ComponentName component = new ComponentName(context, AnomalyCleanUpJobService.class);
        final JobInfo.Builder jobBuilder =
                new JobInfo.Builder(R.id.job_anomaly_clean_up, component)
                .setMinimumLatency(CLEAN_UP_FREQUENCY_MS)
                .setRequiresDeviceIdle(true)
                .setPersisted(true);

        if (jobScheduler.schedule(jobBuilder.build()) != JobScheduler.RESULT_SUCCESS) {
            Log.i(TAG, "Anomaly clean up job service schedule failed.");
        }
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        final BatteryDatabaseManager batteryDatabaseManager = BatteryDatabaseManager
                .getInstance(this);
        final BatteryTipPolicy policy = new BatteryTipPolicy(this);
        ThreadUtils.postOnBackgroundThread(() -> {
            batteryDatabaseManager.deleteAllAnomaliesBeforeTimeStamp(
                    System.currentTimeMillis() - TimeUnit.HOURS.toMillis(
                            policy.dataHistoryRetainHour));
            jobFinished(params, false /* wantsReschedule */);
        });

        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}
+94 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.fuelgauge.batterytip;

import android.app.PendingIntent;
import android.app.StatsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;

import com.android.internal.annotations.VisibleForTesting;

/**
 * Receive broadcast when {@link StatsManager} restart, then check the anomaly config and
 * prepare info for {@link StatsManager}
 */
public class AnomalyConfigReceiver extends BroadcastReceiver {
    private static final String TAG = "AnomalyConfigReceiver";
    private static final int REQUEST_CODE = 0;
    private static final String PREF_DB = "anomaly_pref";
    private static final String KEY_ANOMALY_CONFIG_VERSION = "anomaly_config_version";
    private static final int DEFAULT_VERSION = 0;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (StatsManager.ACTION_STATSD_STARTED.equals(intent.getAction())
                || Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            final StatsManager statsManager = context.getSystemService(StatsManager.class);

            // Check whether to update the config
            checkAnomalyConfig(context, statsManager);

            // Upload PendingIntent to StatsManager
            final Intent extraIntent = new Intent(context, AnomalyDetectionReceiver.class);
            final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE,
                    extraIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            uploadPendingIntent(statsManager, pendingIntent);
        }
    }

    @VisibleForTesting
    void uploadPendingIntent(StatsManager statsManager, PendingIntent pendingIntent) {
        Log.i(TAG, "Upload PendingIntent to StatsManager. configKey: "
                + StatsManagerConfig.ANOMALY_CONFIG_KEY + " subId: "
                + StatsManagerConfig.SUBSCRIBER_ID);
        statsManager.setBroadcastSubscriber(StatsManagerConfig.ANOMALY_CONFIG_KEY,
                StatsManagerConfig.SUBSCRIBER_ID, pendingIntent);
    }

    private void checkAnomalyConfig(Context context, StatsManager statsManager) {
        final SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_DB,
                Context.MODE_PRIVATE);
        final int currentVersion = sharedPreferences.getInt(KEY_ANOMALY_CONFIG_VERSION,
                DEFAULT_VERSION);
        final int newVersion = Settings.Global.getInt(context.getContentResolver(),
                Settings.Global.ANOMALY_CONFIG_VERSION, DEFAULT_VERSION);
        Log.i(TAG, "CurrentVersion: " + currentVersion + " new version: " + newVersion);

        if (newVersion > currentVersion) {
            final byte[] config = Base64.decode(
                    Settings.Global.getString(context.getContentResolver(),
                            Settings.Global.ANOMALY_CONFIG), Base64.DEFAULT);
            if (statsManager.addConfiguration(StatsManagerConfig.ANOMALY_CONFIG_KEY, config)) {
                Log.i(TAG, "Upload the anomaly config. configKey: "
                        + StatsManagerConfig.ANOMALY_CONFIG_KEY);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt(KEY_ANOMALY_CONFIG_VERSION, newVersion);
                editor.apply();
            } else {
                Log.i(TAG, "Upload the anomaly config failed. configKey: "
                        + StatsManagerConfig.ANOMALY_CONFIG_KEY);
            }
        }
    }
}
+78 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.fuelgauge.batterytip;

import android.app.StatsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.StatsDimensionsValue;
import android.support.annotation.VisibleForTesting;
import android.util.Log;

import com.android.settings.fuelgauge.BatteryUtils;

import java.util.List;

/**
 * Receive the anomaly info from {@link StatsManager}
 */
public class AnomalyDetectionReceiver extends BroadcastReceiver {
    private static final String TAG = "SettingsAnomalyReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        final BatteryDatabaseManager databaseManager = BatteryDatabaseManager.getInstance(context);
        final BatteryUtils batteryUtils = BatteryUtils.getInstance(context);
        final long configUid = intent.getLongExtra(StatsManager.EXTRA_STATS_CONFIG_UID, -1);
        final long configKey = intent.getLongExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, -1);
        final long subscriptionId = intent.getLongExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID,
                -1);

        Log.i(TAG, "Anomaly intent received.  configUid = " + configUid + " configKey = "
                + configKey + " subscriptionId = " + subscriptionId);
        saveAnomalyToDatabase(databaseManager, batteryUtils, intent);

        AnomalyCleanUpJobService.scheduleCleanUp(context);
    }

    @VisibleForTesting
    void saveAnomalyToDatabase(BatteryDatabaseManager databaseManager, BatteryUtils batteryUtils
            , Intent intent) {
        // The Example of intentDimsValue is: 35:{1:{1:{1:10013|}|}|}
        StatsDimensionsValue intentDimsValue =
                intent.getParcelableExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE);
        Log.i(TAG, "Extra stats value: " + intentDimsValue.toString());
        List<StatsDimensionsValue> intentTuple = intentDimsValue.getTupleValueList();

        if (!intentTuple.isEmpty()) {
            try {
                // TODO(b/72385333): find more robust way to extract the uid.
                final StatsDimensionsValue intentTupleValue = intentTuple.get(0)
                        .getTupleValueList().get(0).getTupleValueList().get(0);
                final int uid = intentTupleValue.getIntValue();
                // TODD(b/72385333): extract anomaly type
                final int anomalyType = 0;
                final String packageName = batteryUtils.getPackageName(uid);
                final long timeMs = System.currentTimeMillis();
                databaseManager.insertAnomaly(packageName, anomalyType, timeMs);
            } catch (NullPointerException | IndexOutOfBoundsException e) {
                Log.e(TAG, "Parse stats dimensions value error.", e);
            }
        }
    }
}
Loading