Search code examples
androidbackground-processforeground-service

Run an app in foreground & background (Time sharing)


I'm in need to run an android app in background for sometime (say 5 sec) and then run in foreground for sometime (say again 5 secs). The app should switch between foreground & background. Since I'm new to android, I found a solution that an IntentService can be created to make it run in background and then to make run in foreground, some help docs say I should use Activity to make it bring front.


Solution

  • I wrote a service that will keep receiving values from other devices and based on the values I will trigger actions (like opening cam, locking, setting brightness, etc). To trigger actions I used intents. You could open any application installed in your phone by calling the following function by sending their package names (To get the package names install "Package Name Viewer" from play store).

    public void triggerAction(String packageName) {
        Intent i = null;
    
        PackageManager manager = getPackageManager();
        try {
            i = manager.getLaunchIntentForPackage(packageName);
    
            if (i == null)
                throw new PackageManager.NameNotFoundException();
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(i);
        } catch (PackageManager.NameNotFoundException e) {
            Toast.makeText(getApplicationContext(), "FAILED",
                    Toast.LENGTH_SHORT).show();
        }
    }