Stopping and restarting timer - android

I'm using a pageslider and timer for it. I wrote a timer method for this pageslider such:
public void setTimerToSlider() {
sliderTimer = new Timer();
sliderHandler = new Handler();
sliderTimerTask = new TimerTask() {
#Override
public void run() {
sliderHandler.post(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem()<images.length-1) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
};
sliderTimer.scheduleAtFixedRate(sliderTimerTask, 0, sliderTimeOut*1000);
}
When user slides it manually, timer goes on. So, for example, if 1 second remains, when user slides, it goes to next in 1 second.
My aim is that when user slides it manually, it resets the remaining time and starts the time out from 0.

Are you asking how to cancel the current timer and start a new one each time there's user input?
You allocated a Handler. Use that for your timing instead of a Timer. Handlers are more useful on Android, e.g. the Activity lifecycle knows what to do with them. They might use less battery power, too.
When a new user input event arrives, call sliderHandler.removeMessages(MSG_PAGESLIDER) to cancel any previous timers, then call sliderHandler.sendEmptyMessageDelayed(MSG_PAGESLIDER, 1000), where:
static final int MSG_PAGESLIDER = 1;
class UpdateHandler extends Handler {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_PAGESLIDER:
// react to the timeout; schedule another message if desired
break;
}
}
}
UpdateHandler sliderHandler = new UpdateHandler();

aaaaaannnnnnnnd your question is? ( not my downvote, btw, but we tend to follow a question-answer format )
=]
Consider referencing the Calendar, it goes down to the millisecond and is not as susceptible to delays f'ing up your game
Calendar calendar = Calendar.getInstance();
http://developer.android.com/reference/java/util/Calendar.html
gl hf

Related

Auto Redirect When User Is Taking Too Long Input In Activity Android

I have a scenario, which when a User Rating, or inputting on a data, then the current Activity will Time it to the setted time.
So, if the User isn't do Anything, or taking the Action to Long, then the current Activity will direct the User into the MainActivity.
In my case, i have a Rating app, which is located in a Public place. I thought that if People wants to Rate BUT not completing the Quiz phase, then i don't want to leave the last Quiz to meet the new People who wants to Rate.
I've tried using these code:
int timeout = 4000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Intent homepage = new Intent(Quiz2.this, MainActivity.class);
startActivity(homepage);
finish();
}
}, timeout);
And these one:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Quiz2.this, MainActivity.class));
}
}, 4000);
It works, but it didn't work as expected, as it apply to ALL of the activities (I mean, after these code works in Current Activity, the Rest of the Activities is Applied and Timed too)
I don't want this. What i want is to Apply these Timer ONLY in Current Activity.
How this can be done?
Appreciate for any help, Regards.
I didn't fully understand what you actually wanna do,
but I'm guessing using CountDownTimer and then starting the other activity when the timer finished should do the trick.
new CountDownTimer(4000, 1000) {
public void onTick(long millisUntilFinished) {
// You could show the user the time left using `millisUntilFinished`
}
public void onFinish() {
// Do something when the timer is finished (start your activity & finish)
}
}.start();

A handler that runs every 5 minutes runs in duplicate

My handler will record the camera screen every 5 minutes
recently, I found handler runs in duplicate.
handler is before record the camera screen, create record file name.
if normal, 15:00:00.mp4 , 15:05:00.mp4, 15:10:00.mp4.
but current my state is 15:00:00.mp4, 15:02:15.mp4, 15:05:00.mp4, 15:07:15.mp4.
It seems that the same handler is duplicated and the 2 are executed.
so, I want if there is a handler already working, delete the old handler, execute new handler.
then, I think solve same handler duplicate problem. is right?
to sum it up,
1. Before doing handler.sendEmptyMessage, Is it possible to check if the same handler is working?.
if 1 is possible, How to delete a running handler and run only the new handler.
current my source.
private RecHandler mHandler = new RecHandler(this);
#Override
public void onCreate(Bundle savedInstanceState) {
...
mHandler.sendEmptyMessage(REQUEST_HANDLE_INIT_RECORD);
}
RecHandler.class
public class RecHandler extends Handler {
private final SoftReference<MainActivity> weak;
public RecHandler(MainActivity act) {
weak = new SoftReference<BlackEyeActivity>(act);
}
#Override
public void handleMessage(Message msg) {
MainActivity act = weak.get();
RecHandler mHandler = new RecHandler(act);
if (act != null) {
switch (msg.what) {
case REQUEST_HANDLE_INIT_RECORD:
initCapturing(); //init camera preview..
mHandler = new RecHandler(act);
mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_START_RECORD, 1000); //after 1 second, start REQUEST_HANDLE_START_RECORD.
this.removeMessages(REQUEST_HANDLE_HOLD_RECORD);
break;
case REQUEST_HANDLE_START_RECORD :
startRecording(); //start Recording.. record file 5 minute.
mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_HOLD_RECORD, 300000); //after 5 minute, start REQUEST_HANDLE_HOLD_RECORD.
this.removeMessages(REQUEST_HANDLE_INIT_RECORD);
break;
case REQUEST_HANDLE_HOLD_RECORD:
stopRecording();
mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_INIT_RECORD, 1000); //after 1 second, start REQUEST_HANDLE_INIT_RECORD.
this.removeMessages(REQUEST_HANDLE_START_RECORD);
break;
so, My handler if always record, repeat INIT(1 seconds) -> START (5 minute) -> HOLD(1 seconds)
if you know how to check if the same handler is working, and how to delete a running handler and run only the new handler. please advice for me.

Android compare to a time to current time continuously

I am making an app which need to compare two date and time continuously.
I just saw some example which just compare once. I think I can use timer to repeat a method but it seem not very efficient. Anyone did this before?
Maybe you can use postDelayed like below.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
compareTime();
}
}, 5000);
replace 5000 with your own interval milliseconds.
It is easy, you can use handler; When the first time to check time send the normal message like this
mHandler.sendMessage(mHandler.obtainMessage(CHECK_TIME);
Afterwards sendDelayedMessage from inside the handler.
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case CHECK_TIME:
// Your compare time code here
// ....
// Send the delayed message to handler to check time again
mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_TIME),
DELAY_CHECK_TIME_INTERVAL);
break;
}
}
}

How can I control a timer in android?

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.

slowing down a user's ability to button mash in Android

I have an activity that runs some ASCII control over a network port to a remote device.
Every single button push on the interface will trigger an AsyncTask to handle the communication, and (finally) works great.
However, if a user starts button mashing like a chimp on crack, the system will crash with way too many calls on the same socket, so I've come up with a little timer function to slow down the reaction to their excitement.
I'm wondering if somebody has come up with a better way to do this?
First off, inside the onCreate:
btn_pwrtoggle = (Button)findViewById(R.id.pwr_btn);
btn_pwrtoggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!buttonMasher){
if(powerstat.equals("OFF")){
String[] commandToSend = {"POWER","ON"}
}else{
String[] commandToSend = {"POWER","OFF"};
}
deviceControl(commandToSend);
}
startButtonMashTimer();
}else{
Log.w("button masher","slow down there, monkey.");
}
}
});
Then, in the actual Activity:
Timer buttonTimer;
TimerTask buttonMonitorThread;
int chimpCrackCounter;
protected void startButtonMashTimer() {
chimpCrackCounter = 0;
buttonTimer = new Timer();
buttonMonitorThread = new TimerTask(){
#Override
public void run(){
buttonMasher = true;
if(chimpCrackCounter == 1){
buttonMasher = false;
buttonTimer.cancel();
}
chimpCrackCounter++;
}
};
buttonTimer.schedule(buttonMonitorThread, 0, 500);
}
It seems to be working just fine, (and may help somebody having the same difficulty) but I'm open to suggestions.
An easy way to prevent a user from pushing a button too often is to save the time when a button was pushed, and then next time compare the last time with the current time and if the difference is too small, ignore the action.
final static long minTimeBetweenClicks = 1000;
long lastTime;
onClick(View v){
if( System.currentTimeMillis() < lastTime + minTimeBetweenClicks ) return;
//Handle the click
lastTime = System.currentTimeMillis();
}
The beauty of this is that it doesn't require any new threads or timers, and your AsyncTasks won't have to know about the buttons.
Disable the Button after a click (setEnabled(false), perhaps in onPreExecute, and enable after the task is done, in onPostExecute.
Also, be sure to pay attention to lifecycle changes. Your AsyncTask may be killed if the Activity is paused, so be sure to check the state in onResume.

Categories

Resources