Search code examples
androidandroid-asynctaskandroid-thread

How to check and set network status in TextView every 2 seconds?


I want to set network status in TextView, which I want to repetitively call method and set in background, so I used AsyncTask class with infinite loop

class setNetworkText extends AsyncTask
{

    @Override
    protected Object doInBackground(Object[] params) {
        for(;;)
        {
            if(isNetworkConnected()) //check internet connection and if found it return true
                setOnline();         // it set my TextView text to Online
            else
                setOffline();        // it set my TextView text to Offline

            Thread.sleep(2000);
        }

        return null;
    }
}

but it is not working, it stops my application.


Solution

  • new CountDownTimer(30000, 1000) {
    
         public void onTick(long millisUntilFinished) {
            //check something on time interval here 1 second  
         }
    
         public void onFinish() {
             //when your task done here 3 second is time to end 
         }
      }.start();
    

    explanation
    CountDownTimer(long millisInFuture, long countDownInterval)

    millisInfuture will be how long you want to run the task and countDownInterval is the interval in your case it is 2 seconds