通过 startActivity 启动应用程序无法从服务运行

Launching app through startActivity not working from Service

我正在使用一项服务 (BlockAppsService) 检查哪个应用程序在前台。当某些应用程序位于前台时,我想在设备上启动家庭应用程序并向用户显示 Toast 消息。一切正常,显示 Toast,但无法启动家庭应用程序。

我的相关代码BlockAppsService class:

private boolean blockApp(AppCacheInfo appInfo, String packageInForeground) {
    String toastMessage = appInfo == null ? getString(R.string.this_app) : appInfo.getLabel() + " "
                + getString(R.string.toast_error_distracting_app);
    postToastOnMainThread(toastMessage);
    launchHome();
}

private void postToastOnMainThread(String toastMessage) {
    // Post the toast on the UI thread.
    getMainHandler().post(() -> {
        Utils.showToast(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT);
    });
}

private void launchHome() {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}

private Handler getMainHandler() {
    if (mainHandler == null) {
        mainHandler = new Handler(getMainLooper());
    }
    return mainHandler;
}

例如,启动我自己的 MainActivity 而不是家庭应用程序也不起作用。

有趣的是,当我打开 Android 设置并通过这些方法阻止它时,它 工作。只是对于其他应用程序,它不会:我没有得到任何例外,家庭应用程序不会通过 startActivity().

启动

有人知道这里发生了什么吗?

非常感谢!

我认为你的问题是你没有出现在顶部的权限。

尝试将此添加到您的主 activity,它将打开设置 window 用户需要允许您出现在顶部

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, 1);
    }
}

希望这能奏效