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?
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
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();
}
}
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);
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
Related
i have to create an android service which needs to get the current G P S coordinates and display a toast through a timer with an interval of every minute. i cant seem to get the coordinates unless i send it manually through the emulator control. i already have a service that runs a timer every minute to display the toast "hello". but i haven't come across any solutions so far.
public static final long NOTIFY_INTERVAL = 60 * 1000; // 60 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(getApplicationContext(), "hello",
Toast.LENGTH_SHORT).show();
}
});
}
Take a look at this:
http://developer.android.com/training/location/retrieve-current.html
It explains how to get the current location on a device.
I have this code where I want to try to send an e-mail report every hour (in the example to every second). If there is no coverage, try again within an hour etc. Somehow I managed to break the timer in sendUnsendedReports(): it fires only once. If I remove the call to sendUnsendedReports() than the timer is working perfectly. Even with the try-catch block around it, the timer only fires once. Please advice.
private void createAndScheduleSendReport() {
delayedSendTimer = new Timer();
delayedSendTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.w("UrenRegistratie", "Try to send e-mail...");
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
Log.w("UrenRegistratie", "Mail scheduler goes to sleep.");
}
}, 0, 1000);
}
It seems that sometimes timer doesn't works well as it should be. The alternative of this is use of Handler instead TimerTask.
You can use it like :
private Handler handler = new Handler();
handler.postDelayed(runnable, 1000);
private Runnable runnable = new Runnable() {
#Override
public void run() {
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
/* and here comes the "trick" */
handler.postDelayed(this, 1000);
}
};
Check out this link for more detail. :)
schedule() can be called in various ways, depending on if you want the task to execute once, or periodically.
To execute the task only once:
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000);
To execute the task every second after 3 s.
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000, 1000);
More example usages can be found in the method headers
public void schedule(TimerTask task, Date when) {
// ...
}
public void schedule(TimerTask task, long delay) {
// ...
}
public void schedule(TimerTask task, long delay, long period) {
// ...
}
public void schedule(TimerTask task, Date when, long period) {
// ...
}
It is clearly that you hit the exception and get out of the Timer run method, thus interrupting the timer restart.
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);
I need to perform some code in regular intervals (connect to a server and pull data from MySQL database every minute). For this purpose I have a Sync class:
public class Sync {
static private Handler handler = new Handler();
Runnable task;
public Sync(Runnable task, long time) {
this.task = task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
}
and in my Activity I have:
public void onCreate(Bundle savedInstanceState) {
...
Sync sync = new Sync(call,60*1000);
...
}
final private Runnable call = new Runnable() {
public void run() {
//This is where my sync code will be, but for testing purposes I only have a Log statement
Log.v("test","this will run every minute");
}
};
I have tried this with a shorter time period for testing, but It only runs once. When it Logs the message for the first time, its also the last. Does anyone see what Im doing erong here? Thanks!
You can do that using the below code,
Hope it helps!
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
try{
//do your code here
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 1000);
}
}
};
//runnable must be execute once
handler.post(runnable);
First you have to declare handler globally
Second you have to use post Delay method again in runnable to trigger it again.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Sync sync = new Sync(call,60*1000);
}
final private Runnable call = new Runnable() {
public void run() {
//This is where my sync code will be, but for testing purposes I only have a Log statement
Log.v("test","this will run every minute");
handler.postDelayed(call,60*1000);
}
};
public final Handler handler = new Handler();
public class Sync {
Runnable task;
public Sync(Runnable task, long time) {
this.task = task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
}
}
handler.postDelayed(task, time); will only execute once, if you want the code to trigger at regular intervals I would suggest a Timer and a TimerTask instead of a Handler and a Runnable.
TimerTasks can be set to run once, every x seconds, or with a fixed period e.g. x seconds - however long it took to run last time.
An alternative way, using ScheduledExecutorService's scheduleAtFixedRate:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepEvery10Seconds() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 10, SECONDS);
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
try{
//Your code
}
catch (Exception e) {
// TODO: handle exception
}
}
}, 0, 10000);
}
I have to display some data after every 10 seconds. Can anyone tell me how to do that?
There is an another way also that you can use to update the UI on specific time interval. Above two options are correct but depends on the situation you can use alternate ways to update the UI on specific time interval.
First declare one global varialbe for Handler to update the UI control from Thread, like below
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Probably the simplest thing to do is this:
while(needToDisplayData)
{
displayData(); // display the data
Thread.sleep(10000); // sleep for 10 seconds
}
Alternately you can use a Timer:
int delay = 1000; // delay for 1 sec.
int period = 10000; // repeat every 10 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
displayData(); // display the data
}
}, delay, period);
Andrahu was on the right track with defining a handler. If you have a handler that calls your update functions you can simply delay the message sent to the handler for 10 seconds.
In this way you don't need to start your own thread or something like that that will lead to strange errors, debugging and maintenance problems.
Just call:
Handler myHandler = new MyUpdateHandler(GUI to refresh); <- You need to define a own handler that simply calls a update function on your gui.
myHandler.sendMessageDelayed(message, 10000);
Now your handleMessage function will be called after 10 seconds. You could just send another message in your update function causing the whole cycle to run over and over
There is Also Another way by Using Handler
final int intervalTime = 10000; // 10 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Display Data here
}
}, intervalTime);
There is a Simple way to display some data after every 10 seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
ActionStartsHere();
}
public void ActionStartsHere() {
againStartGPSAndSendFile();
}
public void againStartGPSAndSendFile() {
new CountDownTimer(11000,10000) {
#Override
public void onTick(long millisUntilFinished) {
// Display Data by Every Ten Second
}
#Override
public void onFinish() {
ActionStartsHere();
}
}.start();
}
Every 10 seconds automatically refreshed your app screen or activity refreshed
create inside onCreate() method i tried this code will work for me
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
//CALL ANY METHOD OR ANY URL OR FUNCTION or any view
}
});
}
} catch (InterruptedException e) {
}
}
};t.start();