forked from home-assistant/android
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSettingsFragment.kt
More file actions
688 lines (618 loc) · 29.4 KB
/
SettingsFragment.kt
File metadata and controls
688 lines (618 loc) · 29.4 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
package io.homeassistant.companion.android.settings
import android.app.UiModeManager
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.getSystemService
import androidx.core.net.toUri
import androidx.fragment.app.commit
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import com.google.android.material.snackbar.Snackbar
import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.authenticator.Authenticator
import io.homeassistant.companion.android.common.R as commonR
import io.homeassistant.companion.android.common.util.isAutomotive
import io.homeassistant.companion.android.common.util.isIgnoringBatteryOptimizations
import io.homeassistant.companion.android.common.util.maybeAskForIgnoringBatteryOptimizations
import io.homeassistant.companion.android.database.server.Server
import io.homeassistant.companion.android.launch.intentLaunchOnboarding
import io.homeassistant.companion.android.nfc.NfcSetupActivity
import io.homeassistant.companion.android.settings.assist.AssistSettingsFragment
import io.homeassistant.companion.android.settings.assist.DefaultAssistantManager
import io.homeassistant.companion.android.settings.controls.ManageControlsSettingsFragment
import io.homeassistant.companion.android.settings.developer.DeveloperSettingsFragment
import io.homeassistant.companion.android.settings.gestures.GesturesFragment
import io.homeassistant.companion.android.settings.language.LanguagesProvider
import io.homeassistant.companion.android.settings.license.LicensesFragment
import io.homeassistant.companion.android.settings.notification.NotificationChannelFragment
import io.homeassistant.companion.android.settings.notification.NotificationHistoryFragment
import io.homeassistant.companion.android.settings.qs.ManageTilesFragment
import io.homeassistant.companion.android.settings.sensor.SensorSettingsFragment
import io.homeassistant.companion.android.settings.sensor.SensorUpdateFrequencyFragment
import io.homeassistant.companion.android.settings.server.ServerSettingsFragment
import io.homeassistant.companion.android.settings.shortcuts.ManageShortcutsSettingsFragment
import io.homeassistant.companion.android.settings.vehicle.ManageAndroidAutoSettingsFragment
import io.homeassistant.companion.android.settings.wear.SettingsWearActivity
import io.homeassistant.companion.android.settings.wear.SettingsWearDetection
import io.homeassistant.companion.android.settings.widgets.ManageWidgetsSettingsFragment
import io.homeassistant.companion.android.util.QuestUtil
import io.homeassistant.companion.android.util.applyBottomSafeDrawingInsets
import io.homeassistant.companion.android.webview.WebViewActivity
import io.homeassistant.companion.android.websocket.WebsocketManager
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import timber.log.Timber
class SettingsFragment(
private val presenter: SettingsPresenter,
private val langProvider: LanguagesProvider,
private val defaultAssistantManager: DefaultAssistantManager,
) : PreferenceFragmentCompat(),
SettingsView {
private val requestNotificationPermissionResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
updateNotificationChannelPrefs()
}
private var serverAuth: Int? = null
private val serverMutex = Mutex()
private var snackbar: Snackbar? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
presenter.init(this)
preferenceManager.preferenceDataStore = presenter.getPreferenceDataStore()
setPreferencesFromResource(R.xml.preferences, rootKey)
findPreference<Preference>("nfc_tags")?.let {
val pm: PackageManager = requireContext().packageManager
it.isVisible = pm.hasSystemFeature(PackageManager.FEATURE_NFC)
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(NfcSetupActivity.newInstance(requireActivity()))
true
}
}
removeSystemFromThemesIfNeeded()
updateBackgroundAccessPref()
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
presenter.getServersFlow().collect {
updateServers(it)
}
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
presenter.getSuggestionFlow().collect { suggestion ->
findPreference<SettingsSuggestionPreference>("settings_suggestion")?.let {
if (suggestion != null) {
it.setTitle(suggestion.title)
it.setSummary(suggestion.summary)
it.setIcon(suggestion.icon)
it.setOnPreferenceClickListener {
when (suggestion.id) {
SettingsPresenter.SUGGESTION_ASSISTANT_APP -> updateAssistantApp()
SettingsPresenter.SUGGESTION_NOTIFICATION_PERMISSION -> openNotificationSettings()
}
return@setOnPreferenceClickListener true
}
it.setOnPreferenceCancelListener {
presenter.cancelSuggestion(requireContext(), suggestion.id)
}
}
it.isVisible = suggestion != null
}
}
}
}
findPreference<Preference>("server_add")?.let {
it.setOnPreferenceClickListener {
requireContext().apply {
startActivity(
intentLaunchOnboarding(
urlToOnboard = null,
hideExistingServers = true,
skipWelcome = true,
),
)
}
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>("sensors")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, SensorSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.sensors))
}
return@setOnPreferenceClickListener true
}
findPreference<Preference>("sensor_update_frequency")?.let {
it.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, SensorUpdateFrequencyFragment::class.java, null)
addToBackStack(getString(commonR.string.sensor_update_frequency))
}
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>("assist_settings")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, AssistSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.assist))
}
return@setOnPreferenceClickListener true
}
findPreference<Preference>("gestures")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, GesturesFragment::class.java, null)
addToBackStack(getString(commonR.string.gestures))
}
return@setOnPreferenceClickListener true
}
findPreference<ListPreference>("page_zoom")?.let {
// The list of percentages for iOS/Android should match
// https://github.com/home-assistant/iOS/blob/ff66bbf2e3f9add0abb0b492499b81e824db36ed/Sources/Shared/Settings/SettingsStore.swift#L108
val percentages = listOf(50, 75, 85, 100, 115, 125, 150, 175, 200)
it.entries = percentages.map { pct ->
getString(if (pct == 100) commonR.string.page_zoom_default else commonR.string.page_zoom_pct, pct)
}.toTypedArray()
it.entryValues = percentages.map { pct -> pct.toString() }.toTypedArray()
}
val isAutomotive = requireContext().isAutomotive()
findPreference<PreferenceCategory>("assist")?.isVisible = !isAutomotive
findPreference<PreferenceCategory>("widgets")?.isVisible = !QuestUtil.isQuest && !isAutomotive
findPreference<Preference>("manage_widgets")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, ManageWidgetsSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.widgets))
}
return@setOnPreferenceClickListener true
}
if (!QuestUtil.isQuest) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
findPreference<PreferenceCategory>("shortcuts")?.let {
it.isVisible = true
}
findPreference<Preference>("manage_shortcuts")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, ManageShortcutsSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.shortcuts))
}
return@setOnPreferenceClickListener true
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
findPreference<PreferenceCategory>("quick_settings")?.let {
it.isVisible = true
}
findPreference<Preference>("manage_tiles")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, ManageTilesFragment::class.java, null)
addToBackStack(getString(commonR.string.tiles))
}
return@setOnPreferenceClickListener true
}
}
if (!isAutomotive && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
findPreference<PreferenceCategory>("device_controls")?.let {
it.isVisible = true
}
findPreference<Preference>("manage_device_controls")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, ManageControlsSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.controls_setting_title))
}
return@setOnPreferenceClickListener true
}
}
}
findPreference<PreferenceCategory>("notifications")?.let {
it.isVisible = true
}
updateNotificationChannelPrefs()
updatePushProviderPrefs()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
findPreference<Preference>("notification_permission")?.let {
it.setOnPreferenceClickListener {
openNotificationSettings()
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>("notification_channels")?.let { pref ->
pref.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, NotificationChannelFragment::class.java, null)
addToBackStack(getString(commonR.string.notification_channels))
}
return@setOnPreferenceClickListener true
}
}
}
findPreference<Preference>("notification_history")?.let {
it.isVisible = true
it.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, NotificationHistoryFragment::class.java, null)
addToBackStack(getString(commonR.string.notifications))
}
return@setOnPreferenceClickListener true
}
}
if (BuildConfig.FLAVOR == "full") {
findPreference<Preference>("notification_rate_limit")?.let {
lifecycleScope.launch(Dispatchers.Main) {
// Runs in IO Dispatcher
val rateLimits = presenter.getNotificationRateLimits()
if (rateLimits != null) {
var formattedDate = rateLimits.resetsAt
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
val utcDateTime = Instant.parse(rateLimits.resetsAt)
formattedDate =
DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.MEDIUM,
).format(utcDateTime.atZone(ZoneId.systemDefault()))
} catch (e: Exception) {
Timber.d(e, "Cannot parse notification rate limit date \"${rateLimits.resetsAt}\"")
}
}
it.isVisible = true
it.summary =
"\n${getString(
commonR.string.successful,
)}: ${rateLimits.successful} ${getString(
commonR.string.errors,
)}: ${rateLimits.errors}" +
"\n\n${getString(
commonR.string.remaining,
)}/${getString(commonR.string.maximum)}: ${rateLimits.remaining}/${rateLimits.maximum}" +
"\n\n${getString(commonR.string.resets_at)}: $formattedDate"
}
}
}
}
findPreference<SwitchPreference>("crash_reporting")?.let {
it.isVisible = BuildConfig.FLAVOR == "full"
}
lifecycleScope.launch {
findPreference<Preference>("wear_settings")?.let {
it.isVisible = SettingsWearDetection.hasAnyNodes(requireContext())
it.setOnPreferenceClickListener {
startActivity(SettingsWearActivity.newInstance(requireContext()))
return@setOnPreferenceClickListener true
}
}
}
findPreference<Preference>("changelog_github")?.let {
val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL")) {
"https://github.com/home-assistant/android/releases"
} else {
"https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace(
"-full",
"",
).replace("-minimal", "")}"
}
it.summary = link
it.intent = Intent(Intent.ACTION_VIEW, link.toUri())
}
findPreference<Preference>("changelog_prompt")?.setOnPreferenceClickListener {
lifecycleScope.launch {
presenter.showChangeLog(requireContext())
}
true
}
findPreference<SwitchPreference>("change_log_popup_enabled")?.let {
lifecycleScope.launch {
it.isChecked = presenter.isChangeLogPopupEnabled()
}
it.setOnPreferenceChangeListener { _, newValue ->
lifecycleScope.launch {
presenter.setChangeLogPopupEnabled(newValue as Boolean)
}
true
}
}
findPreference<Preference>("version")?.let {
it.isCopyingEnabled = true
it.summary = BuildConfig.VERSION_NAME
}
findPreference<Preference>("licenses")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, LicensesFragment::class.java, null)
addToBackStack(getString(commonR.string.licenses))
}
return@setOnPreferenceClickListener true
}
findPreference<ListPreference>("languages")?.let {
lifecycleScope.launch {
val languages = langProvider.getSupportedLanguages(requireContext())
it.entries = languages.keys.toTypedArray()
it.entryValues = languages.values.toTypedArray()
}
}
findPreference<Preference>("privacy")?.let {
it.summary = "https://www.home-assistant.io/privacy/"
it.intent = Intent(Intent.ACTION_VIEW, it.summary.toString().toUri())
}
findPreference<Preference>("developer")?.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, DeveloperSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.troubleshooting))
}
return@setOnPreferenceClickListener true
}
findPreference<PreferenceCategory>("android_auto")?.let {
it.isVisible =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
(BuildConfig.FLAVOR == "full" || isAutomotive)
if (isAutomotive) {
it.title = getString(commonR.string.android_automotive)
}
}
findPreference<Preference>("auto_favorites")?.let { pref ->
if (isAutomotive) {
pref.title = getString(commonR.string.android_automotive_favorites)
}
pref.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.content, ManageAndroidAutoSettingsFragment::class.java, null)
addToBackStack(getString(commonR.string.basic_sensor_name_android_auto))
}
return@setOnPreferenceClickListener true
}
}
if (!isAutomotive) {
setupLauncherPrefs()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// We don't consume the insets so that the snackbar can use the insets from the
// CoordinatorLayout and be displayed above the navigation bar.
applyBottomSafeDrawingInsets(consumeInsets = false)
}
private fun removeSystemFromThemesIfNeeded() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
val pref = findPreference<ListPreference>("themes")
if (pref != null) {
val systemIndex = pref.findIndexOfValue("system")
if (systemIndex > 0) {
val entries = pref.entries?.toMutableList()
entries?.removeAt(systemIndex)
val entryValues = pref.entryValues?.toMutableList()
entryValues?.removeAt(systemIndex)
if (entries != null && entryValues != null) {
pref.entries = entries.toTypedArray()
pref.entryValues = entryValues.toTypedArray()
}
}
}
}
}
private fun updateAssistantApp() {
startActivity(defaultAssistantManager.getSetDefaultAssistantIntent())
}
private fun updateBackgroundAccessPref() {
findPreference<Preference>("background")?.let {
if (context?.isIgnoringBatteryOptimizations() == true) {
it.setSummary(commonR.string.background_access_enabled)
it.icon = AppCompatResources.getDrawable(requireContext(), R.drawable.ic_check)
it.setOnPreferenceClickListener {
true
}
} else {
it.setSummary(commonR.string.background_access_disabled)
it.icon = AppCompatResources.getDrawable(requireContext(), R.drawable.ic_close)
it.setOnPreferenceClickListener {
context?.maybeAskForIgnoringBatteryOptimizations()
true
}
}
}
}
private suspend fun updateServers(servers: List<Server>) = serverMutex.withLock {
val category = findPreference<PreferenceCategory>("servers_devices_category")
val numPreferences = category?.preferenceCount ?: 0
val serverPreferences = mutableListOf<Preference>()
val serverKeys = servers.mapIndexed { index, server ->
"server_${index}_${server.id}_${server.friendlyName}_${server.deviceName}"
}
for (i in 0 until numPreferences) {
category?.getPreference(i)?.let {
if (it.key != "server_add" && it.key != "wear_settings") serverPreferences += it
}
}
serverPreferences.forEach {
if (it.key !in serverKeys) category?.removePreference(it)
}
servers.forEachIndexed { index, server ->
if (serverKeys[index] in serverPreferences.map { it.key }) return@forEachIndexed // Already exists!
val serverPreference = Preference(requireContext())
serverPreference.title = server.friendlyName
serverPreference.summary = server.deviceName
serverPreference.key = serverKeys[index]
serverPreference.order = index
try {
serverPreference.icon =
AppCompatResources.getDrawable(requireContext(), commonR.drawable.ic_stat_ic_notification_blue)
} catch (e: Exception) {
Timber.e(e, "Unable to set the server icon")
}
serverPreference.setOnPreferenceClickListener {
serverAuth = server.id
val settingsActivity = requireActivity() as SettingsActivity
lifecycleScope.launch {
val needsAuth = settingsActivity.isAppLocked(server.id)
if (!needsAuth) {
onServerLockResult(Authenticator.SUCCESS)
} else {
val canAuth = settingsActivity.requestAuthentication(
getString(commonR.string.biometric_set_title),
::onServerLockResult,
)
if (!canAuth) {
onServerLockResult(Authenticator.SUCCESS)
}
}
}
return@setOnPreferenceClickListener true
}
category?.addPreference(serverPreference)
}
}
private fun updateNotificationChannelPrefs() {
val notificationsEnabled =
Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
NotificationManagerCompat.from(requireContext()).areNotificationsEnabled()
findPreference<Preference>("notification_permission")?.let {
it.isVisible = !notificationsEnabled
}
findPreference<Preference>("notification_channels")?.let {
val uiManager = requireContext().getSystemService<UiModeManager>()
it.isVisible =
notificationsEnabled &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
uiManager?.currentModeType != Configuration.UI_MODE_TYPE_TELEVISION
}
}
private fun updatePushProviderPrefs() {
findPreference<ListPreference>("notification_push_provider")?.let { pref ->
pref.preferenceDataStore = null
pref.setOnPreferenceChangeListener { _, newValue ->
val value = newValue as? String
lifecycleScope.launch(Dispatchers.IO) {
presenter.handlePushProviderChange(value)
}
if (value == "WebSocket") {
Toast.makeText(requireContext(), commonR.string.push_provider_websocket_enabled, Toast.LENGTH_SHORT).show()
lifecycleScope.launch {
WebsocketManager.restart(requireContext())
}
}
true
}
lifecycleScope.launch(Dispatchers.IO) {
val entries = mutableListOf<String>()
val values = mutableListOf<String>()
val providers = presenter.getAvailablePushProviders()
for (provider in providers) {
entries.add(provider.second)
values.add(provider.first)
}
val activeValue = presenter.getActivePushProviderValue()
withContext(Dispatchers.Main) {
pref.entries = entries.toTypedArray()
pref.entryValues = values.toTypedArray()
if (pref.value == null || pref.value !in values) {
pref.value = activeValue
}
}
}
}
}
private fun onServerLockResult(result: Int): Boolean {
if (result == Authenticator.SUCCESS && serverAuth != null) {
(activity as? SettingsActivity)?.setAppActive(serverAuth, true)
parentFragmentManager.commit {
replace(
R.id.content,
ServerSettingsFragment::class.java,
Bundle().apply { putInt(ServerSettingsFragment.EXTRA_SERVER, serverAuth!!) },
ServerSettingsFragment.TAG,
)
addToBackStack(getString(commonR.string.server_settings))
}
}
return true
}
private fun openNotificationSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
requestNotificationPermissionResult.launch(
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, requireContext().packageName)
},
)
}
}
private fun getDefaultLauncherInfo(): String {
val intent = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME)
getPackageManager()?.let { packageManager ->
packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)?.let {
val packageName = it.activityInfo.packageName
return packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString()
}
}
return getString(commonR.string.unknown_launcher_label)
}
private fun setupLauncherPrefs() {
val launcherSwitchPref = findPreference<SwitchPreference>("enable_ha_launcher")
val launcherPref = findPreference<Preference>("set_launcher_app")
findPreference<PreferenceCategory>("launcher_category")?.isVisible = true
launcherSwitchPref?.setOnPreferenceClickListener {
launcherPref?.isVisible = launcherSwitchPref.isChecked
true
}
launcherPref?.apply {
isVisible = launcherSwitchPref?.isChecked ?: false
summary = getString(commonR.string.default_launcher_prompt_def, getDefaultLauncherInfo())
setOnPreferenceClickListener {
startActivity(Intent(Settings.ACTION_HOME_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
true
}
}
}
override fun onAddServerResult(success: Boolean, serverId: Int?) {
view?.let {
snackbar = Snackbar.make(
it,
if (success) commonR.string.server_add_success else commonR.string.server_add_failed,
5_000,
).apply {
if (success && serverId != null) {
setAction(commonR.string.activate) {
val intent = WebViewActivity.newInstance(requireContext(), null, serverId).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
requireContext().startActivity(intent)
}
}
show()
}
}
}
override fun getPackageManager(): PackageManager? = context?.packageManager
override fun onPause() {
super.onPause()
snackbar?.dismiss()
}
override fun onResume() {
super.onResume()
activity?.title = getString(commonR.string.companion_app)
context?.let { presenter.updateSuggestions(it) }
findPreference<Preference>("set_launcher_app")?.summary =
getString(commonR.string.default_launcher_prompt_def, getDefaultLauncherInfo())
}
override fun onDestroy() {
presenter.onFinish()
super.onDestroy()
}
}