My code is intended to update the hint of an EditText with the time, allowing the user to enter a different time as the text or use the hint if the user has not entered anything like so:
mTicker = new Runnable()
{
public void run()
{
time.setHint(new TimeDate().getTime());
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
spaceTimeHandler.postAtTime(mTicker, next);
}
This code runs except that the EditText remains blank; if you exchange setHint with setText then everything works fine. Is this a bug?
I realize I should probably use the DateTimePicker or whatever but I haven't gotten around to that yet, and this issue would occur regardless of what string I try to setHint with.
mTicker = new Runnable()
{
public void run()
{
runOnUiThread(new Runnable(){
#Override
public void run() {
time.setHint(new TimeDate().getTime());
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
spaceTimeHandler.postAtTime(mTicker, next);
}
});
}
}
Enclose it in a runOnUiThread, let me know if it worked.
Related
I am pretty new on programing, and I am having a hard time trying to figure out how to make a random countdowntimer. This random countdowntimer was supposed to execute an object after the time (between 3-10 sec) has reached zero.And I really donĀ“t know how to do that. Could someone please give me some examples on how I maybe could solve this problem.
Thanks!
countDownTimer = new CountDownTimer(random value, tick value) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}
};
you can put random value as a value 3-10 its means onFinish called after this time
to create random value use code below
Random r = new Random();
int randomInt = r.nextInt(10 - 3) + 3;
int time = new Random().nextInt(8) + 3;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// execute yor code
}
},time * 1000);
Use this. Hope help you.
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.
EDIT: Code works now. I ended up calling loadingIllusionLoader() from within createDialog()...
I am trying to get a 'fake' progress bar to show up once a user presses a button. I want the progress bar to appear for some random time ~ 2000ms and then have a Dialog box appear as well as hiding the progress bar (because it 'loaded').
I was told to try and use handler since Thread.sleep locks up the UI, which I dont want to really do. However, once I execute the code below, it runs the handler's postDelayed function and a new Dialog box appears every moment or so... the handeler is executing itself over and over again. How do I STOP the handler. the removeCallbacksAndMessages function on the handler was an option, but Im not sure how to exactly STOP the Dialog boxes from opening.
public void loadingIllusionLoader()
{
ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
theCircleLoader.setVisibility(View.VISIBLE);
int timeToRest = (int) (Math.random() * 1000) + 1500;
final Handler newHandle = new Handler();
newHandle.postDelayed(new Runnable() {
#Override
public void run() {
createDialog();
hidingIllusionLoader();
newHandle.removeCallbacksAndMessages(null);
}
}, timeToRest);
}
public void hidingIllusionLoader()
{
ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
theCircleLoader.setVisibility(View.INVISIBLE);
}
I think you'd rather want to use a CountDownTimer:
CountDownTimer timer = new CountDownTimer( 10000, 1000 ) {
#Override public void onTick( long millisUntilFinished ) {
theCircleLoader.setProgress( theCircleLoader.getProgress() - 1 );
}
#Override public void onFinish() {
theCircleLoader.setVisibility(View.INVISIBLE);
}
};
EDIT: almost forgotten:
timer.start();
EDIT2:
after looking at your code, I suggest you modify it so:
Random rnd = new Random();
int progressBarMax = rnd.nextInt( 10 ) + 1; // 10 - change it the way you like
int timeToRest = progressBarMax * 500;
theBarLoader.setMax( progressBarMax );
theBarLoader.setProgress( 0 );
CountDownTimer theTimer = new CountDownTimer(timeToRest, 500)
{
#Override public void onTick( long millisUntilFinished ) {
theBarLoader.setProgress( theCircleLoader.getProgress() + 1 );
}
#Override public void onFinish() {
theCircleLoader.setVisibility(View.INVISIBLE);
// theBarLoader.setVisibility(View.INVISIBLE);
createDialog();
}
};
theTimer.start();
Im working on a Quiz App. in which I have a different types of quizzes. Quiz with Time and Quiz without Time. Quiz without time is simple and there is no certain or specific time given to attempt the quiz. But the Quiz with Time is time restricted Quiz.
What I Want:
When an individual try to attempt a time restricted quiz. The certain amount of time will be show on an activity for instance remaining time (30 min left). and after the 30th min the activity automatically stop. I have tried timer class but that is used for delay.
how can I stop a activity after a certain time?
Thanks in Advance
public void countDown() {
new CountDownTimer(60000*30, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60 ;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
String my_new_str =((((((((( (pad(hours)+":"+pad(minutes)+":"+pad(seconds)));
timer.setText( my_new_str);
float pvalue = ( float)(millisUntilFinished*100)/(60000*30);
myprogressbar.setProgress((int)(Math.round(pvalue)));
}
public void onFinish() {
timer.setText("Completed");
goToResult();
this,finish();
}
}.start();
}
you can do this using Handlers
try some thing like this...
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
finish();
}
};
handler.postDelayed(x, 6000);
Put your question in Thread...
Thread t=new Thread()
{
public void run()
{
try{
sleep(30000);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(Splash.this, Login.class);
startActivity(intent);
finish();
}
}
};
t.start();
Try to use AsyncTask or Handler in your Activity. i think you set some certain time limits for the
Quiz Question so please make sure to use any one of this above i mentioned.
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
finish();// activity will kill. or use
System.Exit();
}
};
handler.postDelayed(x, yourtimelimit(in timemills or millisecond));
Even you doesn't work yet means try to use onComplete listener and the put it finish in that method or
use onDestroy method inside to finish().
thank you
I've made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make the activity Runnable and put this in run():
int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
Thread.sleep(1000);
position = MPService.getSongPosition();
} catch (InterruptedException e) {
return;
}
// ... convert position to formatted minutes:seconds string ...
currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?
new code:
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
public void run() {
final int start = startTime;
int millis = appService.getSongPosition() - start;
int seconds = (int) ((millis / 1000) % 60);
int minutes = (int) ((millis / 1000) / 60);
Log.d("seconds",Integer.toString(seconds)); // no problem here
if (seconds < 10) {
// this is hit, yet the text never changes from the original value of 0:00
currentTime.setText(String.format("%d:0%d",minutes,seconds));
} else {
currentTime.setText(String.format("%d:%d",minutes,seconds));
}
timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
}
};
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService();
// start playing the song, etc.
if (startTime == 0) {
startTime = appService.getSongPosition();
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime,1000);
}
}
what about this:
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
//your code
}
}, delay, period);
Use a Timer for this (instead of a while loop with a Thread.Sleep in it). See this article for an example of how to use a timer to update a UI element periodically:
Updating the UI from a timer
Edit: updated way-back link, thanks to Arialdo: http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html
Edit 2: non way-back link, thanks to gatoatigrado: http://android-developers.blogspot.com/2007/11/stitch-in-time.html
You have to use a handler to handle the interaction with the GUI. Specifically a thread cannot touch ANYTHING on the main thread. You do something in a thread and if you NEED something to be changed in your main thread, then you call a handler and do it there.
Specifically it would look something like this:
Thread t = new Thread(new Runnable(){
... do stuff here
Handler.postMessage();
}
Then somewhere else in your code, you do
Handler h = new Handler(){
something something...
modify ui element here
}
Idea its like this, thread does something, notifies the handler, the handler then takes this message and does something like update a textview on the UI thread.
This is one more Timer example and I'm using this code in my project.
https://stackoverflow.com/a/18028882/1265456
I think the below blog article clearly gives a very nice solution. Especially, if you are a background service and want to regularly update your UI from this service using a timer-like functionality.
It really helped me, much more than the 2007 blog link posted by MusiGenesis above.
https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/