androidgoogle-signinandroid-googleapiclient

Android App still remains connected to Google Sign in even after Uninstalling and reinstalling it


I have this strange problem in my App. My app has a GSigninActivity which is shown after Splash screen to facilitate Single Sign On with Google and Firebase. The problem is that on First Install and Launch, the app directly goes MainActivity without asking for Sign In.I have to the log Out from there and then Sign In. How is it that some Sign in data is present. Please Help.

GSigninActivity Code

    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>

Solution

  • Looks like you have android:allowBackup="true" in your AndroidManifest.xml.

    Since Android 6.0 (API 23), Android has offered the Auto Backup for Apps feature as a way for developers to quickly add backup functionality to their apps. Auto Backup preserves app data by uploading it to the user's Google Drive account, where it is protected by the user's Google account credentials. The amount of data is limited to 25MB per user of your app and there is no charge for storing backup data.

    You may want to disable backups. Read here in detail https://developer.android.com/guide/topics/data/autobackup.html#Files