Submit a web service request every 5 seconds

I want to listen to the sql server database to find out if there are changes in the data in android, so I want to send a request to the web service every 5 seconds to know the new data value. How can i do this? Can you give an example?

+6
source share
4 answers

You can do this with AsyncTask,

public void callAsynchronousTask() { final Handler handler = new Handler(); Timer timer = new Timer(); TimerTask doAsynchronousTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { try { PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask(); // PerformBackgroundTask this class is the class that extends AsynchTask performBackgroundTask.execute(); } catch (Exception e) { // TODO Auto-generated catch block } } }); } }; timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms } 

Read more: How to perform an Async task again at regular intervals

+12
source

Use the Service class and implement a thread scheduler inside the service class that will send a request every 5 seconds. The following is an ecode snippet:

 public class ProcessingService extends Service { private Timer timer = new Timer(); @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { sendRequest(); } }, 0, 5000;//5 Seconds } @Override public void onDestroy() { super.onDestroy(); shutdownService(); } } 
+1
source

Use this code:

  ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // Hit WebService } }, 0, 5, TimeUnit.SECONDS); 
0
source

Polling is usually not a good idea. Because it creates unnecessary load on the server. In your case, 20 requests per minute for each user.

So go for Push Mechanism. So the idea would be this: whenever you receive a push message, you call the web service to get the latest data.

This link will help you: Push, Dont Poll - How to use GCM to update the application

0
source

Source: https://habr.com/ru/post/975877/


All Articles