Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for repeated network tasks?

I have a small Android application in which I need to do some FTP stuff every couple of seconds. After learning the hard way that running network stuff on the UI thread is something Android does not really like, I've come to this solution:

// This class gets declared inside my Activity
private class CheckFtpTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... dummy) {
        Thread.currentThread().setName("CheckFtpTask");
        // Here I'll do the FTP stuff       
        ftpStuff();
        return null;
    }
}

// Member variables inside my activity
private Handler checkFtpHandler;
private Runnable checkFtpRunnable;

// I set up the task later in some of my Activitiy's method:
checkFtpHandler = new Handler();
checkFtpRunnable = new Runnable() {
    @Override
    public void run() {
        new CheckFtpTask().execute((Void[])null);
        checkFtpHandler.postDelayed(checkFtpRunnable, 5000);
    }
};
checkFtpRunnable.run();

Is this good practice to perform a recurring task that cannot run on the UI thread directly? Furthermore, instead of creating a new AsyncTask object all the time by calling

new CheckFtpTask().execute((Void[])null);

would it be an option to create the CheckFtpTask object once and then reuse it? Or will that give me side effects?

Thanks in advance, Jens.

like image 540
Jens Avatar asked Nov 11 '22 22:11

Jens


1 Answers

would it be an option to create the CheckFtpTask object once and then reuse it? Or will that give me side effects?

No, there will be side-effects. Quoting the docs Threading Rules:

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

You will just need to create a separate instance of the task each time you want to run it.

And I'm not sure why you need the Runnable or Handler. AsyncTask has methods that run on the UI Thread (all but doInBackground(), actually) if you need to update the UI.

Check this answer if you need a callback to update the UI when the task has finished.

like image 144
codeMagic Avatar answered Nov 15 '22 11:11

codeMagic