import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.round
class MainActivity : AppCompatActivity() {
var brightnessValue = 255
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
@RequiresApi(Build.VERSION_CODES.M)
fun decrease() {
val context = applicationContext
val settingsCanWrite = hasWriteSettingsPermission(context)
if (!settingsCanWrite) {
changeWriteSettingsPermission(context)
} else {
if (brightnessValue >= 11) {
brightnessValue -= 10
changeScreenBrightness(context, brightnessValue)
val k = brightnessValue.toDouble() / 255
Toast.makeText(
applicationContext, "Brightness : ${round(k * 100)}%",
Toast.LENGTH_SHORT
).show()
}
}
}
@RequiresApi(Build.VERSION_CODES.M)
fun increase() {
val context = applicationContext
val settingsCanWrite = hasWriteSettingsPermission(context)
if (!settingsCanWrite) {
changeWriteSettingsPermission(context)
} else {
if (brightnessValue <= 245) {
brightnessValue += 10
changeScreenBrightness(context, brightnessValue)
val k = brightnessValue.toDouble() / 255
Toast.makeText(
applicationContext, "Brightness : ${round(k * 100)}%",
Toast.LENGTH_SHORT
).show()
}
}
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
decrease()
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
increase()
}
return true
}
@RequiresApi(Build.VERSION_CODES.M)
private fun hasWriteSettingsPermission(context: Context): Boolean {
var ret = true
ret = Settings.System.canWrite(context)
return ret
}
private fun changeWriteSettingsPermission(context: Context) {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
context.startActivity(intent)
}
private fun changeScreenBrightness(context: Context, screenBrightnessValue: Int) {
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
Settings.System.putInt(
context.contentResolver, Settings.System.SCREEN_BRIGHTNESS,
screenBrightnessValue
)
}
}