如何检查后台是否允许 startActivity (Android)?

How to check if startActivity is Allowed in background (Android)?

提问人:SHASHIDHAR MANCHUKONDA 提问时间:9/25/2023 更新时间:9/25/2023 访问量:17

问:

收到通知时,由于 android 中的后台限制,无法启动活动

如何检查我是否允许在没有 try catch 块的情况下通过代码调用 startActivity https://developer.android.com/guide/components/activities/background-starts

Android 开始活动

评论


答:

-1赞 Hezy Ziv 9/25/2023 #1

使用 PackageManager

Intent intent = new Intent(this, YourTargetActivity.class);

// Check if there is at least one activity that can handle the intent packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);

if (!activities.isEmpty()) {
    // There's at least one activity that can handle this intent, so it's safe to start it
    startActivity(intent);
} else {
    // No activity can handle the intent, handle this case as needed (e.g., show an error message)
}