简体   繁体   中英

How can I launch the splash screen only when the app is killed or started for the first time ?

I don't know why but the splashscreen always starts. I would like it to start only when the app is killed or runs for the first time.

Here is my code :

public class SplashScreenActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash_screen);

        Thread splashscreen = new Thread() {
            public void run(){
                try{
                    int sp = 0;
                    while(sp < 1000){
                        sleep(100);
                        sp = sp +100;
                    };

                }

                catch (InterruptedException e) {
                    e.printStackTrace();
                }

                finally{
                    finish();
                    startActivity(new Intent(SplashScreenActivity.this, TutoActivity.class));
                }
            }
        };

        splashscreen.start();
    }

Your should start a new activity like bellow (In case user press back button and return to splash page)

Intent intent = new Intent(this, A.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent);
    finish(); // call this to finish the current activity

Reason

Since there can only be one launcher activity for a android application, therefore i don't think that your application is showing splash screen every time you minimize your app, if it is then the app is restarting while you resume it . Reason the app is still restarting instead of resuming is that the device which you are using is not having sufficient ram to hold your application and provide you a smooth multitasking experience .

Solution

You have to install your app in different device which have sufficient amount of ram to run you application . This should prevent your app from restarting even when you are minimizing it .

Hope this helps

I think you've got the answer, but for good practice, never sleep the main thread. you can use this to delay this instead of sleep.

int showSplashFor = 2500;

new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                startActivity(new Intent(SplashScreen.this, MainActivity.class));
                SplashScreen.this.finish();
            }
        }, showSplashFor);

Okay, so the trick is to first call

finish()

and then

startActivity()

on your SplashScreenActivity, so it won't appear until you kill the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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