-->

Google plus login from one activity and logout fro

2019-08-04 07:36发布

问题:

Google plus login from one activity (this activity stored the login details in shared preference) and logout from another activity (this activity retreives the login details).Logout activity has the logout button. My issue:I need to login from first activity (AndroidGooglePlusExample) and the login details (username,userimage,emailid) are stored in shared preference. I retreive these values in second activity(HomePage), and display it there, and from this second activity I need to logout on clicking the logout button. Please help me to solve this issue .This is my login activity

 public class AndroidGooglePlusExample extends Activity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 0;

    // Google client to communicate with Google
    private GoogleApiClient mGoogleApiClient;

    private boolean mIntentInProgress;
    private boolean signedInUser;
    private ConnectionResult mConnectionResult;
    private SignInButton signinButton;
    private ImageView image;
    private TextView username, emailLabel;
    private LinearLayout profileFrame, signinFrame;
    private SharedPreferences mPrefs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        signinButton = (SignInButton) findViewById(R.id.button1);
        signinButton.setOnClickListener(this);

    //  image = (ImageView) findViewById(R.id.image);
    //  username = (TextView) findViewById(R.id.username);
    //  emailLabel = (TextView) findViewById(R.id.email);

        profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
    //  signinFrame = (LinearLayout) findViewById(R.id.signinFrame);

        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build()).addScope(Plus.SCOPE_PLUS_LOGIN).build();
    }

    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
            return;
        }

        if (!mIntentInProgress) {
            // store mConnectionResult
            mConnectionResult = result;

            if (signedInUser) {
                resolveSignInError();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
        switch (requestCode) {
        case RC_SIGN_IN:
            if (responseCode == RESULT_OK) {
                signedInUser = false;

            }
            mIntentInProgress = false;
            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
            break;
        }
    }

    @Override
    public void onConnected(Bundle arg0) {
        signedInUser = false;
        Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
        getProfileInformation();
    }

    private void updateProfile(boolean isSignedIn) {
//      if (isSignedIn) {
//          signinFrame.setVisibility(View.GONE);
//          profileFrame.setVisibility(View.VISIBLE);
//
//      } else {
//          signinFrame.setVisibility(View.VISIBLE);
//          profileFrame.setVisibility(View.GONE);
//      }
        if (isSignedIn) {
             Intent intent = new Intent(AndroidGooglePlusExample.this, HomePage.class);
             startActivity(intent);   

        }
    }

    private void getProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
                String personName = currentPerson.getDisplayName();
                String personPhotoUrl = currentPerson.getImage().getUrl();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

                username.setText(personName);
                emailLabel.setText(email);

                new LoadProfileImage(image).execute(personPhotoUrl);

                // update profile frame with new info about Google Account
                // profile
                updateProfile(true);
                //storing details in shared preference
                 if(mPrefs == null){
                        mPrefs = this.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
                    }
                 SharedPreferences.Editor editor = mPrefs.edit();
                 //editor.putInt("login",401);
                 editor.putString("Guser_name", personName);
                 editor.putString("Guserpic_url", personPhotoUrl);
                 editor.putString("Guser_email", email);
                 editor.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int cause) {
        mGoogleApiClient.connect();
        updateProfile(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            googlePlusLogin();
            break;
        }
    }

    public void signIn(View v) {
        googlePlusLogin();
    }

//  public void logout(View v) {
//      googlePlusLogout();
//  }

    private void googlePlusLogin() {
        if (!mGoogleApiClient.isConnecting()) {
            signedInUser = true;
            resolveSignInError();
        }
    }

//  private void googlePlusLogout() {
//      if (mGoogleApiClient.isConnected()) {
//          Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
//          mGoogleApiClient.disconnect();
//          mGoogleApiClient.connect();
//          updateProfile(false);
//      }
//  }

    // download Google Account profile image, to complete profile
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView downloadedImage;

        public LoadProfileImage(ImageView image) {
            this.downloadedImage = image;
        }

        protected Bitmap doInBackground(String... urls) {
            String url = urls[0];
            Bitmap icon = null;
            try {
                InputStream in = new java.net.URL(url).openStream();
                icon = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return icon;
        }

        protected void onPostExecute(Bitmap result) {
            downloadedImage.setImageBitmap(result);
        }
    }
}

This is my second activity

        public class HomePage extends Fragment {
            SharedPreferences mPrefs;
             Button logout_btn;
            // Google client to communicate with Google
                private GoogleApiClient mGoogleApiClient;
             @Override
             public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {

              View rootView = inflater.inflate(R.layout.activity_home_page, container, false);
        //      TextView name =(TextView)rootView.findViewById(R.id.username);
        //      TextView emailid =(TextView)rootView.findViewById(R.id.email);
        //      ImageView myimage=(ImageView)rootView.findViewById(R.id.image);
              logout_btn=(Button)rootView.findViewById(R.id.logout);

              logout_btn.setOnClickListener(new OnClickListener() {

                  @Override
                  public void onClick(View v) {
                      // TODO Auto-generated method stub
                      Editor editor = mPrefs.edit();
                      String name = mPrefs.getString("Guser_name", "");
                      Log.d("", name);
                      String pic = mPrefs.getString("Guserpic_url", "");
                      String email = mPrefs.getString("Guser_email", "");



                  }

                  public void logout(View v) {
                    googlePlusLogout();
                }


                  private void googlePlusLogout() {
                    if (mGoogleApiClient.isConnected()) {
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.disconnect();
                        mGoogleApiClient.connect();
              //            updateProfile(false);
                    }
                }


                  });
              return rootView;
              }
        }




this is my login xml

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:padding="15dp"
            tools:context=".AndroidGooglePlusExample" >


            <LinearLayout
                android:id="@+id/signinFrame"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:gravity="center"
                android:orientation="vertical"
                android:visibility="visible" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:padding="10dp"
                    android:text="@string/loginText"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#ffffff" />

                <com.google.android.gms.common.SignInButton
                    android:id="@+id/button1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:textSize="18dp" />




logout xml

         <LinearLayout
                android:id="@+id/profileFrame"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:gravity="center"
                android:orientation="vertical"
                 >

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="80dp"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:textSize="20dp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:textSize="16dp" />

                <Button
                    android:id="@+id/logout"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:onClick="logout"
                    android:padding="10dp"
                    android:text="@string/logout"
                    android:textSize="18dp" />
            </LinearLayout>

回答1:

As per the initial chat discussion, you have a working code example for implementation of Android Login with Google Plus Account but you need to modify it with as per your requirement. I can give an idea only but unable to give an example for it !!

So here is my suggestions to meet your task completion.

  1. As you mentioned in the post your able to login with Google+ account successfully. After successful login you need to store the credentials of the user (user name & password) in Shared Preferences along with a Boolean value (true/false) as a login status (logged-in /logged-out)
  2. Then when your navigating to the second screen you can place a button in that and set an action to it for logout. after clicking the button you need to check the Boolean value in the shared preferences and if it is login you can logout the Google+ and update your preferences with new values ( username - null, password -null , Boolean status -false)

This links may help you to Role on

  • Start integrating Google+ into your Android

  • Google Plus Account in Android Example