Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tutorial for Android Services? [closed]

Tags:

android

I've done very little with android dev and I was wondering if anyone has a good tutorial in regards to Services. I'm looking to make an app that starts and continues to loop forever even in the background.

like image 572
Takkun Avatar asked Aug 05 '26 08:08

Takkun


1 Answers

There is a wealth of resources on Services if you do a simple google search so I'm not going to explain how services work. The code snippet below uses a service that isn't bound to the Activity.

My approach uses a Timer and a Task, note I use a task that repeats but this is not necessary. There are other ways you can approach this.

public class MyService extends Service {

    private Task retryTask;
    Timer myTimer;

    private boolean timerRunning = false;

    private long RETRY_TIME = 200000;
    private long START_TIME = 5000;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        myTimer = new Timer();
        myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
        timerRunning = true;

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!timerRunning) {
            myTimer = new Timer();
            myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
            timerRunning = true;
        }

        return super.onStartCommand(intent, flags, startId);

    }

    public class Task extends TimerTask {

        @Override
        public void run() {

            // DO WHAT YOU NEED TO DO HERE
        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        if (myTimer != null) {
            myTimer.cancel();

        }

        timerRunning = false;
    }
}

You would then start the service from an Activity using an Intent

Intent intent = new Intent(WorkSelectionActivity.this,MyService.class);
        startService(intent);

Hope this helps

like image 113
Bear Avatar answered Aug 06 '26 23:08

Bear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!