Disable sound just for one application

删除回忆录丶 提交于 2019-12-08 08:07:55

问题


Is it possible to turn off all sounds of just one app and to save the choice until the next start of the app?

So I have a ToggleButton at the StartActivity and by pressing this Button, all sounds of the app should be deactivated, but sounds of other apps should still be working.

I tried it with Preferences, using the SharedPreferences class, an xml file and so on, like in my book. But going through the introduction i realized, that the Preferences are just a way to save data permanent. So I would have to include for example on every Button with a sound an if-clause that checks if this or that saved preference for sound on/off is true/false and then activates/deactivates the sound?

I thought that it could be easier?


回答1:


Actually, if you want to disable a sound in your application - you can just don't play it. You can store the flags for each sound you want to play in the SharedPreferences and check it every time you want to play a sound. It's really easy!




回答2:


You can probably write your own MyButton class that extends Button and override onClick.




回答3:


  1. Declare a string

    String strSound;

  2. enter this line in your shared preference settings

    strSound = prefs.getString("sound", "on");

  3. enter this line in your onActivityResult

    strSound = prefs.getString("sound", "on");

  4. put this lines in your media player which is used to give sounds for your application

    private void playSound()
    {
    mp = MediaPlayer.create(MyActivity.this, R.raw."your_soundfile_name");
    
    mp.setOnCompletionListener(new OnCompletionListener() 
    {
        @Override
        public void onCompletion(MediaPlayer mp) 
        {
            mp.release();
        }
    }); 
    if(strSound.equals("on"))
    mp.start();
    
  5. now put this lines on your toggle button activity

    your_togglebutton_id.setOnCheckedChangeListener(new     CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            if (isChecked)
            {
                editor.putString("sound", "on");
                editor.commit();
            }
            else
            {
                editor.putString("sound", "off");
                editor.commit();
            }
        }
    }
    


来源:https://stackoverflow.com/questions/7236678/disable-sound-just-for-one-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!