简体   繁体   English

在不将应用程序置于前台的情况下启动活动

[英]start activity without bringing application to foreground

I'm facing a problem with my android app.我的 android 应用程序遇到问题。 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.在经过一些验证后,在我的启动画面中,应用程序启动了 homeactivity,但如果用户进入另一个应用程序,我的应用程序的 homeactivity 仍将进入设备的前台。 Is there a way to start the homeactivity without bringing my app to front?有没有办法在不将我的应用程序放在前面的情况下启动 homeactivity? 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);

Instead of launching HomeActivity instantly just raise a flag and consume it next time your SplashScreen is in resumed state.与其立即启动HomeActivity ,不如在下次启动SplashScreen恢复 state 时升起一个标志并使用它。 For example you can use LiveData to store the flag and observe it:例如,您可以使用LiveData存储标志并观察它:

// 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值:

isVerifiedLiveData.setValue(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM