Search code examples
androidandroid-intentsplash-screenandroid-homebutton

Stop application from going to foreground when an activity is started


So, I have an app with a splash screen that starts another activity once it's done loading. When the user hits the home button while it's loading, the application goes to the background and then comes back to the foreground once that activity is started. Is there any way to stop that from happening?


Solution

  • Two things:

    First, make sure you're tearing down the reference to the location service in onPause. I assume you're using Google's API Client. If you're not, you really should be. So in onPause, make sure you unregister the listeners:

    @Override
    public void onPause()
    {
        // Tear down Google API Client.
        if (googleApiClient != null)
        {
            if (googleApiClient.isConnected())
            {
                // Turn off location polling.
                LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
            }
    
            // Avoid leaks by making sure callbacks get unregistered.
            googleApiClient.unregisterConnectionCallbacks(this);
            googleApiClient.unregisterConnectionFailedListener(this);
            googleApiClient.disconnect();
        }
    }
    

    BUT: I think you're over thinking the solution on this one. Why have two activities? Why not one, and have a "wait state" until you get the location fix? Your wait state could be anything. Or a full screen splash as you say (Use a RelativeLayout and stack the views). When you get the fix, fade out the splash.

    Then stash the location to the savedInstanceState bundle. When your activity's state changes, you'll know to not display the splash again.