Israël Mekomou
Israël Mekomou

Reputation: 125

start activity without bringing application to foreground

I'm facing a problem with my android app. In my splashscreen after some verifications the app starts the homeactivity but if the user gets to another app, the homeactivity of my app will still get to the foreground of the device. Is there a way to start the homeactivity without bringing my app to front? I tried this code but it did not work

Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

Upvotes: 3

Views: 277

Answers (1)

Pawel
Pawel

Reputation: 17248

Instead of launching HomeActivity instantly just raise a flag and consume it next time your SplashScreen is in resumed state. For example you can use LiveData to store the flag and observe it:

// inside SplashScreen or its ViewModel if you have one
MutableLiveData<Boolean> isVerifiedLiveData = new MutableLiveData<>();

// inside SplashScreen
@Override
protected void onCreate(Bundle savedInstanceState) {

    /* ...... add this to onCreate .... */

    isVerifiedLiveData.observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean isVerified) {
            if(isVerified){
                Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }
        }
    });
}

Then to trigger activity change simply modify isVerifiedLiveData value:

isVerifiedLiveData.setValue(true);

Upvotes: 1

Related Questions