android onstop方法导致强制关闭
问题描述:
这是我的代码如下。 我在我的应用程序中有一个meidaplayer。如果用户播放音乐,则所有事情都是正确的,但当用户离开活动而不播放音乐时,会导致力量关闭。android onstop方法导致强制关闭
有什么问题?
public class Elementary1Activity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView tx1 = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getAssets(), "font.ttf");
title1.setTypeface(font);
tx1.setTypeface(font);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBarnew2);
startMedia = (ImageButton) findViewById(R.id.playbuttonnew2);
pauseMedia = (ImageButton) findViewById(R.id.pausebuttonnew2);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
pauseMedia.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
startMedia.setVisibility(View.INVISIBLE);
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
pauseMedia.setVisibility(View.INVISIBLE);
startMedia.setVisibility(View.VISIBLE);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
public void onStop() {
super.onStop();
mp.stop();
}
}
答
至于我能读懂你的代码赖特,如果用户离开你的活动,这意味着用户使用后退按钮或做其他事,使应用程序停止,对不对?如果是的话,我认为问题在于,您目前不会初始化您的MediaPlayer。您首先在Button Click上初始化此MediaPlayer,但是在onStop()中停止未初始化的MediaPlayer。初始化中的onCreate(MediaPlayer的):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView tx1 = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getAssets(), "font.ttf");
title1.setTypeface(font);
tx1.setTypeface(font);
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
AudioControl();
}
我haven't测试你的代码,但如果这doesn't工作还存在另一个错误,这是我hadn't搜索。但这绝对是错误的。
什么是关闭力量的例外?我认为你应该检查mp是否为空,并用try/catch块包围你的代码行 – Aerilys