简体   繁体   English

成功登录android facebook应用程序并在新页面上获取注销按钮后如何开始新活动并隐藏登录页面

[英]How to start a new activity and hide login page after successful login in android facebook app and get logout button on new page

I am integrating facebook app with my android app and I don't want to perform default behaviour of android facebook app ie after successful login I don't want to come back on same login page and get the logout button there.我正在将 facebook 应用程序与我的 android 应用程序集成,我不想执行 android facebook 应用程序的默认行为,即成功登录后我不想回到同一个登录页面并在那里获得注销按钮。 After successful login it quickly start a new activity having logout button there and login page doesn't appear on return back from login.成功登录后,它会快速启动一个具有注销按钮的新活动,并且登录页面不会出现在从登录返回时。 Here is my main activity Java class code:这是我的主要活动 Java 类代码:

package com.example.facebook;

import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;

public class MainActivity extends FragmentActivity {

    private LoginButton loginBtn;
    private Button postImageBtn;
    private Button updateStatusBtn;

    private TextView userName;

    private UiLifecycleHelper uiHelper;

    private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

    private static String message = "Sample status posted from android app";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        uiHelper = new UiLifecycleHelper(this, statusCallback);
        uiHelper.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    
    

        userName = (TextView) findViewById(R.id.user_name);
        loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
        loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                if (user != null) {
                    
                    userName.setText("Hello, " + user.getName());
                } else {
                    userName.setText("You are not logged");
                }
            }
        });
        
        

        postImageBtn = (Button) findViewById(R.id.post_image);
        postImageBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                postImage();
            }
});

        updateStatusBtn = (Button) findViewById(R.id.update_status);
        updateStatusBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });

        buttonsEnabled(false);
    }

    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                buttonsEnabled(true);
                 if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()){
                     Intent i = new Intent(MainActivity.this,nextscreen.class);
                    startActivity(i);
                }
        
        
                Log.d("FacebookSampleActivity", "Facebook session opened");
            } else if (state.isClosed()) {
                buttonsEnabled(false);
                
                Log.d("FacebookSampleActivity", "Facebook session closed");
            }
        }
    };

    public void buttonsEnabled(boolean isEnabled) {
    
        postImageBtn.setEnabled(isEnabled);
        updateStatusBtn.setEnabled(isEnabled);
    }

    public void postImage() {
        if (checkPermissions()) {
            Bitmap img = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher);
            Request uploadRequest = Request.newUploadPhotoRequest(
                    Session.getActiveSession(), img, new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                        Toast.makeText(MainActivity.this,
                                    "Photo uploaded successfully",
                                    Toast.LENGTH_LONG).show();
                        }
                });
            uploadRequest.executeAsync();
        } else {
            requestPermissions();
}
    }

    public void postStatusMessage() {
        if (checkPermissions()) {
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            if (response.getError() == null)
                                Toast.makeText(MainActivity.this,
                                        "Status updated successfully",
                                        Toast.LENGTH_LONG).show();
                        }
                    });
            request.executeAsync();
        } else {
            requestPermissions();
        }
    }

    public boolean checkPermissions() {
        Session s = Session.getActiveSession();
        if (s != null) {
            return s.getPermissions().contains("publish_actions");
        } else
            return false;
    }

    public void requestPermissions() {
        Session s = Session.getActiveSession();
        if (s != null)
            s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                    this, PERMISSIONS));
    }

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    //  buttonsEnabled(Session.getActiveSession().isOpened());
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    //  Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        // if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()){
         //    Intent i = new Intent(MainActivity.this,nextscreen.class);
          //  startActivity(i);
      //  }
        
        
        
    }
    

    @Override
    public void onSaveInstanceState(Bundle savedState) {
        super.onSaveInstanceState(savedState);
        uiHelper.onSaveInstanceState(savedState);
    }

}

after applying activity(intent) in if (state.isOpened()) method it return me on login page having logout button for a while and then jump on a new activity by own.if (state.isOpened())方法中应用 activity(intent) 后,它会在登录页面上返回我一段时间,并有注销按钮,然后自己跳转到新的活动。 But I don't want that.但我不想那样。 I want to return on a new activity having logout button there and don't want to show login page again and on click of logout button on new activity, I want login page.我想返回一个有注销按钮的新活动,不想再次显示登录页面,点击新活动上的注销按钮,我想要登录页面。

Facebook login button if you success login. Facebook 登录按钮,如果您成功登录。 It will change the wording from "Log In Facebook" to "Logout".它将措辞从“登录 Facebook”更改为“注销”。 If you don't want to see that, just setVisibility GONE or Intent to desired activity.如果您不想看到它,只需将 Visibility GONE 或 Intent 设置为所需的活动。 If you using intent, set the flag like below如果您使用意图,请设置如下标志

Intent next = new Intent(getApplicationContext(), MenuActivity.class);
next.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(next);

Below is the example of facebook loginbutton下面是facebook登录按钮的示例

loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), (object, response) -> {
                    // hide this facebook login button
                    // Intent to your desired activity

                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,birthday,gender,first_name,last_name");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), Message.LOGINCANCEL, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(getApplicationContext(), Message.LOGINFAILED, Toast.LENGTH_SHORT).show();
            }
        });

If you want to change the "Logout" facebook button to "Log in Facebook" use below code.如果您想将“注销”facebook 按钮更改为“登录 Facebook”,请使用以下代码。 Just create BUtton and do onClick() to trigger below code只需创建 BUtton 并执行 onClick() 即可触发以下代码

if (AccessToken.getCurrentAccessToken() != null && com.facebook.Profile.getCurrentProfile() != null){
    LoginManager.getInstance().logOut();
}

I am also facing the same issue and not able to find any solution till date.我也面临同样的问题,到目前为止还没有找到任何解决方案。 But I am using workaround there.但我在那里使用解决方法。 I am showing the ProgressDialog on Facebook callback method, so user can at least understand some thing is happing when login activity load again after Facebook successful login.我在 Facebook 回调方法上显示 ProgressDialog,因此用户至少可以理解 Facebook 成功登录后再次加载登录活动时发生的一些事情。

Below are the code:-以下是代码:-

private void onSessionStateChange(Session session, SessionState state,
        Exception exception) {

    if (state.isOpened()) {
        Log.i(TAG, "Logged in...");

        //------ Show loading progress
        ProgressDialog dialog = ProgressDialog.show(LoginPopup.this, "Please wait...", "Retrieving data ...", true);
        LinearLayout layout = (LinearLayout) findViewById(R.id.LayoutLoginPopup);
        layout.setEnabled(false);
        LinearLayout layout_LayoutLogin = (LinearLayout) findViewById(R.id.LayoutLogin);
        layout_LayoutLogin.setEnabled(false);
        //------ End Show loading progress
        Request.newMeRequest(session, new Request.GraphUserCallback() {

            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
                // TODO Auto-generated method stub

                FacebookRequestError error = response.getError();
                if (error != null) {
                    Log.e(TAG, error.toString());
                    // handleError(error, true);
                    return;
                }

                if (user != null) {
                    // Display the parsed user info
                    buildUserInfoDisplay(user, response, bar);

                } else {
                    Log.d(TAG, "Failed to login");
                    bar.setVisibility(View.INVISIBLE);
                    Utils.showAlert(LoginPopup.this, "Message",
                            "Failed to login!");
                }

            }
        }).executeAsync();

    } else if (state.isClosed()) {
        Log.i(TAG, "Logged out...");
        // Toast.makeText(Login.this, "Logged out...", Toast.LENGTH_SHORT)
        // .show();
    }

    //------ Hide loading progress
    //ProgressDialog dialog = ProgressDialog.show(LoginPopup.this, "", "Loading...", true);
    LinearLayout layout = (LinearLayout) findViewById(R.id.LayoutLoginPopup);
    layout.setEnabled(true);
    LinearLayout layout_LayoutLogin = (LinearLayout) findViewById(R.id.LayoutLogin);
    layout.setEnabled(true);
    //------ End Hide loading progress
}

What I did was store a file that contains a value called isLoggedIn on the device using sharedPreferrences.我所做的是使用 sharedPreferrence 在设备上存储一个包含名为 isLoggedIn 的值的文件。 When the user logs in, I set this value to true and then clear the value when he/she presses the loggout button.当用户登录时,我将此值设置为 true,然后在他/她按下注销按钮时清除该值。 So anytime I start my app, I first check if the value is true.所以每当我启动我的应用程序时,我首先检查该值是否为真。 If true, move to the next activity, else, stay on the login page.如果为真,则转到下一个活动,否则,留在登录页面。

Still trying to figure out how to solve the problem in a professional way.仍在尝试找出如何以专业的方式解决问题。 All the best.一切顺利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 成功登录Facebook后如何启动新活动? - How start new activity after successful Facebook login? 成功登录GWT Java后如何打开新页面 - How to open new page after a successful login GWT Java 如何在Android登录成功后开始新活动? - How to start new activity after login success in Android? 如何在以下代码中成功登录后开始新的活动? - how to start new activity on successful login in the following code? 登录按钮facebook android不会重定向到新活动 - Login button facebook android doesn't redirect to new activity 1个应用程序中有两个Facebook登录,都将我重定向到同一页面(成功登录后,每次登录都会强制将我带到家庭活动) - Two Facebook login inside 1 app, both redirects me to same page (Both login forcefully takes me to home activity every time after successful login) 成功登录后如何跳过重新启动应用程序中的登录活动....? - How to skip the login activity in relaunching app after a successful login....? 注销后如何在登录页面上重定向 - How to redirect on login page after logout Android中的Facebook登录按钮在登录后将用户返回到同一页面 - Facebook login button in Android returns user to the same page after logging in 如何在自定义登录页面中获取注销消息 - How to get the logout message in custom login page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM