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);
Related
i had tried this:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
videoview.getCurrentPosition;
}
},0,1000);
but it does not work(it crashes).
it says:
"cant create handler inside thread that has not called looper.prepare" =/
Please , post your answer if you have one , i found this way.
final Handler handler = new Handler();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
handler.post( new Runneable(){
public void run (){
//Your function =D
}
});
}
},0,1000);
My app needs tracking of real time so I need a button that needs to trigger every 5 seconds but I have no idea how to do it. Can you teach me how?
I want that in every 5 seconds that AsyncTask will be triggered.
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postLoc = new HashMap();
postLoc.put("txtLat", tvLat.getText().toString());
postLoc.put("txtLng", tvLong.getText().toString());
postLoc.put("txtOwner", pref.getString("username","").toString());
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
});
I think this code might be useful to trigger the code every 5 second
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//code to run after every 5 seconds
}
});
}
};
}
Create a method like this and call the method on button click and also call the method by using a handler like this:
mRunnable = new Runnable() {
public void run() {
public void toBecalled_Every_5_Second();
mHandler.postDelayed(mRunnable, 5000);
}
};
mHandler.postDelayed(mRunnable, 5000);
public void toBecalled_Every_5_Second(){
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
so it will call the method every 5 second and the a sync task will execute....
I would like to have a CountDownTimer which will trigger the button click function after every 5 seconds.
CountDownTimer mTimer = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
btnStart.performClick();
this.start(); // Restart
}
}.start();
You can use Timer with TimerTask and Handler to update the result to main thread i.e your UI.
Something like this:
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run process
handler.post(new Runnable() {
public void run() {
/**************************/
/** Do your process here **/
/**************************/
}
});
}
};
}
private void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, start run TimerTask then run every 5000ms i.e 5 seconds.
timer.schedule(timerTask, 0, 5000); //
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
Insert your processing code in Handler.post(). Then start the trigger by calling startTimer(). To stop the trigger, just call stopTimerTask().
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
/**
* Send Button click event.
**/
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NetAsync(view);
}
});
}
On click event the "NetAsync(view)" execute and send the gps coordinates to server, but what i want is that instead of using button click event when user start the app "NetAsync(view)" execute automatically after every 10 minutes. Please tell me how to do this as i am new to android programming.
you can do it using TimerTask and Timer class like this
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 {
//your method here
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 600000); //execute in every 10 minutes
Try Something like below:
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
NetAsync(view);
}
});
}};
t.schedule(scanTask, 300, 600000);
}
Using Handler You can easily achieve your goal please follow bellow code,
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!isSyncStart) {
startSyncProcess(true); //write Your Method Here!
}
}
}, 600000);
Use AlarmManager with Broadcast Receiver
private PendingIntent mPingAlarmPendIntent;
private static final String PING_ALARM = "com.sithagi.PING_ALARM";
private Intent mPingAlarmIntent = new Intent(PING_ALARM);
private BroadcastReceiver mPingAlarmReceiver = new PingAlarmReceiver();
mPingAlarmPendIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mPingAlarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Each and every 15 minutes will trigger onReceive of your BroadcastReceiver
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (AlarmManager.INTERVAL_FIFTEEN_MINUTES), AlarmManager.INTERVAL_FIFTEEN_MINUTES, mPingAlarmPendIntent);
// Register the receiver
registerReceiver(mPingAlarmReceiver, new IntentFilter(PING_ALARM));
// To cancel Alarm Service
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).cancel(mPingAlarmPendIntent);
// unregister the receiver onDestroy or if you want stop
unregisterReceiver(mPingAlarmReceiver);
/**
* BroadcastReceiver will trigger
*/
private class PingAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent i) {
// Do your work here
}
}
I am using the following code to execute a method after a specific time period say 9seconds.The code works fine only after the first execution.However i want that when the activity is launched the method must be called after 9 secs.Now what happens is the method is called the moment the activity is launched followed by after 9 seconds again it is called.
Following is my code:
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 9000);
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable()
{
public void run()
{
//Did some UI Operation
Toast.makeText(context, msg, 1000).show();
}
};
You can use this:
private void TimeMethod() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//TODO after 9 sec
}
}, 9000);
}
Hope this will be usefull,
Cheers