Using handler wants to run periodically The count is 0, if the countis 1, else Please fix this code.
mRunnable = new Runnable(){
@Override
public void run() {
if (count == 0) {
setImage();
count = 1;
} else {
weather = mContentResolver.getType(mUri);
setWeather(weather);
count = 0;
}
}
};
mHandler = new Handler();
mHandler.postDelayed(mRunnable, 3000);
This example demonstrates how do I run a method every 10 seconds in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
There are at least four ways to run periodic tasks: Handler - Execute a Runnable task on the UIThread after an optional delay. ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool. AlarmManager - Execute any periodic task in the background as a service.
Looper is an abstraction over event loop (infinite loop which drains queue with events) and Handler is an abstraction to put/remove events into/from queue with events (which is drained by Looper) and handle these events when they are processed.
Try the below
m_Handler = new Handler();
mRunnable = new Runnable(){
@Override
public void run() {
if(count == 0){
// do something
count = 1;
}
else if (count==1){
// do something
count = 0;
}
m_Handler.postDelayed(mRunnable, 3000);// move this inside the run method
}
};
mRunnable.run(); // missing
Also check this
Android Thread for a timer
You should go for Timer and TimerTask in that case. Below is a small example:
//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)
//put your code here
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
3000);
Hope this is what you needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With