简体   繁体   中英

Create a Timer to send HTTP request Periodically - Android

I want to end HTTP request from a Android device to a web server and check a particular data of a database periodically (once a minute). I couldn't implement a timer for this.

Thanks

public class MyActivity extends Activity {
Timer t ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {


            //Your code will be here 

        }
      }, 1000);

   }
}

Try AlarmManager running Service . I wouldn't recommend sending request each minute thou, unless it's happening only when user manually triggered this.

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

doAsynchronousTask = new TimerTask() {

    @Override
    public void run() {

        handler.post(new Runnable() {
            public void run() {
                 if(isOnline){// check net connection
                  //what u want to do....
                }

            }
        });

    }

};

timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s

The most easy method is to loop a Handler:

private Handler iSender = new Handler() { 
    @Override
    public void handleMessage(final Message msg) { 
        //Do your code here
        iSender.sendEmptyMessageDelayed(0, 60*1000);
    }
};

To start the loop call this sentence:

    iSender.sendEmptyMessage(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM