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"); } }
You can use this for Simplest Solution: new Handler(). postDelayed(new Runnable() { @Override public void run() { //Write your code here } }, 5000); //Timer is in ms here.
Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run . This interface is designed to provide a common protocol for objects that wish to execute code while they are active.
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.
Assign millisDelayTime variable with the milliseconds you desire to cause a delay. mActivity is an object of Activity for providing Application Context. In your case millisDelayTime should be initialized with 5000
mActivity.runOnUiThread(new Runnable() { @Override public void run() { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //your code here } }, millisDelayTime); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With