我正在使用最近的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 onError(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>
这是我的Mainifest
<?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模块: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"}
如果有关于我的应用的任何问题,请告诉我。
答案 0 :(得分:3)
试试这个对我有用的希望所以它对你也有用 我建立了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 onError(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>
设置,gradle这个
include ':app', ':facebook-android-sdk-4.7.0'
答案 1 :(得分:0)
使用我的代码更改onClickListener
的部分:
btnLoginFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Procesando datos...");
progressDialog.show();
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", response.toString());
// Get facebook data from login
Bundle bFacebookData = getFacebookData(object);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // Parámetros que pedimos a facebook
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
System.out.println("onCancel");
}
@Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
private Bundle getFacebookData(JSONObject object) {
try {
Bundle bundle = new Bundle();
String id = object.getString("id");
try {
URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");
Log.i("profile_pic", profile_pic + "");
bundle.putString("profile_pic", profile_pic.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
bundle.putString("idFacebook", id);
if (object.has("first_name"))
bundle.putString("first_name", object.getString("first_name"));
if (object.has("last_name"))
bundle.putString("last_name", object.getString("last_name"));
if (object.has("email"))
bundle.putString("email", object.getString("email"));
if (object.has("gender"))
bundle.putString("gender", object.getString("gender"));
if (object.has("birthday"))
bundle.putString("birthday", object.getString("birthday"));
if (object.has("location"))
bundle.putString("location", object.getJSONObject("location").getString("name"));
return bundle;
}
不要忘记查看此行以获得更好的结果:
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // Parámetros que pedimos a facebook
希望,它也会对你有所帮助:)。
答案 2 :(得分:0)
试试这个对我有用的希望所以它也适合你
在您的主Activity或使用FaceBookSignIn方法
的活动中调用此方法FacebookSdk.sdkInitialize(MainActivity.this);
在您的活动中添加此方法
public void FaceBookSignIn() {
callbackManager = CallbackManager.Factory.create();
loginType = Constants.loginTypeFaceBook;
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Success", true);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
String email = jsonObject.getString(Constants.FacebookEmail),
String name = jsonObject.getString(Constants.FacebookName),
String firstName = jsonObject.getString(Constants.FacebookFirstName),
String lastName = jsonObject.getString(Constants.FacebookLastName),
String id = jsonObject.getString(Constants.FacebookID);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,birthday,email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Sign In Cancel", true);
}
@Override
public void onError(FacebookException e) {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Error", true);
}
});
}