Yao Yao - 1 year ago 63
Android Question

Network utility design in Android app

I am creating an Android app prototype which functions like this:

When users launch the app, they can browse through article title list. When they click one of them, the app switches to another activity, which contains the article contents and so on. Users can also post an article when they are on the article title list.

I am trying to create a utility class, let's say ServerConnect.java, to handle all the REST request and response. In the beginning, the class has 3 public static methods to send requests for different purpose.

1. requestArticleList

2. requestArticleContent

3. userSendArticle (user post a new article)

Then I find out that I cannot just call ServerConnect.requestArticleList(), as Android forbids network behavior on UI thread. So I change the ServerConnect class to

extends AsyncTask
class. And put requestArticleList() in doInBackground(), then do things like
new ConnectServer().execute()

Well, this gives me what I what when I lauch the app and request for article list. However, my problem is, this ConnectServer class can only do requestArticleList as it is hardcoded in doInBackground
protected String doInBackground(Location userLocation) {
return requestArticleList(userLocation);

Is there any ways I can handle all these 3 method as public static method in one utility class?

Thanks all for your patience for such a long story.

Answer Source

I don't think that putting this in one class is a good idea. If you afraid that some function will repeat in 3 different class you can put it in some base class like below.

Create abstract base class with common functions

public abstract class ConnectionUtils<A,B,C> extends AsyncTask<A,B,C> {
    // put common functions here

Then create 3 separate class for each request

public class RequestArticleList extends ConnectionUtils<Location, Void, String> {
    protected String doInBackground(Location... userLocation) {
        return requestArticleList(userLocation);

If you really want all this functionality in one class you can create callback interface

public interface Callback<ResultType> {
    void onResult(ResultType result);

and then in each function create new Thread

public void requestArticleList(final Callback<MyResult> callback) {
    new Thread(new Runnable() {
        public void run() {
            // your code

Drawback is that its require switching to main thread before ui update.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download