我想将Google登录整合到我的游戏中。但是,我不希望使用按钮进行登录过程,一旦用户打开应用程序,我希望它发生。 每当创建MenuActivity时,它都会要求选择要登录的帐户。但我希望它只选择一次帐户(第一次)并记住每次。这是代码:
public class MenuActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
if(!mGoogleApiClient.isConnected()){
signIn();
}
}
public void startGame(View view){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
} else {
}
}
}
答案 0 :(得分:0)
首先创建SharedPreferences
public void saveUser (String key, String value ) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
public String getUser (String key) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
return pref.getString(key, "");
}
检查用户的电子邮件是否为空,添加SharedPreferences
if(!mGoogleApiClient.isConnected() && getUser("email").isEmpty() ){
signIn();
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
saveUser("email", acct.getEmail());
saveUser("name", acct.getDisplayName());
} else {
}
}