package com.Aina.Android;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
/**
* com.Aina.Android
* Pro_SharedPreferences
* @author Aina.huang E-mail: 674023920@qq.com
* @version 创建时间:2010 Jun 18, 2010 5:11:14 PM
* 类说明
*/
public class MIDIPlayer {
private MediaPlayer mMediaPlayer = null;
private Context mContext = null;
public MIDIPlayer(Context context){
this.mContext = context;
}
//播放音乐
public void PlayMusic(){
mMediaPlayer = MediaPlayer.create(mContext, R.raw.start);//装载音乐
mMediaPlayer.setLooping(true);//设置是否循环播放
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.start();
}
//停止并是否音乐
public void FreeMusic(){
if(mMediaPlayer != null){
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
}
package com.Aina.Android;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
public class Test_SharedPreferences extends Activity {
/** Called when the activity is first created. */
private MIDIPlayer mMIDIPlayer = null;
private Boolean mbMusic = false;
private TextView tv = null;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i("TAG-onCreate", "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.TextView);
mMIDIPlayer = new MIDIPlayer(this);
//取得活动的Preferences对象.
SharedPreferences settings = this.getPreferences(Activity.MODE_PRIVATE);
//取得值
mbMusic = settings.getBoolean("bmusic", false);
if(mbMusic){
tv.setText("当前音乐状态:开");
mbMusic = true;
mMIDIPlayer.PlayMusic();//播放
}else{
tv.setText("当前音乐状态:关");
mbMusic = false;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_UP){
tv.setText("当前音乐状态:开");
mbMusic = true;
mMIDIPlayer.PlayMusic();//播放
}else if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
tv.setText("当前音乐状态:关");
mbMusic = false;
mMIDIPlayer.FreeMusic();
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onPause() {
Log.i("TAG-onPause", "onPause()");
//取得活动的Preferences对象.
SharedPreferences uistate = this.getPreferences(Activity.MODE_PRIVATE);
//取得编辑对象
SharedPreferences.Editor e = uistate.edit();
//设置值
e.putBoolean("bmusic", mbMusic);
//提交
e.commit();
if(mbMusic){
mMIDIPlayer.FreeMusic();//停止释放音乐.
}
super.onPause();
}
}