GoogleSignIn.getLastSignedInAccount устарел.
Могу ли я узнать, какая альтернатива существует при переходе на Credential Manager API/API авторизации?
В настоящее время я не используйте API диспетчера учетных данных.
Я использую API авторизации для выполнения входа в систему клиента на основе фрагмента кода – https://developers.google.com/identity/ ... on/android
List requestedScopes = Arrays.asList(DriveScopes.DRIVE_APPDATA);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Identity.getAuthorizationClient(this)
.authorize(authorizationRequest)
.addOnSuccessListener(
authorizationResult -> {
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
try {
// This code will enable user to perform login.
startIntentSenderForResult(pendingIntent.getIntentSender(),
REQUEST_AUTHORIZE, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
}
} else {
// Access already granted, continue with user action
saveToDriveAppFolder(authorizationResult);
}
})
.addOnFailureListener(e -> Log.e(TAG, "Failed to authorize", e));
Как я могу получить данные последней учетной записи для входа?
Я попробовал следующий фрагмент кода от AI. Но это не то, чего я хочу. Следующий фрагмент кода откроет диалоговое окно входа в систему. Я хочу молча получить последнюю учетную запись, которую я использовал для доступа к Google Диску.
[img]https://i. sstatic.net/U9LddoED.png[/img]
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.credentials.CredentialManager;
import androidx.credentials.CredentialManagerCallback;
import androidx.credentials.GetCredentialRequest;
import androidx.credentials.GetCredentialResponse;
import androidx.credentials.exceptions.GetCredentialException;
import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
public class AuthManager {
private final Context context;
private final CredentialManager credentialManager;
public AuthManager(Context context) {
this.context = context;
this.credentialManager = CredentialManager.create(context);
}
public interface AuthCallback {
void onSuccess(GoogleIdTokenCredential credential);
void onFailure(Exception e);
}
public void getLastSignedInAccount(AuthCallback callback) {
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
.setServerClientId(WENOTE_CLOUD_STORAGE_CLIENT_ID)
.build();
GetCredentialRequest request = new GetCredentialRequest.Builder()
.addCredentialOption(googleIdOption)
.build();
android.util.Log.i("CHEOK", "Call getCredentialAsync");
credentialManager.getCredentialAsync(
context,
request,
null, // pass in a CancelationSignal to allow cancelling the request
Runnable::run, // Execute the callback immediately
new CredentialManagerCallback() {
@Override
public void onResult(@NonNull GetCredentialResponse result) {
android.util.Log.i("CHEOK", "onResult " + result);
if (result != null) {
GoogleIdTokenCredential credential = (GoogleIdTokenCredential) result.getCredential();
callback.onSuccess(credential);
} else {
callback.onFailure(new Exception("No credential found"));
}
}
@Override
public void onError(@NonNull GetCredentialException e) {
android.util.Log.i("CHEOK", "onError " + e);
// Handle errors
callback.onFailure(e);
}
}
);
}
}
Использование Identity.getAuthorizationClient
Другой подход, который я пробовал, — использование Identity.getAuthorizationClient. Но это дает мне нулевое время за все время.
List requestedScopes = java.util.Arrays.asList(
new Scope(DriveScopes.DRIVE_APPDATA),
new Scope("email"),
new Scope("profile"),
new Scope("openid")
);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Task task = Identity.getAuthorizationClient(MyApplication.instance())
.authorize(authorizationRequest);
if (task.isSuccessful()) {
AuthorizationResult authorizationResult = task.getResult();
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
IntentSender intentSender = pendingIntent.getIntentSender();
...
} else {
// Access already granted, continue with user action
Log.i("CHEOK", "Email = " + authorizationResult.toGoogleSignInAccount().getEmail());
Log.i("CHEOK", "getDisplayName = " + authorizationResult.toGoogleSignInAccount().getDisplayName());
Log.i("CHEOK", "getId = " + authorizationResult.toGoogleSignInAccount().getId());
Log.i("CHEOK", "getIdToken = " + authorizationResult.toGoogleSignInAccount().getIdToken());
}
} else {
getCommonExecutor().execute(new Runnable() {
@Override
public void run() {
try {
Tasks.await(task);
try {
AuthorizationResult authorizationResult = task.getResult(ApiException.class);
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
IntentSender intentSender = pendingIntent.getIntentSender();
...
} else {
// Access already granted, continue with user action
Log.i("CHEOK", "Email = " + authorizationResult.toGoogleSignInAccount().getEmail());
Log.i("CHEOK", "getDisplayName = " + authorizationResult.toGoogleSignInAccount().getDisplayName());
Log.i("CHEOK", "getId = " + authorizationResult.toGoogleSignInAccount().getId());
Log.i("CHEOK", "getIdToken = " + authorizationResult.toGoogleSignInAccount().getIdToken());
}
} catch (ApiException e) {
// TODO:
}
} catch (ExecutionException e) {
// TODO:
} catch (InterruptedException e) {
// TODO:
}
}
});
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... igrating-t
Какая замена GoogleSignIn.getLastSignedInAccount при переходе на Credential Manager API/API авторизации? ⇐ JAVA
Программисты JAVA общаются здесь
1734072634
Anonymous
GoogleSignIn.getLastSignedInAccount устарел.
Могу ли я узнать, какая альтернатива существует при переходе на Credential Manager API/API авторизации?
В настоящее время я не используйте [b]API диспетчера учетных данных[/b].
Я использую [b]API авторизации[/b] для выполнения входа в систему клиента на основе фрагмента кода – https://developers.google.com/identity/authorization/android
List requestedScopes = Arrays.asList(DriveScopes.DRIVE_APPDATA);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Identity.getAuthorizationClient(this)
.authorize(authorizationRequest)
.addOnSuccessListener(
authorizationResult -> {
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
try {
// This code will enable user to perform login.
startIntentSenderForResult(pendingIntent.getIntentSender(),
REQUEST_AUTHORIZE, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
}
} else {
// Access already granted, continue with user action
saveToDriveAppFolder(authorizationResult);
}
})
.addOnFailureListener(e -> Log.e(TAG, "Failed to authorize", e));
Как я могу получить данные последней учетной записи для входа?
Я попробовал следующий фрагмент кода от AI. Но это не то, чего я хочу. Следующий фрагмент кода откроет диалоговое окно входа в систему. Я хочу молча получить последнюю учетную запись, которую я использовал для доступа к Google Диску.
[img]https://i. sstatic.net/U9LddoED.png[/img]
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.credentials.CredentialManager;
import androidx.credentials.CredentialManagerCallback;
import androidx.credentials.GetCredentialRequest;
import androidx.credentials.GetCredentialResponse;
import androidx.credentials.exceptions.GetCredentialException;
import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
public class AuthManager {
private final Context context;
private final CredentialManager credentialManager;
public AuthManager(Context context) {
this.context = context;
this.credentialManager = CredentialManager.create(context);
}
public interface AuthCallback {
void onSuccess(GoogleIdTokenCredential credential);
void onFailure(Exception e);
}
public void getLastSignedInAccount(AuthCallback callback) {
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
.setServerClientId(WENOTE_CLOUD_STORAGE_CLIENT_ID)
.build();
GetCredentialRequest request = new GetCredentialRequest.Builder()
.addCredentialOption(googleIdOption)
.build();
android.util.Log.i("CHEOK", "Call getCredentialAsync");
credentialManager.getCredentialAsync(
context,
request,
null, // pass in a CancelationSignal to allow cancelling the request
Runnable::run, // Execute the callback immediately
new CredentialManagerCallback() {
@Override
public void onResult(@NonNull GetCredentialResponse result) {
android.util.Log.i("CHEOK", "onResult " + result);
if (result != null) {
GoogleIdTokenCredential credential = (GoogleIdTokenCredential) result.getCredential();
callback.onSuccess(credential);
} else {
callback.onFailure(new Exception("No credential found"));
}
}
@Override
public void onError(@NonNull GetCredentialException e) {
android.util.Log.i("CHEOK", "onError " + e);
// Handle errors
callback.onFailure(e);
}
}
);
}
}
Использование Identity.getAuthorizationClient
Другой подход, который я пробовал, — использование Identity.getAuthorizationClient. Но это дает мне нулевое время за все время.
List requestedScopes = java.util.Arrays.asList(
new Scope(DriveScopes.DRIVE_APPDATA),
new Scope("email"),
new Scope("profile"),
new Scope("openid")
);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Task task = Identity.getAuthorizationClient(MyApplication.instance())
.authorize(authorizationRequest);
if (task.isSuccessful()) {
AuthorizationResult authorizationResult = task.getResult();
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
IntentSender intentSender = pendingIntent.getIntentSender();
...
} else {
// Access already granted, continue with user action
Log.i("CHEOK", "Email = " + authorizationResult.toGoogleSignInAccount().getEmail());
Log.i("CHEOK", "getDisplayName = " + authorizationResult.toGoogleSignInAccount().getDisplayName());
Log.i("CHEOK", "getId = " + authorizationResult.toGoogleSignInAccount().getId());
Log.i("CHEOK", "getIdToken = " + authorizationResult.toGoogleSignInAccount().getIdToken());
}
} else {
getCommonExecutor().execute(new Runnable() {
@Override
public void run() {
try {
Tasks.await(task);
try {
AuthorizationResult authorizationResult = task.getResult(ApiException.class);
if (authorizationResult.hasResolution()) {
// Access needs to be granted by the user
PendingIntent pendingIntent = authorizationResult.getPendingIntent();
IntentSender intentSender = pendingIntent.getIntentSender();
...
} else {
// Access already granted, continue with user action
Log.i("CHEOK", "Email = " + authorizationResult.toGoogleSignInAccount().getEmail());
Log.i("CHEOK", "getDisplayName = " + authorizationResult.toGoogleSignInAccount().getDisplayName());
Log.i("CHEOK", "getId = " + authorizationResult.toGoogleSignInAccount().getId());
Log.i("CHEOK", "getIdToken = " + authorizationResult.toGoogleSignInAccount().getIdToken());
}
} catch (ApiException e) {
// TODO:
}
} catch (ExecutionException e) {
// TODO:
} catch (InterruptedException e) {
// TODO:
}
}
});
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79275021/what-is-the-replacement-for-googlesignin-getlastsignedinaccount-when-migrating-t[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия