我正在寻找答案,当usep按下设备上的“返回”或“主页”按钮时,如何关闭MediaPlayer。
当我按回/家或......时出错 按回家时一切正常,但应用程序恢复时出错。 任何人都可以帮助我,我找不到任何有用的代码:(?
这是我的代码:
package com.gwynbleiddesign.dzwiekizwierzat;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class AnimalDescription extends Activity {
ImageView animalImage;
TextView txtNazwa, txtOpisZwierzecia;
int selectedAnimal = 0;
MediaPlayer mPlayer = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animal_description);
Typeface segoeFont=Typeface.createFromAsset(getAssets(),"fonts/segoeprb.ttf");
txtNazwa = (TextView)findViewById(R.id.txtAnimalName);
txtNazwa.setTypeface(segoeFont);
txtOpisZwierzecia = (TextView)findViewById(R.id.txtAnimalDescription);
txtOpisZwierzecia.setTypeface(segoeFont);
animalImage = (ImageView)findViewById(R.id.imgAnimalPhoto);
selectedAnimal = getIntent().getExtras().getInt("selectedAnimal");
txtNazwa.setText(dane.nazwy[selectedAnimal]+"");
animalImage.setImageResource(dane.zdjecia[selectedAnimal]);
mPlayer = MediaPlayer.create(this,dane.dzwieki[selectedAnimal]);
animalImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPlayer.start();
}
});
}
@Override
public void onBackPressed(){
mPlayer.reset();
mPlayer.release();
mPlayer = null;
super.onBackPressed();
}
@Override
public void onPause(){
//mPlayer.reset();
mPlayer.release();
mPlayer = null;
super.onPause();
}
@Override
public void onStop(){
mPlayer.reset();
mPlayer.release();
mPlayer = null;
super.onStop();
}
}
答案 0 :(得分:0)
如果您是第一次运行应用,则会调用onCreate
方法。如果你关闭它并重新打开它(并且JVM没有释放内存),onCreate
不再被调用,所以MediaPlayer
是null
因为onPause
被触发了活动已经结束。
检查Android Activity Lifecycle并初始化MediaPlayer
onResume
请在下次发布Logcat