سؤال

I have created a media player in android where the MediaPlayer is on a service. my main activity has an option menu with single item "exit" onOptionsItemSelected calls another method (mp is and instance of MediaPlayer in service)

private void exitPlayer() {
        PlayerService.mp.stop();
        onDestroy();
    }

and onDestroy method is simple

protected void onDestroy() {
        super.onDestroy();
        if (!PlayerService.mp.isPlaying()) {
            stopService(playerService);
            cancelNotification();
            finish();
        }   
    }

but it throws

java.lang.RuntimeException: Unable to destroy activity java.lang.IllegalStateException

can any one help me? thanks

هل كانت مفيدة؟

المحلول 2

oh no such a silly mistake , finish() it self calls onDestroy() again so I had to simple change my code to :

private void exitPlayer() {
        if(PlayerService.mp.isPlaying())
        PlayerService.mp.stop();
        finish();
    }
protected void onDestroy() {
        super.onDestroy();
        if (!PlayerService.mp.isPlaying()) {
            stopService(playerService);
            cancelNotification();
        }

    }

نصائح أخرى

Instead of calling onDestroy() try this:

private void exitPlayer() {
     PlayerService.mp.stop();
     exitAll();
}

private void exitAll() {
    if (!PlayerService.mp.isPlaying()) {
        stopService(playerService);
        cancelNotification();
        finish();
}

The finish() will destroy the Activity. But you can't be sure that onDestroy() will be called! The system can destroy an Activity at any time like on low memory situations and onDestroy() will not be called.

The last callback which surely will be called is onPause(). So, move your code out of onDestroy() to be safe.

This is not the perfect way to do but even if it's not a good practice the IllegalStateException could be avoid this way. (Use solution above from Steve)

Because onDestroy() is called at least. (as shown on this image : Activity lifecycle.)

your activity is almost finished at that time or being finished. by finish() .

So to use onDestroy() method without IllegalStateException, you will have to do so :

protected void onDestroy() {
    if (!PlayerService.mp.isPlaying()) {
        stopService(playerService);
        cancelNotification();
        //finish();
    } 
    super.onDestroy();  
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top