Android:如何让应用程序记住是否已按下静音按钮 [英] Android: How to get app to remember if mute button has been pressed or not

查看:123
本文介绍了Android:如何让应用程序记住是否已按下静音按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功创建了一个按钮,该按钮可以根据需要使我的按钮按下声音静音.我遇到的问题是,当我离开页面或关闭应用程序并返回声音时,将返回到默认的打开状态.我正在尝试通过首选项实现此目的,但是它不起作用.我以前曾使用首选项来成功存储高分,但是这次我可以按预期使它正常工作.这是我的声音代码:

I have successfully created a button that mute my button press sound if wanted. The problem I am having is that when I leave the page or close the app and return sound a returned to the default of being on. I am trying to achieve this through preferences but it is not working. I have used preferences before to successfully store high scores but I can get it to work this time as I intend. Here is my sound code:

import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;

public class homePage extends Activity {
    ;
    Button Mute;

        int Sound = 1;


     public void onCreate(Bundle savedInstanceState) { 
         setContentView(R.layout.home_page);

         Mute = (Button) findViewById(R.id.mute);
          setButtonOnClickListeners();

             RelativeLayout layout = new RelativeLayout(this);

             layout = (RelativeLayout) findViewById(R.id.home);



     }
     public void onPause(Bundle savedInstanceState) { 
         SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("SP", Context.MODE_PRIVATE);
         Editor editor = sharedPrefs.edit();
         editor.putInt("SP", Sound);
         editor.commit();


     }
     public void onResume(Bundle savedInstanceState) {   SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("SP", Context.MODE_PRIVATE);
     int counter = sharedPrefs.getInt("SP", 0);}

     public void sound(){
         final MediaPlayer mp = new MediaPlayer();
         if (Sound==1){
         try {

                AssetFileDescriptor afd;
                afd = getAssets().openFd("butpress.mp3");
                mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
             mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     }else if(Sound==0){mp.stop();}}


     private void setButtonOnClickListeners(){

         Mute.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(Sound==1){
                        Mute.setBackgroundResource( R.drawable.sound_off);
                        --Sound;

                    }
                    else if(Sound==0){
                        Mute.setBackgroundResource( R.drawable.sound_high);
                        Sound++;
                    }

                }


            });


}
}

静音是有效的,我只需要保存它,然后知道发生了什么问题?

The muting of sound works I just need it to save, and idea whats going wrong?

更新1:

这是已编辑的代码.

public class homePage extends Activity {

    Button Mute;

        int Sound = 0;
        private final static String PREFS_KEY = "shared_prefs"; 
     public void onCreate(Bundle savedInstanceState) { 
         setContentView(R.layout.home_page);

          super.onCreate(savedInstanceState); 

         Mute = (Button) findViewById(R.id.mute);
          setButtonOnClickListeners();


             onResume();// is this needed here? not noticed any difference either way   

             if(Sound==1){
                    Mute.setBackgroundResource( R.drawable.sound_high);
                    getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                }
                else if(Sound==0){
                    Mute.setBackgroundResource( R.drawable.sound_off);
                    getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                }

            }



     public void sound(){
         final MediaPlayer mp = new MediaPlayer();
         if (Sound==1){
         try {

                AssetFileDescriptor afd;
                afd = getAssets().openFd("butpress.mp3");
                mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
             mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     }else if(Sound==0){mp.stop();}}


     private void setButtonOnClickListeners(){


         Mute.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(Sound==1){
                        Mute.setBackgroundResource( R.drawable.sound_off);
                        --Sound;
                        getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                    }
                    else if(Sound==0){
                        Mute.setBackgroundResource( R.drawable.sound_high);
                        Sound++;
                        getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                    }

                }


            });


} public void onPause(Bundle savedInstanceState) { 
     SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE);
     Editor editor = sharedPrefs.edit();
     editor.putInt("SP", Sound);
     editor.commit();


}
public void onResume(Bundle savedInstanceState) {    SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE);
Sound = sharedPrefs.getInt("SP", 0);}

}

我认为存储的号码不正确

I don't think the correct number is being stored

推荐答案

在OnClickListener的onClick方法中,您可以保存状态

In your OnClickListener's onClick method you can save the state

getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

或者如果要像在onPause中一样保存int值,请

or if you want to save the int value like you are in onPause just do

getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_val", Sound).commit();

因为到现在为止,您实际上并没有在增加/减少时进行保存,而只是保存了onPause().然后,您可以通过更改

Because as of right now you aren't actually saving as you increment/decrement you are only saving onPause(). You can then restore that value in onResume() by changing

int counter = ...
// to
Sound =...

这会将您的类Sound变量设置为旧的存储值.

This will set your classes Sound variable to the old stored value.

我还建议您不要使用"SP"(我强烈建议不要在共享偏好键和存储值键同时使用相同的键值),而是使用在顶部设置的静态变量像这样的班级

I would also recommend, instead of using "SP" (I highly recommend against using the same key values for your shared preference key and your stored value key while I am at it), to use static variables you set in the top of your class as something like

private final static String PREFS_KEY = "shared_prefs";

然后使用变量

getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)...

这有助于本地化.您还应该检查一下Java中的命名约定,以免在事情变得更加复杂时避免头痛.

this helps with localization. You should also check into naming conventions in Java to avoid headaches down the road when things get more complicating.

已更新,可以使用您的代码

// this should be HomePage, not homePage
public class homePage extends Activity {

    private final static String PREFS_KEY = "shared_prefs";
    private final static String MUTE_PRESSED_KEY = "mute_pressed";

    private Button Mute;    // this should be mute, not Mute
    private int Sound = 0;  // this should be sound, not Sound
    private SharedPreferences prefs;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_page);

        Mute = (Button) findViewById(R.id.mute);
        setButtonOnClickListeners();

        prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
        if(prefs.getBoolean(MUTE_PRESSED_KEY, false))
            Sound = 1;
        else
            Sound = 0;
    }

    // I DIDN'T REALLY LOOK AT THIS SO COUNTING ON YOU THAT IT WORKS
    public void sound() {
        final MediaPlayer mp = new MediaPlayer();
        if (Sound == 1) {
            try {
                AssetFileDescriptor afd;
                afd = getAssets().openFd("butpress.mp3");
                mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                        afd.getLength());
                mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (Sound == 0) {
            mp.stop();
        }
    }

    private void setButtonOnClickListeners() {

        Mute.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Sound == 1) {
                    Mute.setBackgroundResource(R.drawable.sound_off);
                    Sound = 0;
                    prefs.edit().putBoolean(MUTE_PRESSED_KEY, false).commit();

                } else if (Sound == 0) {
                    Mute.setBackgroundResource(R.drawable.sound_high);
                    Sound = 1;
                    prefs.edit().putBoolean(MUTE_PRESSED_KEY, true).commit();
                }

            }

        });

    }

}

这篇关于Android:如何让应用程序记住是否已按下静音按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆