我有简单的imageview应用程序,可以在后台播放音乐。然而,我的问题是当用户将设备侧向转换为横向模式时...第一首音乐(比如a),再次开始播放,首先播放的音乐也随之播放。我知道我对媒体播放器有一些问题,但我不知道它在我的代码中的确切位置...如何阻止这个问题....
Maainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
ImageAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(MyViewPagerListener);
}
private int pos = 0;
@Override
protected void onPause() {
super.onPause();
if(oursong != null){
pos = oursong.getCurrentPosition();
oursong.release();
oursong = null;
}
}
@Override
protected void onResume(){
super.onResume();
/*
* This is the important part, basically since your releasing the song
* in onPause() you are getting rid of its reference, in this case check
* if your song is null then if it is re-create it, else you can reuse the
* the original, but i suspect that calling release() in onPause() allows the
* song to get cleaned up by Java's Garbage Collector.
*/
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(pos); // You will probably want to save an int to restore here
oursong.start();
}
/*
* May want to add two methods here: onSaveInstanceState(Bundle outstate) &
* onRestoreInstanceState(Bundle savedInstanceState) to maintain playback position
* in onResume instead of just restarting the song.
*/
private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {
@Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1){
// adding null checks for safety
if(oursong != null){
oursong.pause();
}
} else if (!oursong.isPlaying()){
// adding null check for safety
if(oursong != null){
oursong.start();
}
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
}
答案 0 :(得分:0)
每次旋转手机并从纵向切换到横向时,活动都会被销毁并重新创建,这意味着再次调用onCreate()。
将此行添加到清单中,告诉android在这种情况下不要破坏您的活动。
android:configChanges="orientation|screenSize"
更多信息HERE