I have an Android project in which I get a token from the server for authentication and use it for further queries to the server. The token expires approximately in 10 minutes so I have to fetch a new one. My current pattern is like that:
1- Fetch the token when the user first starts the application
2- Block the user input with a “Please Wait” dialog so he does not try to send queries with a null token from other activites
3- Save the token and the timestamp, stop blocking user input
4- Check the timestamp regularly in onCreate() methods of the activities
5- Update if necessary.
My problem is this; if user opens an activity and the token is expired my application again blocks the user input and tries to fetch the token. However, in background, normal logic/flow of the application continues and it tries to send a query to the server with an old or a null token.
So I want to block this query task -which is an AsyncTask like the token fetching- and start it after the token fetching is finished. How can i use this pattern and is this a correct one?
Making one thread wait for another to finish?
I would consider using the Android Account manager with a custom authenticator for handling the tokens. The SampleSyncAdapter shows you how to proceed with that. Use the AccountManager‘s getAuthToken to fetch the current token. In the authenticator you can include logic to invalidate tokens at timeout which will cause the authenticator at the next request for a token to contact the server.
But I guess it could be too much overhead for your project to implement this. Two approaches I see for your current setup:
Use Java synchronization primitives to block. E.g., create a “lock” object and use it in the async task and where you update your token: