编程语言
首页 > 编程语言> > java-在Android中通过fb登录后无法获取emailId

java-在Android中通过fb登录后无法获取emailId

作者:互联网

我正在使用最新的Fb SDK.
我正在Android Studio中进行fb集成.
我已经完成了fb docs的所有步骤.
但是通过fb成功登录后,我没有收到电子邮件ID.

这是我的MainActivity.java

package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
    private CallbackManager callbackManager;
    Button fb;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    LoginButton loginButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(this.getApplicationContext());
        setContentView(R.layout.activity_main);
//        fb = (Button)findViewById(R.id.button);
        callbackManager = CallbackManager.Factory.create();
        fb = (Button) findViewById(R.id.fb);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        List< String > permissionNeeds = Arrays.asList("user_photos", "email",
                "user_birthday", "public_profile", "AccessToken");
        loginButton.registerCallback(callbackManager,
                new FacebookCallback < LoginResult > () {@Override
                                                         public void onSuccess(LoginResult loginResult) {
                    System.out.println("onSuccess");
                    String accessToken = loginResult.getAccessToken()
                            .getToken();
                    Log.i("accessToken", accessToken);
                    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),new GraphRequest.GraphJSONObjectCallback(){
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.i("LoginActivity",
                                    object.toString());
                            Toast.makeText(getApplicationContext(), object.toString(),Toast.LENGTH_LONG).show();
                            try {
                                String  id = object.getString("id").toString();
                                String name = object.getString("name");
                                String  email = object.getString("email");
                                String gender = object.getString("gender");
                                String birthday = object.getString("birthday");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields",
                            "id,name,email,gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
                    @Override
                    public void onCancel() {
                        System.out.println("onCancel");
                    }
                    @Override
                    public void one rror(FacebookException exception) {
                        System.out.println("onError");
                        Log.v("LoginActivity", exception.getCause().toString());
                    }
                });
    }
    public void onClick(View v) {
        if (v == fb) {
            loginButton.performClick();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent data) {
        super.onActivityResult(requestCode, responseCode, data);
        callbackManager.onActivityResult(requestCode, responseCode, data);
    }
}

这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.myapp.MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <FrameLayout
        android:id="@+id/FrameLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt">

        <com.facebook.login.widget.LoginButton
            android:id="@+id/login_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />

        <Button
            android:id="@+id/fb"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#416BC1"
            android:onClick="onClick"
            android:text="FaceBook"
            android:textColor="#ffffff"
            android:textStyle="bold" />
    </FrameLayout>

</RelativeLayout>

这是我的清单

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

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

    <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.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:label="@string/app_name" />
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->

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

</manifest>

这是我的build.gradle Module:app

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'

}

当我回应时

12-03 21:28:10.452 8572-8572/? I/LoginActivity: {"id":"983511081738745","name":"Subhankar Chakraborty","gender":"male"}

如果对我的应用有任何疑问,请告诉我.

解决方法:

尝试一下,它对我有用,希望它也对您有用
我在android studio.and sdk4.7.0中构建

MainActivity.class

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;


public class MainActivity extends Activity {



    Button fb;

    private CallbackManager callbackManager;
    private LoginManager loginManager;
    private List<String> permissionNeeds= Arrays.asList("user_photos", "email", "user_birthday", "user_friends");
    private String fbUserId;
    private String fbUserName;
    private String fbEmail;
    private String fbGender;
    private String fbDob;
    TextView txt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(this);
        callbackManager = CallbackManager.Factory.create();
        loginManager = LoginManager.getInstance();

        setContentView(R.layout.activity_main);
        fb = (Button)findViewById(R.id.button);
        txt=  (TextView)findViewById(R.id.txt);








    }
    public void onClick(View v) {
       /* if (v == fb) {
            loginButton.performClick();
        }*/
        FaceBookLogin();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }




    private void FaceBookLogin() {
        loginManager.logInWithReadPermissions(MainActivity.this, permissionNeeds);
        loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(
                                    JSONObject object,
                                    GraphResponse response) {

                                Log.v("LoginActivity", response.toString());


                                try {
                                    fbUserId = object.getString("id");
                                    fbUserName = object.getString("name");
                                    fbEmail = object.getString("email");
                                    fbGender = object.getString("gender");
                                    fbDob = object.getString("birthday");

                                    txt.setText(object.toString());

                                    if (fbUserName.contains(" ")) {
                                        String first_name = fbUserName.substring(0, fbUserName.indexOf(' '));
                                        String lastName = fbUserName.substring(fbUserName.indexOf(' ') + 1);


                                    } else {
                                       // first_name = fbUserName;
                                        //lastName = " ";
                                    }
                                    if (fbEmail != null) {
                                       // SendValueToServer(fbUserName, first_name, lastName, fbEmail);
                                        Toast.makeText(getApplicationContext(),"fbEmail"+fbEmail,Toast.LENGTH_SHORT).show();
                                    } else {
                                       // SendValueToServer(fbUserName, first_name, lastName, " ");
                                        Toast.makeText(getApplicationContext(),"fbEmail:"+"blank",Toast.LENGTH_SHORT).show();
                                    }


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void one rror(FacebookException e) {

            }
        });


    }



}

AndroidManifest.xml

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="test.technoexponent.com.test.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.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:label="@string/app_name" />
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->

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

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.myapp.MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="25sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

  <Button
            android:id="@+id/fb"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#416BC1"
            android:onClick="onClick"
            android:text="FaceBook"
            android:textColor="#ffffff"
            android:textStyle="bold" />
</RelativeLayout>

设置等级

include ':app', ':facebook-android-sdk-4.7.0'

标签:facebook,java,android,facebook-graph-api
来源: https://codeday.me/bug/20191119/2035497.html