Best practice of repeated network tasks?

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.

+4
source share
3 answers

Is it possible to create a CheckFtpTask object once and then reuse it? Or will it give me side effects?

No, there will be side effects. Quoting documents Threading rules:

A task can be executed only once (an exception will be thrown if the second execution is completed).

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

And I'm not sure why you need Runnable or Handler . AsyncTask has methods that execute on UI Thread (everything except doInBackground() , in fact) if you need to update the UI .

Check this answer if you need a callback to update the UI when the task is completed.

+1
source

You must create a new Async task for each call.

See the Android documentation: AsyncTask . According to this documentation:

A task can be executed only once (an exception will be thrown if the second execution is completed).

In particular, see the flow rule section. There is a similar answer here, fooobar.com/questions/1502134 / ...

0
source

Java ThreadPools and ExecutorFramework let you execute threads as needed and reduce the cost of creating threads. Check out singleThreadExecutor . Using a thread pool is pretty easy!

0
source

Source: https://habr.com/ru/post/1502133/


All Articles