Hello everyone,

I'm implementing a client interacting with a server by HTTP. There are
lots of different API commands, which I'm keeping in one class as
methods. Each method takes different arguments and can return
different object types. Server response is pretty fast except when I'm
downloading anything larger, but that I'm handling already. However,
it can happen to take longer than 200ms which is why it should be
threaded.

Since there quite a lot interactions between the server and the
client, I suppose spawning a thread on each request is not the
smartest thing to do. I'm more thinking about one single thread with a
queue, executing one request after another or idleing otherwise.

I imagine accessing the API like this:

// Create thread once
mApiThread = new ApiThread();
mApiThread.start();

// Then run a command and treat the result
mApiThread.getVersion(new ApiResult<String>() {
  public void run() {
    Log.i("callback", "Server version is " + value); // GUI updates,
here only log print.
  }
});

// using a simple container class
public abstract class ApiResult<T> implements Runnable {
  public T value;
}

Now what I'm struggling with is the implementation of the ApiThread
class. I ended up doing something like this:

public class ApiThread extends Thread {
  private Handler mHandler;
  public void run() {
    Looper.prepare();
    mHandler = new Handler();
    Looper.loop();
  }
  public void getVersion(final ApiResult<String> result) {
    mHandler.post(new Runnable() {
      public void run() {
        // get version from server
        result. value = HTTPApi.getVersion(); // can take a while
        mHandler.post(result);
  }
}

Is that something anyone would want to do? Isn't there still a lot of
overhead? Does anyone know of an open source application doing
something similar? What's the "Android Way" to accomplish this?

Any hints and suggestions greatly appreciated!

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to