Dev
Dev

Reputation: 360

Simplest way to call a method in Thread using Handler after every 10 seconds

I have created a method and i want to call it after every 10 seconds with the help of Thread in Handler. My code is..

 public void saveDataToServer(){
 //do logic here
 }

 @Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new Handler().postDelayed(
        new Runnable() {
            @Override
            public void run() {
                saveDataToServer();
            }
        },
    10000);
}

There is no error in code, But unfortunately not running. Can anybody please tell what i am doing wrong.. Thanks in advance.

Upvotes: 1

Views: 826

Answers (1)

M D
M D

Reputation: 47817

You should call

 new Handler().postDelayed(this,10000);

in Run like

Runnable r=new Runnable() {
        @Override
        public void run() {
            saveDataToServer();
            new Handler().postDelayed(this,10000);
        }
    };

new Handler().postDelayed(r,10000);

Upvotes: 2

Related Questions