androidandroid-serviceandroid-launcherstart-activity

Launching app through startActivity not working from Service


I'm using a Service (BlockAppsService) that checks which app is in the foreground. When certain apps are in the foreground, I want to launch the home application on the device and show a Toast message to the user. Everything is working fine, the Toast is displayed, but launching the home app is not working.

The relevant code from my 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;
}

Launching, for example, my own MainActivity instead of the home app also doesn't work.

The interesting thing is that when I open the Android settings and I block it through these methods, it is working. It's just that with other apps, it doesn't: I don't get any exceptions, the home app just doesn't launch through startActivity().

Anyone knows what's going on here?

Many thanks!


Solution

  • I think your problem is that you do not have permission to appear on top.

    Try adding this to your main activity, it will open the settings window the user needs to allow you to appear on top

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

    Hopefully this works