8

I want to listen sql server database for know whether there are changes of data in android so I want to send request to web service every 5 second to know of new data value.How can I do this? Can you give a example about it?

Rıdvan
  • 248
  • 1
  • 3
  • 9

4 Answers4

20

You can do it 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
}

More: How to execute Async task repeatedly after fixed time intervals

Community
  • 1
  • 1
sjain
  • 23,126
  • 28
  • 107
  • 185
1

Use Service class and within the service class implement thread scheduler that will send request every 5 seconds. Below is th 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();

}

}
ngrashia
  • 9,869
  • 5
  • 43
  • 58
0

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);
Nadeem Iqbal
  • 2,357
  • 1
  • 28
  • 43
-1

Polling is generally not a good idea. Because it creates unnecessary load in server. In your case, 20 requests per minute per user.

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

This link will help you : Push, Don’t Poll – How to Use GCM to Update App

Dipin
  • 1,085
  • 6
  • 19
  • you are right,it doesn't efficiently for server. I used GCM api it is better than polling but when I use GCM I have to enter input for the push.I want to listen database and if some data value changed I need to get new value. How can I do this? Do you have a idea? – Rıdvan Sep 26 '14 at 13:46