I developed a simple android application and was able to post and get information from database through http request and doing this with AsyncTask. My question is if i want to poll information from the db every 5 mins or check if any new data has been posted to the db how i could this be done in android?
Use CountDownTimer
check this out
300000ms = 5 min
CountDownTimer chkDb= new CountDownTimer(300000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
//code for db check
chkDb.start();//start again after 5 min
}
}.start();
OR
Use TimerTask
private TimerTask mTimerTask;
private Timer t = new Timer();
public void doTimerTask() {
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
callYourMethodHere();
Log.i("TIMER", "TimerTask run");
}
});
}
};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 1000); //
}
public void stopTask() {
if (mTimerTask != null) {
Log.i("TIMER", "timer canceled");
mTimerTask.cancel();
}
}
task -- This is the task to be scheduled.
delay -- This is the delay in milliseconds before task is to be executed.
period -- This is the time in milliseconds between successive task executions.
I don't think that polling the DB every 5 min is a nice solution. It's a waste of resources.
Instead of that, consider using some mechanism that informs you when something in the DB has change so your UI can refresh properly.
For example, in some projects I have used Otto to send an event when a new item has been inserted in the DB. My fragments subscribe to a default bus so they are aware when something has change.
Pros: Performance. The app only works when it has to
Cons: Well, not much really. The easy solution is to say: "OK, something has change. Let's throw all the current info shown in UI and make a new query to DB!". BUT the nice solution is to say: "OK, something has change. What has change and how can I add that new info to UI?"
But that depends on the app context ;)
Related
I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.
I have this method
public void GetSMS(){
//in this method I read SMS in my app inbox,
//If have new SMS create notification
}
for this I think create timer tick method and every 5 sec call GetSMS()
How can I create a correct method for that ?
Here is an example of Timer and Timer Task. Hope this helps.
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// Do whatever you want
}
});
}
};
timer.schedule(timerTask, 1000); // 1000 = 1 second.
Maybe with a timer and a timertask?
See javadocs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Yet receiving broadcasts is probably a more solid solution.
See: Android - SMS Broadcast receiver
Use Timer.scheduleAtFixedRate() as follow:
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
GetSMS();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 5000, 5000); // every 5 seconds.
I saw it by accident.. This is not the right way to do it..
You don't need to check if there is a sms that received. Android provide broadcast receiver to get notified when sms is income.
Here you go, you have the link here.. Copy paste and it will work great
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87
Hope that this make sense
Although the above timer methods are the correct way to use timers of the sort you are after, I quite like this little hack:
new CountDownTimer(Long.MAX_VALUE, 5000)
{
public void onTick(long millisUntilFinished)
{
// do something every 5 seconds...
}
public void onFinish()
{
// finish off when we're all dead !
}
}.start();
Long.MAX_VALUE has, according the Java docs, a (signed) value of 2^63-1, which is around 292471 millennia ! So starting up one of these countdown timers effectively lasts forever relatively speaking. Of course this depends on your interval time. If you want a timer every 1 second the timer would "only" last 58494 millenia, but we don't need to worry about that in the grander scheme of things.
Is there a way to continuously loop through a countdown timer? I have a basic timer of going though 60 seconds, then updating a text field and it's working, but I want to add the functionality: when it's counted down, to automatically restart again until the user cancels it? Maybe run it through a thread? Not sure how to handle it. Here is what I have, and again, this code works, but I can only stop and start the countdown timer, not do a continuous loop:
cdt = new CountDownTimer(60000,1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText("remaining : " + millisUntilFinished/1000 + " secs");
}
public void onFinish() {
tvTimer.setText("");
bell.start();
}
};
/***************On Click/Touch Listeners*******************/
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tvTimer.setText("");
btnStart.setText("Start Timer");
SetImageView2(myDbHelper);
cdt.cancel();
}
});
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!TimerTicking){
cdt.start();
btnStart.setText("Stop Timer");
}
else {
tvTimer.setText("");
cdt.cancel();
btnStart.setText("Start Timer");
}
}
});
One very basic way to loop a CountDownTimer is to call start() in onFinished().
public void onFinish() {
...
start(); // Start this timer over
}
(Make sure you cancel your CountDownTimer in onPause() when you do this otherwise the timer might leak and keep firing in the background... Oops.)
However CountDownTimers has fundamental flaws (in my opinion): it often skips the last call to onTick() and it gains a few milliseconds each time onTick() is called... :( I re-wrote CountDownTimer in a previous question to be more accurate and call every tick.
The first value to the CountDownTimer() constructor, the total time to run, is a long and can hold a value approaching 300 million years. That ought to be long enough for most mobile applications. :-)
So just call it with cdt = new CountDownTimer(Long.MAX_VALUE, 1000) for a one second loop that will run continously.
I am working on a mini game for Android. I am using this code to create a 3 minute timer that pauses when the game is paused:
class update extends Thread{
#Override
public final void interrupt(){
super.interrupt();
}
#Override
public void run(){
try{
while(true){
sleep(50);
iTime++;
if(iTime>=3600)
bEnd = true; //finish
postInvalidate();
}
}catch(InterruptedException e){
}
}
}
update thread = null;
3600 = 20*3*60
The timer finishes in the emulator within about 5 minutes, and in the Galaxy Tab after about 1.5 minutes.
Why doesn't it always take 3 minutes? How do I ensure that it finishes within 3 minutes?
How about using the Android CountDownTimer class?
// 30 second countdown
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
I am not sure what are you doing in the postInvalidate() but maybe you can do something with AlarmManager and a service. You could create a task that will run in 3 minutes from now, and it will execute the service which, in your case, will invalidate the game.
I've seen many questions that were trying to handle timeouts with sleep method and I believe Android doesn't guaranteed that it will work that way.
Post back if you need help creating the service or running something with AlarmManager. I answered a question about it a couple of days ago.
In my application one option is there which is used to select the application trigger time that is implemented in RadioButtons like : 10 mins, 20Mins, 30mins and 60mins
after selecting one of them the application starts at that time.. up to this working fine.
But, now I want to display a count down clock after selecting one option from above from that time onwords one clock, I want to display
That will useful to user how much time remaining to trigger the application
if any body knows about this please try to help me
Thanks for reading
Something like this for short counts:
public void timerCountDown(final int secondCount){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (secondCount > 0){
//format time and display
counterBox.setText(Integer.toString((secondCount)));
timerCountDown(secondCount - 1);
}else{
//do after time is up
removeCounterViews();
}
}
}, 1000);
}
But this one is even better and it has two events which update the main UI thread: on tick and on finish, where tick's lenght is defined in the second parameter:
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();