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 import android.support.annotation.VisibleForTesting; 21 22 public class ManagedProvisioningSharedPreferences { 23 public static final long DEFAULT_PROVISIONING_ID = 0L; 24 25 @VisibleForTesting 26 static final String KEY_PROVISIONING_ID = "provisioning_id"; 27 28 @VisibleForTesting 29 static final String SHARED_PREFERENCE = "managed_profile_shared_preferences"; 30 31 /** 32 * It's a process-wise in-memory write lock. No other processes will write the same file. 33 */ 34 private static final Object sWriteLock = new Object(); 35 36 private final SharedPreferences mSharedPreferences; 37 38 public ManagedProvisioningSharedPreferences(Context context) { 39 mSharedPreferences = context.getSharedPreferences(SHARED_PREFERENCE, Context.MODE_PRIVATE); 40 } 41 42 @VisibleForTesting 43 public long getProvisioningId() { 44 return mSharedPreferences.getLong(KEY_PROVISIONING_ID, DEFAULT_PROVISIONING_ID); 45 } 46 47 /** 48 * Can assume the id is unique across all provisioning sessions 49 * @return a new provisioning id by incrementing the current id 50 */ 51 public long incrementAndGetProvisioningId() { 52 synchronized (sWriteLock) { 53 long provisioningId = getProvisioningId(); 54 provisioningId++; 55 // commit synchronously 56 mSharedPreferences.edit().putLong(KEY_PROVISIONING_ID, provisioningId).commit(); 57 return provisioningId; 58 } 59 } 60 } 61