Add SharedPrefs helper class to access shared preferences
This commit is contained in:
BinTianqi
2025-02-07 15:51:01 +08:00
parent 5e18c2684c
commit 5e109d74b1
17 changed files with 140 additions and 125 deletions

View File

@@ -12,6 +12,7 @@ Use Android Device owner privilege to manage your device.
- _Wipe data_ - _Wipe data_
- ... - ...
- Network - Network
- Add/modify/delete Wi-Fi
- Minimum Wi-Fi security level - Minimum Wi-Fi security level
- Always-on VPN - Always-on VPN
- Network logging - Network logging

View File

@@ -12,6 +12,7 @@
- 清除数据 - 清除数据
- ... - ...
- 网络 - 网络
- 添加/修改/删除 Wi-Fi
- 最小Wi-Fi安全等级 - 最小Wi-Fi安全等级
- VPN保持打开 - VPN保持打开
- 网络日志 - 网络日志

View File

@@ -76,13 +76,6 @@
<receiver <receiver
android:name=".ApiReceiver" android:name=".ApiReceiver"
android:exported="true"> android:exported="true">
<intent-filter>
<action android:name="com.bintianqi.owndroid.action.HIDE"/>
<action android:name="com.bintianqi.owndroid.action.UNHIDE"/>
<action android:name="com.bintianqi.owndroid.action.SUSPEND"/>
<action android:name="com.bintianqi.owndroid.action.UNSUSPEND"/>
<action android:name="com.bintianqi.owndroid.action.LOCK"/>
</intent-filter>
</receiver> </receiver>
<provider <provider
android:name="rikka.shizuku.ShizukuProvider" android:name="rikka.shizuku.ShizukuProvider"

View File

@@ -1,6 +1,5 @@
package com.bintianqi.owndroid package com.bintianqi.owndroid
import android.annotation.SuppressLint
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
@@ -9,41 +8,40 @@ import com.bintianqi.owndroid.dpm.getDPM
import com.bintianqi.owndroid.dpm.getReceiver import com.bintianqi.owndroid.dpm.getReceiver
class ApiReceiver: BroadcastReceiver() { class ApiReceiver: BroadcastReceiver() {
@SuppressLint("NewApi")
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
val sharedPrefs = context.getSharedPreferences("data", Context.MODE_PRIVATE) val requestKey = intent.getStringExtra("key") ?: ""
if(sharedPrefs.getBoolean("enable_api", false)) return var log = "OwnDroid API request received. action: ${intent.action}\nkey: $requestKey"
val key = sharedPrefs.getString("api_key", null) val sp = SharedPrefs(context)
if(key != null && key == intent.getStringExtra("key")) { if(!sp.isApiEnabled) return
val key = sp.apiKey
if(!key.isNullOrEmpty() && key == requestKey) {
val dpm = context.getDPM() val dpm = context.getDPM()
val receiver = context.getReceiver() val receiver = context.getReceiver()
val app = intent.getStringExtra("package") ?: "" val app = intent.getStringExtra("package")
if(!app.isNullOrEmpty()) log += "\npackage: $app"
try { try {
@SuppressWarnings("NewApi")
val ok = when(intent.action) { val ok = when(intent.action) {
"com.bintianqi.owndroid.action.HIDE" -> dpm.setApplicationHidden(receiver, app, true) "com.bintianqi.owndroid.action.HIDE" -> dpm.setApplicationHidden(receiver, app, true)
"com.bintianqi.owndroid.action.UNHIDE" -> dpm.setApplicationHidden(receiver, app, false) "com.bintianqi.owndroid.action.UNHIDE" -> dpm.setApplicationHidden(receiver, app, false)
"com.bintianqi.owndroid.action.SUSPEND" -> dpm.setPackagesSuspended(receiver, arrayOf(app), true).isEmpty() "com.bintianqi.owndroid.action.SUSPEND" -> dpm.setPackagesSuspended(receiver, arrayOf(app), true).isEmpty()
"com.bintianqi.owndroid.action.UNSUSPEND" -> dpm.setPackagesSuspended(receiver, arrayOf(app), false).isEmpty() "com.bintianqi.owndroid.action.UNSUSPEND" -> dpm.setPackagesSuspended(receiver, arrayOf(app), false).isEmpty()
"com.bintianqi.owndroid.action.LOCK" -> { dpm.lockNow(); true } "com.bintianqi.owndroid.action.LOCK" -> { dpm.lockNow(); null }
else -> { else -> {
Log.w(TAG, "Invalid action") log += "\nInvalid action"
resultData = "Invalid action"
false false
} }
} }
if(!ok) resultCode = 1 log += "success: $ok"
} catch(e: Exception) { } catch(e: Exception) {
e.printStackTrace() e.printStackTrace()
val message = (e::class.qualifiedName ?: "Exception") + ": " + (e.message ?: "") val message = (e::class.qualifiedName ?: "Exception") + ": " + (e.message ?: "")
Log.w(TAG, message) log += "\n$message"
resultCode = 1
resultData = message
} }
} else { } else {
Log.w(TAG, "Unauthorized") log += "\nUnauthorized"
resultCode = 1
resultData = "Unauthorized"
} }
Log.d(TAG, log)
} }
companion object { companion object {
private const val TAG = "API" private const val TAG = "API"

View File

@@ -1,6 +1,5 @@
package com.bintianqi.owndroid package com.bintianqi.owndroid
import android.content.Context
import android.widget.Toast import android.widget.Toast
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.biometric.BiometricManager import androidx.biometric.BiometricManager
@@ -81,9 +80,8 @@ fun Authenticate(activity: FragmentActivity, navCtrl: NavHostController) {
fun startAuth(activity: FragmentActivity, callback: AuthenticationCallback) { fun startAuth(activity: FragmentActivity, callback: AuthenticationCallback) {
val context = activity.applicationContext val context = activity.applicationContext
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE)
val promptInfo = Builder().setTitle(context.getText(R.string.authenticate)) val promptInfo = Builder().setTitle(context.getText(R.string.authenticate))
if(sharedPref.getInt("biometrics_auth", 0) != 0) { if(SharedPrefs(context).biometricsAuth != 0) {
promptInfo.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL or BiometricManager.Authenticators.BIOMETRIC_WEAK) promptInfo.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL or BiometricManager.Authenticators.BIOMETRIC_WEAK)
} else { } else {
promptInfo.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL) promptInfo.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL)

View File

@@ -1,7 +1,6 @@
package com.bintianqi.owndroid package com.bintianqi.owndroid
import android.app.admin.DevicePolicyManager import android.app.admin.DevicePolicyManager
import android.content.Context
import android.os.Build.VERSION import android.os.Build.VERSION
import android.os.Bundle import android.os.Bundle
import android.widget.Toast import android.widget.Toast
@@ -170,12 +169,12 @@ class MainActivity : FragmentActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
val sharedPref = applicationContext.getSharedPreferences("data", MODE_PRIVATE) val sp = SharedPrefs(applicationContext)
if (sharedPref.getBoolean("dhizuku", false)) { if (sp.dhizuku) {
if (Dhizuku.init(applicationContext)) { if (Dhizuku.init(applicationContext)) {
if (!dhizukuPermissionGranted()) { dhizukuErrorStatus.value = 2 } if (!dhizukuPermissionGranted()) { dhizukuErrorStatus.value = 2 }
} else { } else {
sharedPref.edit().putBoolean("dhizuku", false).apply() sp.dhizuku = false
dhizukuErrorStatus.value = 1 dhizukuErrorStatus.value = 1
} }
} }
@@ -190,7 +189,7 @@ fun Home(activity: FragmentActivity, vm: MyViewModel) {
val context = LocalContext.current val context = LocalContext.current
val dpm = context.getDPM() val dpm = context.getDPM()
val receiver = context.getReceiver() val receiver = context.getReceiver()
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
val focusMgr = LocalFocusManager.current val focusMgr = LocalFocusManager.current
val backToHome by backToHomeStateFlow.collectAsState() val backToHome by backToHomeStateFlow.collectAsState()
val lifecycleOwner = LocalLifecycleOwner.current val lifecycleOwner = LocalLifecycleOwner.current
@@ -325,10 +324,8 @@ fun Home(activity: FragmentActivity, vm: MyViewModel) {
DisposableEffect(lifecycleOwner) { DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event -> val observer = LifecycleEventObserver { _, event ->
if( if(
(event == Lifecycle.Event.ON_RESUME && (event == Lifecycle.Event.ON_RESUME && sp.auth && sp.lockInBackground) ||
sharedPref.getBoolean("auth", false) && (event == Lifecycle.Event.ON_CREATE && sp.auth)
sharedPref.getBoolean("lock_in_background", false)) ||
(event == Lifecycle.Event.ON_CREATE && sharedPref.getBoolean("auth", false))
) { ) {
navCtrl.navigate("Authenticate") { launchSingleTop = true } navCtrl.navigate("Authenticate") { launchSingleTop = true }
} }
@@ -339,11 +336,10 @@ fun Home(activity: FragmentActivity, vm: MyViewModel) {
} }
} }
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
val profileInitialized = sharedPref.getBoolean("ManagedProfileActivated", false) val profileNotActivated = !sp.managedProfileActivated && context.isProfileOwner && (VERSION.SDK_INT < 24 || dpm.isManagedProfile(receiver))
val profileNotActivated = !profileInitialized && context.isProfileOwner && (VERSION.SDK_INT < 24 || dpm.isManagedProfile(receiver))
if(profileNotActivated) { if(profileNotActivated) {
dpm.setProfileEnabled(receiver) dpm.setProfileEnabled(receiver)
sharedPref.edit().putBoolean("ManagedProfileActivated", true).apply() sp.managedProfileActivated = true
Toast.makeText(context, R.string.work_profile_activated, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.work_profile_activated, Toast.LENGTH_SHORT).show()
} }
} }
@@ -355,7 +351,6 @@ private fun HomePage(navCtrl:NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val dpm = context.getDPM() val dpm = context.getDPM()
val receiver = context.getReceiver() val receiver = context.getReceiver()
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE)
var activated by remember { mutableStateOf(false) } var activated by remember { mutableStateOf(false) }
var activateType by remember { mutableStateOf("") } var activateType by remember { mutableStateOf("") }
val deviceAdmin = context.isDeviceAdmin val deviceAdmin = context.isDeviceAdmin
@@ -364,7 +359,7 @@ private fun HomePage(navCtrl:NavHostController) {
val refreshStatus by dhizukuErrorStatus.collectAsState() val refreshStatus by dhizukuErrorStatus.collectAsState()
LaunchedEffect(refreshStatus) { LaunchedEffect(refreshStatus) {
activated = context.isProfileOwner || context.isDeviceOwner activated = context.isProfileOwner || context.isDeviceOwner
activateType = if(sharedPref.getBoolean("dhizuku", false)) context.getString(R.string.dhizuku) + " - " else "" activateType = if(SharedPrefs(context).dhizuku) context.getString(R.string.dhizuku) + " - " else ""
activateType += context.getString( activateType += context.getString(
if(deviceOwner) { R.string.device_owner } if(deviceOwner) { R.string.device_owner }
else if(profileOwner) { else if(profileOwner) {
@@ -456,10 +451,9 @@ fun HomePageItem(name: Int, imgVector: Int, navTo: String, navCtrl: NavHostContr
private fun DhizukuErrorDialog() { private fun DhizukuErrorDialog() {
val status by dhizukuErrorStatus.collectAsState() val status by dhizukuErrorStatus.collectAsState()
if (status != 0) { if (status != 0) {
val context = LocalContext.current val sp = SharedPrefs(LocalContext.current)
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE)
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
sharedPref.edit().putBoolean("dhizuku", false).apply() sp.dhizuku = false
} }
AlertDialog( AlertDialog(
onDismissRequest = { dhizukuErrorStatus.value = 0 }, onDismissRequest = { dhizukuErrorStatus.value = 0 },
@@ -477,7 +471,7 @@ private fun DhizukuErrorDialog() {
else -> R.string.failed_to_init_dhizuku else -> R.string.failed_to_init_dhizuku
} }
) )
if(sharedPref.getBoolean("dhizuku", false)) text += "\n" + stringResource(R.string.dhizuku_mode_disabled) if(sp.dhizuku) text += "\n" + stringResource(R.string.dhizuku_mode_disabled)
Text(text) Text(text)
} }
) )

View File

@@ -25,8 +25,7 @@ class ManageSpaceActivity: FragmentActivity() {
enableEdgeToEdge() enableEdgeToEdge()
WindowCompat.setDecorFitsSystemWindows(window, false) WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val sharedPref = applicationContext.getSharedPreferences("data", MODE_PRIVATE) val authenticate = SharedPrefs(applicationContext).auth
val authenticate = sharedPref.getBoolean("auth", false)
val vm by viewModels<MyViewModel>() val vm by viewModels<MyViewModel>()
fun clearStorage() { fun clearStorage() {
filesDir.deleteRecursively() filesDir.deleteRecursively()
@@ -35,6 +34,7 @@ class ManageSpaceActivity: FragmentActivity() {
if(Build.VERSION.SDK_INT >= 24) { if(Build.VERSION.SDK_INT >= 24) {
dataDir.resolve("shared_prefs").deleteRecursively() dataDir.resolve("shared_prefs").deleteRecursively()
} else { } else {
val sharedPref = applicationContext.getSharedPreferences("data", MODE_PRIVATE)
sharedPref.edit().clear().apply() sharedPref.edit().clear().apply()
} }
finish() finish()

View File

@@ -1,8 +1,6 @@
package com.bintianqi.owndroid package com.bintianqi.owndroid
import android.app.Application import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
@@ -16,19 +14,13 @@ class MyViewModel(application: Application): AndroidViewModel(application) {
val userRestrictions = MutableStateFlow(Bundle()) val userRestrictions = MutableStateFlow(Bundle())
init { init {
val sharedPrefs = application.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(application)
theme.value = ThemeSettings( theme.value = ThemeSettings(sp.materialYou, sp.darkTheme, sp.blackTheme)
materialYou = sharedPrefs.getBoolean("material_you", Build.VERSION.SDK_INT >= 31),
darkTheme = if(sharedPrefs.contains("dark_theme")) sharedPrefs.getBoolean("dark_theme", false) else null,
blackTheme = sharedPrefs.getBoolean("black_theme", false)
)
viewModelScope.launch { viewModelScope.launch {
theme.collect { theme.collect {
val editor = sharedPrefs.edit() sp.materialYou = it.materialYou
editor.putBoolean("material_you", it.materialYou) sp.darkTheme = it.darkTheme
if(it.darkTheme == null) editor.remove("dark_theme") else editor.putBoolean("dark_theme", it.darkTheme) sp.blackTheme = it.blackTheme
editor.putBoolean("black_theme", it.blackTheme)
editor.commit()
} }
} }
} }
@@ -36,6 +28,6 @@ class MyViewModel(application: Application): AndroidViewModel(application) {
data class ThemeSettings( data class ThemeSettings(
val materialYou: Boolean = false, val materialYou: Boolean = false,
val darkTheme: Boolean? = null, val darkTheme: Int = -1,
val blackTheme: Boolean = false val blackTheme: Boolean = false
) )

View File

@@ -74,8 +74,7 @@ class Receiver : DeviceAdminReceiver() {
override fun onTransferOwnershipComplete(context: Context, bundle: PersistableBundle?) { override fun onTransferOwnershipComplete(context: Context, bundle: PersistableBundle?) {
super.onTransferOwnershipComplete(context, bundle) super.onTransferOwnershipComplete(context, bundle)
val sp = context.getSharedPreferences("data", Context.MODE_PRIVATE) SharedPrefs(context).dhizuku = false
sp.edit().putBoolean("dhizuku", false).apply()
} }
override fun onLockTaskModeEntering(context: Context, intent: Intent, pkg: String) { override fun onLockTaskModeEntering(context: Context, intent: Intent, pkg: String) {

View File

@@ -53,12 +53,12 @@ fun Settings(navCtrl: NavHostController) {
@Composable @Composable
fun SettingsOptions(navCtrl: NavHostController) { fun SettingsOptions(navCtrl: NavHostController) {
val sharedPref = LocalContext.current.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(LocalContext.current)
MyScaffold(R.string.options, 0.dp, navCtrl) { MyScaffold(R.string.options, 0.dp, navCtrl) {
SwitchItem( SwitchItem(
R.string.show_dangerous_features, icon = R.drawable.warning_fill0, R.string.show_dangerous_features, icon = R.drawable.warning_fill0,
getState = { sharedPref.getBoolean("dangerous_features", false) }, getState = { sp.displayDangerousFeatures },
onCheckedChange = { sharedPref.edit().putBoolean("dangerous_features", it).apply() } onCheckedChange = { sp.displayDangerousFeatures = it }
) )
} }
} }
@@ -68,9 +68,9 @@ fun Appearance(navCtrl: NavHostController, vm: MyViewModel) {
val theme by vm.theme.collectAsStateWithLifecycle() val theme by vm.theme.collectAsStateWithLifecycle()
var darkThemeMenu by remember { mutableStateOf(false) } var darkThemeMenu by remember { mutableStateOf(false) }
val darkThemeTextID = when(theme.darkTheme) { val darkThemeTextID = when(theme.darkTheme) {
true -> R.string.on 1 -> R.string.on
false -> R.string.off 0 -> R.string.off
null -> R.string.follow_system else -> R.string.follow_system
} }
MyScaffold(R.string.appearance, 0.dp, navCtrl) { MyScaffold(R.string.appearance, 0.dp, navCtrl) {
if(VERSION.SDK_INT >= 31) { if(VERSION.SDK_INT >= 31) {
@@ -85,27 +85,27 @@ fun Appearance(navCtrl: NavHostController, vm: MyViewModel) {
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.follow_system)) }, text = { Text(stringResource(R.string.follow_system)) },
onClick = { onClick = {
vm.theme.value = theme.copy(darkTheme = null) vm.theme.value = theme.copy(darkTheme = -1)
darkThemeMenu = false darkThemeMenu = false
} }
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.on)) }, text = { Text(stringResource(R.string.on)) },
onClick = { onClick = {
vm.theme.value = theme.copy(darkTheme = true) vm.theme.value = theme.copy(darkTheme = 1)
darkThemeMenu = false darkThemeMenu = false
} }
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.off)) }, text = { Text(stringResource(R.string.off)) },
onClick = { onClick = {
vm.theme.value = theme.copy(darkTheme = false) vm.theme.value = theme.copy(darkTheme = 0)
darkThemeMenu = false darkThemeMenu = false
} }
) )
} }
} }
AnimatedVisibility(theme.darkTheme == true || (theme.darkTheme == null && isSystemInDarkTheme())) { AnimatedVisibility(theme.darkTheme == 1 || (theme.darkTheme == -1 && isSystemInDarkTheme())) {
SwitchItem(R.string.black_theme, state = theme.blackTheme, onCheckedChange = { vm.theme.value = theme.copy(blackTheme = it) }) SwitchItem(R.string.black_theme, state = theme.blackTheme, onCheckedChange = { vm.theme.value = theme.copy(blackTheme = it) })
} }
} }
@@ -114,33 +114,33 @@ fun Appearance(navCtrl: NavHostController, vm: MyViewModel) {
@Composable @Composable
fun AuthSettings(navCtrl: NavHostController) { fun AuthSettings(navCtrl: NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
var auth by remember{ mutableStateOf(sharedPref.getBoolean("auth",false)) } var auth by remember{ mutableStateOf(sp.auth) }
MyScaffold(R.string.security, 0.dp, navCtrl) { MyScaffold(R.string.security, 0.dp, navCtrl) {
SwitchItem( SwitchItem(
R.string.lock_owndroid, state = auth, R.string.lock_owndroid, state = auth,
onCheckedChange = { onCheckedChange = {
sharedPref.edit().putBoolean("auth", it).apply() sp.auth = it
auth = sharedPref.getBoolean("auth", false) auth = it
} }
) )
if(auth) { if(auth) {
var bioAuth by remember { mutableIntStateOf(sharedPref.getInt("biometrics_auth", 0)) } // 0:Disabled, 1:Enabled 2:Force enabled var bioAuth by remember { mutableIntStateOf(sp.biometricsAuth) } // 0:Disabled, 1:Enabled 2:Force enabled
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
val bioManager = BiometricManager.from(context) val bioManager = BiometricManager.from(context)
if(bioManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL) != BiometricManager.BIOMETRIC_SUCCESS) { if(bioManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL) != BiometricManager.BIOMETRIC_SUCCESS) {
sp.biometricsAuth = 2
bioAuth = 2 bioAuth = 2
sharedPref.edit().putInt("biometrics_auth", 2).apply()
} }
} }
SwitchItem( SwitchItem(
R.string.enable_bio_auth, state = bioAuth != 0, R.string.enable_bio_auth, state = bioAuth != 0,
onCheckedChange = { bioAuth = if(it) 1 else 0; sharedPref.edit().putInt("biometrics_auth", bioAuth).apply() }, enabled = bioAuth != 2 onCheckedChange = { bioAuth = if(it) 1 else 0; sp.biometricsAuth = bioAuth }, enabled = bioAuth != 2
) )
SwitchItem( SwitchItem(
R.string.lock_in_background, R.string.lock_in_background,
getState = { sharedPref.getBoolean("lock_in_background", false) }, getState = { sp.lockInBackground },
onCheckedChange = { sharedPref.edit().putBoolean("lock_in_background", it).apply() } onCheckedChange = { sp.lockInBackground = it }
) )
} }
} }
@@ -149,16 +149,14 @@ fun AuthSettings(navCtrl: NavHostController) {
@Composable @Composable
fun ApiSettings(navCtrl: NavHostController) { fun ApiSettings(navCtrl: NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
MyScaffold(R.string.api, 8.dp, navCtrl) { MyScaffold(R.string.api, 8.dp, navCtrl) {
var enabled by remember { mutableStateOf(sharedPref.getBoolean("enable_api", false)) } var enabled by remember { mutableStateOf(sp.isApiEnabled) }
LaunchedEffect(enabled) { SwitchItem(R.string.enable, state = enabled, onCheckedChange = {
sharedPref.edit { enabled = it
putBoolean("enable_api", enabled) sp.isApiEnabled = it
if(!enabled) remove("api_key") if(!it) sp.sharedPrefs.edit { remove("api.key") }
} }, padding = false)
}
SwitchItem(R.string.enable, state = enabled, onCheckedChange = { enabled = it }, padding = false)
if(enabled) { if(enabled) {
var key by remember { mutableStateOf("") } var key by remember { mutableStateOf("") }
OutlinedTextField( OutlinedTextField(
@@ -179,13 +177,13 @@ fun ApiSettings(navCtrl: NavHostController) {
Button( Button(
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
onClick = { onClick = {
sharedPref.edit().putString("api_key", key).apply() sp.apiKey = key
context.showOperationResultToast(true) context.showOperationResultToast(true)
} }
) { ) {
Text(stringResource(R.string.apply)) Text(stringResource(R.string.apply))
} }
if(sharedPref.contains("api_key")) InfoCard(R.string.api_key_exist) if(sp.apiKey != null) InfoCard(R.string.api_key_exist)
} }
} }
} }

View File

@@ -0,0 +1,45 @@
package com.bintianqi.owndroid
import android.content.Context
import android.os.Build
import androidx.core.content.edit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class SharedPrefs(context: Context) {
val sharedPrefs = context.getSharedPreferences("data", Context.MODE_PRIVATE)
var managedProfileActivated by BooleanSharedPref("managed_profile_activated")
var dhizuku by BooleanSharedPref("dhizuku_mode")
var isDefaultAffiliationIdSet by BooleanSharedPref("default_affiliation_id_set")
var displayDangerousFeatures by BooleanSharedPref("display_dangerous_features")
var isApiEnabled by BooleanSharedPref("api.enabled")
var apiKey by StringSharedPref("api.key")
var auth by BooleanSharedPref("auth")
var biometricsAuth by IntSharedPref("auth.biometrics")
var lockInBackground by BooleanSharedPref("auth.lock_in_background")
var materialYou by BooleanSharedPref("theme.material_you", Build.VERSION.SDK_INT >= 31)
/** -1: follow system, 0: off, 1: on */
var darkTheme by IntSharedPref("theme.dark", -1)
var blackTheme by BooleanSharedPref("theme.black")
}
private class BooleanSharedPref(val key: String, val defValue: Boolean = false): ReadWriteProperty<SharedPrefs, Boolean> {
override fun getValue(thisRef: SharedPrefs, property: KProperty<*>): Boolean =
thisRef.sharedPrefs.getBoolean(key, defValue)
override fun setValue(thisRef: SharedPrefs, property: KProperty<*>, value: Boolean) =
thisRef.sharedPrefs.edit { putBoolean(key, value) }
}
private class StringSharedPref(val key: String): ReadWriteProperty<SharedPrefs, String?> {
override fun getValue(thisRef: SharedPrefs, property: KProperty<*>): String? =
thisRef.sharedPrefs.getString(key, null)
override fun setValue(thisRef: SharedPrefs, property: KProperty<*>, value: String?) =
thisRef.sharedPrefs.edit { putString(key, value) }
}
private class IntSharedPref(val key: String, val defValue: Int = 0): ReadWriteProperty<SharedPrefs, Int> {
override fun getValue(thisRef: SharedPrefs, property: KProperty<*>): Int =
thisRef.sharedPrefs.getInt(key, defValue)
override fun setValue(thisRef: SharedPrefs, property: KProperty<*>, value: Int) =
thisRef.sharedPrefs.edit { putInt(key, value) }
}

View File

@@ -23,6 +23,7 @@ import androidx.annotation.RequiresApi
import androidx.annotation.StringRes import androidx.annotation.StringRes
import com.bintianqi.owndroid.R import com.bintianqi.owndroid.R
import com.bintianqi.owndroid.Receiver import com.bintianqi.owndroid.Receiver
import com.bintianqi.owndroid.SharedPrefs
import com.bintianqi.owndroid.backToHomeStateFlow import com.bintianqi.owndroid.backToHomeStateFlow
import com.rosan.dhizuku.api.Dhizuku import com.rosan.dhizuku.api.Dhizuku
import com.rosan.dhizuku.api.Dhizuku.binderWrapper import com.rosan.dhizuku.api.Dhizuku.binderWrapper
@@ -42,10 +43,9 @@ lateinit var addDeviceAdmin: ActivityResultLauncher<Intent>
val Context.isDeviceOwner: Boolean val Context.isDeviceOwner: Boolean
get() { get() {
val sharedPref = getSharedPreferences("data", Context.MODE_PRIVATE)
val dpm = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager val dpm = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
return dpm.isDeviceOwnerApp( return dpm.isDeviceOwnerApp(
if(sharedPref.getBoolean("dhizuku", false)) { if(SharedPrefs(this).dhizuku) {
Dhizuku.getOwnerPackageName() Dhizuku.getOwnerPackageName()
} else { } else {
"com.bintianqi.owndroid" "com.bintianqi.owndroid"
@@ -66,8 +66,7 @@ val Context.isDeviceAdmin: Boolean
val Context.dpcPackageName: String val Context.dpcPackageName: String
get() { get() {
val sharedPref = getSharedPreferences("data", Context.MODE_PRIVATE) return if(SharedPrefs(this).dhizuku) {
return if(sharedPref.getBoolean("dhizuku", false)) {
Dhizuku.getOwnerPackageName() Dhizuku.getOwnerPackageName()
} else { } else {
"com.bintianqi.owndroid" "com.bintianqi.owndroid"
@@ -119,8 +118,7 @@ private fun binderWrapperPackageInstaller(appContext: Context): PackageInstaller
} }
fun Context.getPackageInstaller(): PackageInstaller { fun Context.getPackageInstaller(): PackageInstaller {
val sharedPref = this.getSharedPreferences("data", Context.MODE_PRIVATE) if(SharedPrefs(this).dhizuku) {
if(sharedPref.getBoolean("dhizuku", false)) {
if (!dhizukuPermissionGranted()) { if (!dhizukuPermissionGranted()) {
dhizukuErrorStatus.value = 2 dhizukuErrorStatus.value = 2
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
@@ -133,8 +131,7 @@ fun Context.getPackageInstaller(): PackageInstaller {
} }
fun Context.getDPM(): DevicePolicyManager { fun Context.getDPM(): DevicePolicyManager {
val sharedPref = this.getSharedPreferences("data", Context.MODE_PRIVATE) if(SharedPrefs(this).dhizuku) {
if(sharedPref.getBoolean("dhizuku", false)) {
if (!dhizukuPermissionGranted()) { if (!dhizukuPermissionGranted()) {
dhizukuErrorStatus.value = 2 dhizukuErrorStatus.value = 2
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
@@ -147,8 +144,7 @@ fun Context.getDPM(): DevicePolicyManager {
} }
fun Context.getReceiver(): ComponentName { fun Context.getReceiver(): ComponentName {
val sharedPref = this.getSharedPreferences("data", Context.MODE_PRIVATE) return if(SharedPrefs(this).dhizuku) {
return if(sharedPref.getBoolean("dhizuku", false)) {
Dhizuku.getOwnerComponent() Dhizuku.getOwnerComponent()
} else { } else {
ComponentName(this, Receiver::class.java) ComponentName(this, Receiver::class.java)
@@ -547,8 +543,8 @@ fun parseSecurityEventData(event: SecurityLog.SecurityEvent): JsonElement? {
fun setDefaultAffiliationID(context: Context) { fun setDefaultAffiliationID(context: Context) {
if(VERSION.SDK_INT < 26) return if(VERSION.SDK_INT < 26) return
val sharedPrefs = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
if(!sharedPrefs.getBoolean("default_affiliation_id_set", false)) { if(!sp.isDefaultAffiliationIdSet) {
try { try {
val um = context.getSystemService(Context.USER_SERVICE) as UserManager val um = context.getSystemService(Context.USER_SERVICE) as UserManager
if(context.isDeviceOwner || (!um.isSystemUser && context.isProfileOwner)) { if(context.isDeviceOwner || (!um.isSystemUser && context.isProfileOwner)) {
@@ -557,7 +553,7 @@ fun setDefaultAffiliationID(context: Context) {
val affiliationIDs = dpm.getAffiliationIds(receiver) val affiliationIDs = dpm.getAffiliationIds(receiver)
if(affiliationIDs.isEmpty()) { if(affiliationIDs.isEmpty()) {
dpm.setAffiliationIds(receiver, setOf("OwnDroid_default_affiliation_id")) dpm.setAffiliationIds(receiver, setOf("OwnDroid_default_affiliation_id"))
sharedPrefs.edit().putBoolean("default_affiliation_id_set", true).apply() sp.isDefaultAffiliationIdSet = true
Log.d("DPM", "Default affiliation id set") Log.d("DPM", "Default affiliation id set")
} }
} }

View File

@@ -134,6 +134,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.bintianqi.owndroid.MyViewModel import com.bintianqi.owndroid.MyViewModel
import com.bintianqi.owndroid.R import com.bintianqi.owndroid.R
import com.bintianqi.owndroid.SharedPrefs
import com.bintianqi.owndroid.formatFileSize import com.bintianqi.owndroid.formatFileSize
import com.bintianqi.owndroid.humanReadableDate import com.bintianqi.owndroid.humanReadableDate
import com.bintianqi.owndroid.showOperationResultToast import com.bintianqi.owndroid.showOperationResultToast
@@ -164,8 +165,7 @@ fun Network(navCtrl:NavHostController) {
val receiver = context.getReceiver() val receiver = context.getReceiver()
val deviceOwner = context.isDeviceOwner val deviceOwner = context.isDeviceOwner
val profileOwner = context.isProfileOwner val profileOwner = context.isProfileOwner
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val dhizuku = SharedPrefs(context).dhizuku
val dhizuku = sharedPref.getBoolean("dhizuku", false)
MyScaffold(R.string.network, 0.dp, navCtrl) { MyScaffold(R.string.network, 0.dp, navCtrl) {
if(!dhizuku) FunctionItem(R.string.wifi, icon = R.drawable.wifi_fill0) { navCtrl.navigate("Wifi") } if(!dhizuku) FunctionItem(R.string.wifi, icon = R.drawable.wifi_fill0) { navCtrl.navigate("Wifi") }
if(VERSION.SDK_INT >= 30) { if(VERSION.SDK_INT >= 30) {

View File

@@ -69,6 +69,7 @@ import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat.startActivity import androidx.core.content.ContextCompat.startActivity
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.bintianqi.owndroid.R import com.bintianqi.owndroid.R
import com.bintianqi.owndroid.SharedPrefs
import com.bintianqi.owndroid.showOperationResultToast import com.bintianqi.owndroid.showOperationResultToast
import com.bintianqi.owndroid.ui.CardItem import com.bintianqi.owndroid.ui.CardItem
import com.bintianqi.owndroid.ui.CheckBoxItem import com.bintianqi.owndroid.ui.CheckBoxItem
@@ -82,14 +83,13 @@ import com.bintianqi.owndroid.yesOrNo
@Composable @Composable
fun Password(navCtrl: NavHostController) { fun Password(navCtrl: NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val sharedPrefs = context.getSharedPreferences("data", Context.MODE_PRIVATE)
val deviceAdmin = context.isDeviceAdmin val deviceAdmin = context.isDeviceAdmin
val deviceOwner = context.isDeviceOwner val deviceOwner = context.isDeviceOwner
val profileOwner = context.isProfileOwner val profileOwner = context.isProfileOwner
var dialog by remember { mutableIntStateOf(0) } var dialog by remember { mutableIntStateOf(0) }
MyScaffold(R.string.password_and_keyguard, 0.dp, navCtrl) { MyScaffold(R.string.password_and_keyguard, 0.dp, navCtrl) {
FunctionItem(R.string.password_info, icon = R.drawable.info_fill0) { navCtrl.navigate("PasswordInfo") } FunctionItem(R.string.password_info, icon = R.drawable.info_fill0) { navCtrl.navigate("PasswordInfo") }
if(sharedPrefs.getBoolean("dangerous_features", false)) { if(SharedPrefs(context).displayDangerousFeatures) {
if(VERSION.SDK_INT >= 26 && (deviceOwner || profileOwner)) { if(VERSION.SDK_INT >= 26 && (deviceOwner || profileOwner)) {
FunctionItem(R.string.reset_password_token, icon = R.drawable.key_vertical_fill0) { navCtrl.navigate("ResetPasswordToken") } FunctionItem(R.string.reset_password_token, icon = R.drawable.key_vertical_fill0) { navCtrl.navigate("ResetPasswordToken") }
} }

View File

@@ -46,6 +46,7 @@ import androidx.navigation.NavHostController
import androidx.navigation.NavOptions import androidx.navigation.NavOptions
import com.bintianqi.owndroid.MyViewModel import com.bintianqi.owndroid.MyViewModel
import com.bintianqi.owndroid.R import com.bintianqi.owndroid.R
import com.bintianqi.owndroid.SharedPrefs
import com.bintianqi.owndroid.backToHomeStateFlow import com.bintianqi.owndroid.backToHomeStateFlow
import com.bintianqi.owndroid.showOperationResultToast import com.bintianqi.owndroid.showOperationResultToast
import com.bintianqi.owndroid.ui.* import com.bintianqi.owndroid.ui.*
@@ -63,7 +64,6 @@ fun Permissions(navCtrl: NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val dpm = context.getDPM() val dpm = context.getDPM()
val receiver = context.getReceiver() val receiver = context.getReceiver()
val sharedPref = LocalContext.current.getSharedPreferences("data", Context.MODE_PRIVATE)
val deviceAdmin = context.isDeviceAdmin val deviceAdmin = context.isDeviceAdmin
val deviceOwner = context.isDeviceOwner val deviceOwner = context.isDeviceOwner
val profileOwner = context.isProfileOwner val profileOwner = context.isProfileOwner
@@ -75,7 +75,7 @@ fun Permissions(navCtrl: NavHostController) {
if(!dpm.isDeviceOwnerApp(context.packageName)) { if(!dpm.isDeviceOwnerApp(context.packageName)) {
SwitchItem( SwitchItem(
R.string.dhizuku, R.string.dhizuku,
getState = { sharedPref.getBoolean("dhizuku", false) }, getState = { SharedPrefs(context).dhizuku },
onCheckedChange = { toggleDhizukuMode(it, context) }, onCheckedChange = { toggleDhizukuMode(it, context) },
onClickBlank = { dialog = 4 } onClickBlank = { dialog = 4 }
) )
@@ -235,9 +235,9 @@ fun Permissions(navCtrl: NavHostController) {
} }
private fun toggleDhizukuMode(status: Boolean, context: Context) { private fun toggleDhizukuMode(status: Boolean, context: Context) {
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
if(!status) { if(!status) {
sharedPref.edit().putBoolean("dhizuku", false).apply() sp.dhizuku = false
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
return return
} }
@@ -246,7 +246,7 @@ private fun toggleDhizukuMode(status: Boolean, context: Context) {
return return
} }
if(dhizukuPermissionGranted()) { if(dhizukuPermissionGranted()) {
sharedPref.edit().putBoolean("dhizuku", true).apply() sp.dhizuku = true
Dhizuku.init(context) Dhizuku.init(context)
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
} else { } else {
@@ -254,7 +254,7 @@ private fun toggleDhizukuMode(status: Boolean, context: Context) {
@Throws(RemoteException::class) @Throws(RemoteException::class)
override fun onRequestPermission(grantResult: Int) { override fun onRequestPermission(grantResult: Int) {
if(grantResult == PackageManager.PERMISSION_GRANTED) { if(grantResult == PackageManager.PERMISSION_GRANTED) {
sharedPref.edit().putBoolean("dhizuku", true).apply() sp.dhizuku = true
Dhizuku.init(context) Dhizuku.init(context)
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
} else { } else {
@@ -444,14 +444,14 @@ fun DeviceOwner(navCtrl: NavHostController) {
} }
} }
if(deactivateDialog) { if(deactivateDialog) {
val sp = SharedPrefs(context)
var resetPolicy by remember { mutableStateOf(false) } var resetPolicy by remember { mutableStateOf(false) }
val sharedPref = LocalContext.current.getSharedPreferences("data", Context.MODE_PRIVATE)
val coroutine = rememberCoroutineScope() val coroutine = rememberCoroutineScope()
AlertDialog( AlertDialog(
title = { Text(stringResource(R.string.deactivate)) }, title = { Text(stringResource(R.string.deactivate)) },
text = { text = {
Column { Column {
if(sharedPref.getBoolean("dhizuku", false)) Text(stringResource(R.string.dhizuku_will_be_deactivated)) if(sp.dhizuku) Text(stringResource(R.string.dhizuku_will_be_deactivated))
Spacer(Modifier.padding(vertical = 4.dp)) Spacer(Modifier.padding(vertical = 4.dp))
CheckBoxItem(text = R.string.reset_device_policy, checked = resetPolicy, operation = { resetPolicy = it }) CheckBoxItem(text = R.string.reset_device_policy, checked = resetPolicy, operation = { resetPolicy = it })
} }
@@ -470,9 +470,9 @@ fun DeviceOwner(navCtrl: NavHostController) {
coroutine.launch { coroutine.launch {
if(resetPolicy) context.resetDevicePolicy() if(resetPolicy) context.resetDevicePolicy()
dpm.clearDeviceOwnerApp(context.dpcPackageName) dpm.clearDeviceOwnerApp(context.dpcPackageName)
if(sharedPref.getBoolean("dhizuku", false)) { if(sp.dhizuku) {
if (!Dhizuku.init(context)) { if (!Dhizuku.init(context)) {
sharedPref.edit().putBoolean("dhizuku", false).apply() sp.dhizuku = false
backToHomeStateFlow.value = true backToHomeStateFlow.value = true
} }
} }

View File

@@ -124,6 +124,7 @@ import androidx.navigation.NavHostController
import com.bintianqi.owndroid.MyViewModel import com.bintianqi.owndroid.MyViewModel
import com.bintianqi.owndroid.NotificationUtils import com.bintianqi.owndroid.NotificationUtils
import com.bintianqi.owndroid.R import com.bintianqi.owndroid.R
import com.bintianqi.owndroid.SharedPrefs
import com.bintianqi.owndroid.formatFileSize import com.bintianqi.owndroid.formatFileSize
import com.bintianqi.owndroid.humanReadableDate import com.bintianqi.owndroid.humanReadableDate
import com.bintianqi.owndroid.showOperationResultToast import com.bintianqi.owndroid.showOperationResultToast
@@ -151,9 +152,8 @@ fun SystemManage(navCtrl: NavHostController) {
val context = LocalContext.current val context = LocalContext.current
val dpm = context.getDPM() val dpm = context.getDPM()
val receiver = context.getReceiver() val receiver = context.getReceiver()
val sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE) val sp = SharedPrefs(context)
val dhizuku = sharedPref.getBoolean("dhizuku", false) val dhizuku = sp.dhizuku
val dangerousFeatures = sharedPref.getBoolean("dangerous_features", false)
val deviceOwner = context.isDeviceOwner val deviceOwner = context.isDeviceOwner
val profileOwner = context.isProfileOwner val profileOwner = context.isProfileOwner
var dialog by remember { mutableIntStateOf(0) } var dialog by remember { mutableIntStateOf(0) }
@@ -208,7 +208,7 @@ fun SystemManage(navCtrl: NavHostController) {
if(VERSION.SDK_INT >= 30 && (deviceOwner || dpm.isOrgProfile(receiver))) { if(VERSION.SDK_INT >= 30 && (deviceOwner || dpm.isOrgProfile(receiver))) {
FunctionItem(R.string.frp_policy, icon = R.drawable.device_reset_fill0) { navCtrl.navigate("FRPPolicy") } FunctionItem(R.string.frp_policy, icon = R.drawable.device_reset_fill0) { navCtrl.navigate("FRPPolicy") }
} }
if(dangerousFeatures && context.isDeviceAdmin && !(VERSION.SDK_INT >= 24 && profileOwner && dpm.isManagedProfile(receiver))) { if(sp.displayDangerousFeatures && context.isDeviceAdmin && !(VERSION.SDK_INT >= 24 && profileOwner && dpm.isManagedProfile(receiver))) {
FunctionItem(R.string.wipe_data, icon = R.drawable.device_reset_fill0) { navCtrl.navigate("WipeData") } FunctionItem(R.string.wipe_data, icon = R.drawable.device_reset_fill0) { navCtrl.navigate("WipeData") }
} }
} }

View File

@@ -97,7 +97,7 @@ fun OwnDroidTheme(
content: @Composable () -> Unit content: @Composable () -> Unit
) { ) {
val theme by vm.theme.collectAsStateWithLifecycle() val theme by vm.theme.collectAsStateWithLifecycle()
val darkTheme = theme.darkTheme == true || (theme.darkTheme == null && isSystemInDarkTheme()) val darkTheme = theme.darkTheme == 1 || (theme.darkTheme == -1 && isSystemInDarkTheme())
val context = LocalContext.current val context = LocalContext.current
var colorScheme = when { var colorScheme = when {
theme.materialYou && VERSION.SDK_INT >= 31 -> { theme.materialYou && VERSION.SDK_INT >= 31 -> {