简体   繁体   中英

3 seconds for pressing the back button

I tried to write an app, in which first user see splashcreen and after 3 seconds he is moved to mainscreen. If user press back button during this 3 seconds, he will stay on splashscreen

I tried few methods of delay ( like stopping the thread or some stupid for loop) but i couldn't do my task ( changing screen after 3 sec and not if back was pressed)

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;

import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity {

    boolean checkerbool=true;// check if its in the 3s loop
    boolean background=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
         Handler handler=new Handler();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                checkerbool=false;
            }
            }, 3000);
      if(background) setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(checkerbool) background=false;

            return true;
        }


        return super.onKeyDown(keyCode, event);
    }
}

But after starting an app it jumps directly into mainscreen Working project will be when user is moved to diffrent screen after 3s and if user press the button back, he will stay at splashscreen

override the onBackPressed method :

@Override
public void onBackPressed() {
    checkerbool = true;
}

Change :

boolean checkerbool=false;

Finally :

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        if(!checkerbool)
            setContentView(R.layout.activity_main);
    }
 }, 3000);

You need to move setContent to the run method, because postDelayed will no block the main thread it just post execute what is inside run after the time you mention(3000).

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