开发者

How do I create an Android Service with callbacks?

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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜