简体   繁体   中英

Android app crash when call onPause

Hello I am newish to android dev, I am using Eclipse and I have been developing some soundboards. my issue is this:

public class BernardsActivity extends Activity {

    MediaPlayer eileanBeag;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bernards_layout);

        Button eileanBeagButton = (Button) findViewById(R.id.ButtonB1);

        eileanBeagButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                eileanBeag = MediaPlayer.create(getApplicationContext(), R.raw.eilean_beag);
                eileanBeag.start();
            }    
      });  

    ***public void onPause() {
        eileanBeag.release();                   
    }***    
}

the app works fine, all audio is playing well, but when I leave the app using the back button, it tells me that the process has stop unexpectedly and I have to force quit.

the method works fine when I define the MediaPlayer outside of the onCreate method, but I wish to use many sounds and to cut down on loading time I only define it once the button has been pushed.

I have tried using an OnCompleteListener and it does seem to work but then it cuts my sound clip off early.

so any help on this would be very much appreciated.

thanks.

The only thing that looks like a problem is, before calling eileanBeag.release(); you should call eileanBeag.stop(); . You cannot directly release a Player when you are playing. Also you are missing super.onPause();

It should be like this:

public void onPause() {
    super.onPause();
    eileanBeag.pause();
}

protected void onDestroy() {
    super.onDestroy();
    if(eileanBeag != null) {
        eileanBeag.stop();  
        eileanBeag.release();
    }
}

您需要在onPause方法中调用super.onPause()作为第一条语句

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM