Android AsyncTask/doInBackground pattern

12 views
Skip to first unread message

Peavers via StackOverflow

unread,
Jan 18, 2015, 6:23:32 PM1/18/15
to google-appengin...@googlegroups.com

This is more a "how should I design" than a "how do I code" so I hope this is in the right place...

I've got a pretty standard class that extends from AsyncTask.

How do I best lay this out to do many different tasks? For example working with GAE I have standard get, insert, delete, update methods that all need to run asynchronously.

@Override
protected String doInBackground(String... params) {
    if (tipApiService == null) {
        TipBeanApi.Builder builder = new TipBeanApi.Builder(AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(), null)

                .setRootUrl("http://10.0.2.2:8080/_ah/api/").setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });

        tipApiService = builder.build();
    }

    try {
        tipApiService.insert(tip).execute();
    } catch (IOException e) {
        Log.d(TAG, "pushToRemote: " + e.toString());
    }

    return null;
}

You can see in the try block I execute the insert method.

What if I wanted to do something else instead? Should I create a entire new class for each operation, or pass a condition statement in that dictates what should be done? Is there another cleaner/better way that I just don't know about?



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/28015957/android-asynctask-doinbackground-pattern

Halim Qarroum via StackOverflow

unread,
Jan 18, 2015, 6:33:33 PM1/18/15
to google-appengin...@googlegroups.com

Fortunately, there are several existing libraries out there that will help you achieve what you want in a DRY manner, and will handle for you the asynchronous aspect of the requests.

Not to make any advertisement, but rather because I used it for some time now, volley is pretty good for what you want. It is an asynchronous HTTP client which manages a queue of requests. The main features of volley are (from the docs) :

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

You simply need to create a type of request (GET, POST, PUT ...), and to push them into the request queue of volley, that's it.



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/28015957/android-asynctask-doinbackground-pattern/28016035#28016035

TheRedBaron via StackOverflow

unread,
Jan 18, 2015, 8:08:35 PM1/18/15
to google-appengin...@googlegroups.com

I've been working on an Android app for the past few months that uses GAE and Google Cloud endpoints, so hopefully my approach will help you out.

In my Application class is where I build all my endpoints, so for you it will look something like this:

public class ThisApp extends Application {

    private static TipBeanApi tipApiService;

    @Override
    public void onCreate() {
        super.onCreate();
        buildCloudEndpoints();
    }

    private void buildCloudEndpoints() {
        TipBeanApi.Builder builder = new TipBeanApi.Builder(AndroidHttp.newCompatibleTransport(),
        new AndroidJsonFactory(), null)
            .setRootUrl("http://10.0.2.2:8080/_ah/api/").setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {@Override
            public void initialize(AbstractGoogleClientRequest <? > abstractGoogleClientRequest) throws IOException {
                abstractGoogleClientRequest.setDisableGZipContent(true);
            }
        });

        tipApiService = builder.build();
    }

    public static TipBeanApi getApiService() {
        return tipApiService;
    }

}

Now anywhere, in your app you can just do ThisApp.getApiService().yourEndpoint().execute(); to execute an endpoint call.

Finally, I recommend making all the AsyncTasks as embedded classes, so that you're not creating a new java file for every single API call you wish to make. A good rule of thumb is that if you only call the API once in your app, then just embed the AsyncTask in the Activity which calls it e.g. private class YourApiCallTask extends AsyncTask ... otherwise if you call it multiple times, then you should create a class called "ApiServiceEndpoints" and use it to hold all your API call tasks e.g. public static class YourApiCallTask extends AsyncTask ... If you have say less than 10 or so endpoints, then you can just stick all the AsyncTasks in your ApiServiceEndpoints class, and your activities' code will be a lot cleaner.

I hope this helps, and don't hesitate to ask any more questions about using GAE/cloud endpoints with an Android app!



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/28015957/android-asynctask-doinbackground-pattern/28016608#28016608
Reply all
Reply to author
Forward
0 new messages