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

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

Android BackgroundServiceStartNotAllowedException only for API 31 above

问题

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

  1. try {
  2. context.startService(service);
  3. } catch (IllegalStateException e) {
  4. e.printStackTrace();
  5. } catch (BackgroundServiceStartNotAllowedException e) {
  6. e.printStackTrace();
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }

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.

  1. try {
  2. context.startService(service);
  3. } catch (IllegalStateException e) {
  4. e.printStackTrace();
  5. } catch (BackgroundServiceStartNotAllowedException e) {
  6. e.printStackTrace();
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }

BackgroundServiceStartNotAllowedException

答案1

得分: 2

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

  1. try {
  2. context.startService(service);
  3. } catch (IllegalStateException e) {
  4. if (e.getClass().getName().equals("android.app.BackgroundServiceStartNotAllowedException")) {
  5. // 处理 BackgroundServiceStartNotAllowedException
  6. }
  7. e.printStackTrace();
  8. }
英文:

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:

  1. try {
  2. context.startService(service);
  3. } catch (IllegalStateException e) {
  4. if (e.getClass().getName().equals("android.app.BackgroundServiceStartNotAllowedException") {
  5. // handle BackgroundServiceStartNotAllowedException
  6. }
  7. e.printStackTrace();
  8. }
  9. </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:

确定