Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dimming with Volume Buttons #72

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app/src/main/kotlin/com/cyb3rko/flashdim/Camera.kt
Original file line number Diff line number Diff line change
@@ -94,5 +94,12 @@ internal class Camera(activity: AppCompatActivity) {
handleFlashlightException(e)
}
}

fun getLightLevel(context: Context): Int {
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE)
as CameraManager
val cameraId = cameraManager.cameraIdList[0]
return cameraManager.getTorchStrengthLevel(cameraId)
}
}
}
Original file line number Diff line number Diff line change
@@ -152,6 +152,63 @@ internal class SettingsActivity : AppCompatActivity(), OnSharedPreferenceChangeL
true
}
}

findPreference<Preference>(Safe.TIMEOUT_DURATION)?.apply {
Safe.initialize(myContext)
if (!Safe.getBoolean(Safe.MULTILEVEL, false)) {
isEnabled = false
return@apply
}

val timeoutDuration = Safe.getFloat(Safe.TIMEOUT_DURATION, 2.toFloat())
val summaryString = getString(R.string.preference_item_timeout_duration_summary)
summary = "$summaryString: $timeoutDuration"

setOnPreferenceClickListener { preference ->
val currentTimeoutDuration = Safe.getFloat(Safe.TIMEOUT_DURATION, 2.toFloat())
val withVibration = Safe.getBoolean(Safe.BUTTON_VIBRATION, true)
val content = LinearLayout(myContext).apply {
orientation = LinearLayout.VERTICAL
setPadding(75, 0, 75, 0)
}
val levelView = TextView(myContext).apply {
textSize = 18f
setPadding(24, 24, 24, 50)
gravity = Gravity.CENTER_HORIZONTAL
text = String.format(
getString(R.string.preference_item_timeout_duration_dialog_message),
currentTimeoutDuration,
currentTimeoutDuration
)
}
content.addView(levelView)
val slider = Slider(myContext).apply {
valueFrom = 1F // 1 second min
valueTo = 5F // 10 seconds max
value = currentTimeoutDuration.toFloat()
stepSize = .5F
addOnChangeListener { _, value, _ ->
if (withVibration) Vibrator.vibrateTick()
levelView.text = String.format(
getString(R.string.preference_item_timeout_duration_dialog_message),
value,
currentTimeoutDuration
)
}
}
content.addView(slider)
showTimeoutDurationDialog(content) {
val value = slider.value
Safe.writeFloat(Safe.TIMEOUT_DURATION, value) // make a Safe.writeFloat() function/

val summary = getString(R.string.preference_item_timeout_duration_summary)
preference.summary = "$summary: $value"
}
true
}
}


findPreference<Preference>("volume_buttons")?.setOnPreferenceClickListener {
AccessibilityInfoDialog.show(myContext)
true
@@ -175,5 +232,25 @@ internal class SettingsActivity : AppCompatActivity(), OnSharedPreferenceChangeL
)
.show()
}

private fun showTimeoutDurationDialog(content: View, onSave: () -> Unit) {
MaterialAlertDialogBuilder(
requireContext(),
MaterialR.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered
)
.setIcon(R.drawable.ic_level)
.setTitle(getString(R.string.preference_item_timeout_duration_dialog_title))
.setView(content)
.setPositiveButton(android.R.string.ok) { _, _ ->
onSave()
}
.setNegativeButton(
getString(R.string.preference_item_initial_level_dialog_negative_button),
null
)
.show()
}
// make my own function for the volume dimmer duration view

}
}
Original file line number Diff line number Diff line change
@@ -26,10 +26,14 @@ import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.cyb3rko.flashdim.Camera
import com.cyb3rko.flashdim.utils.Safe
import kotlin.math.max
import kotlin.math.min

class VolumeButtonService : AccessibilityService() {
private var volumeUpPressed = false
private var volumeDownPressed = false
private var flashlightOnTime = 0 // Timestamp of flashlight on time
private val DIM_INCREMENT = 10 // How much each click +/- the brightness

override fun onServiceConnected() {
Safe.initialize(applicationContext)
@@ -46,6 +50,8 @@ class VolumeButtonService : AccessibilityService() {

override fun onKeyEvent(event: KeyEvent?): Boolean {
if (event == null) return false
var shouldEatMessage = false // Used to determine if the message should be consumed

if ((event.keyCode == KeyEvent.KEYCODE_VOLUME_UP) ||
(event.keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
) {
@@ -58,21 +64,57 @@ class VolumeButtonService : AccessibilityService() {
if (volumeUpPressed && volumeDownPressed) {
Log.i("FlashDim Service", "Both volume buttons pressed")
val flashActive = Safe.getBoolean(Safe.FLASH_ACTIVE, false)
if (!flashActive) flashlightOnTime = System.currentTimeMillis().toInt()

val flashLevel = if (!flashActive) getFlashLevel() else 0
Camera.sendLightLevel(applicationContext, flashLevel, !flashActive)
shouldEatMessage = true

} else if ((volumeUpPressed || volumeDownPressed) &&
event.action == KeyEvent.ACTION_DOWN &&
Safe.getBoolean(Safe.FLASH_ACTIVE, false)) {
val timeoutDuration = (Safe.getFloat(Safe.TIMEOUT_DURATION, 2F)) * 1000

// if the light is on, handle dimming w/ buttons
if ((System.currentTimeMillis().toInt() - flashlightOnTime) < timeoutDuration) { // Come back in 31 years to fix this
val flashLevel = Camera.getLightLevel(applicationContext)

when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> {
Camera.sendLightLevel(
applicationContext,
min(flashLevel + DIM_INCREMENT, Safe.getInt(Safe.MAX_LEVEL, -1)),
true
)
shouldEatMessage = true
flashlightOnTime = System.currentTimeMillis().toInt() // reset time
}

KeyEvent.KEYCODE_VOLUME_DOWN -> {
Camera.sendLightLevel(
applicationContext,
max(1, flashLevel - DIM_INCREMENT),
true
)
shouldEatMessage = true
flashlightOnTime = System.currentTimeMillis().toInt() // reset time
}
}
}
}
} else {
}
else {
volumeUpPressed = false
volumeDownPressed = false
}
return false
return shouldEatMessage
}

private fun getFlashLevel(): Int {
return if (Safe.getBoolean(Safe.VOLUME_BUTTONS_LINK, false)) {
Safe.getInt(Safe.INITIAL_LEVEL, -1)
if (Safe.getBoolean(Safe.VOLUME_BUTTONS_LINK, false)) {
return Safe.getInt(Safe.INITIAL_LEVEL, Safe.getInt(Safe.MAX_LEVEL, -1))
} else {
-1
return -1
}
}

11 changes: 11 additions & 0 deletions app/src/main/kotlin/com/cyb3rko/flashdim/utils/Safe.kt
Original file line number Diff line number Diff line change
@@ -36,6 +36,8 @@ internal object Safe {
const val REPORT_DIALOG_SHOWN = "${BuildConfig.VERSION_CODE}-report_dialog"
const val STARTUP_COUNTER = "startup_counter"
const val VOLUME_BUTTONS_LINK = "volume_buttons_link"
const val TIMEOUT_DURATION = "timeout_duration" // default 2 seconds, 2000 ms // Make it so that the user can customize this later


private lateinit var sharedPreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
@@ -51,12 +53,21 @@ internal object Safe {

fun getInt(label: String, default: Int) = sharedPreferences.getInt(label, default)

fun getFloat(label: String, default: Float) = sharedPreferences.getFloat(label, default)


fun writeInt(label: String, value: Int) {
try {
editor.putInt(label, value).apply()
} catch (_: Exception) {}
}

fun writeFloat(label: String, value: Float) {
try {
editor.putFloat(label, value).apply()
} catch (_: Exception) {}
}

fun writeBoolean(label: String, value: Boolean) {
try {
editor.putBoolean(label, value).apply()
4 changes: 4 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -71,9 +71,13 @@
<string name="preference_item_initial_level_summary">Dim level for Initial Flash, optionally for quick settings tile and volume button press</string>
<string name="preference_item_volume_buttons">Volume Buttons Service</string>
<string name="preference_item_volume_buttons_summary">Activate the service for toggling the flashlight when pressing both volume buttons.</string>
<string name="preference_item_timeout_duration">Volume Button Dimming</string>
<string name="preference_item_timeout_duration_summary">After pressing both volume buttons, quickly adjust the flashlight\'s dim level within a customizable amount of time</string>
<string name="preference_item_initial_level_dialog_title">Set Initial Level</string>
<string name="preference_item_initial_level_dialog_message">New: %1$s\nCurrent: %2$s</string>
<string name="preference_item_initial_level_dialog_negative_button">Cancel</string>
<string name="preference_item_timeout_duration_dialog_title">Set Timeout Duration</string>
<string name="preference_item_timeout_duration_dialog_message">New: %1$s seconds\nCurrent: %2$s seconds</string>
<string name="preference_category_vibration">Vibration</string>
<string name="preference_item_tactile_buttons">Tactile buttons</string>
<string name="preference_item_tactile_buttons_summary">Vibrate on button clicks and seekbar swipes</string>
6 changes: 6 additions & 0 deletions app/src/main/res/xml/preferences.xml
Original file line number Diff line number Diff line change
@@ -53,6 +53,12 @@
app:summary="@string/preference_item_volume_buttons_summary"
app:icon="@drawable/ic_button_service" />

<Preference
app:key="timeout_duration"
app:title="@string/preference_item_timeout_duration"
app:summary="@string/preference_item_timeout_duration_summary"
app:icon="@drawable/ic_level_scaled" />

</PreferenceCategory>

<PreferenceCategory
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[versions]
agp = "8.3.0"
agp = "8.5.0"
kotlin = "1.9.23"
kotlinter = "4.2.0"
dexcount = "4.0.0"
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=9631d53cf3e74bfa726893aee1f8994fee4e060c401335946dba2156f440f24c
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME