1 /*
2  * Copyright (C) 2015 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.app.AlarmManager;
20 import android.app.PendingIntent;
21 import android.app.backup.BackupAgent;
22 import android.app.backup.BackupDataInput;
23 import android.app.backup.BackupDataOutput;
24 import android.content.ContentResolver;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.SharedPreferences;
29 import android.os.ParcelFileDescriptor;
30 import android.os.SystemClock;
31 import android.preference.PreferenceManager;
32 import android.support.annotation.NonNull;
33 
34 import com.android.deskclock.alarms.AlarmStateManager;
35 import com.android.deskclock.provider.Alarm;
36 import com.android.deskclock.provider.AlarmInstance;
37 
38 import java.io.File;
39 import java.io.IOException;
40 import java.util.Calendar;
41 import java.util.List;
42 
43 public class DeskClockBackupAgent extends BackupAgent {
44 
45     private static final String KEY_RESTORE_FINISHED = "restore_finished";
46 
47     public static final String ACTION_COMPLETE_RESTORE =
48             "com.android.deskclock.action.COMPLETE_RESTORE";
49 
50     private static final String TAG = "DeskClockBackupAgent";
51 
52     @Override
onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)53     public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
54             ParcelFileDescriptor newState) throws IOException { }
55 
56     @Override
onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)57     public void onRestore(BackupDataInput data, int appVersionCode,
58             ParcelFileDescriptor newState) throws IOException { }
59 
60     @Override
onRestoreFile(@onNull ParcelFileDescriptor data, long size, File destination, int type, long mode, long mtime)61     public void onRestoreFile(@NonNull ParcelFileDescriptor data, long size, File destination,
62             int type, long mode, long mtime) throws IOException {
63         // The preference file on the backup device may not be the same on the restore device.
64         // Massage the file name here before writing it.
65         if (destination.getName().endsWith("_preferences.xml")) {
66             final String prefFileName = getPackageName() + "_preferences.xml";
67             destination = new File(destination.getParentFile(), prefFileName);
68         }
69 
70         super.onRestoreFile(data, size, destination, type, mode, mtime);
71     }
72 
73     /**
74      * When this method is called during backup/restore, the application is executing in a
75      * "minimalist" state. Because of this, the application's ContentResolver cannot be used.
76      * Consequently, the work of scheduling alarms on the restore device cannot be done here.
77      * Instead, a future callback to DeskClock is used as a signal to reschedule the alarms. The
78      * future callback may take the form of ACTION_BOOT_COMPLETED if the device is not yet fully
79      * booted (i.e. the restore occurred as part of the setup wizard). If the device is booted, an
80      * ACTION_COMPLETE_RESTORE broadcast is scheduled 10 seconds in the future to give
81      * backup/restore enough time to kill the Clock process. Both of these future callbacks result
82      * in the execution of {@link #processRestoredData(Context)}.
83      */
84     @Override
onRestoreFinished()85     public void onRestoreFinished() {
86         if (Utils.isNOrLater()) {
87             // TODO: migrate restored database and preferences over into
88             // the device-protected storage area
89         }
90 
91         // Write a preference to indicate a data restore has been completed.
92         final SharedPreferences prefs = Utils.getDefaultSharedPreferences(this);
93         prefs.edit().putBoolean(KEY_RESTORE_FINISHED, true).apply();
94 
95         // Create an Intent to send into DeskClock indicating restore is complete.
96         final PendingIntent restoreIntent = PendingIntent.getBroadcast(this, 0,
97                 new Intent(ACTION_COMPLETE_RESTORE).setClass(this, AlarmInitReceiver.class),
98                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
99 
100         // Deliver the Intent 10 seconds from now.
101         final long triggerAtMillis = SystemClock.elapsedRealtime() + 10000;
102 
103         // Schedule the Intent delivery in AlarmManager.
104         final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
105         alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, restoreIntent);
106 
107         LogUtils.i(TAG, "Waiting for %s to complete the data restore", ACTION_COMPLETE_RESTORE);
108     }
109 
110     /**
111      * @param context a context to access resources and services
112      * @return {@code true} if restore data was processed; {@code false} otherwise.
113      */
processRestoredData(Context context)114     public static boolean processRestoredData(Context context) {
115         // If the preference indicates data was not recently restored, there is nothing to do.
116         final SharedPreferences prefs = Utils.getDefaultSharedPreferences(context);
117         if (!prefs.getBoolean(KEY_RESTORE_FINISHED, false)) {
118             return false;
119         }
120 
121         LogUtils.i(TAG, "processRestoredData() started");
122 
123         // Now that alarms have been restored, schedule new instances in AlarmManager.
124         final ContentResolver contentResolver = context.getContentResolver();
125         final List<Alarm> alarms = Alarm.getAlarms(contentResolver, null);
126 
127         final Calendar now = Calendar.getInstance();
128         for (Alarm alarm : alarms) {
129             // Remove any instances that may currently exist for the alarm;
130             // these aren't relevant on the restore device and we'll recreate them below.
131             AlarmStateManager.deleteAllInstances(context, alarm.id);
132 
133             if (alarm.enabled) {
134                 // Create the next alarm instance to schedule.
135                 AlarmInstance alarmInstance = alarm.createInstanceAfter(now);
136 
137                 // Add the next alarm instance to the database.
138                 alarmInstance = AlarmInstance.addInstance(contentResolver, alarmInstance);
139 
140                 // Schedule the next alarm instance in AlarmManager.
141                 AlarmStateManager.registerInstance(context, alarmInstance, true);
142                 LogUtils.i(TAG, "DeskClockBackupAgent scheduled alarm instance: %s", alarmInstance);
143             }
144         }
145 
146         // Remove the preference to avoid executing this logic multiple times.
147         prefs.edit().remove(KEY_RESTORE_FINISHED).apply();
148 
149         LogUtils.i(TAG, "processRestoredData() completed");
150         return true;
151     }
152 }