0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Abhishek Sahay
  • 141
  • 1
  • 9
  • Can you tell me why you want to check it every 2 secs, because its a heavy task and will drain too much battery. If i can understand your purpose to do so I can help you with another solution. – Pratik Kate May 19 '17 at 07:26
  • Have a look at this: http://stackoverflow.com/questions/6242268/repeat-a-task-with-a-time-delay – tknell May 19 '17 at 07:26
  • I want to set my **TextView** text to show that I am online or not .. and I want to check it in every 2secs bcoz i think it is enough to call check method in 2 sec instead of calling it in every small millisecond.. – Abhishek Sahay May 19 '17 at 07:39

3 Answers3

1

Android will (in most versions) only execute one AsyncTask at a time - so if you keep blocking in doInBackground of one AsyncTask, no other AsyncTasks will run, thus blocking your application.

Take a look at using Handler.postDelayed or using a TimerTask. They are more suited for repeating actions.

tknell
  • 9,007
  • 3
  • 24
  • 28
1

You can not use AsyncTask to do that. You should use Handler to schedule a task periodically.

// Create the Handler
Handler handler = new Handler();

// Define the code block to be executed
private Runnable runnableTask = new Runnable() {
    @Override
    public void run() {
      if(isNetworkConnected())
            setOnline(); 
        else
            setOffline();         
    }
};

// Call on main thread (for example, inside onResume())
@Override
protected void onResume() {
    super.onResume();
    handler.postDelayed(runnableTask, 2000);
}
// Remember to unregister it onPause()
@Override
protected void onPause() {
    super.onPause();
    handler.removeCallbacks(runnableTask);
}
Quang Nguyen
  • 2,600
  • 2
  • 17
  • 24
0
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

Pratik Vyas
  • 644
  • 7
  • 20