Android Facebook SDK 登录

Android Facebook SDK Login

我的 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;
    }
}

编辑

好的,我跟着一些帮助这是我的 activity 现在:

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 编辑 设置内容视图 登录按钮 轮廓 和 回调管理器

"Cannot resolve symbol .(every names above)."

还有一些错误:

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 中,如果您不想在按下此 button 后添加自定义行为,则不应指定为来自 Facebook 的按钮。 它可以看起来像这样:

<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" />

稍后在您的 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一定是你猜的全局变量。

别忘了用 FacebookActivity 更新您的 Manifest.xml 并设置使用互联网的权限:

<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" />

Activity:

   //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" />