1 /*
2  * Copyright (C) 2020 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 
17 package com.android.deskclock
18 
19 import android.annotation.TargetApi
20 import android.app.Application
21 import android.content.Context
22 import android.content.SharedPreferences
23 import android.os.Build
24 import android.preference.PreferenceManager
25 
26 import com.android.deskclock.controller.Controller
27 import com.android.deskclock.data.DataModel
28 import com.android.deskclock.events.LogEventTracker
29 import com.android.deskclock.uidata.UiDataModel
30 
31 class DeskClockApplication : Application() {
32     override fun onCreate() {
33         super.onCreate()
34 
35         val applicationContext = applicationContext
36         val prefs = getDefaultSharedPreferences(applicationContext)
37 
38         DataModel.dataModel.init(applicationContext, prefs)
39         UiDataModel.uiDataModel.init(applicationContext, prefs)
40         Controller.getController().setContext(applicationContext)
41         Controller.getController().addEventTracker(LogEventTracker(applicationContext))
42     }
43 
44     companion object {
45         /**
46          * Returns the default [SharedPreferences] instance from the underlying storage context.
47          */
48         @TargetApi(Build.VERSION_CODES.N)
49         private fun getDefaultSharedPreferences(context: Context): SharedPreferences {
50             val storageContext: Context
51             if (Utils.isNOrLater) {
52                 // All N devices have split storage areas. Migrate the existing preferences
53                 // into the new device encrypted storage area if that has not yet occurred.
54                 val name = PreferenceManager.getDefaultSharedPreferencesName(context)
55                 storageContext = context.createDeviceProtectedStorageContext()
56                 if (!storageContext.moveSharedPreferencesFrom(context, name)) {
57                     LogUtils.wtf("Failed to migrate shared preferences")
58                 }
59             } else {
60                 storageContext = context
61             }
62             return PreferenceManager.getDefaultSharedPreferences(storageContext)
63         }
64     }
65 }