1 /* 2 * Copyright 2016, 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 package com.android.managedprovisioning.common; 17 18 import android.content.Context; 19 import android.content.SharedPreferences; 20 21 import androidx.annotation.Keep; 22 import androidx.annotation.VisibleForTesting; 23 24 import java.util.Collections; 25 import java.util.Set; 26 27 public class ManagedProvisioningSharedPreferences { 28 public static final long DEFAULT_PROVISIONING_ID = 0L; 29 30 @VisibleForTesting 31 static final String KEY_PROVISIONING_ID = "provisioning_id"; 32 33 @VisibleForTesting 34 static final String KEY_PROVISIONING_START_TIMESTAMP = "provisioning_start_timestamp"; 35 36 @VisibleForTesting 37 static final String SHARED_PREFERENCE = "managed_profile_shared_preferences"; 38 39 /** 40 * It's a process-wise in-memory write lock. No other processes will write the same file. 41 */ 42 private static final Object sWriteLock = new Object(); 43 44 private final SharedPreferences mSharedPreferences; 45 ManagedProvisioningSharedPreferences(Context context)46 public ManagedProvisioningSharedPreferences(Context context) { 47 mSharedPreferences = context.getSharedPreferences(SHARED_PREFERENCE, Context.MODE_PRIVATE); 48 } 49 50 @VisibleForTesting getProvisioningId()51 public long getProvisioningId() { 52 return mSharedPreferences.getLong(KEY_PROVISIONING_ID, DEFAULT_PROVISIONING_ID); 53 } 54 55 /** 56 * Can assume the id is unique across all provisioning sessions 57 * @return a new provisioning id by incrementing the current id 58 */ incrementAndGetProvisioningId()59 public long incrementAndGetProvisioningId() { 60 synchronized (sWriteLock) { 61 long provisioningId = getProvisioningId(); 62 provisioningId++; 63 // commit synchronously 64 mSharedPreferences.edit().putLong(KEY_PROVISIONING_ID, provisioningId).commit(); 65 return provisioningId; 66 } 67 } 68 69 /** 70 * @param time the provisioning started timestamp, in milliseconds 71 */ writeProvisioningStartedTimestamp(long time)72 public void writeProvisioningStartedTimestamp(long time) { 73 mSharedPreferences.edit() 74 .putLong(KEY_PROVISIONING_START_TIMESTAMP, time) 75 .apply(); 76 } 77 78 /** 79 * @return the provisioning started timestamp, in milliseconds 80 */ getProvisioningStartedTimestamp()81 public long getProvisioningStartedTimestamp() { 82 return mSharedPreferences.getLong(KEY_PROVISIONING_START_TIMESTAMP, 0L); 83 } 84 } 85