通过单击第二个活动中的注销按钮,Google加上一个活动的登录和第二个活动的注销

时间:2015-08-12 04:57:43

标签: android logout google-plus-signin

Google plus从一个活动登录(此活动以共享首选项存储登录详细信息)并从另一个活动注销(此活动会检索登录详细信息).Logout活动具有注销按钮。 我的问题:我需要从第一个活动(AndroidGooglePlusExample)登录,登录详细信息(用户名,userimage,emailid)存储在共享首选项中。我在第二个活动(HomePage)中检索这些值,并在那里显示它,从第二个活动我需要在点击退出按钮时注销。请帮我解决这个问题。这是我的登录活动

 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);
        }
    }
}

这是我的第二项活动

        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 个答案:

答案 0 :(得分:0)

根据最初的聊天讨论,您有一个实现Android Login with Google Plus Account的工作代码示例,但您需要根据您的要求对其进行修改。我只能提出一个想法,但无法给出一个例子!!

所以这是我的建议,以满足你的任务完成。

  1. 正如您在帖子中提到的,您可以成功登录Google+帐户。成功登录后,您需要将Shared Preferences中的用户凭据(用户名和密码)以及布尔值(true / false)存储为登录状态(已登录/已注销)
  2. 然后,当您导航到第二个屏幕时,您可以在其中放置一个按钮并为其设置操作以进行注销。单击按钮后,您需要检查共享首选项中的布尔值,如果是登录,您可以注销Google+并使用新值更新您的首选项(用户名 - null,密码-null,布尔状态-false)
  3. 此链接可以帮助您加入角色