【问题标题】:unable to destroy activity IllegalStateException无法销毁活动 IllegalStateException
【发布时间】:2015-04-02 22:03:21
【问题描述】:

我在 android 中创建了一个媒体播放器,其中 MediaPlayer 位于服务上。 我的主要活动有一个选项菜单,其中包含单个项目“退出”onOptionsItemSelected 调用另一个方法(mp 是服务中的 MediaPlayer 实例)

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

而onDestroy方法很简单

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

但它会抛出

java.lang.RuntimeException:无法销毁活动 java.lang.IllegalStateException

谁能帮帮我?谢谢

【问题讨论】:

  • 你永远不要直接打电话给onDestroy(),这很糟糕
  • IllegalStateException 通常包含更多信息,可以准确地告诉您发生了什么。你的 logcat 的其余部分在说什么?
  • @tyczj mp.stop() 正在停止媒体播放器!为什么不直接调用 onDestroy 呢?如果我从活动中暂停音乐并通过后退按钮退出活动 onDestory() 会毫无例外地被调用,我认为这与硬编码相同

标签: android android-service android-mediaplayer illegalstateexception ondestroy


【解决方案1】:

不要调用 onDestroy() 试试这个:

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

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

finish() 将销毁 Activity。但是你不能确定会调用 onDestroy() !系统可以随时销毁 Activity,例如在内存不足的情况下,不会调用 onDestroy()。

最后一个肯定会被调用的回调是 onPause()。因此,将代码移出 onDestroy() 以确保安全。

【讨论】:

  • 我还需要 onDestroy() 中 exitAll() 的前 3 行,因为我不希望用户按下后退按钮以任何方式停止音乐谢谢我没有想到像内存不足的情况很好的提示
【解决方案2】:

哦,没有这么愚蠢的错误,finish() 它再次自己调用 onDestroy() 所以我不得不简单地将我的代码更改为:

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

    }

【讨论】:

    【解决方案3】:

    这不是完美的做法,但即使这不是一个好的做法,IllegalStateException 也可以避免这种方式。 (使用史蒂夫的上述解决方案)

    因为至少调用了onDestroy()。 (如图所示:Activity lifecycle.

    您的活动在那个时候几乎完成或即将完成。由finish() .

    所以要在没有IllegalStateException 的情况下使用onDestroy() 方法,您必须这样做:

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

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多