2015-05-09 92 views
0

我想做出可以播放背景音乐服务的切换按钮。这是我的代码。如何保存更改切换按钮

public class MainActivity extends Activity { 

private Switch mySwitch; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    } 

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
    } 

     public void playRain(View view) { 
     // Is the toggle on? 
     boolean on = ((Switch) view).isChecked(); 

     if (on) { 
      Intent objIntent = new Intent(this, PlayRain.class); 
      startService(objIntent); 
     } else { 
      Intent objIntent = new Intent(this, PlayRain.class); 
      stopService(objIntent); 
     } 
    } 

} 

当我将开关按钮切换到打开声音播放。但是当我点击主页按钮并重新打开应用程序时,切换按钮将返回关闭状态。如何保存更改切换按钮?以便切换按钮不会自行回到关闭状态。对不起我的英语不好。

回答

0

您可能需要在SharedPreferences中保存切换按钮的状态。 This可能会有所帮助。

我写了一个示例代码。我希望它有帮助

public class MainActivity1 extends Activity { 

private Switch mySwitch; 
SharedPreferences pref; 
Editor edit; 
final String SOUND_PREF_KEY = "background_sound"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mySwitch = (Switch) findViewById(R.id.switch1); 
    pref = getPreferences(MODE_PRIVATE); 
    edit = pref.edit(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 
    mySwitch.setChecked(pref.getBoolean(SOUND_PREF_KEY, false)); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (mySwitch.isChecked()) { 
     edit.putBoolean(SOUND_PREF_KEY, true); 
    } else { 
     edit.putBoolean(SOUND_PREF_KEY, false); 
    } 
    edit.commit(); 

} 

public void playRain(View view) { 
    // Is the toggle on? 
    boolean on = ((Switch) view).isChecked(); 

    if (on) { 
     Intent objIntent = new Intent(this, PlayRain.class); 
     startService(objIntent); 
    } else { 
     Intent objIntent = new Intent(this, PlayRain.class); 
     stopService(objIntent); 
    } 
} 

} 
+0

它的工作原理,谢谢! –