javaandroidandroid-intenthandlerhomescreen

Why can't I go to home screen from service


Running project on API KitKat(19) Pixel 2 with target API 30.

I have a service that is running in the foreground, with this handler inside of it that I can confirm is running normally via the println statements I see.

    Handler handler = new Handler(Looper.getMainLooper());
    private Runnable periodicUpdate = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(periodicUpdate, 1000 - SystemClock.elapsedRealtime()%500);
            currentApp = getForegroundApp();
            for (AppObject restrictedApp : allAppsRestricted) {
                System.out.println("restricted app: " + restrictedApp.packageName);
                System.out.println("foreground app: " + currentApp);
                if (currentApp.equals(restrictedApp.packageName)) {
                    showHomeScreen();
                    System.out.println("We're trying to go home");
                }
            }
        }
    };

I can also confirm that the current app and foreground app packages are the same via the "We're trying to go home" println statements I see. Also in my service I have a showHomeScreen() method. The code for the showHomeScreen() method ideally takes the user out of the foreground app that matches the restricted app by showing them the home screen. Here it is:

    public void showHomeScreen(){        
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getContext().startActivity(startMain);
}

Outside of my service I have the App class and the getContext() method my showHomeScreen() is calling:

public class App extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannel();
        App.context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

I've seen the contents of my showHomeScreen() method posted as the top answer for multiple questions on how to take the user to the home screen, however it has not once taken me to the home screen. What am I missing? How do I take the user to the home screen from within my service?


Solution

  • DISCLAIMER: You shouldn't use this permission unless you are providing some kind of administrative or parental control type service to your users. but... You CAN launch your activity via a background service by putting this permission into your manifest: <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    And by directing the user to enable system overlays by rerouting them to settings to enable your app's overlaying activities from your background service: startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION));