V
V
vikS2013-07-13 13:05:06
Android
vikS, 2013-07-13 13:05:06

MUTE button for android app?

There is an Activity, I'm trying to change the visibility (Visibility) of some View-elements in the onCreate () method, depending on the current volume level in the application.
Below is some poor code of how I'm trying to do this. I suspect that I did not understand the getStreamVolume principle (I realized that it returns the current volume value).

int app_volume = 1;  

           AudioManager audioManager2 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      	 audioManager2.getStreamVolume(app_volume);

                 // Если громкость нулевая, то:
      	  if(app_volume == 0){
      	        MUTE_btn.setVisibility(View.INVISIBLE);
      	        UNMUTE_btn.setVisibility(View.VISIBLE);
      	  }
                  // Если нет, то:
      	  else{
      		MUTE_btn.setVisibility(View.INVISIBLE);
       	        UNMUTE_btn.setVisibility(View.INVISIBLE); 
      	  }

Has anyone implemented something similar? share your experience?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vikS, 2013-07-13
@vikS

So, I figured it out, and I'm ready to demonstrate my solution to this problem to Habr visitors. Moreover, no advice on this issue was received here (after all, it's Saturday, normal people have a rest).
So, first things first:
What did I want to do?
And I wanted to make in my application a button to turn the sound on and off, which, when pressed, turns off the sound, and when pressed again, turns it on. Many will say that it is better to do this with the help of RadioButton, but I did it stupidlyin its own way with the help of two ImageView elements (in the course of the presentation I will call them Button, because they essentially perform the function of buttons), of course, only one of these Views should be visible on the screen at the current time, depending on whether which volume level is set to "zero" or "greater than zero". At the same time, I also wanted to take into account the possible manipulations of the user with the volume rocker so that this situation does not happen: the user increased the volume with the hardware volume_up button, and the button to increase it is currently available on the screen (although where to increase it further) ... and vice versa.
Code:
The markup file contains two buttons: stop_sound (which the user should see when the volume is not zero, i.e. something is playing) and the play_sound button (which the user should see when the volume is zero, i.e. nothing is playing)

      <ImageView
        android:id="@+id/stop_sound"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/sound_on"
         />

    <ImageView
        android:id="@+id/play_sound"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/sound_off"
         />

This is how these Views look separately (I drew them myself in Adobe Flash):
MUTE_btn button:
id= sound_stop UNMUTE_btn
image
button:
id= sound_play
image
In the code of our activity (Activity), we write the following:
    private ImageView MUTE_btn;    // Кнопка MUTE   (уменьшения громкости до нуля во всем приложении)
    private ImageView UNMUTE_btn;  // Кнопка UNMUTE (увеличения громкости почти до max во всем приложении)

    @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
        
       // Кнопка при нажатии, на которую громкость в приложении станет НУЛЕВОЙ (MUTE_btn).
       // Сама кнопка станет невидимой, а ВИДИМОЙ станет кнопка ВКЛючения звука (UNMUTE_btn).   

          MUTE_btn = (ImageView)this.findViewById(R.id.stop_sound); 
        
          MUTE_btn.setOnClickListener(new OnClickListener(){
                 public void onClick(View v) {
                      	  AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                      	  audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                      	  MUTE_btn.setVisibility(View.INVISIBLE);
                      	  UNMUTE_btn.setVisibility(View.VISIBLE);
                 }
          });

       // Кнопка при нажатии, на которую громкость в приложеии станет почти MAX (UNMUTE_btn).
       // Сама кнопка станет невидимой, а ВИДИМОЙ станет кнопка ВЫКЛючения звука (MUTE_btn).    

          UNMUTE_btn = (ImageView)this.findViewById(R.id.play_sound);

          UNMUTE_btn.setOnClickListener(new OnClickListener(){
                 public void onClick(View v) {
                      	  AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                      	  audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 90, 90);
                      	  MUTE_btn.setVisibility(View.VISIBLE);
                      	  UNMUTE_btn.setVisibility(View.INVISIBLE);
                 }
          });  
          
        // Установка видимости соответствующих кнопок при запуске Activity
    int app_volume;  

           AudioManager audioManager2 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
           app_volume = audioManager2.getStreamVolume(AudioManager.STREAM_MUSIC); // вот тут у меня и была ошибка

      	  if(app_volume == 0){
      		 MUTE_btn.setVisibility(View.INVISIBLE);
      	         UNMUTE_btn.setVisibility(View.VISIBLE);
      	  }
      	  else{
      		MUTE_btn.setVisibility(View.VISIBLE);
       	        UNMUTE_btn.setVisibility(View.INVISIBLE); 
      	  } 
       	  
  }    

      // А теперь займемся аппаратными кнопками volume_up и volume_down

       @Override
  public boolean onKeyUp(int keyCode, KeyEvent event){

          // при нажатии на кнопку громкости вверх, смена видимости соответствующих кнопок 

      if (keyCode == KeyEvent.KEYCODE_VOLUME_UP){

      	     MUTE_btn.setVisibility(View.VISIBLE);
      	     UNMUTE_btn.setVisibility(View.INVISIBLE);
               return true;

                }
      
    // при нажатии на кнопку громкости вниз, смена видимости соответствующих кнопок   

      if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){

           //  заметьте, тот же код, что и в методе on Create, т.к. необходимо, чтобы фон кнопки менялся только
           // при достижении нулевого уровня громкости

      	int app_volume;
               AudioManager audioManager2 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
         app_volume = audioManager2.getStreamVolume(AudioManager.STREAM_MUSIC);
        
        if(app_volume == 0){

      		   MUTE_btn.setVisibility(View.INVISIBLE);
      	           UNMUTE_btn.setVisibility(View.VISIBLE);

      	  }
      	  else{

      		 MUTE_btn.setVisibility(View.VISIBLE);
       	         UNMUTE_btn.setVisibility(View.INVISIBLE); 

      	  };  

            return true;
                }    
  }



Bottom line:
Voila, everything works as it should (Tested on my GalaxyNexus). Now, if the user wants, he can change the volume by pressing the “button” developed by us, the image of which will notify you of the presence or absence of sound. And if suddenly, the user will change the volume with the hardware keys, then in this case the image of the button will correspond to the situation.
I hope the above can help someone in the difficult task of developing Android applications. You can write your suggestions and implementation options below. My code is definitely not pulling on the best implementation, tk. I don't have much development experience.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question