I have set a counter and when the counter value is zero the button will be disabled. But I want to re-enable it after 3minutes. so, how am I supposed to set a timer for this?
One option is you could use a handler that will run in 3 minutes
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
}
},3_MINUTES_IN_MILIS);
okay. So when you disable the button, you can do this,
button.postDelayed(new Runnable() {
#Override
public void run() {
//enable the button
}
}, 3 * 60 * 1000);
This code should be run from UI/Main thread
When you disable the button, call this code
Handler handler = new Handler();
handler .postDelayed(new Runnable() {
#Override
public void run() {
}
},3 * 60 * 1000);
Let me know if it solved your purpose.
Related
I have a small view (call it "user-object") which overlap the background view (call it map). I can drag the "user-object".
I want the "user-object" automatically move to "mid-point" (screen_width/2, screen_height/2) after some seconds (for instance 4s) if three is no touch/drag.
You can send a delay(3000ms) message at the beging and move "user-object" in the Handler's callback,If "user-object" was touched,remove the message
An example using Handler
Handler mHandler;
public void useHandler() {
mHandler = new Handler();
mHandler.postDelayed(mRunnable, 1000);
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
// Perform this here
"user-object" automatically move to "mid-point" (screen_width/2, screen_height/2)
mHandler.postDelayed(mRunnable, 1000);
}
After a drag/touch event is triggered, again apply handler.postDelayed().
in one of my Activities I want to keep screen on for 2 minutes (e.g.). I know I can keep screen on with:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
but how to do that for an specific duration ?
You have many ways to clear flags after 2 minutes..like you can use timer or thread or handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}, 20000);
in this way you can clear the flags
Take this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// turn screen off function
}
}, 2000);
After 2sec it will turn off the screen. You just have to put the turn off function in it.
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
// start your screen
}
}, 2000); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
I have a TextView. I want to update its text (append a "1") after 1 second of a button click.
public class HaikuDisplay extends Activity {
Method m;
Timer t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
m = HaikuDisplay.class.getMethod("change");
}
//Event handler of the button
public void onRefresh(View view)
{
//To have the reference of this inside the TimerTask
final HaikuDisplay hd = this;
TimerTask task1 = new TimerTask(){
public void run(){
/*
* I tried to update the text here but since this is not the UI thread, it does not allow to do so.
*/
//Calls change() method
m.invoke(hd, (Object[])null);
}
};
t.schedule(task1, 1000);
}
public void change()
{
//Appends a "1" to the TextView
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "1");
}
//Event handler of another button which updates the text directly by appending "2".
//This works fine unless I click the first button.
public void onRefresh1(View view)
{
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "2");
}
}
Consider all Exceptions be handled.
On first click, m.invoke gives InvocationTargetException. But it calls the method change() on successive invokes without any Exceptions(verified by logging). But it does not update the text. Where am I wrong?
Also, I see in the debugger that it creates a new Thread every time I click the button. That is fine. But why isn't it removing the previous Threads though their execution has been completed?
Do something like this
public void onRefresh1(View v) {
// You can have this in a field not to find it every time
final EditText t = (EditText) findViewById(R.id.textView1);
t.postDelayed(new Runnable() {
#Override
public void run() {
t.append("1");
}
}, 1000);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Update UI
}
}, 1000);
implement this on button click
UPDATE:
There are some other answers. dtmilano suggested another solution which is almost same to mine except he is calling the postDelayed method of View class and In my answer I used postDelayed method of handler class.
from the api reference of android the postDelayed method of Handler says
The runnable will be run on the thread to which this handler is
attached.
and the postDelayed method of View says
The runnable will be run on the user interface thread.
This is the only difference between these two solution. in my answer instead of creating new Handler every time you can use any other handler instance. Then the runnable will be run on that thread where that specific handler is declared. And if the postDelayed of EditText is used the the runnable method will be run on the user Interface Thread.
Now the performance issue, both has the same performance (If anybody can prove me wrong with reference I will be happy)
That's looking awful convoluted - have you considered using CountDownTimer instead?
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
// no-op
}
public void onFinish() {
change();
}
}.start();
This should call change (and hence change the text) on the UI thread, avoiding reflection and threading errors.
Hi Use the following code for that. Hope this will help you .
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
1000
);
Have a look of this question also.
display data after every 10 seconds in Android
You can try with this also.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
**EDIT 3**
Try with this once you are need to enable once (i mean if you put your code in yourmethod()== this will get automatically call 1 seconds once.
private Timer timer;
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
yourmethod();
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,100);
I have created a custom control panel for a video player. Now I want to give a effect like default MediaController where the panel becomes visible when the screen is touched and it becomes invisible again after the last touch time. I can use this type of code for that.
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// make the panel invisible
}
});
}
};
I can start the thread when the screen is touched and make it invisible after 60 seconds. But in my case, if the user touches the screen again in between this 60 seconds, the panel should vanish after 60 seconds from the last touch. How to consider this case also?
I would recommend using a combination of Runnables and a Handler. You can do Handler calls using postDelayed() to do something after, say, 60 seconds.
Here's an example:
private Handler mHandler = new Handler();
mHandler.post(showControls); // Call this to show the controls
private Runnable showControls = new Runnable() {
public void run() {
// Code to show controls
mHandler.removeCallbacks(showControls);
mHandler.postDelayed(hideControls, 60000);
}
};
private Runnable hideControls = new Runnable() {
public void run() {
// Code to hide the controls
}
};
Simply delete/cancel current timer.
Btw, you should not do it by Thread, but by posting message to a Handler. Such future timer task doesn't need another thread.
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);
}
}