Automatically silence the sound volume of Android Phone programmatically?

后端 未结 2 656
抹茶落季
抹茶落季 2021-01-03 15:38

I\'m developing an application that can turn off the sound of Android Phone automatically. How can I detect the volume of the sound and turn it off programmatically?

相关标签:
2条回答
  • 2021-01-03 15:48

    Have a look at the AudioManager, especially the getStreamVolume and setStreamVolume methods

    EDIT

    You can also use the method Nikola Despotoski provided with setRingerMode

    A Service is a child of a Context so you can call directly getSystemService

    See the updated code below (untested):

    if (hour == myTime.getHour() && minute == myTime.getMinute()) {
            if (Settings.getSetMyTime(this))
                showNotificationAlarm(R.drawable.icon,"It's time to work");
                AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
                am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    
    }
    
    0 讨论(0)
  • 2021-01-03 16:13

    Register for AUDIO_SERVICE and then use the AudioManager to control the volume up/down or set profiles.

    Or if you want to listen for changes in the Audio focus then make your Activity implements AudioManager.OnAudioFocusChangeListener. Override unimplemented method. Create switch that will take care of types of changes.

    Like:

    @Override
        public void onAudioFocusChange(int focusChange) {
            switch(focusChange)
            {
            case AudioManager.AUDIOFOCUS_GAIN:
                //do something
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                break;
            }
    

    Or if you want to listen for changes on the audio output, like unplugging the headphones (switching to phone speaker) use ACTION_AUDIO_BECOMING_NOISY sticky broadcast

    http://developer.android.com/reference/android/media/AudioManager.html#ACTION_AUDIO_BECOMING_NOISY

    http://developer.android.com/reference/android/media/AudioManager.html#RINGER_MODE_SILENT

    See here

    Edit: This is the solution. There was no need to handle AudioFocus but just set different ringer profile or adjusting volume

    if (hour == myTime.getHour() && minute == myTime.getMinute()) {
            if (Settings.getSetMyTime(this))
                showNotificationAlarm(R.drawable.icon,
                        "It's time to work");
                        AudioManager audiomanager =(AudioManager)YourActivityName.this.getSystemService(Context.AUDIO_SERVICE);
            audiomanager.setRingerMode(AudioManager.RINGER_MODE_SILENT); //or adjust volume here instead setting silent profile for the ringer
        }
    
    0 讨论(0)
提交回复
热议问题