2017-07-08 122 views
0

我在我的应用程序中有这个奇怪的问题。我的应用程序具有一个GSigninActivity,它在Splash屏幕后显示,以促进Google和Firebase的单一登录。问题是,在第一次安装和启动时,应用程序直接进入MainActivity而不询问登录。我必须从那里注销,然后登录。它是如何登录数据的一些存在。请帮忙。Android应用程序仍然保持连接到谷歌登录,即使卸载并重新安装它

GSigninActivity代码

package com.example.joelmathew.firebidtest; 

import android.annotation.TargetApi; 
import android.content.Intent; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.support.annotation.NonNull; 
import android.support.v4.content.ContextCompat; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.view.WindowManager; 
import android.widget.TextView; 
import android.widget.Toast; 


import com.example.joelmathew.firebidtest.models.User; 
import com.google.android.gms.auth.api.Auth; 
import com.google.android.gms.auth.api.signin.GoogleSignInAccount; 
import com.google.android.gms.auth.api.signin.GoogleSignInResult; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.ResultCallback; 
import com.google.android.gms.common.api.Status; 
import com.google.android.gms.tasks.OnCompleteListener; 
import com.google.android.gms.tasks.Task; 
import com.google.firebase.FirebaseApp; 
import com.google.firebase.auth.AuthCredential; 
import com.google.firebase.auth.AuthResult; 
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.auth.FirebaseUser; 
import com.google.firebase.auth.GoogleAuthProvider; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 

import com.google.android.gms.auth.api.signin.GoogleSignInOptions; 
import com.google.android.gms.common.api.GoogleApiClient; 

/** 
* Created by Joel Mathew on 01-Jul-17. 
*/ 

public class GSignInActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { 

    private static final String TAG = "GoogleActivity"; 
    private static final int RC_SIGN_IN = 9001; 

    // [START declare_auth] 
    private FirebaseAuth mAuth; 
    private DatabaseReference mDatabase; 
    // [END declare_auth] 

    protected GoogleApiClient mGoogleApiClient; 
    private String signout="false"; 
    public String personName; 
    // private TextView mStatusTextView; 
    // private TextView mDetailTextView; 

    @Override 
    @TargetApi(21) 
    protected void onCreate(Bundle savedInstanceState) { 
     FirebaseApp.initializeApp(this); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.gsignin_activity); 

     getSupportActionBar().hide(); 
     Window w = getWindow(); 
     w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
     w.setStatusBarColor(ContextCompat.getColor(this, R.color.statusSplash)); 




     // Views 
     // mStatusTextView = (TextView) findViewById(R.id.status); 
     // mDetailTextView = (TextView) findViewById(R.id.detail); 

     // Button listeners 
     findViewById(R.id.sign_in_button).setOnClickListener(this); 
     //findViewById(R.id.sign_out_button).setOnClickListener(this); 
     // findViewById(R.id.disconnect_button).setOnClickListener(this); 

     // [START config_signin] 
     // Configure Google Sign In 
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestIdToken(getString(R.string.default_web_client_id)) 
       .requestEmail() 
       .build(); 
     // [END config_signin] 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) 
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
       .build(); 

     // [START initialize_auth] 
     mDatabase = FirebaseDatabase.getInstance().getReference(); 
     mAuth = FirebaseAuth.getInstance(); 
     // [END initialize_auth] 


     /*Bundle b = getIntent().getExtras(); 
     if(b!=null) { 
      signout = b.getString("Signout"); 
      if (signout.equals("true")) { 
       Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
         new ResultCallback<Status>() { 
          @Override 
          public void onResult(@NonNull Status status) { 
           updateUI(null); 
          } 
         }); 
      } 
     }*/ 


    } 

    // [START on_start_check_user] 
    @Override 
    public void onStart() { 
     super.onStart(); 
     // Check if user is signed in (non-null) and update UI accordingly. 
     FirebaseUser currentUser = mAuth.getCurrentUser(); 
     updateUI(currentUser); 
    } 
    // [END on_start_check_user] 

    // [START onactivityresult] 
    @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); 
      if (result.isSuccess()) { 
       // Google Sign In was successful, authenticate with Firebase 
       GoogleSignInAccount account = result.getSignInAccount(); 
       personName = account.getDisplayName(); 
       Log.v("LOG_VAL","GSigninActivity,onActivityResult: Person Name : "+ personName); 
       PostKeyHolder.setGlobalPersonName(personName); 
       Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName()); 


       //String Number = account. 
       firebaseAuthWithGoogle(account); 
      } else { 
       // Google Sign In failed, update UI appropriately 
       // [START_EXCLUDE] 
       updateUI(null); 
       // [END_EXCLUDE] 
      } 
     } 
    } 
    // [END onactivityresult] 

    // [START auth_with_google] 
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { 
     Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); 
     // [START_EXCLUDE silent] 
     showProgressDialog(); 
     // [END_EXCLUDE] 
     final GoogleSignInAccount temp = acct; 

     AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); 
     mAuth.signInWithCredential(credential) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         if (task.isSuccessful()) { 
          // Sign in success, update UI with the signed-in user's information 
          Log.d(TAG, "signInWithCredential:success"); 
          FirebaseUser user = mAuth.getCurrentUser(); 
          personName = temp.getDisplayName(); 
          Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: Person Name : "+ personName); 
          PostKeyHolder.setGlobalPersonName(personName); 
          Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: REturned from setting Person Name : "+ PostKeyHolder.getGlobalPersonName()); 
          updateUI(user); 
          onAuthSuccess(user); 
         } else { 
          // If sign in fails, display a message to the user. 
          Log.w(TAG, "signInWithCredential:failure", task.getException()); 
          Toast.makeText(GSignInActivity.this, "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
          updateUI(null); 
         } 

         // [START_EXCLUDE] 
         hideProgressDialog(); 
         // [END_EXCLUDE] 
        } 
       }); 
    } 
    // [END auth_with_google] 

    // [START signin] 
    private void signIn() { 
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
     startActivityForResult(signInIntent, RC_SIGN_IN); 
    } 
    // [END signin] 

    private void signOut() { 
     // Firebase sign out 
     mAuth.signOut(); 

     // Google sign out 
     Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
       new ResultCallback<Status>() { 
        @Override 
        public void onResult(@NonNull Status status) { 
         updateUI(null); 
        } 
       }); 
    } 


    private void onAuthSuccess(FirebaseUser user) { 
     String username = usernameFromEmail(user.getEmail()); 
     personName = user.getDisplayName(); 

     Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Person Name : "+ personName); 
     PostKeyHolder.setGlobalPersonName(personName); 
     Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName()); 



     // Write new user 
     writeNewUser(user.getUid(), username, user.getEmail(),personName); 

     // PostKeyHolder.setGlobalPersonName(personName); //Setting Global Person handler 

     // Go to MainActivity 

     //Intent apiClient = new Intent(GSignInActivity.this,MainActivity.class); 
     //apiClient.putExtra("ApiClient",mGoogleApiClient); 
     updateUI(user); 
     //startActivity(new Intent(GSignInActivity.this, MainActivity.class)); 
     finish(); 
    } 

    private String usernameFromEmail(String email) { 
     if (email.contains("@")) { 
      return email.split("@")[0]; 
     } else { 
      return email; 
     } 
    } 

    // [START basic_write] 
    private void writeNewUser(String userId, String username, String email, String personName) { 
     User user = new User(username, email, personName); 
     Log.v("LOG_VAL","GSigninActivity,writeNewUser: Person Name : "+ personName); 
     PostKeyHolder.setGlobalPersonName(personName); 
     Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName()); 

     mDatabase.child("GoogleSignIn").child(userId).setValue(user); 
     mDatabase.child("users").child("GoogleSignIn").child(userId).setValue(user); 
    } 
    // [END basic_write] 


    private void revokeAccess() { 
     // Firebase sign out 
     mAuth.signOut(); 

     // Google revoke access 
     Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
       new ResultCallback<Status>() { 
        @Override 
        public void onResult(@NonNull Status status) { 
         //updateUI(null); 
        } 
       }); 
    } 

    private void updateUI(FirebaseUser user) { 
     hideProgressDialog(); 
     if (user != null) { 

      personName = user.getDisplayName(); 
      Log.v("LOG_VAL","GSigninActivity,updateUI: Person Name : "+ personName); 

      PostKeyHolder.setGlobalPersonName(personName); 
      Log.v("LOG_VAL","GSigninActivity,updateUI: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName()); 

      // mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail())); 
      // mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid())); 

      findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); 
      startActivity(new Intent(GSignInActivity.this, MainActivity.class)); 
      finish(); 
      // findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE); 
     } else { 


      // mStatusTextView.setText(R.string.signed_out); 
//   mDetailTextView.setText(null); 

      findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); 
     // findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE); 
     } 
    } 

    @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); 
     Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onClick(View v) { 
     int i = v.getId(); 
     if (i == R.id.sign_in_button) { 
      signIn(); 
     } //else if (i == R.id.sign_out_button) 
     /* // { 
      signOut(); 
     } //else if (i == R.id.disconnect_button) 
     /* { 
      //evokeAccess(); 
     }*/ 
    } 



} 

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.joelmathew.firebidtest"> 

    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme" /> 
     <activity android:name=".NewPostActivity" 
      android:windowSoftInputMode="adjustPan"/> 

     <activity android:name=".BuyNow"/> 
     <activity android:name=".BidMainScreen3" 
      android:windowSoftInputMode="adjustPan"/> 

     <!--activity android:name=".SignInActivity"--> 
      <!--intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter--> 
     <!--/activity--> 

     <activity android:name=".SplashScreen"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 

     </activity> 

     <activity android:name=".GSignInActivity"></activity> 
     <activity android:name=".PostDetailActivity"></activity> 
     <activity android:name=".TopBidsActivity"></activity> 
     <activity android:name=".OrdersActivity"></activity> 
    </application> 


</manifest> 
+0

没有人会通读所有的代码。我的猜测是你的手机存储了一个长期访问令牌,可能在首选项中。 –

+0

你能显示你的'AndroidManifest.xml'吗? –

+0

@TGMCians我编辑了我的答案以包含清单文件。请看一下。谢谢你节省时间。 –

回答

1

看起来。

自从Android 6.0(API 23)开始,Android提供了“自动备份应用程序”功能,以便开发人员快速向其应用程序添加备份功能。自动备份功能会将应用数据上传到用户的Google云端硬盘帐户,并由用户的Google帐户凭据保护。数据量限制为每个用户25MB,并且不需要存储备份数据。

您可能想要禁用备份。在这里详细阅读https://developer.android.com/guide/topics/data/autobackup.html#Files

0

你需要清除应用数据需要时。像退出或类似的东西。就像你在你的AndroidManifest.xmlandroid:allowBackup="true"这将解决所有您的问题

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
          ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE)) 
            .clearApplicationUserData(); // note: it has a return value! 
         } else { 
          clearApplicationData(); 
         } 

public void clearApplicationData() { 
     File cache = getCacheDir(); 
     File appDir = new File(cache.getParent()); 
     if (appDir.exists()) { 
      String[] children = appDir.list(); 
      for (String s : children) { 
       if (!s.equals("lib")) { 
        deleteDir(new File(appDir, s)); 
        Log.i("TAG", "File /data/data/APP_PACKAGE/" + s + " DELETED"); 
       } 
      } 
     } 
    } 
相关问题