如何处理退出按钮单击fb sdk 4.18.0?

时间:2016-12-22 07:50:24

标签: android facebook-sdk-4.0

我想在用户从我的应用程序注销时执行某些功能,他已登录使用Facebook ,但点击按钮登录 onSuccess()是被叫,用户登录并显示一个注销按钮。点击注销按钮,用户只需注销,但在此期间调用没有特定的功能因此我无法处理在退出时执行一些任务。请帮助我。谢谢。我使用了facebook sdk 4.18.0。

这是我的LoginActivity代码,其中包含google和facebook登录按钮。

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private SignInButton googleLoginButton;
    private Button btnSignOut;
    private Button btnRevokeAccess;
    private AccessTokenTracker tokenTracker;
    private ProfileTracker profileTracker;
    private TextView mText;
    private ImageView profile_pic;
    private ProgressDialog mProgressDialog;
    private LoginButton fbLoginButton;
    private GoogleSignInResult result1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //FACEBOOK SDK
        FacebookSdk.sdkInitialize(getApplicationContext());
        mcallbackManager = CallbackManager.Factory.create();
        tokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

            }
        };
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            }
        };
        profileTracker.startTracking();
        tokenTracker.startTracking();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mText = (TextView) findViewById(R.id.txt);
        profile_pic = (ImageView) findViewById(R.id.profile_pic);
        googleLoginButton = (SignInButton) findViewById(R.id.google_login_button);
        btnSignOut = (Button) findViewById(R.id.btn_sign_out);
        btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
        fbLoginButton = (LoginButton) findViewById(R.id.fb_login_button);
        fbLoginButton.setReadPermissions("user_friends");
        fbLoginButton.registerCallback(mcallbackManager, callback);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        googleLoginButton.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnRevokeAccess.setOnClickListener(this);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestProfile().requestId().requestEmail().build();
        mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

        googleLoginButton.setSize(SignInButton.SIZE_STANDARD);
        googleLoginButton.setScopes(gso.getScopeArray());
    }

    @Override
    public void onDestroy() {
        tokenTracker.stopTracking();
        profileTracker.stopTracking();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
        mcallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
      }

    private static final int RC_SIGN_IN = 007;

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

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                updateUI(false);
            }
        });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                updateUI(false);
            }
        });
    }

    private void handleSignInResult(GoogleSignInResult result) {
        if (result.isSuccess()) {
            //Signed in successfully
            (new SessionManager(LoginActivity.this)).setLogin(true);
            GoogleSignInAccount acct = result.getSignInAccount();
            String personName = acct.getDisplayName();
            String email = acct.getEmail();
            mText.setText("Welcome " + personName + "  " + email + "  buddy!!");
            Picasso.with(this).load(acct.getPhotoUrl()).into(profile_pic);
            updateUI(true);
        } else {
            updateUI(false);
        }
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.google_login_button:
                signIn();
                break;
            case R.id.btn_sign_out:
                signOut();
                break;
            case R.id.btn_revoke_access:
                revokeAccess();
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading");
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            googleLoginButton.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.VISIBLE);
            fbLoginButton.setVisibility(View.GONE);
            btnSignOut.setEnabled(true);
            btnRevokeAccess.setEnabled(true);
            googleLoginButton.setEnabled(false);
            btnRevokeAccess.setVisibility(View.VISIBLE);
             } else {
            googleLoginButton.setVisibility(View.VISIBLE);
            fbLoginButton.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);
            btnSignOut.setEnabled(false);
            btnRevokeAccess.setEnabled(false);
            googleLoginButton.setEnabled(true);
            btnRevokeAccess.setVisibility(View.GONE);
            mText.setText("Hello Buddy Log in to know your name!!");
            profile_pic.setImageResource(R.drawable.common_full_open_on_phone);

        }
    }

    private CallbackManager mcallbackManager;
    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            (new SessionManager(LoginActivity.this)).setLogin(true);
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();
            if (profile != null) {
                // googleLoginButton.setVisibility(View.INVISIBLE);
                mText.setText("Welcome " + profile.getName() + " buddy!!");
                Picasso.with(LoginActivity.this).load(profile.getProfilePictureUri(50, 50)).into(profile_pic);
                //"https://graph.facebook.com/" +profile.getId() + "/picture?type=large"
            }
        }

        @Override
        public void onCancel() {

            Snackbar.make(findViewById(R.id.rel_layout), "Login Attempt Cancelled!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();

        }

        @Override
        public void onError(FacebookException error) {
            Snackbar.make(findViewById(R.id.rel_layout), error.getMessage().toString(), Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        Profile profile=Profile.getCurrentProfile();
        if(profile!=null)
            displayWelcomeMessage(1);
       result1=Auth.GoogleSignInApi.getSignInResultFromIntent(new Intent());
    }
    private void displayWelcomeMessage(int i){
        mText.setText("Hello "+Profile.getCurrentProfile().getName());

    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用AccessTokenTracker。您必须侦听对空标记的更改。表示用户在单击注销时注销

tokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
            if (currentAccessToken == null) {
                    Log.d("FB", "User Logged Out.");
                    //Do your task here after logout
                }
        }
    };
       tokenTracker.startTracking();

您还可以使用自定义按钮注销用户并在那里使用您的方法.. 只需隐藏loginButton的视图,然后点击onClick

上的custom_logout按钮
custom_logout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            LoginManager.getInstance().logOut();
            //Do your task
        }
    });