英文:
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();
}
答案1
得分: 2
最简单的方法是在 IllegalStateException
中添加对异常类名 BackgroundServiceStartNotAllowedException
的检查。由于 BackgroundServiceStartNotAllowedException
是 IllegalStateException
的子类,异常将会被捕获到这里:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论