我是 Android 新手,我必须创建MediaPlayer
以播放音频音乐。当开始我的活动歌曲开始播放。但是,当我更改模拟器屏幕上的方向时,MediaPlayer
会重新初始化并开始播放另一个音频。我怎样才能避免它?
这是我的代码:
public class Audio_Activity extends Activity {
MediaPlayer mp = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(isLaunched)
{
setContentView(R.layout.audio);
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
length = settings.getInt("TheOffset", 0);
init();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah);
playMusic();
mp.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer arg0)
{
// TODO Auto-generated method stub
}
});
}
private void playMusic()
{
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
class httpGetAsynchTask extends AsyncTask<String,Integer, Void>
{
protected void onPreExdcute()
{
}
@Override
protected Void doInBackground(String... arg0)
{
// TODO Auto-generated method stub
final SharedPreferences.Editor prefsEdit = prefs.edit();
Log.e("Song is playing", "in Mediya Player ");
mp.setLooping(false);
mp.start();
int millisecond=mp.getDuration();
Log.e("Song is playing", "in Mediya Player " + millisecond);
prefsEdit.putBoolean("mediaplaying", true);
prefsEdit.commit();
//btnChapter.setEnabled(false);
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
btnChapter.setEnabled(false);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Configuration config=getResources().getConfiguration();
if(config.orientation == Configuration.ORIENTATION_PORTRAIT)
{
setContentView(R.layout.audio);
}
else if(config.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(R.layout.audio);
}
}
@Override
public void onPause() {
super.onPause();
SharedPreferences.Editor prefsEdit = prefs.edit();
boolean isPlaying = prefs.getBoolean("mediaplaying", false);
if (isPlaying)
{
mp.pause();
int position = mp.getCurrentPosition();
Log.e("Current ", "Position -> " + position);
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
@Override
protected void onResume() {
super.onResume();
mp.start();
boolean isPlaying = prefs.getBoolean("mediaplaying", false);
if (isPlaying) {
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
// mp.start();
}
}
}
我在 Manifest.xml 文件中做了一些更改。
< android:configChanges="orientation|screenSize|keyboard" >
并创建 layout-land 文件夹。
为什么音乐播放两次?