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

烂漫一生 提交于 2019-12-25 04:57:07

问题


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


回答1:


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

    }



回答2:


You want to use a ScheduledExecutorService

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(command, initialDelay, period, unit);

Create the executor OnCreate of your activity, start the execution onResume and stop it onPause.

then you can call runOnUiThread(action); to post actions back to the UI.




回答3:


  1. From your code, it looks like you are trying to show the network state. It is not a good idea to poll for the information. It is better to use a BroadcastReceiver to listen for changes in network state. Check these question: Android - Network State broadcast receiver does not receive intent, Broadcast Intent when network state has changend
  2. If you have to perform periodic operations, you could use a Timer



回答4:


At first you can't work with views from non-UI thread so you can't call TextView.setText from AsyncTask.doInBackground method. You can simply use Handler and submit a message every second using Handler.sendMessageDelayed




回答5:


the way I did this was to put the thread in a Service

the service would do a countdown timer from a very large number, so it would never get to zero, but that was just a use case for my app, you might need something that goes forever

then there is the dilemma of manipulating the UI thread. My loop in the Service would edit a variable in SharedPreferences and my Activity had a loop checked SharedPreferences and would update UI objects if SharedPreferences returned a certain value, problem solved.

You may be able to do something similar with broadcast receivers




回答6:


Use Handler.

    private class MyHandler extends Handler{
        @Override
        public void handleMessage(Message message){

            YourAsyncTask task = new YourAsyncTask(...);
            task.execute();
                    this.sendMessageDelayed(new Message(), 1000);}
}

Then when you want to start just do this

MyHandler handler = new MyHandler();
handler.sendMessageDelayed(new Message(), 1000);


来源:https://stackoverflow.com/questions/12896821/how-to-call-a-section-of-code-every-second-in-background-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!