android - 如何处理 fb sdk 4.18.0 中的注销按钮单击?

标签 android facebook-sdk-4.0

当用户从我的应用程序注销时,我想执行一些功能,他已经登录了 using 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());

    }
}

最佳答案

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

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 的 View 并监听 custom_logout 按钮 onClick

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

关于android - 如何处理 fb sdk 4.18.0 中的注销按钮单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278182/

相关文章:

android - 登录 : after going to another activity app forgot Facebook picture, 和名称文本

android - Facebook 登录按钮导致崩溃

ios - FBSDKLoginManager 返回 "You have already authorized foobar"并且不重定向到我的 View

java - 如何在 Android 中设置带有特定步骤的进度条?

android - 如何防止系统杀死我的 'foreground' 服务?

android - 无法在 Android 模拟器 - Windows 上运行 React-Native 应用程序

安卓工作室问题 : Could not find ads:AdQuality:unspecified

java - GPS 应用程序可以在模拟器上运行,但不能在我的手机上运行

c# - 如何在 monodroid 中删除用于编辑文本的 TextChangedListener

angularjs - 使用 Ionic Framework v1 进行 Facebook 分析