[英]Android Facebook SDK Login
我在具有4個選項卡的android應用程序中具有此頁面,並且在其中一個選項卡中應該有一個登錄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;
}
}
EDITS
好的,我遵循了一些幫助,這是我現在的活動:
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 Studio告訴我:sdkInitialize profileTracker sharedPreferences fbUserId編輯器setContentView loginButton配置文件和callbackManager
“無法解析符號。(上面的每個名稱)。”
還有一些錯誤,如:
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()
}
在您的layout
,你不應該指定為從按鈕Facebook
,如果你不想按這個后添加自定義行為button
。 它看起來可能像這樣:
<com.facebook.widget.LoginButton
android:id="@+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
然后在第3種case
您可以采取行動並指定其他工作。 我想這是一個很好的教程,如何使用它。 同樣,facebook在他自己的教程中也很清楚。 由於它是官方的,因此您應該先嘗試一下。
UPDATE在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"));
您需要將此部分添加到必須Override
onActivityResult()
方法中。
if(callbackManager != null){
callbackManager.onActivityResult(requestCode, resultCode, data);
}
如您所料, callbackManager
必須是全局變量。
不要忘記使用FacebookActivity
更新Manifest.xml
並設置使用Internet的權限:
<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" />
希望這足夠了。 快樂的編碼:)
遵循此答案 。 這是一個如何使用facebook 4.0.+ API
的分析示例。
請參閱下面的工作代碼。
在布局中添加FB按鈕:
<com.facebook.login.widget.LoginButton
android:id="@+id/connectWithFbButton"
android:layout_width="match_parent"
android:layout_height="40dp"
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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.