我是Android Studio的新手,我尝试在第一个活动中使用Google登录按钮制作一个小型应用程序。在我点击Google登录按钮并选择帐户后,该应用程序会与登录按钮保持相同的活动,并且不会切换到下一个帐户。
我厌倦了更改google-services.json文件,但没有希望。
这是带有按钮的MainActivity
package routes.example.route;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int RC_SIGN_IN = 0;
SignInButton signInButton;
GoogleSignInClient mGoogleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI();
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
protected void updateUI(){
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if(account!=null){
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
super.onStart();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
updateUI();
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
updateUI();
}
}
}
这是登录按钮单击并选择帐户后以及登录期间logcat所显示的内容。
2019-07-23 09:10:18.413 8908-8908/routes.example.route D/HwCust: Create obj success use class android.app.HwCustActivityImpl
2019-07-23 09:10:18.415 8908-8908/routes.example.route D/HwCust: Create obj success use class android.app.HwCustHwWallpaperManagerImpl
2019-07-23 09:10:18.431 8908-10612/routes.example.route D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=624539, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=190881185532362415}]
2019-07-23 09:10:18.445 8908-8908/routes.example.route D/ActivityThread: add activity client record, r= ActivityRecord{463f641 token=android.os.BinderProxy@2d1f2c5 {routes.example.route/com.google.android.gms.auth.api.signin.internal.SignInHubActivity}} token= android.os.BinderProxy@2d1f2c5
2019-07-23 09:10:18.451 8908-8920/routes.example.route I/zygote64: Do full code cache collection, code=124KB, data=103KB
2019-07-23 09:10:18.452 8908-8920/routes.example.route I/zygote64: After code cache collection, code=111KB, data=63KB
2019-07-23 09:10:18.453 8908-8978/routes.example.route D/OpenGLRenderer: HWUI Binary is enabled
2019-07-23 09:10:18.460 8908-8908/routes.example.route I/PressGestureDetector: onAttached begin
2019-07-23 09:10:18.461 8908-8908/routes.example.route I/PressGestureDetector: onAttached end
2019-07-23 09:10:18.462 8908-10613/routes.example.route I/PressGestureDetector: HiTouch restricted: AboardArea.
2019-07-23 09:10:18.478 8908-8978/routes.example.route D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
2019-07-23 09:10:18.487 8908-10612/routes.example.route D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=190881185532362415, firebase_screen_class(_sc)=SignInHubActivity, firebase_screen_id(_si)=190881185532362419}]
2019-07-23 09:10:18.534 8908-8978/routes.example.route D/OpenGLRenderer: HWUI Binary is enabled
2019-07-23 09:10:18.536 8908-8908/routes.example.route W/InputMethodManager: startInputReason = 1
2019-07-23 09:10:18.537 8908-8908/routes.example.route W/InputMethodManager: startInputOrWindowGainedFocus failed. Window focus may have already been lost. win=android.view.ViewRootImpl$W@6a02c79 view=DecorView@845ffd4[SignInHubActivity],focus=false,windowFocus=true,window=android.view.ViewRootImpl$W@6a02c79,temporaryDetach=false
2019-07-23 09:10:18.551 8908-10612/routes.example.route D/FA: Connected to remote service
2019-07-23 09:10:22.583 8908-8908/routes.example.route W/InputMethodManager: startInputReason = 1
2019-07-23 09:10:22.713 8908-8908/routes.example.route W/InputMethodManager: startInputReason = 1
2019-07-23 09:10:22.729 8908-8978/routes.example.route W/libEGL: EGLNativeWindowType 0x739775c010 disconnect failed
2019-07-23 09:10:22.730 8908-10612/routes.example.route D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=SignInHubActivity, firebase_previous_id(_pi)=190881185532362419, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=190881185532362415}]
2019-07-23 09:10:22.760 8908-8908/routes.example.route D/ActivityThread: Remove activity client record, r= ActivityRecord{463f641 token=android.os.BinderProxy@2d1f2c5 {routes.example.route/com.google.android.gms.auth.api.signin.internal.SignInHubActivity}} token= android.os.BinderProxy@2d1f2c5
答案 0 :(得分:1)
在UpdateUI
方法中,为什么要调用GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
以及super.onStart()?我不知道。
我认为您在handleSignInResult
方法中遇到了例外情况
您需要优化几件事。
您是否在handleSignInResult
方法中检查了任何异常?因为你
在UpdateUI
中也称为catch block
在handleSignInResult
中,您获得了GoogleSignInAccount
,可以在account
方法中传递updateUI
变量。
通过updateUI
方法,您可以检查account
参数是否为空,然后转到下一个活动。
代码时间:
更新您的updateUi
方法:
protected void updateUI(GoogleSignInAccount account){
if(account!=null){
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}else{
//Show alert that an exception occured.
}
//super.onStart(); remove this line
}
现在您必须修改以下方法:
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
Log.d("ExceptionTag",e.getMessage());
// Please check that you got any exception here or not.
updateUI(null);
}
}
答案 1 :(得分:0)
此代码很好用,祝您好运
public class MainActivity extends AppCompatActivity {
int RC_SIGN_IN = 0;
SignInButton signInButton;
GoogleSignInClient mGoogleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this,gso);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent,RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
startActivity(new Intent(MainActivity.this,Main2Activity.class));
} catch (ApiException e) {
Log.w("Google Sign In Error " , "signInResult:failed code : " + e.getStatusCode());
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStart() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null){
startActivity(new Intent(MainActivity.this,Main2Activity.class));
}
super.onStart();
}
}
ClassTwo
public class Main2Activity extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
Button sign_out;
TextView nameTV,emailTV,idTV;
ImageView photoIV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
sign_out = findViewById(R.id.log_out);
nameTV = findViewById(R.id.name);
emailTV = findViewById(R.id.email);
idTV = findViewById(R.id.id);
photoIV = findViewById(R.id.photo);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(Main2Activity.this);
if (acct != null){
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
nameTV.setText("Name : " + personName);
emailTV.setText("Email : " + personEmail);
idTV.setText("ID : " + personId);
Glide.with(this).load(personPhoto).into(photoIV);
}
sign_out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signOut();
}
});
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(Main2Activity.this, "Successfully signed out ", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Main2Activity.this,MainActivity.class));
finish();
}
});
}
}