Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handler, I want to run periodically

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);
like image 894
Jonghwan Seo Avatar asked Jul 31 '13 05:07

Jonghwan Seo


People also ask

How do you call every 10 seconds on Android?

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.

How can you perform repeated tasks in a service in Android?

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.

What are handlers and loopers in Android?

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.


2 Answers

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

like image 167
Raghunandan Avatar answered Sep 22 '22 04:09

Raghunandan


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.

like image 32
Android Killer Avatar answered Sep 20 '22 04:09

Android Killer