50

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");
    }

}
Jishad
  • 2,876
  • 8
  • 33
  • 62

9 Answers9

134

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.

Kartheek
  • 7,104
  • 3
  • 30
  • 44
6

Use a CountDownTimer

// There's a TextView txtCount in Main Activity

final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
    @Override
    public final void onTick(final long millisUntilFinished)
    {
        txtCount.setText("" + (int) (millisUntilFinished * .001f));
    }
    @Override
    public final void onFinish()
    {
        txtCount.setText("GO!");
        finish();
        // Time's up - Start the Login Activity
        final Intent tnt =
            new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(tnt);
    }
}.start();
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
6

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);
  }
});
mushahid
  • 504
  • 5
  • 21
6

Since, Handler is now deprecated so use this code :

 new Handler(Looper.myLooper()).postDelayed(new Runnable() {
     @Override
     public void run() {
         //do what you want 
     }
 }, 5000);
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
vishal pathak
  • 71
  • 1
  • 2
4

Try this, code create CountDownTimer with one tick

timer = new CountDownTimer(5000, 5000)
{
    public void onTick(long millisUntilFinished)
    {
    }

    public void onFinish()
    {
        displayData();
    }
};
timer.start();
bongo
  • 733
  • 4
  • 12
4
long delay = 1000;
long period = 50000;
Timer task = new Timer();
task.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        getDriver(sessionManager.getKEY(), ride_id);
    }
}, delay, period);
Subhrajyoti Sen
  • 1,525
  • 14
  • 18
Fazeel Qureshi
  • 854
  • 9
  • 18
  • not a usable ..did you tried it yourself or just copied pasted here? – satya prakash Mar 15 '18 at 09:28
  • @satyaprakash i have tried it, and it works for me... why you have given negative vote? – Fazeel Qureshi Mar 16 '18 at 11:23
  • Because you can't pass a integer parameter in scheduleAtFixedRate which accepts a TIMEUNIT type of parameter(last parameter as periods). – satya prakash Mar 16 '18 at 11:26
  • @satyaprakash Brother scheduleAtFixedRate() method accept three parameter. 1. task 2. delay 3. period. you can also refer to this link https://www.tutorialspoint.com/java/util/timer_scheduleatfixedrate_delay.htm . delay and period only accepts integer parameter. I don't know where you are finding me wrong. – Fazeel Qureshi Mar 16 '18 at 11:32
  • see this developer site:- https://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html – satya prakash Mar 16 '18 at 11:35
  • @satyaprakash ok my bad, changed the data type. I think it is correct now? – Fazeel Qureshi Mar 16 '18 at 11:39
  • 1
    No it is not it's still in long, "IT ACCEPT TIMEUNIT(enum) TYPE OF PERIOD" – satya prakash Mar 16 '18 at 11:58
4

For kotlin way

Handler().postDelayed({
        //do something
    }, 5000)
lgn
  • 119
  • 4
0

The best option to achieve this is using a Handler:

int TIME = 5000; //5000 ms (5 Seconds)

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

        function(); //call function!

    }
}, TIME);
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

When possible, try to avoid using postDelayed. It is a bad practice, since it can lose the reference to the objects that you want to draw on your screen and cause a NPE. Use a Handler instead. First of all, create a global variable Handler in which you will have to "handle" the logic for your code. Do so by using the function handleMessage.

Handler  handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == 1){
            // your code here
        }
    }
};       

Then, wherever you want to execute it, just call the function:

// 1 is the ID of your process
handler.sendEmptyMessageDelayed(1, 5000);

Please remember that in the onDestroyView method (in a Fragment) or the onDestroy (in an Activity) you will have to call

    handler.removeMessages(1)
franzesz
  • 146
  • 1
  • 7