1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("AutoOnFeature")
package com.android.server.bluetooth
import android.app.AlarmManager
import android.app.BroadcastOptions
import android.bluetooth.BluetoothAdapter.ACTION_AUTO_ON_STATE_CHANGED
import android.bluetooth.BluetoothAdapter.AUTO_ON_STATE_DISABLED
import android.bluetooth.BluetoothAdapter.AUTO_ON_STATE_ENABLED
import android.bluetooth.BluetoothAdapter.EXTRA_AUTO_ON_STATE
import android.bluetooth.BluetoothAdapter.STATE_ON
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import com.android.modules.expresslog.Counter
import com.android.server.bluetooth.airplane.hasUserToggledApm as hasUserToggledApm
import com.android.server.bluetooth.airplane.isOnOverrode as isAirplaneModeOn
import com.android.server.bluetooth.satellite.isOn as isSatelliteModeOn
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration
private const val TAG = "AutoOnFeature"
public fun resetAutoOnTimerForUser(
looper: Looper,
context: Context,
state: BluetoothAdapterState,
callback_on: () -> Unit
) {
// Remove any previous timer
timer?.cancel()
timer = null
if (!isFeatureEnabledForUser(context.contentResolver)) {
Log.d(TAG, "Not Enabled for current user: ${context.getUser()}")
return
}
if (state.oneOf(STATE_ON)) {
Log.d(TAG, "Bluetooth already in ${state}, no need for timer")
return
}
if (isSatelliteModeOn) {
Log.d(TAG, "Satellite prevent feature activation")
return
}
if (isAirplaneModeOn) {
if (!hasUserToggledApm(context)) {
Log.d(TAG, "Airplane prevent feature activation")
return
}
Log.d(TAG, "Airplane bypassed as airplane enhanced mode has been activated previously")
}
val receiver =
object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
Log.i(TAG, "Received ${intent.action} that trigger a new alarm scheduling")
pause()
resetAutoOnTimerForUser(looper, context, state, callback_on)
}
}
timer = Timer.start(looper, context, receiver, callback_on)
}
public fun pause() {
timer?.pause()
timer = null
}
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
public fun notifyBluetoothOn(context: Context) {
timer?.cancel()
timer = null
if (!isFeatureSupportedForUser(context.contentResolver)) {
val defaultFeatureValue = true
if (!setFeatureEnabledForUserUnchecked(context, defaultFeatureValue)) {
Log.e(TAG, "Failed to set feature to its default value ${defaultFeatureValue}")
} else {
Log.i(TAG, "Feature was set to its default value ${defaultFeatureValue}")
}
} else {
// When Bluetooth turned on state, any saved time will be obsolete.
// This happen only when the phone reboot while Bluetooth is ON
Timer.resetStorage(context.contentResolver)
}
}
public fun isUserSupported(resolver: ContentResolver) = isFeatureSupportedForUser(resolver)
public fun isUserEnabled(context: Context): Boolean {
if (!isUserSupported(context.contentResolver)) {
throw IllegalStateException("AutoOnFeature not supported for user: ${context.getUser()}")
}
return isFeatureEnabledForUser(context.contentResolver)
}
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
public fun setUserEnabled(
looper: Looper,
context: Context,
state: BluetoothAdapterState,
status: Boolean,
callback_on: () -> Unit,
) {
if (!isUserSupported(context.contentResolver)) {
throw IllegalStateException("AutoOnFeature not supported for user: ${context.getUser()}")
}
if (isFeatureEnabledForUser(context.contentResolver) && status == true) {
Log.i(TAG, "setUserEnabled: Nothing to do, feature is already enabled")
return
}
if (!setFeatureEnabledForUserUnchecked(context, status)) {
throw IllegalStateException("AutoOnFeature database failure for user: ${context.getUser()}")
}
Counter.logIncrement(
if (status) "bluetooth.value_auto_on_enabled" else "bluetooth.value_auto_on_disabled"
)
Timer.resetStorage(context.contentResolver)
resetAutoOnTimerForUser(looper, context, state, callback_on)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// PRIVATE METHODS /////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
@VisibleForTesting internal var timer: Timer? = null
@VisibleForTesting
internal class Timer
private constructor(
looper: Looper,
private val context: Context,
private val receiver: BroadcastReceiver,
private val callback_on: () -> Unit,
private val now: LocalDateTime,
private val target: LocalDateTime,
private val timeToSleep: Duration
) : AlarmManager.OnAlarmListener {
private val alarmManager: AlarmManager = context.getSystemService(AlarmManager::class.java)!!
private val handler = Handler(looper)
init {
writeDateToStorage(target, context.contentResolver)
alarmManager.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + timeToSleep.inWholeMilliseconds,
"Bluetooth AutoOnFeature",
this,
handler
)
Log.i(TAG, "[${this}]: Scheduling next Bluetooth restart")
context.registerReceiver(
receiver,
IntentFilter().apply {
addAction(Intent.ACTION_DATE_CHANGED)
addAction(Intent.ACTION_TIMEZONE_CHANGED)
addAction(Intent.ACTION_TIME_CHANGED)
},
null,
handler
)
}
override fun onAlarm() {
Log.i(TAG, "[${this}]: Bluetooth restarting now")
callback_on()
cancel()
timer = null
}
companion object {
@VisibleForTesting internal val STORAGE_KEY = "bluetooth_internal_automatic_turn_on_timer"
private fun writeDateToStorage(date: LocalDateTime, resolver: ContentResolver): Boolean {
return Settings.Secure.putString(resolver, STORAGE_KEY, date.toString())
}
private fun getDateFromStorage(resolver: ContentResolver): LocalDateTime? {
val date = Settings.Secure.getString(resolver, STORAGE_KEY)
return date?.let { LocalDateTime.parse(it) }
}
fun resetStorage(resolver: ContentResolver) {
Settings.Secure.putString(resolver, STORAGE_KEY, null)
}
fun start(
looper: Looper,
context: Context,
receiver: BroadcastReceiver,
callback_on: () -> Unit
): Timer? {
val now = LocalDateTime.now()
val target = getDateFromStorage(context.contentResolver) ?: nextTimeout(now)
val timeToSleep =
now.until(target, ChronoUnit.NANOS).toDuration(DurationUnit.NANOSECONDS)
if (timeToSleep.isNegative()) {
Log.i(TAG, "Starting now (${now}) as it was scheduled for ${target}")
callback_on()
resetStorage(context.contentResolver)
return null
}
return Timer(looper, context, receiver, callback_on, now, target, timeToSleep)
}
/** Return a LocalDateTime for tomorrow 5 am */
private fun nextTimeout(now: LocalDateTime) =
LocalDateTime.of(now.toLocalDate(), LocalTime.of(5, 0)).plusDays(1)
}
/** Save timer to storage and stop it */
internal fun pause() {
Log.i(TAG, "[${this}]: Pausing timer")
context.unregisterReceiver(receiver)
alarmManager.cancel(this)
handler.removeCallbacksAndMessages(null)
}
/** Stop timer and reset storage */
@VisibleForTesting
internal fun cancel() {
Log.i(TAG, "[${this}]: Cancelling timer")
context.unregisterReceiver(receiver)
alarmManager.cancel(this)
handler.removeCallbacksAndMessages(null)
resetStorage(context.contentResolver)
}
override fun toString() =
"Timer was scheduled at ${now} and should expire at ${target}. (sleep for ${timeToSleep})."
}
@VisibleForTesting internal val USER_SETTINGS_KEY = "bluetooth_automatic_turn_on"
/**
* *Do not use outside of this file to avoid async issues*
*
* @return whether the auto on feature is enabled for this user
*/
private fun isFeatureEnabledForUser(resolver: ContentResolver): Boolean {
return Settings.Secure.getInt(resolver, USER_SETTINGS_KEY, 0) == 1
}
/**
* *Do not use outside of this file to avoid async issues*
*
* @return whether the auto on feature is supported for the user
*/
private fun isFeatureSupportedForUser(resolver: ContentResolver): Boolean {
return Settings.Secure.getInt(resolver, USER_SETTINGS_KEY, -1) != -1
}
/**
* *Do not use outside of this file to avoid async issues*
*
* @return whether the auto on feature is enabled for this user
*/
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
private fun setFeatureEnabledForUserUnchecked(context: Context, status: Boolean): Boolean {
val ret =
Settings.Secure.putInt(context.contentResolver, USER_SETTINGS_KEY, if (status) 1 else 0)
if (ret) {
context.sendBroadcast(
Intent(ACTION_AUTO_ON_STATE_CHANGED)
.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY)
.putExtra(
EXTRA_AUTO_ON_STATE,
if (status) AUTO_ON_STATE_ENABLED else AUTO_ON_STATE_DISABLED
),
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
BroadcastOptions.makeBasic()
.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
.toBundle(),
)
}
return ret
}
|