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

Android 通过startActivity启动应用程序无法从服务启动,android,android-service,android-launcher,start-activity,Android,Android Service,Android Launcher,Start Activity,我正在使用一个服务(BlockAppsService)来检查前台的应用程序。当某些应用程序位于前台时,我想在设备上启动家庭应用程序,并向用户显示祝酒词。一切正常,祝酒词也会显示出来,但启动home应用程序不起作用 myBlockAppsService类中的相关代码: private boolean blockApp(AppCacheInfo appInfo, String packageInForeground) { String toastMessage = appInfo == nu

我正在使用一个服务(
BlockAppsService
)来检查前台的应用程序。当某些应用程序位于前台时,我想在设备上启动家庭应用程序,并向用户显示祝酒词。一切正常,祝酒词也会显示出来,但启动home应用程序不起作用

my
BlockAppsService
类中的相关代码:

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而不是home应用程序也不起作用

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

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


非常感谢

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

尝试将此添加到主活动中,它将打开用户需要的设置窗口,以允许您显示在顶部

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);
    }
}

希望这能通过测试,而且确实有效。我现在遇到的麻烦是,我想在没有授予覆盖权限的情况下执行此操作;)。但这是另一个问题,非常感谢你的帮助!