如何通过开关首选项打开和关闭背景音乐?

时间:2014-03-04 10:07:25

标签: android sharedpreferences android-preferences android-music-player

我正在创建一个应用程序,当用户登录时,他可以根据需要设置设置。我有首选项xml(名为settings.xml)。有两个选项1)背景音乐(通过开关首选项打开或关闭)2)选择歌曲(列表首选项).Below是我的主要活动代码: -

public class SettingsActivity extends PreferenceActivity {

MediaPlayer mp;
SharedPreferences pref;
Preference p;
MyProfile myProfile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
     pref = PreferenceManager.getDefaultSharedPreferences(this);
    getFragmentManager().beginTransaction().replace(android.R.id.content,
            new PrefsFragment()).commit();
          PreferenceManager.setDefaultValues(SettingsActivity.this, R.xml.settings, false);

}

@SuppressLint("ValidFragment")
public class PrefsFragment extends PreferenceFragment{

      @Override
      public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       addPreferencesFromResource(R.xml.settings);
      }

      @Override
      public void onResume(){
       super.onResume();
       // Set up a listener whenever a key changes             
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);

        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
            Preference preference = getPreferenceScreen().getPreference(i);
            if (preference instanceof PreferenceGroup) {
              PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
              for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
                updatePrefSummary(preferenceGroup.getPreference(j));
              }
            } else {
              updatePrefSummary(preference);
            }
          }
      }

      @Override
      public void onPause() { 
       super.onPause();
       // Unregister the listener whenever a key changes   
        stopPlay();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);     
      } 

      public void onDestroy() {
          super.onDestroy();
           // Unregister the listener whenever a key changes             
            getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
      };

      OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                String key) {
            // TODO Auto-generated method stub
             updatePrefSummary(findPreference(key));
              String ringTone = sharedPreferences.getString("prefRingtone", "0");
             int num = Integer.parseInt(ringTone);     

                if(num == 0){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.airtel);
                }
                else if(num == 1){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dance);
                }
                else if(num == 2){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dhoom);
                }
                else{
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.guitar);
                }
                mp.setLooping(false);

                if(sharedPreferences.getBoolean("prefMusic", false)){
                        mp.start();

                }
                else {
                        mp.stop();
                    //  mp.release();
                }
        }
        };

      private void updatePrefSummary(Preference p){

          if(p instanceof ListPreference){
              ListPreference listPref = (ListPreference) p; 
                p.setSummary(listPref.getEntry()); 
          }
          else{
              SwitchPreference swPref = (SwitchPreference)p;
              if(pref.getBoolean("prefMusic", true)){
                  swPref.setSwitchTextOn("ON");
                  p.setSummary(swPref.getSwitchTextOn());
              }
              else{
                  swPref.setSwitchTextOff("OFF");
                  p.setSummary(swPref.getSwitchTextOff());
              }
          }
      }

      public void stopPlay(){
/*        if(myProfile.isFinishing()){
                mp.stop();
                //mp.release();
            }*/
            Context context = getApplicationContext();
            ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> taskinfo = am.getRunningTasks(1);
            if(!taskinfo.isEmpty()){
                ComponentName topActivity = taskinfo.get(0).topActivity;
                if(!topActivity.getPackageName().equals(context.getPackageName())){
                    mp.stop();
                    //mp.release();
                }
                else{

                }
            }
            super.onPause();
      }
}
}

我的问题是当我分别打开和关闭它们时,背景音乐无法正常工作。有些时间没有播放,当它开始播放时,它不会停止(我是否选择关闭)。请帮助我摆脱这个。任何帮助都将受到高度赞赏。

感谢。

2 个答案:

答案 0 :(得分:1)

private class BackgroundPlayer {

    private Context ctx;
    private MediaPlayer mediaPlayer;

    public BackgroundPlayer(Context ctx, int res) {
        this.ctx = ctx;
        mediaPlayer = MediaPlayer.create(this.ctx, res);
        mediaPlayer.setLooping(true);
    }

    public void startBackgroundMusic() {
        if(mediaPlayer!=null&&!mediaPlayer.isPlaying()) 
            mediaPlayer.start();            
    }

    public void stopBackgroundMusic() {
        if(mediaPlayer!=null)
            mediaPlayer.pause();
    }

    public void kill() {
        if(mediaPlayer!=null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            ctx = null;
        }
    }

}
创建

backgroundPlayer = new BackgroundPlayer(this, R.raw.filename);

在onPause

backgroundPlayer.stopBackgroundMusic();
onResume中的

if(condition == true) backgroundPlayer.startBackgroundMusic();
在onDestroy中

backgroundPlayer.kill();

答案 1 :(得分:0)

好的,我得到了正常工作的代码: -

public class SettingsActivity extends PreferenceActivity {

MediaPlayer mp;
SharedPreferences pref;
Preference p;
MyProfile myProfile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
     pref = PreferenceManager.getDefaultSharedPreferences(this);
    getFragmentManager().beginTransaction().replace(android.R.id.content,
            new PrefsFragment()).commit();
          PreferenceManager.setDefaultValues(SettingsActivity.this, R.xml.settings, false);

}

@SuppressLint("ValidFragment")
public class PrefsFragment extends PreferenceFragment{

      @Override
      public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       addPreferencesFromResource(R.xml.settings);
      }

      @Override
      public void onResume(){
       super.onResume();
       // Set up a listener whenever a key changes             
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);

        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
            Preference preference = getPreferenceScreen().getPreference(i);
            if (preference instanceof PreferenceGroup) {
              PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
              for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
                updatePrefSummary(preferenceGroup.getPreference(j));
              }
            } else {
              updatePrefSummary(preference);
            }
          }
      }

      @Override
      public void onPause() { 
       super.onPause();
       // Unregister the listener whenever a key changes   
      //  stopPlay();
     //     getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);     
      } 

      public void onDestroy() {
          super.onDestroy();
           // Unregister the listener whenever a key changes 
         // stopPlay();
            getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
      };

      OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                String key) {
            // TODO Auto-generated method stub
             updatePrefSummary(findPreference(key));
             String ringTone = sharedPreferences.getString("prefRingtone", "0");
             int num = Integer.parseInt(ringTone);     
             if(mp!=null){
                 if(mp.isPlaying()){
                     mp.stop();
                 } 
                if(num == 0){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.airtel);
                }
                else if(num == 1){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dance);
                }
                else if(num == 2){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dhoom);
                }
                else{
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.guitar);
                }   
             }  
             else{
                 if(num == 0){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.airtel);
                }
                else if(num == 1){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dance);
                }
                else if(num == 2){
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.dhoom);
                }
                else{
                    mp= MediaPlayer.create(getApplicationContext(), R.raw.guitar);
                }   
             }
            //    mp= MediaPlayer.create(getApplicationContext(), R.raw.airtel);
                mp.setLooping(true);
                Boolean onORoff = sharedPreferences.getBoolean("prefMusic", false); 
                if(onORoff){
                        mp.start();
                }
                else {
                        mp.pause();
                    //  mp.release();
                }
        }
        };

      private void updatePrefSummary(Preference p){

          if(p instanceof ListPreference){
              ListPreference listPref = (ListPreference) p; 
                p.setSummary(listPref.getEntry()); 
          }
          else{
              SwitchPreference swPref = (SwitchPreference)p;
              if(pref.getBoolean("prefMusic", true)){
                  swPref.setSwitchTextOn("ON");
                  p.setSummary(swPref.getSwitchTextOn());
              }
              else{
                  swPref.setSwitchTextOff("OFF");
                  p.setSummary(swPref.getSwitchTextOff());
              }
          }
      }

}
 }