Android Facebook SDK 登录
Posted
技术标签:
【中文标题】Android Facebook SDK 登录【英文标题】:Android Facebook SDK Login 【发布时间】:2015-04-28 18:22:08 【问题描述】:我在我的 android 应用程序中有这个页面,有 4 个选项卡,其中一个选项卡应该有一个登录 Facebook 按钮,我按照 Facebook 教程进行操作,但我无法添加任何脚本,如果我放了一些imports Facebook..
他们是灰色的.. 我该怎么办? Facebook 在我的 build.gradle 中连接良好
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import static com.Andrea.material.sample.R.layout.page;
public class SampleFragment extends Fragment
private static final String ARG_POSITION = "position";
private WebView myWebView;
private String LOG_TAG = "AndroidWebViewActivity";
private int position;
public static SampleFragment newInstance(int position)
SampleFragment f = new SampleFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
position = getArguments().getInt(ARG_POSITION);
View rootView = inflater.inflate(page, container, false);
ProgressBarCircular progressBarCircular = (ProgressBarCircular) rootView.findViewById(R.id.progress);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
fab.setDrawableIcon(getResources().getDrawable(R.drawable.plus));
switch (position)
case 0:
webView.loadUrl("http://www.google.com");
break;
case 1:
webView.loadUrl("http://www.google.com");
break;
case 2:
webView.loadUrl("http://www.google.com");
break;
case 3:
webView.loadUrl("http://www.google.com");
break;
return rootView;
编辑
好的,我接受了一些帮助,这是我现在的活动:
package com.Andrea.material.sample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
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.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
import static com.Andrea.material.sample.R.layout.page;
public class SampleFragment extends Fragment
private static final String ARG_POSITION = "position";
private WebView myWebView;
private String LOG_TAG = "AndroidWebViewActivity";
FacebookSdk.sdkInitialize(getApplicationContext());
private int position;
public static SampleFragment newInstance(int position)
SampleFragment f = new SampleFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
position = getArguments().getInt(ARG_POSITION);
View rootView = inflater.inflate(page, container, false);
ProgressBarCircular progressBarCircular = (ProgressBarCircular) rootView.findViewById(R.id.progress);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
fab.setDrawableIcon(getResources().getDrawable(R.drawable.plus));
switch (position)
case 0:
webView.loadUrl("http://www.google.com");
break;
case 1:
webView.loadUrl("http://www.google.com");
break;
case 2:
webView.loadUrl("http://www.google.com");
break;
case 3:
//if the facebook profile is changed, below code block will be called
profileTracker = new ProfileTracker()
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile)
if(currentProfile != null)
fbUserId = currentProfile.getId();
if(!sharedPreferences.contains("UserName"))
editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
if(!sharedPreferences.contains("FbId"))
editor.putString("FbId",currentProfile.getId());
if(!sharedPreferences.contains("ProfilePicture"))
editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
editor.commit();
;
//when new fb user logged in , below code block will be called
AccessTokenTracker accessTokenTracker = new AccessTokenTracker()
@Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2)
System.out.println("acesstoken trackercalled");
;
//set layout resource
setContentView(R.layout.page);
//fb login button
loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);
//set fb permissions
loginButton.setReadPermissions(Arrays.asList("public_profile,email"));
//call the login callback manager
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
@Override
public void onSuccess(LoginResult loginResult)
profile = Profile.getCurrentProfile();
if(profile != null)
fbUserId = profile.getId();
if(!sharedPreferences.contains("UserName"))
editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
if(!sharedPreferences.contains("FbId"))
editor.putString("FbId",profile.getId());
if(!sharedPreferences.contains("ProfilePicture"))
editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
editor.commit();
//get here value of variables FBID and USERNAME to pass in
//other webview
@Override
public void onCancel()
@Override
public void onError(FacebookException e)
);
break;
return rootView;
Android 工作室告诉我: sdk初始化 档案追踪器 共享偏好 fbUserId 编辑 设置内容视图 登录按钮 轮廓 和 回调管理器
“无法解析符号。(以上所有名称)。”
还有一些错误:
Error:(34, 30) error: <identifier> expected
Error:(34, 52) error: <identifier> expected
Error:(34, 53) error: ';' expected
Error:(34, 54) error: illegal start of type
Error:(34, 55) error: <identifier> expected
Error:(34, 56) error: ';' expected
EDIT2
不,Facebook sdks 似乎导入良好...这是我的应用 build.gradle:
apply plugin: 'com.android.application'
android
compileSdkVersion 21
buildToolsVersion "21.1"
defaultConfig
applicationId "com.tekinarslan.material.sample"
minSdkVersion 16
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:support-v4:21.0.0'
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.android.tools.build:gradle:1.1.2'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
repositories
mavenCentral()
【问题讨论】:
在你的代码中我没有看到任何与Facebook API
相关的东西,如果你说import
s 是灰色的,那么你确实安装了,但永远不要使用这个class
。你想达到什么目标?
@Yurets 我正在尝试进入我的最后一个标签:“案例 3”一个带有 Facebook 登录的按钮,请帮助我。
没有恐慌。您想自定义点击后的行为或只是启动 facebook LoginActivity
?
如果可能,当单击 Facebook 按钮时,我想打开 Facebook 应用程序,登录并在获取用户 ID 和用户名后,我需要将它们传递到我的 Web 视图。在 ios 编程中更容易 ^^ @Yurets
login facebook getlocation and email 的可能重复项
【参考方案1】:
如果您不想在按下此 button
后添加自定义行为,则不应在您的 layout
中指定为来自 Facebook
的按钮。
它可能看起来像这样:
<com.facebook.widget.LoginButton
android:id="@+id/fb_login_button"
android:layout_
android:layout_
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
稍后在您的case
#3 中,您可以捕捉动作并指定额外的工作。
我想这很好tutorial 如何使用它。
此外,facebook 在他自己的tutorial 中非常清楚。既然是官方的,那就先试试吧。
更新
在Activity
中调用setContentView
之前应添加此行:
FacebookSdk.sdkInitialize(this);
将此代码添加到您要执行它的位置。
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
@Override
public void onSuccess(LoginResult loginResult)
isFbUserLoggedIn = true;
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback()
@Override
public void onCompleted(JSONObject JSONUser, GraphResponse graphResponse)
if (graphResponse.getError() != null)
showErrorDialog(graphResponse.getError().toString());
else
String firstName = JSONUser.optString(FinalValues.FIRST_NAME);
String lastName = JSONUser.optString(FinalValues.LAST_NAME);
String id = JSONUser.optString(FinalValues.ID);
);
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name");
request.setParameters(parameters);
request.executeAsync();
@Override
public void onCancel()
@Override
public void onError(FacebookException exception)
Log.d("LOG", exception.toString());
);
LoginManager.getInstance().logInWithReadPermissions((Activity) activity, Arrays.asList("public_profile"));
这部分你需要添加到onActivityResult()
方法中,你必须添加到Override
。
if(callbackManager != null)
callbackManager.onActivityResult(requestCode, resultCode, data);
callbackManager
一定是你猜到的全局变量。
不要忘记将您的Manifest.xml
更新为FacebookActivity
并设置使用互联网的权限:
<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"/>
还有:
<uses-permission android:name="android.permission.INTERNET" />
希望这已经足够了。快乐编码:)
【讨论】:
问题是当我导入import com.facebook.Session; 12 import com.facebook.SessionState; 13 import com.facebook.UiLifecycleHelper; 14 import com.facebook.model.GraphUser; 15 import com.facebook.widget.LoginButton; 16 import com.facebook.widget.LoginButton.UserInfoChangedCallback;
它不起作用.. @Yurets
我遵循了 Deepika 的示例,但无论如何它都不起作用,请查看我的编辑@Yurets
如果无法解析所有字符,则说明您没有正确安装facebook-sdk
。将此行添加到dependencies
中的build.gradle
,compile 'com.facebook.android:facebook-android-sdk:4.0.0'
按“立即同步”,它将出现在右上角,然后重试。
Facebook 似乎导入得很好.. 看看我的编辑2 @Yurets【参考方案2】:
关注this answer。这是一个关于如何使用facebook 4.0.+ API
的分析示例。
【讨论】:
【参考方案3】:在下面查看我的工作代码。
在布局中添加FB按钮:
<com.facebook.login.widget.LoginButton
android:id="@+id/connectWithFbButton"
android:layout_
android:layout_
android:layout_centerInParent="true"
android:text="connect with facebook"
android:layout_marginTop="200dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp" />
活动:
//Initialize Facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//if the facebook profile is changed, below code block will be called
profileTracker = new ProfileTracker()
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile)
if(currentProfile != null)
fbUserId = currentProfile.getId();
if(!sharedPreferences.contains("UserName"))
editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
if(!sharedPreferences.contains("FbId"))
editor.putString("FbId",currentProfile.getId());
if(!sharedPreferences.contains("ProfilePicture"))
editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
editor.commit();
;
//when new fb user logged in , below code block will be called
AccessTokenTracker accessTokenTracker = new AccessTokenTracker()
@Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2)
System.out.println("acesstoken trackercalled");
;
//set layout resource
setContentView(R.layout.activity_login);
//fb login button
loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);
//set fb permissions
loginButton.setReadPermissions(Arrays.asList("public_profile,email"));
//call the login callback manager
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
@Override
public void onSuccess(LoginResult loginResult)
profile = Profile.getCurrentProfile();
if(profile != null)
fbUserId = profile.getId();
if(!sharedPreferences.contains("UserName"))
editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
if(!sharedPreferences.contains("FbId"))
editor.putString("FbId",profile.getId());
if(!sharedPreferences.contains("ProfilePicture"))
editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
editor.commit();
goToNewActivity();
@Override
public void onCancel()
@Override
public void onError(FacebookException e)
);
AndroidManifest.xml
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/fb_app_id" />
【讨论】:
我按照你的例子,但我不工作..请看我的编辑以上是关于Android Facebook SDK 登录的主要内容,如果未能解决你的问题,请参考以下文章
Android Facebook SDK 4.0 登录:用户登录 Facebook 应用程序时出错
通过 Xamarin.Facebook.Android sdk 登录 Facebook