Firebase 谷歌身份验证使用 android 登录

时间:2020-12-24 19:17:22

标签: java android firebase-authentication google-signin

在我在Android studio上做的项目中,我在用户登录页面放了一个按钮,用google账户登录。账户名出现在Choose an account部分。 在身份验证部分,该名称不会显示为帐户登录。用户的邮件和密码已输入并保存。当我使用该帐户登录应用程序时,我希望它重定向到另一个页面,但它没有重定向到 MainActivity2.java 页面。如果您能提供帮助,我会很高兴。

运行:

    Connected to process 18504 on device 'emulator-5556'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/MultiDex: VM with version 2.1.0 has multidex support
    Installing application
    VM has multidex support, MultiDex support library is disabled.
I/ple.geziprojec: Waiting for a blocking GC ClassLinker
I/ple.geziprojec: WaitForGcToComplete blocked ClassLinker on ClassLinker for 176.388ms
W/ple.geziprojec: Verification of void com.google.android.gms.common.internal.StringResourceValueReader.<init>(android.content.Context) took 177.170ms (118.53 bytecodes/s) (1040B approximate peak alloc)
W/ComponentDiscovery: Class com.google.firebase.dynamicloading.DynamicLoadingRegistrar is not an found.
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
I/FirebaseInitProvider: FirebaseApp initialization successful
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:20 and remote module com.google.android.gms.measurement.dynamite:21
    Selected remote version of com.google.android.gms.measurement.dynamite, version >= 21
V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
W/ple.geziprojec: Verification of void com.google.android.gms.common.api.internal.GoogleApiManager$zaa.connect() took 107.853ms (806.65 bytecodes/s) (2328B approximate peak alloc)
W/ple.geziprojec: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ple.geziprojec: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
W/ple.geziprojec: Verification of void com.google.android.gms.common.internal.BaseGmsClient.zza(int, android.os.IInterface) took 133.587ms (3346.13 bytecodes/s) (5928B approximate peak alloc)
I/ple.geziprojec: The ClassLoaderContext is a special shared library.
I/ple.geziprojec: The ClassLoaderContext is a special shared library.
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
I/DynamiteModule: Considering local module com.google.android.gms.signinbutton_dynamite:0 and remote module com.google.android.gms.signinbutton_dynamite:2
    Selected remote version of com.google.android.gms.signinbutton_dynamite, version >= 2
W/ple.geziprojec: Verification of int com.google.android.gms.common.internal.GmsClientSupervisor$zza.zzq() took 161.972ms (18.52 bytecodes/s) (720B approximate peak alloc)
V/FA: onActivityCreated
D/HostConnection: HostConnection::get() New Host Connection established 0xe9121d40, tid 18553
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xe9124ba0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xe9124ba0: ver 2 0 (tinfo 0xe9455f70) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xe9123ef0, tid 18553
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fe83c000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
W/ple.geziprojec: Verification of void ic.e() took 123.348ms (6809.95 bytecodes/s) (11464B approximate peak alloc)
W/ple.geziprojec: Verification of void ie.<init>(jc) took 152.305ms (98.49 bytecodes/s) (968B approximate peak alloc)
I/OpenGLRenderer: Davey! duration=771ms; Flags=1, IntendedVsync=4143801720841, Vsync=4143835054173, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=4143845992300, AnimationStart=4143846040000, PerformTraversalsStart=4143846105800, DrawStart=4144157390900, SyncQueued=4144354861800, SyncStart=4144360117400, IssueDrawCommandsStart=4144360507700, SwapBuffers=4144536078100, FrameCompleted=4144578165500, DequeueBufferDuration=318500, QueueBufferDuration=1625500, GpuCompleted=0, 
W/ple.geziprojec: Verification of void lt.B() took 115.481ms (207.83 bytecodes/s) (992B approximate peak alloc)
I/Choreographer: Skipped 49 frames!  The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=988ms; Flags=0, IntendedVsync=4143851699017, Vsync=4144668365651, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=4144680002300, AnimationStart=4144680060000, PerformTraversalsStart=4144680717500, DrawStart=4144727417500, SyncQueued=4144728390300, SyncStart=4144731782000, IssueDrawCommandsStart=4144731852000, SwapBuffers=4144734026400, FrameCompleted=4144844020200, DequeueBufferDuration=279000, QueueBufferDuration=16261600, GpuCompleted=0, 
W/ple.geziprojec: Verification of void rc.<clinit>() took 163.597ms (378.98 bytecodes/s) (1416B approximate peak alloc)
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.example.geziproject, 1:1088981466528:android:40238883a0fda69fa1f8c5
I/FA: App measurement initialized, version: 34027
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.example.geziproject
D/FA: Debug-level message logging enabled
V/FA: Connecting to remote service
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 4143853
I/FA: Tag Manager is not found and thus will not be used
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 5
V/FA: Recording user engagement, ms: 4309
V/FA: Activity paused, time: 4148164
V/FA: onActivityCreated
V/FA: Activity resumed, time: 4148325
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 214
V/FA: Activity paused, time: 4148556
D/FA: Application going to the background
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10154; state: ENABLED
V/FA: Activity resumed, time: 4154166
V/FA: Inactivity, disconnecting from the service
W/ConnectionTracker: Exception thrown while unbinding
    java.lang.IllegalArgumentException: Service not registered: ls@9d99311
        at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1757)
        at android.app.ContextImpl.unbindService(ContextImpl.java:1874)
        at android.content.ContextWrapper.unbindService(ContextWrapper.java:792)
        at ci.f(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):1)
        at ci.d(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):2)
        at lt.E(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):9)
        at ld.a(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):3)
        at ef.run(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):3)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at iy.run(:com.google.android.gms.dynamite_measurementdynamite@204713100@20.47.13 (150700-0):5)

Gradle 依赖项:

dependencies {



      implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.firebase:firebase-auth:20.0.1'
    implementation 'com.google.firebase:firebase-database:19.6.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.2'
    implementation 'androidx.navigation:navigation-ui:2.3.2'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.+'
    implementation platform('com.google.firebase:firebase-bom:26.2.0')
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'me.everything:providers-android:1.0.1'
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
    implementation 'com.google.firebase:firebase-auth'


    implementation 'com.google.firebase:firebase-core:18.0.0'
}
apply plugin: 'com.google.gms.google-services'

登录Activity.java:

    public class LoginActivity extends AppCompatActivity {
   private SignInButton signInButton;
   private GoogleSignInClient mGoogleSignInClient;
   private FirebaseAuth mAuth;
   private Button signout;
 
   private final static int RC_SIGN_IN=123;

protected void onStart() {
        super.onStart();
        FirebaseUser user=mAuth.getCurrentUser();
        if(user!=null){
            Intent intent= new Intent(getApplicationContext(),MainActivity2.class);
            startActivity(intent);
        }
}




@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        createRequest();

        signInButton=findViewById(R.id.signin);
        mAuth=FirebaseAuth.getInstance();
        signout=findViewById(R.id.sign_out);



        signInButton.setOnClickListener(v -> signIn());



    }

    private void createRequest() {
        GoogleSignInOptions gso= new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(String.valueOf(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient= GoogleSignIn.getClient(this,gso);
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RC_SIGN_IN){
            Task<GoogleSignInAccount> task=GoogleSignIn.getSignedInAccountFromIntent(data);
            //handleSignInResult(task);
            try{
                GoogleSignInAccount account=task.getResult(ApiException.class);
               Toast.makeText(getApplicationContext(),"giriş başarılı",Toast.LENGTH_LONG).show();
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
            }

        }

    }
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information

                        FirebaseUser user = mAuth.getCurrentUser();
                        Intent intent= new Intent(getApplicationContext(),MainActivity2.class);
                        startActivity(intent);

                    } else {
                        Toast.makeText(LoginActivity.this,"başarısız",Toast.LENGTH_LONG).show();




                    }

                });
    }
MainActivity2.java:


 public class MainActivity2 extends AppCompatActivity {
    TextView name,mail;
    Button logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        logout= findViewById(R.id.logout);
        name=findViewById(R.id.name);
        mail=findViewById(R.id.email);

        GoogleSignInAccount signInAccount= GoogleSignIn.getLastSignedInAccount(this);
        if(signInAccount!=null){
            name.setText(signInAccount.getDisplayName());
            mail.setText(signInAccount.getEmail());
        }

        logout.setOnClickListener(v -> {
            FirebaseAuth.getInstance().signOut();
            Intent intent=new Intent(getApplicationContext(),LoginActivity.class);
            startActivity(intent);
        });
    }
}

0 个答案:

没有答案