I'm developing an Android 2.2 application.
I have the following Activity:
public class StartActivity extends Activity {
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startpage);
}
@Override
protected void onResume() {
super.onResume();
I开发者_如何学PythonmageView ship = (ImageView)findViewById(R.id.greekShip);
ship.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_right));
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.oceanwave);
}
else {
if (mp.isPlaying())
mp.stop();
mp.reset();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mp.start();
}
@Override
protected void onPause() {
super.onPause();
if (mp != null) {
if (mp.isPlaying())
mp.stop();
}
}
}
If I press home button on my telephone, the sound stops. But if I restart the app, the mediaplayer starts but I can't hear anything.
Do you know where is the problem?
mp.prepare()
is only in the else code. Based on your code, I would release mp when the activity is stopped to free up the resources while not being used, then you can create a new one in onResume()
精彩评论