【问题标题】:Launching app through startActivity not working from Service通过 startActivity 启动应用程序在服务中不起作用
【发布时间】:2021-04-16 09:10:04
【问题描述】:

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

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

有趣的是,当我打开 Android 设置并通过这些方法阻止它时,它正在工作。只是其他应用程序没有:我没有遇到任何异常,家庭应用程序只是无法通过startActivity() 启动。

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

非常感谢!

【问题讨论】:

    标签: android android-service android-launcher start-activity


    【解决方案1】:

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

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

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

    希望这可行

    【讨论】:

    • 经过测试,确实有效。我现在所处的泡菜是我想在没有授予覆盖权限时这样做;)。但这是另一个 SO 问题,非常感谢您的帮助!
    猜你喜欢
    • 2012-06-04
    • 2021-07-16
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多