MainActivity.kt 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.wasp.cardash_launcher
  2. import android.media.AudioManager
  3. import android.view.KeyEvent
  4. import io.flutter.embedding.android.FlutterActivity
  5. import io.flutter.embedding.engine.FlutterEngine
  6. class MainActivity : FlutterActivity() {
  7. private var launcherBridge: LauncherBridge? = null
  8. private var systemBridge: SystemBridge? = null
  9. override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
  10. super.configureFlutterEngine(flutterEngine)
  11. launcherBridge = LauncherBridge(this).also {
  12. it.attach(flutterEngine.dartExecutor.binaryMessenger)
  13. }
  14. systemBridge = SystemBridge(this).also {
  15. it.attach(flutterEngine.dartExecutor.binaryMessenger)
  16. }
  17. }
  18. /**
  19. * While the dashboard is visible, the hardware volume keys should change
  20. * the same media stream as the on-screen control. Without this, Android
  21. * falls back to the ring stream when nothing is playing and the dashboard
  22. * and the keys disagree.
  23. */
  24. override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
  25. if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
  26. adjustMediaVolume(if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) 1 else -1)
  27. return true
  28. }
  29. return super.onKeyDown(keyCode, event)
  30. }
  31. override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
  32. if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
  33. return true
  34. }
  35. return super.onKeyUp(keyCode, event)
  36. }
  37. private fun adjustMediaVolume(direction: Int) {
  38. try {
  39. val audio = getSystemService(AudioManager::class.java)
  40. audio.adjustStreamVolume(
  41. AudioManager.STREAM_MUSIC,
  42. if (direction > 0) AudioManager.ADJUST_RAISE else AudioManager.ADJUST_LOWER,
  43. 0,
  44. )
  45. } catch (_: Throwable) {
  46. // Never let a volume-key edge case take down the launcher.
  47. }
  48. }
  49. override fun onDestroy() {
  50. launcherBridge?.dispose()
  51. systemBridge?.dispose()
  52. launcherBridge = null
  53. systemBridge = null
  54. super.onDestroy()
  55. }
  56. }