2016-03-26 42 views
0

今天我的應用程序有一個經典的登錄屏幕(用戶名和密碼),這個類擴展了一個普通的活動。我的初始活動是登錄(如果已經登錄的用戶重定向到家)。Android - AccountManager和登錄經典

我的Android清單:

<!-- Start Activity --> 
    <activity 
     android:name=".activity.LoginActivity" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme.NoActionBar" 
     android:windowSoftInputMode="adjustPan"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

現在我嘗試部署了Android的客戶經理,閱讀文檔和實施。該功能是好的。如果您輸入Android帳戶設置,則可以登錄到該應用程序並創建一個帳戶。但我的問題是如何保持雙向。

作爲facebook,如果用戶打開應用程序,它將登錄並自動在AccountManager上創建一個帳戶,並在帳戶中獲取它的設置也記錄在應用程序中。在我請求服務器上的用戶驗證和密碼(使用排球)之後,我應該如何知道要完成的步驟?將數據返回到AccountManager或添加一個帳戶?

登錄經典,服務器驗證之後添加使用「addAccountExplicitly」帳戶:

private void finishLogin(final String email, final String authToken) { 
     Account account = new Account(email, AccountGeneral.ACCOUNT_TYPE); 
     boolean success = mAccountManager.addAccountExplicitly(account, "", null); 
     if (success) { 
      Log.d(TAG, "Account created"); 
      mAccountManager.setAuthToken(account, mAuthTokenType, authToken); 
     } else { 
      Log.d(TAG, "Account creation failed. Look at previous logs to investigate"); 
     } 
} 

和登錄的帳戶設置:

Bundle data = new Bundle(); 
     data.putString(AccountManager.KEY_ACCOUNT_NAME, email); 
     data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType); 
     data.putString(AccountManager.KEY_AUTHTOKEN, authToken); 
     data.putString(PARAM_USER_PASS, password); 
     final Intent intent = new Intent(); 
     intent.putExtras(data); 

     final Account account = new Account(email, accountType); 

     if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) { 
      Log.d(TAG, " finishLogin > addAccountExplicitly"); 
      // Creating the account on the device and setting the auth token we got 
      // (Not setting the auth token will cause another call to the server to authenticate the user) 
      mAccountManager.addAccountExplicitly(account, password, null); 
      mAccountManager.setAuthToken(account, mAuthTokenType, authToken); 
     } else { 
      Log.d(TAG, " finishLogin > setPassword"); 
      mAccountManager.setPassword(account, password); 
     } 

     setAccountAuthenticatorResult(intent.getExtras()); 
     setResult(RESULT_OK, intent); 
     finish(); 

回答

2

爲了讓你不左右逢源需要有兩個活動並處理兩種情況。只需集成所有登錄過程,設置帳戶數據並在帳戶管理器包中明確添加帳戶即可。 (可以達到的設置 - >添加帳戶)。

然後在您的應用程序中,您可以從AccountManager類中選擇不同的選項。

您可以通過調用getAccountsByType()來檢查是否已有賬戶。

您可以通過致電AddAccount()在您的應用中添加帳戶。它會自動顯示您從設置中獲得的相同活動。它還具有返回所選帳戶名稱和authToken的回調。

您也可以致電newChooseAccountIntent()。這是一個非常好的選擇,因爲如果沒有帳戶,此方法將自動顯示登錄活動,並且如果已經添加帳戶,則將它們顯示爲列表,並且用戶可以選擇一個帳戶。