Vishal Vishal - 6 months ago 34
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> {
@Override
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();

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


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) { ... }

Answer

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() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                handler.post(new Runnable() {
                    public void run() {
                        try {
                          checkNWConnectivity performBackgroundTask = new checkNWConnectivity();
                          performBackgroundTask.execute();

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

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

    }
Comments