Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - Execute function after 5 seconds in Android

I am new in android development and now my launcher activity show only 5 seconds and after that I want to check the user is logged in or not function and perform the actions.

here is my code.

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

    exactPreferences = getSharedPreferences("ExactPreference",MODE_PRIVATE);
    setContentView(R.layout.activity_landing_page);

    session = exactPreferences.getString(Model.getSingleton().SHARED_SESSION_ID,null);
    Log.i("Session Id",session);
        displayData(); // I want to perform this function after 5 seconds.
}


private void displayData() {
    if(session.equals("")){
        Intent loginIntent = new Intent(LandingPage.this,
                LoginActivity.class);
        startActivity(loginIntent);
        Log.i("User Logged In", "False");
    }
    else
    {
        Intent objIntent = new Intent(LandingPage.this,
                IndexPageActivity.class);
        startActivity(objIntent);
        Log.i("User Logged In", "True");
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          displayData();
        }
    }, 5000);

Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...