Search code examples
androidrepeatbackground-service

Android - Simple repeating background task


I am trying to run simple background service, that will be every some period of time checking date ane doing what I want, but I have problems with creation. I was looging via uncle Google, but he coundn't help me. I don't have any code in spite of AndroidManifest.xml line: <service android:name=".HelloService" /> and public class HelloService extends Service { }. How am I to write it? I don't want to use Alarms.


Solution

  • You can set your Service to run indefinitely, like with a while loop. Inside that loop you can use something like Thread.sleep() to make your Service way for a while. Or you could also use Handler, depending on what you want to achieve.

    Dunno why you don't want to use alarms, but that should also do the job.

    More on Handler here.


    EDIT: Sample code using Handler:

    public class MyActivity extends Activity { 
    
        private Handler handler = new Handler();
    
        private Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // The method you want to call every now and then.
                yourMethod();
                handler.postDelayed(this,2000); // 2000 = 2 seconds. This time is in millis.
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_slider);
    
            handler.postDelayed(runnable, 2000); // Call the handler for the first time.
    
        }
    
        private void yourMethod() { 
            // ... 
        } 
        // ...
    }
    

    P.S.: With this solution, your code will stop after the Activity is destroyed.