tags:

views:

79

answers:

2

I'm working on a service for my application whose purpose is to allow easy access to various web services we are running. The service is used to maintain a login state across any applications that want to use it so the user only has to log in once when the service is first started.

What is the best way to go about making the service run asynchronously and call back to the application when it is finished. Currently I am using static classes that extend Thread such as

private static class LogInAsync extends Thread {
    private Handler handler;
    private CallbackWrapper wrapper;
    private Context context;

    protected LogInAsync(Context context, Handler handler, CallbackWrapper wrapper) {
        this.handler = handler;
        this.wrapper = wrapper;
        this.context = context;
    }

    public void run() {
        loginState = true;

        wrapper.setResponse(Types.NOTHING, Functions.LOG_IN, null);
        handler.post(wrapper);
    } 
}

And to make it easy to call

public static void logIn(Context context, ResponseListener callback) {
    (new LogInAsync(context, new Handler(), new CallbackWrapper(callback))).start();
}

But these functions can only be called by my own application. I want anyone to be able to make a one or two line function call and be able to handle the response easily, preferably in a simple callback method.

I figure it has to be done using Intents to start the Threads, but if I do that I can't pass a callback.

A: 

You need to use the Service object, and you can then bind activities to it, and they will be able to communicate with your service.

Read these tutorials:
- Basics of Android : Part III – Android Services
- Remote Service Tutorial

Pentium10
Thanks, but I was using AIDL before and as far as I can tell there is no way to pass my callback interface.
Mr. Ambiguous
+1  A: 

At the Google IO was a session about building REST web applications. Perhaps this will help you to find the best architecture for your app. Using threads is not good (why is explained in the video).

http://www.youtube.com/watch?v=xHXn3Kg2IQE

Mark
Thank you, this video is incredibly helpful, and I like that he's using Intents to start the service. But there's still one point that I am unclear about. How do I perform the binder callback, how does the service tell the helper that the operation has completed?
Mr. Ambiguous
You can pass an Interface in the Intent to use as callback. Check the Google I/O app. Search for iosched
alexanderblom