|
| 1 | +package com.d4rk.musicsleeptimer.plus.services |
| 2 | + |
| 3 | +import android.app.PendingIntent |
| 4 | +import android.content.ComponentName |
| 5 | +import android.content.Intent |
| 6 | +import android.graphics.drawable.Icon |
| 7 | +import android.os.Build |
| 8 | +import android.service.quicksettings.Tile |
| 9 | +import android.service.quicksettings.TileService |
| 10 | +import android.util.Log |
| 11 | +import android.widget.Toast |
| 12 | +import androidx.annotation.RequiresApi |
| 13 | +import com.d4rk.musicsleeptimer.plus.R |
| 14 | + |
| 15 | +/** |
| 16 | + * Quick Settings tile that opens the native Android audio output picker dialog. |
| 17 | + * |
| 18 | + * The tile interacts with SystemUI by sending a broadcast that triggers the |
| 19 | + * system dialog used to switch between audio routes such as headphones, |
| 20 | + * speakers, and Bluetooth devices. |
| 21 | + */ |
| 22 | +@RequiresApi(Build.VERSION_CODES.N) |
| 23 | +class AudioOutputTileService : TileService() { |
| 24 | + companion object { |
| 25 | + private const val TAG = "AudioOutputTileService" |
| 26 | + private const val ACTION_MEDIA_OUTPUT = |
| 27 | + "com.android.systemui.action.LAUNCH_SYSTEM_MEDIA_OUTPUT_DIALOG" |
| 28 | + private const val PACKAGE_SYSTEMUI = "com.android.systemui" |
| 29 | + private const val RECEIVER_CLASS = |
| 30 | + "com.android.systemui.media.dialog.MediaOutputDialogReceiver" |
| 31 | + } |
| 32 | + |
| 33 | + override fun onStartListening() { |
| 34 | + super.onStartListening() |
| 35 | + updateTile() |
| 36 | + } |
| 37 | + |
| 38 | + override fun onClick() { |
| 39 | + super.onClick() |
| 40 | + openMediaOutputDialog() |
| 41 | + } |
| 42 | + |
| 43 | + private fun openMediaOutputDialog() { |
| 44 | + try { |
| 45 | + val intent = Intent(ACTION_MEDIA_OUTPUT).apply { |
| 46 | + component = ComponentName(PACKAGE_SYSTEMUI, RECEIVER_CLASS) |
| 47 | + } |
| 48 | + |
| 49 | + val pendingIntent = PendingIntent.getBroadcast( |
| 50 | + this, 0, intent, PendingIntent.FLAG_IMMUTABLE |
| 51 | + ) |
| 52 | + |
| 53 | + pendingIntent.send() |
| 54 | + } catch (exception: Exception) { |
| 55 | + val errorMessage = |
| 56 | + "Failed to open audio output dialog: ${exception.javaClass.simpleName}: ${exception.message}" |
| 57 | + Log.e(TAG, errorMessage, exception) |
| 58 | + showToast(errorMessage) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private fun updateTile() { |
| 63 | + val tile = qsTile ?: return |
| 64 | + tile.label = getString(R.string.audio_output) |
| 65 | + tile.icon = Icon.createWithResource(this, R.drawable.ic_audio_output) |
| 66 | + tile.state = Tile.STATE_ACTIVE |
| 67 | + tile.updateTile() |
| 68 | + } |
| 69 | + |
| 70 | + private fun showToast(message: String) { |
| 71 | + Toast.makeText(this, message, Toast.LENGTH_SHORT).show() |
| 72 | + } |
| 73 | +} |
0 commit comments