开发者

Android AccountManager [closed]

开发者_JS百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

Can some one help me with step by step approach to use the AccountManager in android along with a minimalistic example for better understanding?


I'm actually answering this so I can get a clear understanding myself, so here goes (I'm by no means proficient with Android yet):

An application will usually want to check for the existence of an account first, you can use:

AccountManager mgr = AccountManager.get(getApplicationContext());
Account[] accounts = mgr.getAccountsByType("com.mydomain");
// assert that accounts is not empty

You'll want to use an AccountManagerFuture<Bundle> to hold results of the authentication token. This has to be async since the Android device may ask the user to login in the meantime:

private AccountManagerFuture<Bundle> myFuture = null;
private AccountManagerCallback<Bundle> myCallback = new AccountManagerCallback<Bundle>() {
    @Override public void run(final AccountManagerFuture<Bundle> arg0) {
        try {
           myFuture.getResult().get(AccountManager.KEY_AUTHTOKEN); // this is your auth token
       } catch (Exception e) {
           // handle error
       }
   }

}

Now you can ask for the auth token asynchronously:

myFuture = mgr.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, true, myCallback, null);

AUTH_TOKEN_TYPE is dependent on your authentication mechanism. For google accounts it is simply 'ah'.

Now whenever you do an authenticated request just pass along the token (in the header, as a param, etc), so the server side knows who you are.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜