Vishal Vishal - 4 months ago 18x
Android Question

how to call a section of code every second in background in Android

I want call the following portion of code every second??
I have tried the following-
But don't know how to call every second??

How can I keep on calling new checkNWConnectivity().execute("Test"); everysecond and from where to call in my android program???

private class checkNWConnectivity extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... params) {

ConnectivityManager manager = (ConnectivityManager)getSystemService(MainActivity.CONNECTIVITY_SERVICE);

// 3G confirm
Boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

// wifi confirm
Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

tvNWConnectivity.setText(" Connected to 3G");
}else if(isWifi){
tvNWConnectivity.setText(" Connected to wifi");
String text = " No Network Connectivity."+"\n" + " Uploading will be resumed from streamlet "+countStreamletUploaded.toString();

return null;


So my question is how to call it every second?
Actually I want to keep on running the portion of code in doInBackground(String... params) { ... }


You can use TimerTask, Timer and a Handler to do this:

 public void toCallAsynchronous() {

   TimerTask doAsynchronousTask;
   final Handler handler = new Handler();
   Timer timer = new Timer();

   doAsynchronousTask = new TimerTask() {
            public void run() {
                // TODO Auto-generated method stub
       Runnable() {
                    public void run() {
                        try {
                          checkNWConnectivity performBackgroundTask = new checkNWConnectivity();

                           } catch (Exception e) {
                              // TODO Auto-generated catch block

                timer.schedule(doAsynchronousTask, 0,30000); //put the time you want