Access View from Timer or Handler - android

App crashes, I am unable to use the same view in Timer Class
I need the app to refresh a value and display it
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
find(v);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
10000);
public void find(View view) {
if (btAdapter.isDiscovering()) {
//the button is pressed when it discovers, so cancel the discovery
btAdapter.cancelDiscovery();
} else {
BTArrayAdapter.clear();
btAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}

Usually in this situation you need to use Activity.runOnUiThread()
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
runOnUiThread(new Runnable() {
public void run() {find(v);}
});
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
10000);

Related

Can be use CountDownTimer within a loop?

I want to use CountDownTimer within a for loop but when I am using following code then CountDownTimer is running only once while I want to run it CountDownTimer as per given condition in for loop. it might be a silly question but I will be very thankful to you if I get some help. Thanks in Advance
for (int i=1;i<=10;i++){
Random random = new Random();
totalques.setText(String.valueOf(i) + "/10");
firstnum.setText(String.valueOf(random.nextInt(100)));
secondnum.setText(String.valueOf(random.nextInt(50)));
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(String.valueOf(millisUntilFinished / 1000)
+"s");
}
#Override
public void onFinish() {
}
}.start();
}
You can use the Timer class for doing your job
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//one second elapsed
}
});
}
};
timer.schedule(timerTask, 0, 1000);
The schedule method say start directly and I want to be notified when every 1000 milliseconds elapse.
Don't forget to cancel the timer when you want to stop it with timer.cancel()
Inside the run you can decrement an int and when it reach 0 you can stop the timer

OTP expiration implementation in Android

I have requirement to implement, In my activity, I receive an OTP for login, the OTP has be expired in 90 seconds.
Questions
1> Is Alarm Manager is best way to implement the 90 second time expiry?
2> If I have received OTP and same time I receive a call and when call is ended after 90 seconds and when i come back to original
activity , user should be shown a pop up saying OTP has been expired?
any help will be appreciated.
Thanks
Use CountDownTimer
new CountDownTimer(90000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("seconds remaining: " , millisUntilFinished / 1000);
}
public void onFinish() {
// Called after timer finishes
}
}.start();
You can use TimerTask like below sample :
public class AndroidTimerTaskExample extends Activity {
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
//onResume we start our timer so it can start when the app comes from the background
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000); //
}
public void stoptimertask(View v) {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
//show the toast
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}}
You can change start and stop of Task as per your call and initialise too whenever you want.

Why isn't my text string updating?

So I am trying to display the time passed since pressing a button on my app.
My code is:
/*This will initiate the timer*/
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
start=System.currentTimeMillis();
time=System.currentTimeMillis()-start;
currenttimedisplay.setText(Long.toString(time));
}
});
}
}, 0, 1000);
The app runs but when I press the button it just shows "0.0".
The app doesn't close out. Any help is appreciated!
Please try this:
/*This will initiate the timer*/
timer = new Timer();
start=System.currentTimeMillis();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
time=System.currentTimeMillis()-start;
currenttimedisplay.setText(Long.toString(time));
}
});
}
}, 0, 1000);
In your code, the value of start is changed everytime the timer elapsed (start = System.currentTimeMillis()), so the value of time is always 0 (System.currentTimeMillis() - System.currentTimeMillis() should be 0 if it is called with no, or very small time difference...). So you should set the value of start on button press, then calculate the difference, and update text view in your timer task.

Android repeat action inside other action repeating

Sorry for my English! :)
Ok, I want to repeat something multiple times every second - like here:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
Now, inside it I want to generate random number between 1-3 (including) and do something if it is 3.
So:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Random rand = new Random();
int num = rand.nextInt(3)+1;
if(num==3){
// repeat action here.
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
And inside the if statement, I want to repeat other action (moving ImageView every 5 milliseconds or something like this). How can I do it? Thank you.
You can use either a CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
e.g. create a CountDownTimer for 30secs (30000ms) and notify each second (1000ms)
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//I get called every 1000ms
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
or just a Handler.
http://developer.android.com/reference/android/os/Handler.html
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
//dostuff
handler.postDelayed(this,1000); //repeat after a second
}
});
For animations you should have a look at ObjectAnimator/ViewPropertyAnimation.

I want show the elapsed seconds from 60 to 1

I want to show a text view with elapsed seconds from 60 to 1.
How should I take handler event?
time = GetTime.Showtime();
elapsetime.setText(time + " Secs");
Use a CountDownTimer, http://developer.android.com/reference/android/os/CountDownTimer.html
First of all, you have to create and initialize Timer object:
Timer myTimer;
myTimer = new Timer();
After that you can call use the schedule method to call timerMethod() (or your method). It will the timerMethod() every second (1000 milliseconds).
myTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 1000);
//Runs your doSomething() in the UI Thread
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
// make your doSomething() runnable
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}
i use handler thread runnable.
handler =new Handler();
runnable = new Runnable() {
#Override
public void run() {
elapsetime.setText(time+" Secs");
time--;
if(time<1){
handler.removeCallbacks(runnable);
}else{
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);

Categories

Resources