我如何才能检测是否在静音模式的Android手机编程

kq4fsx7k  于 2023-01-03  发布在  Android
关注(0)|答案(3)|浏览(558)

如何识别手机是否处于静音模式?
我使用的是安卓1. 5。我尝试使用“安卓。提供者。设置。动作_声音_设置”。它不工作。

4jb9z9bj

4jb9z9bj1#

AudioManager中使用getRingerMode()方法。

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

switch (am.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        Log.i("MyApp","Silent mode");
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        Log.i("MyApp","Vibrate mode");
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        Log.i("MyApp","Normal mode");
        break;
}
b09cbbtk

b09cbbtk2#

以下代码检查手机是否未处于静音模式,然后播放蜂鸣音,格式为kotlin

val manager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
    manager.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 0)
    val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val player: MediaPlayer = MediaPlayer.create(applicationContext, notification)
    if(manager.ringerMode != AudioManager.RINGER_MODE_SILENT)
        player.start()
mmvthczy

mmvthczy3#

如果您要收听振铃器模式更改,即静音振动正常的任何更改,您可以在活动中设置广播接收器,如下所示。

private val volumeKeyReceiver: VolumeKeyReceiver by lazy {
        VolumeKeyReceiver()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerBroadcastListener()
    }

    private fun registerBroadcastListener() {
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.media.RINGER_MODE_CHANGED")
        registerReceiver(volumeKeyReceiver, intentFilter)
    }

并在活动被破坏时取消注册,如下所示。

override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(volumeKeyReceiver)
    }

并在清单中登记接收者

<receiver android:name=".VolumeKeyReceiver"/>

广播接收器来了

class VolumeKeyReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        //Implement Logic
        val audioManager =
            context?.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
        when (audioManager.ringerMode) {
            android.media.AudioManager.RINGER_MODE_SILENT -> Log.d(
                "VolumeKeyReceiver",
                "Silent mode"
            )
            android.media.AudioManager.RINGER_MODE_VIBRATE -> Log.d(
                "VolumeKeyReceiver",
                "Vibrate mode"
            )
            android.media.AudioManager.RINGER_MODE_NORMAL -> Log.d(
                "VolumeKeyReceiver",
                "Normal mode"
            )
        }
    }
}

相关问题