1 /*
2  * Copyright (C) 2021 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.calendar.alerts
17 
18 import android.app.IntentService
19 import android.content.ContentValues
20 import android.content.Intent
21 import android.net.Uri
22 import android.os.SystemClock
23 import android.provider.CalendarContract
24 import android.util.Log
25 
26 /**
27  * Service for clearing all scheduled alerts from the CalendarAlerts table and
28  * rescheduling them.  This is expected to be called only on boot up, to restore
29  * the AlarmManager alarms that were lost on device restart.
30  */
31 class InitAlarmsService : IntentService("InitAlarmsService") {
32     @Override
onHandleIntentnull33     protected override fun onHandleIntent(intent: Intent?) {
34         // Delay to avoid race condition of in-progress alarm scheduling in provider.
35         SystemClock.sleep(DELAY_MS)
36         Log.d(TAG, "Clearing and rescheduling alarms.")
37         try {
38             getContentResolver().update(
39                 SCHEDULE_ALARM_REMOVE_URI, ContentValues(), null,
40                 null
41             )
42         } catch (e: java.lang.IllegalArgumentException) {
43             // java.lang.IllegalArgumentException:
44             //     Unknown URI content://com.android.calendar/schedule_alarms_remove
45 
46             // Until b/7742576 is resolved, just catch the exception so the app won't crash
47             Log.e(TAG, "update failed: " + e.toString())
48         }
49     }
50 
51     companion object {
52         private const val TAG = "InitAlarmsService"
53         private const val SCHEDULE_ALARM_REMOVE_PATH = "schedule_alarms_remove"
54         private val SCHEDULE_ALARM_REMOVE_URI: Uri = Uri.withAppendedPath(
55             CalendarContract.CONTENT_URI, SCHEDULE_ALARM_REMOVE_PATH
56         )
57 
58         // Delay for rescheduling the alarms must be great enough to minimize race
59         // conditions with the provider's boot up actions.
60         private const val DELAY_MS: Long = 30000
61     }
62 }