Android BackgroundServiceStartNotAllowedException 只适用于 API 31 及以上版本。

huangapple go评论80阅读模式
英文:

Android BackgroundServiceStartNotAllowedException only for API 31 above

问题

如何捕获仅在API级别31及以上支持的BackgroundServiceStartNotAllowedException异常。基本上,我的代码如下,我还想支持运行API低于31的设备。

try {
    context.startService(service);
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (BackgroundServiceStartNotAllowedException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

BackgroundServiceStartNotAllowedException

英文:

How to catch BackgroundServiceStartNotAllowedException exception that is supported only after API level 31 above. Basically my code is like this, I also want to support device running API below 31.

try {
    context.startService(service);
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (BackgroundServiceStartNotAllowedException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

BackgroundServiceStartNotAllowedException

答案1

得分: 2

最简单的方法是在 IllegalStateException 中添加对异常类名 BackgroundServiceStartNotAllowedException 的检查。由于 BackgroundServiceStartNotAllowedExceptionIllegalStateException 的子类,异常将会被捕获到这里:

try {
    context.startService(service);
} catch (IllegalStateException e) {
    if (e.getClass().getName().equals("android.app.BackgroundServiceStartNotAllowedException")) {
        // 处理 BackgroundServiceStartNotAllowedException
    }
    e.printStackTrace();
}
英文:

The easiest way would be to simply add a check for the Exception class name in IllegalStateException. As BackgroundServiceStartNotAllowedException is a child class of IllegalStateException the exception will end up there:

try {
    context.startService(service);
} catch (IllegalStateException e) {
    if (e.getClass().getName().equals("android.app.BackgroundServiceStartNotAllowedException") {
        // handle BackgroundServiceStartNotAllowedException
    }
    e.printStackTrace();
}


</details>



huangapple
  • 本文由 发表于 2023年6月15日 16:25:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定