Issue
I've implemented a IntentService that fetchs data from my servers and returns result as JSON through ResultReceiver that's given to the service via intent.
My problem is keeping UI up to date with the services state, for example logging in to my server happens through this service, if I wanted to tell the user that the program is working on the logging in I'd like to show a progress dialog, but what happens when someone calls while the service is still fetching data, user rotates phone or changes activity?
I don't want to leave user looking at screen that has login button and when the login is done it just shows toast indicating the state, I want keep the user notified about the current state.
How can I handle the progress dialog without creating hundreds of lines of duplicate code when accessing my service?
Currently on my LoginActivity after user wants to login it calls login function in my ApiAccessor which handles communicating with service and registers a callback when the result is back in such way:
ProgressDialog dialog;
dialog = ProgressDialog.show(this, "Please wait..", "Logging in..");
accessor.login(usernameField.getText().toString(), passwordField.getText().toString(), new ApiCallback() {
@Override
public void onResponse(ApiResponse response) {
dialog.dismiss();
}
});
but now I have to handle dismissing and respawning dialog in onPause, onResume and onDestroy too, and I have to do this in every activity!
What is the common way of keeping UI up to date with the services state or so?
Solution
you'll want to read on the BIND part of the whole Service guides and documentation.
http://developer.android.com/guide/components/bound-services.html
After an activity is bound to a service, the activity can call up any methods on it, so you can:
- Create an interface
- Create method on the service such as
setOnSomethingHappenListener(MyInterface listener)
- implement the interface on the activity
- from the activity call
myService.setOnSomethingHappenListener(this);
- from the service, if listener not null, you call the methods from the interface (passing those events to whichever activity is attached to it)
- don't forget to override
onUnbind
to null the listener.
Answered By - Budius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.