在Facebook集成中,当我点击登录按钮时,它显示加载并返回主屏幕?

时间:2016-09-27 04:59:21

标签: android facebook-graph-api facebook-login facebook-sdk-4.0

我正在我的项目中进行facebook集成。但问题是,当我点击Facebook登录按钮时,它显示正在加载并返回到主屏幕。任何人都可以告诉我这是什么问题?

这是我的MainActivity: -

public class MainActivity extends AppCompatActivity {

    private FacebookData mFacebookData;
    private Button mLoginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFacebookData = new FacebookData();
        mLoginButton = (Button) findViewById(R.id.button);

        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callFacebookLogin();
            }
        });
    }

    private void callFacebookLogin() {

        Session session = Session.getActiveSession();
        if (session != null) {
            Log.e("session :", "session already build");


            Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {

                    if (user != null) {

                        String str = user.getName();

                        try {


                            String id = user.getId();
                            String firstname = user.getFirstName();
                            String lastname = user.getLastName();
                            String pic = "http://graph.facebook.com/" + id + "/picture?type=large";
                            Log.e("id....", id);
                            Log.e("firstname....", firstname);

                            mFacebookData.setId(id);
                            mFacebookData.setFirstname(firstname);
                            mFacebookData.setLastname(lastname);
                            mFacebookData.setPicture(pic);


                        } catch (Exception e) {

                            e.printStackTrace();
                        }


                    }


                }
            });
            Request.executeBatchAsync(request);
        } else {

            Session.openActiveSession(MainActivity.this, true, new Session.StatusCallback() {
                @Override
                public void call(Session session, SessionState state, Exception exception) {


                    if (session.isOpened()) {
                        if (state == SessionState.OPENED) {

                            Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
                                @Override
                                public void onCompleted(GraphUser user, Response response) {


                                    if (user != null) {

                                        String str = user.getName();


                                    }

                                    try {

                                        String id = user.getId();
                                        String firstname = user.getFirstName();
                                        String lastname = user.getLastName();
                                        String pic = "http://graph.facebook.com/"
                                                + id
                                                + "/picture?type=large";


                                        mFacebookData.setId(id);
                                        mFacebookData.setFirstname(firstname);
                                        mFacebookData.setLastname(lastname);
                                        mFacebookData.setPicture(pic);


                                    } catch (Exception e) {

                                        e.printStackTrace();
                                    }


                                }
                            });

                            Request.executeBatchAsync(request);
                        }

                    }


                }
            });


        }

    }
}

这是我的清单: -

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.aaa.examplepractise">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.facebook.LoginActivity"
            android:screenOrientation="portrait" />

        <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/APP_ID" />


    </application>

</manifest>

这是我的Logcat: -

09-27 10:35:24.405 20441-20615/com.example.aaa.examplepractise E/ActivityThread: Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
09-27 10:35:24.582 20441-20441/com.example.aaa.examplepractise E/ActivityThread: Failed to find provider info for com.facebook.katana.provider.PlatformProvider
09-27 10:35:24.583 20441-20441/com.example.aaa.examplepractise E/ActivityThread: Failed to find provider info for com.facebook.wakizashi.provider.PlatformProvider

1 个答案:

答案 0 :(得分:0)

由于以下原因,可能会发生这种情况:

  1. 您未连接到互联网
  2. 您尚未获得互联网访问权限(Manifest.xml)
  3. 您没有对应用
  4. 使用正确的hashkey
  5. 您未提供正确的应用ID
  6. 尝试使用最新方法

    在你的片段类中包括:

    private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d("Login", "onSuccess");
                    GraphRequest.newMeRequest(
                            loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject me, GraphResponse response) {
                                    if (response.getError() != null) {
                                        // handle error
                                    } else {
                                        email = me.optString("email");
                                        String id = me.optString("id");
                                        String social_id=me.optString("id");
                                        String name= me.optString("name");
                                        String gender=  me.optString("gender");
                                        boolean verified_user=  me.optBoolean("is_verified");                                   
                                    }
                                }
                            }).executeAsync();
                }
    
    
                @Override
                public void onCancel () {
                    Log.d("Login", "onCancel");
                }
    
                @Override
                public void onError (FacebookException e){
                    Log.d("Login", "onError " + e);
    
                }
            };
    

    在oncreateView方法中包含以下代码:

     btn_facebook = (LoginButton) v.findViewById(R.id.btn_fb);
              btn_facebook.setFragment(this);
              btn_facebook.setReadPermissions(Arrays.asList("public_profile, email,user_friends"));
              btn_facebook.registerCallback(mCallbackManager, mFacebookCallback);
    

    在oncreate方法中添加以下代码:

     FacebookSdk.sdkInitialize(getContext());
            mCallbackManager = CallbackManager.Factory.create();
            setupTokenTracker();
            setupProfileTracker();
    
                    mTokenTracker.startTracking();
            mProfileTracker.startTracking();
    
            try {
    
                PackageInfo info = getActivity().getPackageManager().getPackageInfo("package name here", PackageManager.GET_SIGNATURES);
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    // Log.e("Key", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
            } catch (Exception ex) {
                StringWriter errors = new StringWriter();
                ex.printStackTrace(new PrintWriter(errors));
                // Log.e("Error", errors.toString());
    
            }
    

    TokenTracker和PRofileTracker方法:

     private void setupTokenTracker() {
            mTokenTracker = new AccessTokenTracker() {
                @Override
                protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                    // Log.d("VIVZ", "" + currentAccessToken);
                }
            };
        }
    
        private void setupProfileTracker() {
            mProfileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                    // Log.d("VIVZ", "" + currentProfile);
    
                }
            };
        }
    

    在onaCtivityResult中,您将获得数据,所以添加如下:

     @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            // Log.e("info", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
            Bundle bundle = data.getExtras();
            for (String key : bundle.keySet()) {
                Object value = bundle.get(key);
            }      
                mCallbackManager.onActivityResult(requestCode, resultCode, data);
    
        }
    

    在Gradle文件中添加以下依赖项:

      

    compile&#39; com.facebook.android:facebook-android-sdk:4.0.0&#39;

    在xml include按钮中如下:

     <com.facebook.login.widget.LoginButton
                        android:id="@+id/btn_fb"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_margin="1dp"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:singleLine="true"
                        android:textColor="@color/white"
                        android:textSize="16sp"
                        fb:login_text="@string/facebook"
                        fb:logout_text="@string/facebook" />
    

    在清单中添加以下权限和元数据和活动标记:

     <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <activity
                android:name="com.facebook.FacebookActivity"
                android:label="title_facebook_login" />
    
            <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/app_id" />
    

    在活动上添加片段并执行代码。希望它有助于让我知道如果需要问别的什么。