-1

I need to perform a very simple operation that involve network. I know that this must be done with an Async Task, because run a task that involves Network operations on main thread is bad.

Since is pretty verbose using the classic way

private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //to do
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            //to do
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

for a method static method invocation that must download only few bits

I'm wondering if there is some more concise form or alternative that I could use.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
AndreaF
  • 11,975
  • 27
  • 102
  • 168

4 Answers4

1

You don't need an AsyncTask. It is just a convenience to use because it already has callback methods.

You can create a new Thread and execute your network call there.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
1

There are many ways to create a worker thread. It depends on what are you doing with network.

  • If you just want to do simple network operations such as download some JSON data then get it back to update UI: use AsyncTask.
  • If you want to do long network operations which involve moderate to large amounts of data (either uploading or downloading): use Thread.
  • If you want to continuously send/receive message to/from the Internet, use HandlerThread.

So in conclusion: AsyncTask is already the simplest and easiest to use. Beside, you don't need to override all methods, just override doInBackGround() and onPostExecute() if you want to receive data.

See: Asynctask vs Thread in android

Pang
  • 9,564
  • 146
  • 81
  • 122
nhoxbypass
  • 9,695
  • 11
  • 48
  • 71
0

You can always use AsyncTask.execute(() -> { /* network operations */ });, the downside is you don't get any of the callbacks so I tend to only use this when prototyping or with very simple tasks.

LambergaR
  • 2,433
  • 4
  • 24
  • 34
0

Use an anonymous class inside a method:

public void asyncOperation () {
    new AsyncTask<Task, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(String... params) {
            // Your background operation, network, database, etc
            return true;
        }
    }.execute();
}
moictab
  • 959
  • 6
  • 27