I have a small Android application in which I need to make some FTP files every couple of seconds. Having studied the tough way that network stuff works in the UI thread, this is something that Android doesn't really like, I came 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 method: checkFtpHandler = new Handler(); checkFtpRunnable = new Runnable() { @Override public void run() { new CheckFtpTask().execute((Void[])null); checkFtpHandler.postDelayed(checkFtpRunnable, 5000); } }; checkFtpRunnable.run();
Is it good practice to perform a repetitive task that cannot work directly in the user interface thread? Also, constantly creating a new AsyncTask object, calling
new CheckFtpTask().execute((Void[])null);
Is it possible to create a CheckFtpTask
object once and then reuse it? Or will it give me side effects?
Thanks in advance, Jens.
source share