问题描述
在我的Android应用我开发了这个code登录我的帐户,并得到这样的名称,位置和电子邮件用户属性。现在的问题是我能得到这个名字,但我不能让电子邮件和位置。当我想我的code,而不尝试捕捉应用美眉和我的日志点的getProperty(电子邮件)
和的getLocation()
。当我使用的尝试。该应用程序的工作,但没有任何邮件或位置。
公共类股扩展片段{私有静态最后字符串变量=分享;私人UiLifecycleHelper uiHelper;
私人查看otherView;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
//为了保持FB登录会话
uiHelper =新UiLifecycleHelper(getActivity(),回调);
uiHelper.onCreate(savedInstanceState);
}
@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
捆绑savedInstanceState){
查看查看= inflater.inflate(R.layout.share,集装箱,假);
//中查找登录按钮
LoginButton authButton =(LoginButton)view.findViewById(R.id.authButton);
authButton.setFragment(本);
//设置视图应该是可见的后登录无形的最初
otherView = view.findViewById(R.id.other_views);
otherView.setVisibility(View.GONE);
//authButton.setReadPermissions(Arrays.asList("user_likes,user_status,电子邮件,user_birthday));
返回查看;
}
//调用时会改变
私人Session.StatusCallback回调=新Session.StatusCallback(){
@覆盖
公共无效呼叫(会话的会话,SessionState会状态,例外的例外){
onSessionStateChange(会话,状态除外);
}
};
//当会话被改变,此方法是从回调方法称为
私人无效onSessionStateChange(会话的会话,SessionState会状态,例外的例外){
最后的TextView名=(TextView中)getView()findViewById(R.id.name)。
最后的TextView邮件=(TextView中)getView()findViewById(R.id.mail)。
最终TextView的位置=(TextView中)getView()findViewById(R.id.location)。
最后的TextView区域=(TextView中)getView()findViewById(R.id.locale)。
最后的TextView信息=(TextView中)getView()findViewById(R.id.msginfo)。
最后的LinearLayout意见=(的LinearLayout)getView()findViewById(R.id.other_views)。
如果(state.isOpened()){
Log.i(TAG,已登录......);
//使请求/我的API来获得图形用户
views.setVisibility(View.VISIBLE);
info.setText(你现在可以分享到Facebook的图像);
Request.newMeRequest(会话,新Request.GraphUserCallback(){
//后与用户图形API响应回调
// 目的
@覆盖
公共无效onCompleted(GraphUser用户,响应响应){
如果(用户!= NULL){
尝试 {
//设置视图的可见性设置为true
otherView.setVisibility(View.VISIBLE);
//设置用户名
name.setText(你好+ user.getName());
//设置电子邮件
(您的电子邮件:+ user.getProperty(电子邮件)的toString())mail.setText;
locale.setText(区域设置:+ user.getProperty(区域设置)的toString());
(。您现在的位置:+ user.getLocation()的getProperty(姓名)的toString())location.setText;
}
赶上(例外五){
e.printStackTrace();
}
}
}
})executeAsync()。
}否则如果(state.isClosed()){
views.setVisibility(View.INVISIBLE);
info.setText(如果你想在Facebook的共享图像,请登录);
Log.i(TAG注销...);
otherView.setVisibility(View.GONE);
}
}
@覆盖
公共无效onActivityResult(INT申请code,INT结果code,意图数据){
super.onActivityResult(要求code,因此code,数据);
uiHelper.onActivityResult(要求code,因此code,数据);
Log.i(TAG,OnActivityResult ......);
}
@覆盖
公共无效onResume(){
super.onResume();
uiHelper.onResume();
}
@覆盖
公共无效的onPause(){
super.onPause();
uiHelper.onPause();
}
@覆盖
公共无效的onDestroy(){
super.onDestroy();
uiHelper.onDestroy();
}
@覆盖
公共无效的onSaveInstanceState(包outState){
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
问题是,你有没有问权限:
authButton.setReadPermissions(Arrays.asList(user_likes,user_status,电子邮件,user_birthday));
不过,您使用的是旧的Facebook SDK,而最新的SDK是4.0 + 。下面,我会给你一个完整的示例code的Facebook登录,基于最新的API。请记住,你首先要添加您的应用程序 developers.facebook
作为的提到了。
公共类LoginActivity扩展ActionBarActivity {
@覆盖
保护无效onActivityResult(INT申请code,INT响应code,意图数据)
{
super.onActivityResult(要求code,响应code,数据);
callbackManager.onActivityResult(要求code,响应code,数据);
}
@覆盖
保护无效的onCreate(包savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
的setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton =(LoginButton)findViewById(R.id.loginFaceBook_button);
名单<字符串> permissionNeeds = Arrays.asList(user_photos,电子邮件,user_birthday,public_profile);
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager,新FacebookCallback< LoginResult>()
{
@覆盖
公共无效的onSuccess(LoginResult loginResult)
{
的System.out.println(的onSuccess);
GraphRequest请求= GraphRequest.newMeRequest
(loginResult.getAccessToken(),新GraphRequest.GraphJSONObjectCallback()
{
@覆盖
公共无效onCompleted(的JSONObject对象,GraphResponse响应)
{
//应用code
Log.v(LoginActivity,response.toString());
//System.out.println("Check:+ response.toString());
尝试
{
字符串ID = object.getString(ID);
字符串名称= object.getString(姓名);
字符串email = object.getString(电子邮件);
字符串性别= object.getString(性别);
字符串的生日= object.getString(生日);
的System.out.println(ID +,+名称+,+电子邮件+,+性别+,+生日);
}
赶上(JSONException E)
{
e.printStackTrace();
}
}
});
捆绑参数=新包();
parameters.putString(域,编号,姓名,电子邮箱,性别,生日);
request.setParameters(参数);
request.executeAsync();
}
@覆盖
公共无效OnCancel的()
{
的System.out.println(OnCancel的」);
}
@覆盖
公共无效onerror的(FacebookException除外)
{
的System.out.println(onError的);
Log.v(LoginActivity,exception.getCause()的toString());
}
});
}
}
如果你想使用片段
,而不是 ActionBarActivity
时,只需添加 loginButton。 setFragment(本);
右后您的许可行
manifest.xml的:
<使用-权限的Android:名称=android.permission.INTERNET对/>
<使用-权限的Android:名称=android.permission.ACCESS_COARSE_LOCATION/>
<使用-权限的Android:名称=android.permission.ACCESS_FINE_LOCATION/>
<应用
<! - 你的其他ATTRS ..-->
&所述;元数据
机器人:名称=com.facebook.sdk.ApplicationId
机器人:值=@字符串/ APP_ID/> < - !得到这个从developers.facebook - >
<活动
机器人:名称=com.facebook.FacebookActivity
机器人:configChanges =键盘| keyboardHidden |屏幕布置|屏幕尺寸|定位
机器人:主题=@安卓风格/ Theme.Translucent.NoTitleBar
机器人:标签=@字符串/ APP_NAME/>
您将需要添加到您的应用程序的哈希键太。这是一种与code做到这一点:
尝试
{
//粘贴你的包名的第一个参数
PackageInfo信息= getPackageManager()。getPackageInfo(PUT_YOUR_PACKAGE_NAME_HERE
PackageManager.GET_SIGNATURES);
对于(android.content.pm.Signature签名:info.signatures)
{
消息摘要MD = MessageDigest.getInstance(SHA);
md.update(signature.toByteArray());
字符串标志= Base64.en codeToString(md.digest(),Base64.DEFAULT);
Log.e(我的钥匙HASH:符号);
Toast.makeText(getApplicationContext(),标志,Toast.LENGTH_LONG).show();
}
}
赶上(PackageManager.NameNotFoundException E)
{
}
赶上(抛出:NoSuchAlgorithmException E)
{
}
在它打印出来,你的散列键,复制粘贴到您的 facebook.developer
帐户,您的项目所在。
在grandle,您应该添加 jcenter
在库
并添加编译COM .facebook.android:Facebook的Android的SDK:4.0.0
在依赖条件
buildscript {
库{
jcenter()
}
依赖{
类路径com.android.tools.build:gradle:1.1.0
//注意:不要在这里放置应用程序依赖;他们属于
//在单个模块build.gradle文件
}
}
allprojects
{
库{
jcenter()
/ *更多的项目ATTRS .. * /
}
}
和其他grandle文件:
应用插件:com.android.application
安卓{
compileSdkVersion 21
buildToolsVersion21.1.2
defaultConfig {
的applicationIDYOUR_PACKAGE_NAME
的minSdkVersion 14
targetSdkVersion 21
版本code 1
VERSIONNAME1.0
}
buildTypes {
推出 {
minifyEnabled假
proguardFiles getDefaultProguardFile('ProGuard的-android.txt'),'proguard-rules.pro
}
}
} {相关性
编译文件树(导演:库,包括:['的* .jar'])
编译com.android.support:appcompat-v7:21.0.3
编译com.facebook.android:facebook-android-sdk:4.0.0
}
编辑:
为了追踪用户的位置,你需要一个GPS追踪器,像this. user_location
权限不会返回经度,纬度
,但是的对象,我想这是不是你想要的。因此,您的权限应该是名单,其中,字符串> permissionNeeds = Arrays.asList(user_photos,电子邮件,user_birthday,public_profile);
,现在你应该可以检索用户的电子邮件
In my Android application I developed this code to login with my account and get user property like name, location and email. The problem is I can get the name, but I can't get the email and the location. When I tried my code without try catch the application crush and my log point in getproperty("email")
and getlocation()
. When I use the try. The application work but there is no email or location.
public class Share extends Fragment {private static final String TAG ="Share";private UiLifecycleHelper uiHelper;
private View otherView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To maintain FB Login session
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.share, container, false);
// Looks for Login button
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
// Set View that should be visible after log-in invisible initially
otherView = view.findViewById(R.id.other_views);
otherView.setVisibility(View.GONE);
//authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
return view;
}
// Called when session changes
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,Exception exception) {
onSessionStateChange(session, state, exception);
}
};
// When session is changed, this method is called from callback method
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
final TextView name = (TextView) getView().findViewById(R.id.name);
final TextView mail = (TextView) getView().findViewById(R.id.mail);
final TextView location = (TextView) getView().findViewById(R.id.location);
final TextView locale = (TextView) getView().findViewById(R.id.locale);
final TextView info = (TextView)getView().findViewById(R.id.msginfo);
final LinearLayout views= (LinearLayout)getView().findViewById(R.id.other_views);
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// make request to the /me API to get Graph user
views.setVisibility(View.VISIBLE);
info.setText("You can now share images in facebook ");
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
// Set view visibility to true
otherView.setVisibility(View.VISIBLE);
// Set User name
name.setText("Hello " + user.getName());
// Set Email
mail.setText("Your Email: " + user.getProperty("email").toString());
locale.setText("Locale: " + user.getProperty("locale").toString());
location.setText("Your Current Location: " + user.getLocation().getProperty("name").toString());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
} else if (state.isClosed()) {
views.setVisibility(View.INVISIBLE);
info.setText("If you want to share images in Facebook, please Login");
Log.i(TAG, "Logged out...");
otherView.setVisibility(View.GONE);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "OnActivityResult...");
}
@Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
The issue is that you have not asked for permissions:
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
However, you are using an older Facebook SDK, while the newest SDK is 4.0.+. Below, I will give you a full sample code for Facebook login, based on the newest API. Keep in mind that you first have to add your application in developers.facebook
as the documentation mentions out.
public class LoginActivity extends ActionBarActivity{
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.loginFaceBook_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
@Override
public void onSuccess(LoginResult loginResult)
{
System.out.println("onSuccess");
GraphRequest request = GraphRequest.newMeRequest
(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
@Override
public void onCompleted(JSONObject object, GraphResponse response)
{
// Application code
Log.v("LoginActivity", response.toString());
//System.out.println("Check: " + response.toString());
try
{
String id = object.getString("id");
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
System.out.println(id + ", " + name + ", " + email + ", " + gender + ", " + 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());
}
});
}
}
If you want to use Fragment
instead of ActionBarActivity
, the just add loginButton.setFragment(this);
right after your permission line.
manifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
<!-- your other attrs..-->
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id"/> <!-- Get this one from developers.facebook -->
<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"/>
You will need to add to your application a hash key too. Here is a way to do this with code:
try
{
//paste Your package name at the first parameter
PackageInfo info = getPackageManager().getPackageInfo("PUT_YOUR_PACKAGE_NAME_HERE",
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String sign = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.e("MY KEY HASH:", sign);
Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show();
}
}
catch (PackageManager.NameNotFoundException e)
{
}
catch (NoSuchAlgorithmException e)
{
}
After it prints you out the hash key, you copy paste it to your facebook.developer
account, where your project is located.
In grandle, you should add jcenter
in repositories
and also add compile 'com.facebook.android:facebook-android-sdk:4.0.0'
in dependecies
.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects
{
repositories {
jcenter()
/*more project attrs..*/
}
}
And the other grandle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "YOUR_PACKAGE_NAME"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
Edit:
In order to track the user's location, you will need a GPS Tracker, something like this. "user_location"
permission does not return a lon, lat
, but a Page object, which I think is not what you want. So, your permissions should be List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
and now you should be able to retrieve user's email
这篇关于使用Facebook的API无法获取位置和电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!