在Android项目中使用Google提供的GoogleApiClient类,可以轻松获取应用程序默认凭据。以下是示例代码:
dependencies {
implementation 'com.google.android.gms:play-services-auth:16.0.1'
}
public class MyApp extends Application implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = MyApp.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
@Override
public void onCreate() {
super.onCreate();
//创建GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */ , this /* OnConnectionFailedListener */ )
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "GoogleApiClient Connected!");
// 获取默认的凭据
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (account != null) {
String name = account.getDisplayName();
String email = account.getEmail();
String id = account.getId();
Log.i(TAG, "name:" + name);
Log.i(TAG, "email:" + email);
Log.i(TAG, "id:" + id);
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient Suspended!");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient Connection Failed!");
}
}
public class MainActivity extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取GoogleApiClient实例
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
上一篇:Android项目的设置问题