How to cancel a handler before time in Android code? - android

I create 1 minute delayed timer to shutdown service if it's not completed. Looks like this:
private Handler timeoutHandler = new Handler();
inside onCreate()
timeoutHandler.postDelayed(new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
}, 60 * 1000);
If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.

You can't really do it with an anonymous Runnable. How about saving the Runnable to a named variable?
Runnable finalizer = new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
};
timeoutHandler.postDelayed(finalizer, 60 * 1000);
...
// Cancel the runnable
timeoutHandler.removeCallbacks(finalizer);

If you don't want to keep a reference of the runnable, you could simply call:
timeoutHandler.removeCallbacksAndMessages(null);
The official documentation says:
... If token is null, all callbacks and messages will be removed.

You might want to replace use of postDelayed with use of sendMessageDelayed like so:
private Handler timeoutHandler = new Handler(){
#Override
public void handleMessage(Message msg)
{
switch (msg.what){
case 1:
((Runnable)msg.obj).run();
break;
}
}
};
Then post a Message:
Message m = Message.obtain();
m.what = 1;
m.obj = new Runnable(){
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
};
timeoutHandler.sendMessageDelayed(m, 60 * 1000);
and then cancel:
timeoutHandler.removeMessages(1);
No tracking of the runnable necessary.

If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.
Use Handler.removeCallbacks(yourRunnable).

Related

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;
}
}
}

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();
}

What code do i implement to have a time limit in my game

I'm createing a quiz that has a time limit and i dont know what to implement to have a timelimit in my level 1 class. what should i implement? can you show me a complete code?
am i correct?
private Runnable task = new Runnable() {
public void run() {
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
};
private void onCreate() {
Handler handler = new Handler();
handler.postDelayed(task, 60000);
There are different ways to do it. One way is to use a Runnable and a Handler.
First, define the Runnable:
private Runnable task = new Runnable() {
public void run() {
Log.i(TAG, "Time limit reached!");
// Execute code here
}
};
Then you call it (say at the start of the level, onCreate) with this Handler and postDelayed
Handler handler = new Handler();
handler.postDelayed(task, 60000);
The code within the run() method of the Runnable will execute 60 seconds after you call postDelayed
If you need regular notifications you can also use a CountDownTimer

How to run an async task for every x mins in android?

how to run the async task at specific time? (I want to run it every 2 mins)
I tried using post delayed but it's not working?
tvData.postDelayed(new Runnable(){
#Override
public void run() {
readWebpage();
}}, 100);
In the above code readwebpage is function which calls the async task for me..
Right now below is the method which I am using
public void onCreate(Bundle savedInstanceState) {
readwebapage();
}
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute("http://www.google.com");
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response1 = "";
response1=read();
//read is my another function which does the real work
response1=read();
super.onPostExecute(response1);
return response1;
}
protected void onPostExecute(String result) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tvData = (TextView) findViewById(R.id.TextView01);
tvData.setText(result);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
This is what I my code is and it works perfectly fine but the big problem I drains my battery?
You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:
private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable()
{
#Override
public void run() {
doSomething();
mHandler.postDelayed(mHandlerTask, INTERVAL);
}
};
void startRepeatingTask()
{
mHandlerTask.run();
}
void stopRepeatingTask()
{
mHandler.removeCallbacks(mHandlerTask);
}
Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.
Use Handler and PostDelayed:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
readWebpage();
handler.postDelayed(this, 120000); //now is every 2 minutes
}
}, 120000); //Every 120000 ms (2 minutes)
you can use TimerTask instead of AsyncTask.
ex:
Timer myTimer = new Timer("MyTimer", true);
myTimer.scheduleAtFixedRate(new MyTask(), ASAP, TWO_MINUTES);
private class MyTask extends TimerTask {
public void run(){
readWebPage();
}
}
When phone goes to sleep mode, to save battery, and it is quite possible to happen within 2 mins interval, Handler.postDelayed() may miss scheduled time. For such activities you should use AlarmManager, get a lock with PowerManager to prevent going to sleep back while you're running the AsyncTask.
See my post with code sample here
Also you may want to read Scheduling Repeating Alarms
I suggest to go with Handler#postDelayed(Runnable). Keep in mind that this method will work only when your app is running (may be in background) but if user closes it manually or simply Android runs out of memory it'll stop working and won't be restarted again later - for that you need to use services.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2 * 60 * 1000); // every 2 minutes
/* your code here */
}
}, 2 * 60 * 1000); // first run after 2 minutes
This code will wait 2 minutes, execute your code, and then keep doing that every 2 minutes. But if you want it to run instantly for the first time - and then start the wait-do loop, instead use:
final Handler handler = new Handler();
/* your code here */
new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2 * 60 * 1000); // every 2 minutes
/* and also here - your code */
}
}.run();
or, if your code is longer than just one method (readWebsite() in this case), and you don't want that to be duplicated:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2 * 60 * 1000); // every 2 minutes
/* your longer code here */
}
}, 0); // first run instantly
(^ this one is just like the first example but has a 0ms delay before first run instead of 2 minutes)
(This answer is based on #Devashish Mamgain's one but I added too much details for an edit so I had to add a new one)
Try extending the Thread class, set a sleep time of 2000 millis and place your call into the run method. That should do it.
Execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue. This will help you to perform async task in android...
HandlerThread hThread = new HandlerThread("HandlerThread");
hThread.start();
Handler handler = new Handler(hThread.getLooper());
final Handler handler1 = new Handler(hThread.getLooper());
final long oneMinuteMs = 60 * 1000;
Runnable eachMinute = new Runnable() {
#Override
public void run() {
Log.d(TAG, "Each minute task executing");
handler1.postDelayed(this, oneMinuteMs);
sendPostRequest();
}
};
// sendPostRequest();
// Schedule the first execution
handler1.postDelayed(eachMinute, oneMinuteMs);
You can use Time with Handler and TimerTask
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask backtask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
//To task in this. Can do network operation Also
Log.d("check","Check Run" );
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(backtask , 0, 20000); //execute in every 20000 ms*/
You can check logcat to verify whether is running or not using 'check' tag name
You could run a loop within the AsyncTask that sleeps for two seconds between doing the tasks. Something like this:
protected Result doInBackground (Params... params) {
while (!interrupted) {
doWork();
Thread.sleep(2000);
}
}

stop player once time reached

Hi
In my android application i am using videoview.
I would like to start a timer and stop the player after 30 minutes.
I tried using the below code but the alert is displaying before the time is reached.
public final void timerAlert() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mVideoView.pause();
Alerts.ShowAlert("Cannot play",
"Subscribed time has been completed", context);
}
}, realtime);
Where realtime is the time after which i want the dialogue to be executed.
And am calling this in onprepared listener of player.
Please let me know if i require to change anything.
Please forward your valuable suggestions.
Thanks in advance :)
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
Log.d(tag, "Handling msg.");
// YOUR CODE GOES HERE..
// DISPLAY DIALOG..
msg.what = 2;
}
};
};
// USE HANDLER
mHandler.sendEmptyMessageDelayed(1, 30 * 60 * 1000); // 30 Minutes = 30 * 60 * 1000
First you create handler , processe Message : apply your logic here..
use handler to send delayed message after 30Minutes. ( See Comment)
Thanks :)

Categories

Resources