mercredi 25 mai 2016

Android: Effective way to manage UI and function state in an app using AsyncTask?

I'm looking for a tidy solution to something that must be common in Android applications: A clear way to manage state when the result of actions is uncertain and running asynchronously.

I realize that using a progress view will keep the app from having to deal with the user during the AsyncTask. The problem is that there's a bunch to contend with, and it seems to lose maintainability as the applications get more detailed.

For example, say we have an activity that has three states, from a UI point of view. Say the view for the activity has a bunch of things to make visible/invisible, enable/disable, set text for, etc. These things depend upon what has happened in the past sessions, this session, and through configuration changes. One might take the model of a log-in, where there are user credentials that may be untried, tried and failed, tried and worked. And say there's a database with data that becomes stale if the user does something, or if there's a failure in login, for instance. The point is, if there's a lot going on, what's an effective pattern to employ?

I realize that SharedPreferences and SQLiteDatabase are available, and I'm using both of those. It just seems haphazard. Deep in the bowels of the AsyncTask for instance, I might realize that things are not going smoothly, so rather than normal UI state, I'd like make some UI changes. Which I do, but the way I'm keeping track of all of those changes so I can handle the activity restarting due to screen orientation change, seems untidy: I'm constantly putting primitives into preferences all over the place. I can manage it now, but if this app doubled in size, it would not be unmanageable.

It seems like if you have a simple app, there's no reason to expand beyond just tweaking the views as needed. The pattern I'm looking for may or may not have long-running tasks as a central part of it, or multiple resulting states from a single starting state when a specific action is taken, but should allow for orderly management of state when there is 'a lot going on'.

Aucun commentaire:

Enregistrer un commentaire