5

The root problem I'm running into is that I want to make webservice API requests using a token. The token is obtained by hitting an auth endpoint with an email/password. The token has an expiration time, so in order for the Android app to perform smoothly, the token should be refreshed whenever it becomes invalid, without user interaction.

The solution I've been pursuing is to use AccountManager (http://developer.android.com/reference/android/accounts/AccountManager.html) to store email/password and the token. The problem is that to instantiate the AccountManager, I need to pass it a Context (AccountManager.get(context)). Most of where the API requests happen are in places where the context is unavailable, like AsyncTasks or singleton manager classes. Passing in the context is a messy prospect and not always possible.

Is there a way I can get this to work with AccountManager? Or do I need to manage and refresh my auth tokens in a completely different way? I'm assuming that I will need to store the user's email/password encrypted on the phone, but maybe that's not possible. I would like to know what the best practice is.

JZC
  • 470
  • 5
  • 12
  • IIRC what I ended up doing was using the Application context. So in Application.onCreate(), I would store a static reference to the Application instance, then have a static method Application.getAppContext() that would access the static Application instance and return getApplicationContext(). It seems to work okay, but keeping static references like that is frowned upon, so I would be just as interested as you in a better way to accomplish this. – kris larson Apr 09 '15 at 03:28
  • 1
    Does this answer your question? [Static way to get 'Context' in Android?](https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android) – Hossein Farrokhi Aug 02 '20 at 05:57

0 Answers0