Credential Manager 的「Restore Credentials」功能可讓使用者在設定新裝置時還原應用程式帳戶。這個 API 為開發人員預覽版, 適用於所有搭載 Android 9 以上版本的裝置,以及 Google Play 服務 (GMS) 核心版本 242200000 或更高版本。還原憑證的優點 功能包括:
- 提供流暢的使用者體驗:使用者不必手動登入個別應用程式,即可還原應用程式帳戶。
- 提高使用者參與度:如果使用者在設定新裝置時可以還原帳戶,就更有可能繼續使用您的應用程式。
- 減輕開發負擔:整合了還原憑證功能 ,因此支援密碼金鑰的開發人員可新增 及授權復原憑證
運作方式
您可以使用「還原憑證」功能建立、取得及清除相關憑證。
- 建立還原憑證:使用者登入應用程式時,建立一個 與自身帳戶相關聯的還原憑證。已儲存這組憑證 並同步到雲端,前提是使用者啟用了 Google 備份功能 使用端對端加密功能 (應用程式可能會選擇不同步到雲端)
- 取得還原憑證:使用者設定新裝置時,您的應用程式 可以要求透過 Credential Manager 還原憑證。這樣一來,您就能自動登入使用者,不必再輸入任何其他內容。
- 清除還原憑證:使用者登出應用程式後, 應刪除相關聯的還原憑證。
還原憑證功能可與後端系統流暢整合 測試應用程式的運作方式這種相容性 用於建立密碼金鑰和還原金鑰 ( 還原憑證功能) 遵循相同的基礎技術 規格。此對齊方式可確保還原憑證程序 有效擷取及復原已啟用密碼金鑰功能儲存的使用者憑證 跨基礎架構 平台和驗證方式
實作
Restore Credentials API 可透過 Credential Manager Jetpack 使用 資源庫。首先,請按照下列步驟操作:
在專案中加入憑證管理工具依附元件。
// build.gradle.kts implementation("androidx.credentials:credentials:1.5.0-alpha03")
建立
CreateRestoreCredentialRequest
物件。呼叫
CredentialManager
物件的createCredential()
方法。val credentialManager = CredentialManager.create(context) // On a successful authentication create a Restore Key // Pass in the context and CreateRestoreCredentialRequest object val response = credentialManager.createCredential(context, createRestoreRequest)
產生的還原憑證是一種密碼金鑰,也稱為 做為還原密碼金鑰或還原金鑰。
當使用者設定新裝置時,請在以下裝置上呼叫
getCredential()
方法:CredentialManager
物件。// Fetch the Authentication JSON from server val authenticationJson = ... // Create the GetRestoreCredentialRequest object val options = GetRestoreCredentialOption(authenticationJson) val getRequest = GetCredentialRequest(Immutablelist.of(options)) // The restore key can be fetched in two scenarios to // 1. On the first launch of app on the device, fetch the Restore Key // 2. In the onRestore callback (if the app implements the Backup Agent) val response = credentialManager.getCredential(context, getRequest)
當使用者登出應用程式時,請在
CredentialManager
物件上呼叫clearCredentialState()
方法。// Create a ClearCredentialStateRequest object val clearRequest = ClearCredentialStateRequest(TYPE_CLEAR_RESTORE_CREDENTIAL) // On user log-out, clear the restore key val response = credentialManager.clearCredentialState(clearRequest)
如果您使用備份代理程式,請在 onRestore
回呼中執行 getCredential
部分。這可確保應用程式資料還原後,應用程式的憑證會立即還原。