Make activity wait for specific time period - android

I have following code snippet in my application activity.
If user is landing on activity for the first time then only thing that will happen is changing the boolean variable shouldSleep to true.
Thereafter, else part will be executed which contains generation of notification at every 60 seconds.
But the main problem is if I execute this code, the activity NEVER gets displayed as it keeps looping in else part and hence go on sleeping.
What I want is remaining application should run normally while every 60 seconds, else part of this method should be executed.I guess it has got something to do with AsyncTask but I don't have much idea about it.
Any idea how to do this? Thanks in advance for your help.
boolean shouldSleep=false;
private void ShowNotification()
{
//DO SOME TASK
if (shouldSleep)
{
Thread.sleep(60000);
//DO SOME TASK
}
else
{
shouldSleep = true;
}
/** Calling the method recursively so that it always runs. */
ShowNotification();
}

Maybe you can use a Timer object :
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//This code is run all 60seconds
myBooleanVar = true;
//If you want to operate UI modifications, you must run ui stuff on UiThread.
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Activity.this.changeUiStuff();
}
});
}
}, 60000);

Just use a Timer. Instead of a thread approach, you could run your task every 60s:
new Timer().schedule(task, delay, period);
with period = 60*1000

Related

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.

ProgressBar running faster after each onclick in android

I am Stuck here with this application in android. In my application i am trying to implement a progressbar which shows timer for certain seconds. When the Button is clicked the timer should refresh and again start from 0 in progressBar. For this I am using Thread.
The Problem is, When I Click the button the Thread calls the timer function and each time the thread is getting faster and faster. I couldn't resolve it and not having any idea what is going in background.
This is my code for Timerfunction
public void setTimer()
{
prog=0;
progress.setProgress(prog);
if(flag){
t= new Thread(new Runnable(){
public void run()
{
while(prog<100)
{
prog+=1;
handle.post(new Runnable(){
public void run()
{
progress.setProgress(prog);
if(prog==progress.getMax()&& flag){
call_fun();
}
}
});
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
Log.i("Error", null);
}
}
}
});
t.start();
}
}
I called this function in another function called RandomGeneration. If the button is clicked the randomgeneration is called and the set timer is activated everytime. But the progressbar is running faster after every click. It is constantly running in the same specific time. For example if it runs for 3 seconds in the first click, its running 2 seconds in the second click and getting faster considerably.
Can anyone please try to find what is happening in this code.
Thanks in advance..!!
From what I see a new Thread is being created everytime you click the button.
Maybe try to check if t is already running and if so update it's logic to set progress to 0?
Also, what does if(flag) do?

Setting Interval For Activiry and Perform Task

Is there any function in Android that can use to make the activity wait for an interval and continue working?
I mean , for example, I use setContentView() to set a layout , and after 3 seconds it will load another layout, and continue to do another job, I don't need to repeat doing same thing after an interval, just continue do another thing.
Thanks in advanced.
You can Use Following Method to Set Interval
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Do your code here
}
}, 3000);
Here, 1000 = 1 Second
But Before running this code make sure that you are not in BACKGROUND PROCESS THREAD...otherwise this may cause an error..
Do it at Android Style:
Handler mHandler = new Handler();
mHandler.postDelayed(runnableHandler, 3000);
private Runnable runnableHandler = new Runnable() {
#Override
public void run() {
doSomething()
}
};
private void doSomething() {
// Before do something remove all callbacks from Handler
mHandler.removeCallbacks(runnableHandler);
andFinallyDoWhatYouNeed();
}

how to stop a running thread with button toggle (android app)

I finally got my app working, i just have one issue which i would like to correct.
I have a button which controls a thread that runs a couple function in the background. The functions in the background eventually stop the thread whenever a certain value is reached. What i am having issues doing is pressing that same button again to just stop the thread manually. Currently I can only start the thread and wait for itself to finish. I am able to do other things in the app, so the thread is running on its own, i just want to kill it manually.
public void onMonitorClick(final View view){
if (isBLEEnabled()) {
if (!isDeviceConnected()) {
// do nothing
} else if (monitorvis == 0) {
showMonitor();
DebugLogger.v(TAG, "show monitor");
//monitorStop = 4;
Kill.runThread(); // I want a function here that would kill the
// thread below, or is there something that
// can be modified in runThread()?
// I did try Thread.Iteruppted() without luck
shutdownExecutor();
} else if (monitorvis == 1) {
hideMonitor();
DebugLogger.v(TAG, "hide monitor");
monitorStop = 0;
runThread(); //The running thread that works great on its own
}
}
else {
showBLEDialog();
}
}
private void runThread() {
new Thread() {
int i;
public void run() {
while (monitorStop != 3) { //This is where the thread stops itself
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
((ProximityService.ProximityBinder) getService()).getRssi();
rssilevel = ((ProximityService.ProximityBinder) getService()).getRssiValue();
mRSSI.setText(String.valueOf(rssilevel) + "dB");
detectRange(rssilevel);
}
});
Thread.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
On first look, you could simply set monitorStop = 3, which would cause the thread to eventually stop after it's timeout completes.
The problem with this, is that I presume if you push the button again or your code modifies monitorStop at some point in the future, then the thead you wanted dead, might stay alive. ie: monitorStop will need to stay equal to three for at least 750ms to assure the thread will comlete it's loop and die.
The correct way to do this would be to create your thread as a new class with it's own monitorStop parameter. When you create the thread, you would keep a reference to it and modify the thread's monitorStop parameter. This way the thread would finish without interruption. If you wanted to create a new thread, then this would not affect the old thread from finishing appropriately.

Repeat task while activity is open

i want to repeat task while the activity is open.
For example repeat foo() every minute while the activity is open.
I tought about Timer, handler and runable.
I tought about this code:
Maybe there is some better way?
public void setRefreshRate()
{
newTimer = true
while(true)
{
if(newTimer)
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(isNetworkAvailable() && movedToAnotherActivity== false)
new GetWorkouts().execute();
newTimer = true;
}
}, Integer.getInteger(data.getWallRefresh()));
newTimer = false;
}
}
There may be a better way but I like AsyncTask so I would probably use that and call sleep() in doInBackground() then you can call cancel() on your task object and set it to null when the Activity finishes.
public void doInBackground(Void...params)
{
boolean flag = false;
while (!flag)
{
// do some work
Thread.sleep(6000);
}
}
then overide and set flag to true in onBackPressed() and finish(). You can then use any of the other AsyncTask methods to update the UI if necessary.
AsyncTask
Thanks to codeMagic's answer for starting me down the right path, but AsyncTask isn't really designed for this. From the docs:
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
The problem is that AsyncTasks, at least by default, run sequentially on the same worker thread, so if you try to launch another AsyncTask, it won't be able to run, since the timer loop never finishes.
To work around this, I just used a raw Thread and it's working fine.
apiUpdateTimerThread = new Thread(new Runnable() {
#Override
public void run() {
while(true) {
try {
Log.i(TAG, "UPDATE FROM THE API!!!!");
doSomeStuff();
Thread.sleep(5 * 1000);
} catch(InterruptedException e) {
Log.e(TAG, "API Update AsyncTask Interrupted", e);
}
}
}
});
To stop it, just call
apiUpdateTimerThread.interrupt();

Categories

Resources