2015-11-07 54 views

回答

14

此代碼對我的作品,嘗試一下,檢查是否正在使用Facebook的SDK 4.7

package com.kushal.facebooklogin; 

    import java.util.Arrays; 
    import org.json.JSONException; 
    import org.json.JSONObject; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.support.v4.app.FragmentActivity; 
    import android.util.Log; 
    import android.view.View; 
    import android.widget.TextView; 
    import com.facebook.*; 
    import com.facebook.login.LoginManager; 
    import com.facebook.login.LoginResult; 
    import com.facebook.login.widget.LoginButton; 

    public class FacebookLogin extends FragmentActivity 
    { 
     private TextView tvfirst_name, tvlast_namee, tvfull_name, tvEmail; 
     private CallbackManager callbackManager; 
     LoginButton login_button; 
     String email,name,first_name,last_name; 

     @Override 
     public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      FacebookSdk.sdkInitialize(this.getApplicationContext()); 
      callbackManager = CallbackManager.Factory.create(); 

      setContentView(R.layout.main); 

      tvfirst_name  = (TextView) findViewById(R.id.first_name); 
      tvlast_namee  = (TextView) findViewById(R.id.last_name); 
      tvfull_name   = (TextView) findViewById(R.id.full_name); 
      tvEmail    = (TextView) findViewById(R.id.email); 
      login_button  = (LoginButton) findViewById(R.id.login_button); 

      login_button.setReadPermissions(Arrays.asList("public_profile","email")); 
      login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() 
      { 
       @Override 
       public void onSuccess(LoginResult loginResult) 
       { 
        login_button.setVisibility(View.GONE); 

        GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() 
        { 
         @Override 
         public void onCompleted(JSONObject object, GraphResponse response) 
         { 
          Log.d("JSON", ""+response.getJSONObject().toString()); 

          try 
          { 
           email  = object.getString("email"); 
           name  = object.getString("name"); 
           first_name = object.optString("first_name"); 
           last_name = object.optString("last_name"); 

           tvEmail.setText(email); 
           tvfirst_name.setText(first_name); 
           tvlast_namee.setText(last_name); 
           tvfull_name.setText(name); 
           LoginManager.getInstance().logOut(); 
          } 
          catch (JSONException e) 
          { 
           e.printStackTrace(); 
          } 
         } 
        }); 

        Bundle parameters = new Bundle(); 
        parameters.putString("fields", "id,name,first_name,last_name,email"); 
        graphRequest.setParameters(parameters); 
        graphRequest.executeAsync(); 
       } 

       @Override 
       public void onCancel() 
       { 

       } 

       @Override 
       public void onError(FacebookException exception) 
       { 

       } 
      }); 
     } 

     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) 
     { 
      super.onActivityResult(requestCode, resultCode, data); 
      callbackManager.onActivityResult(requestCode, resultCode, data); 
     } 
    } 

的XML設計是遵循

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:facebook="http://schemas.android.com/apk/res-auto" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#FFF" 
    android:gravity="center" 
    android:orientation="vertical" > 

    <com.facebook.login.widget.LoginButton 
     android:id="@+id/login_button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="5dp" 
     /> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:gravity="center_horizontal" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/first_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_marginLeft="10dp" 
      android:textSize="18sp" /> 

     <TextView 
      android:id="@+id/last_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_marginLeft="10dp" 
      android:textSize="18sp" /> 

     <TextView 
      android:id="@+id/full_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_marginLeft="10dp" 
      android:textSize="18sp" /> 

     <TextView 
      android:id="@+id/email" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_marginLeft="10dp" 
      android:textSize="18sp" /> 
    </LinearLayout> 

</LinearLayout> 

mainefest文件如下:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.kushal.facebooklogin" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

    <application 
     android:icon="@drawable/icon" 
     android:label="@string/app_name" 
     android:theme="@android:style/Theme.NoTitleBar" > 
     <activity 
      android:name=".FacebookLogin" 
      android:label="@string/app_name" 
      android:windowSoftInputMode="adjustResize" > 
      <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:label="@string/app_name" 
      android:theme="@android:style/Theme.Translucent.NoTitleBar" /> 

     <meta-data 
      android:name="com.facebook.sdk.ApplicationId" 
      android:value="@string/app_id" /> 
    </application> 

</manifest> 
+1

謝謝老兄...乾淨的代碼 – suku

+0

到ge t profile profile:'「http://graph.facebook.com/」+ loginResult.getAccessToken()。getUserId()+「/ picture?type = large」;' – emiraslan

1

您可以使用Facebook Android SDK。在這裏,您已經在documentation中解釋瞭如何爲您的應用建立Facebook登錄。

它說:

Facebook的登錄添加到您的應用程序最簡單的方法是從SDK添加 LoginButton。這是一個 Button的自定義視圖實現。您可以在您的應用中使用此按鈕來實施Facebook登錄。 enter image description here

添加登錄按鈕

按鈕添加到您的佈局XML文件類的全名, com.facebook.widget.LoginButton:

<com.facebook.login.widget.LoginButton 
    android:id="@+id/login_button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center_horizontal" 
    android:layout_marginTop="30dp" 
    android:layout_marginBottom="30dp" /> 

然後設置通過將其添加到片段中並將其更新到您的活動以使用您的片段。

您可以自定義登錄按鈕的屬性,並在您的onCreateView()方法中註冊 回調。

屬性可以自定義包括LoginBehaviorDefaultAudienceToolTipPopup .Style並在LoginButton權限。例如:

@Override 
public View onCreateView(
     LayoutInflater inflater, 
     ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.splash, container, false); 

    loginButton = (LoginButton) view.findViewById(R.id.login_button); 
    loginButton.setReadPermissions("user_friends"); 
    // If using in a fragment 
    loginButton.setFragment(this);  
    // Other app specific specialization 

    // Callback registration 
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
     @Override 
     public void onSuccess(LoginResult loginResult) { 
      // App code 
     } 

     @Override 
     public void onCancel() { 
      // App code 
     } 

     @Override 
     public void onError(FacebookException exception) { 
      // App code 
     } 
    });  
} 

如果在片段使用LoginButton,你需要設置片段 上的按鈕,如圖致電setFragment

然後,您需要調用FacebookSdk.initialize初始化SDK, 然後調用CallbackManager.Factory.create創建回調 管理器來處理登錄響應。下面是一個片段添加 回調的例子:

public class MainActivity extends FragmentActivity { 
    CallbackManager callbackManager; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     FacebookSdk.sdkInitialize(getApplicationContext()); 
     callbackManager = CallbackManager.Factory.create(); 
     LoginButton loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button); 
     loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { ... }); 
    } 

最後,你應該叫callbackManager.onActivityResult通過callbackManager傳遞 登錄結果向LoginManager

註冊一個回調

要到登錄結果做出反應,你需要 要麼LoginManagerLoginButton註冊一個回調。如果您使用 LoginButton註冊回叫,則不需要在登錄管理器上註冊該回叫。

您的回調添加到您的活動或片段的onCreate()方法:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    FacebookSdk.sdkInitialize(this.getApplicationContext()); 

    callbackManager = CallbackManager.Factory.create(); 

    LoginManager.getInstance().registerCallback(callbackManager, 
      new FacebookCallback<LoginResult>() { 
       @Override 
       public void onSuccess(LoginResult loginResult) { 
        // App code 
       } 

       @Override 
       public void onCancel() { 
        // App code 
       } 

       @Override 
       public void onError(FacebookException exception) { 
        // App code 
       } 
    }); 
} 

如果登錄成功,LoginResult參數有新的AccessToken, 和最近授予或拒絕的權限。

你不需要registerCallback,才能成功登錄,您可以選擇 按照當前與下面描述的AccessTokenTracker 類訪問令牌的變化。

然後在onActivityResult()登錄結果轉發到onCreate()創建的 callbackManager

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    callbackManager.onActivityResult(requestCode, resultCode, data); 
} 

您用FacebookSDK 登錄集成或股份應轉發onActivityResultcallbackManager每項活動和片段。

要了解更多關於獲得額外的權限,請參閱:

Managing Permissions, AndroidPermissions with Facebook Login

+0

我還沒有試過Android SDK。我的意思是你使用哪個版本? –

-2
FACEBOOK LOGIN STEPBYSTEP 

    FacebookSdk.sdkInitialize(getApplicationContext()); 
     callbackManager = CallbackManager.Factory.create(); 
     printHashKey(); 

meta-data 
      android:name="com.facebook.sdk.ApplicationId" 
      android:value="@string/app_id" /> 

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



btnFacebook.setReadPermissions("public_profile","email"); 


btnFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
      String facebook_email; 
      String name; 
      String profilePicUrl; 
      private ProfileTracker mProfileTracker; 

      @Override 
      public void onSuccess(LoginResult loginResult) { 
       Log.e("facabook","Step1"); 
       GraphRequest request = GraphRequest.newMeRequest(
         loginResult.getAccessToken(), 
         new GraphRequest.GraphJSONObjectCallback() { 
          @Override 
          public void onCompleted(JSONObject object, GraphResponse response) { 
           Log.e("LoginActivity", response.toString()); 

           // Application code 
           try { 
            facebook_email = object.getString("email"); 
            name=object.getString("name"); 
            if (object.has("picture")) { 
             profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url"); 
             // set profile image to imageview using Picasso or Native methods 
            } 
           } catch (JSONException e) { 
            e.printStackTrace(); 
           } 

           if(Profile.getCurrentProfile() == null) { 
            mProfileTracker = new ProfileTracker() { 
             @Override 
             protected void onCurrentProfileChanged(Profile profile, Profile profile2) { 
              // profile2 is the new profile 
              Log.e("facebook - profile", profile2.getFirstName()); 

              facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD); 
              mProfileTracker.stopTracking(); 
             } 
            }; 
            mProfileTracker.startTracking(); 
           } else { 
            facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD); 
           } 
          } 
         }); 
       Bundle parameters = new Bundle(); 
       parameters.putString("fields", "id,name,email,picture.type(large)"); 
       request.setParameters(parameters); 
       request.executeAsync(); 
      } 

      @Override 
      public void onCancel() { 
       Log.e("facebook - onCancel", "cancelled"); 
      } 

      @Override 
      public void onError(FacebookException e) { 
       Log.e("facebook - onError", e.getMessage()); 
       Toast.makeText(SignInActivity.this,e.getMessage(),Toast.LENGTH_LONG).show(); 
      } 
     }); 

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     Log.e("Request Code", requestCode + "==========="); 
     if(requestCode==64206) 
     { 
      callbackManager.onActivityResult(requestCode, resultCode, data); 
     } 
    } 
-1

檢查這個簡單的Facebook登錄圖書館:

https://github.com/sromku/android-simple-facebook

這裏是鏈接到我上傳的演示爲簡單的Facebook登錄自定義按鈕:http://www.demoadda.com/demo/android/login-with-facebook_108

它是在Android應用程序中實現Facebook登錄的最簡單的方法。

您可以添加按鈕這樣的:

<TextView 
      android:id="@+id/btnFb" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="5dp" 
      android:background="@null" 
      android:gravity="center" 
      android:text="Login with Facebook" 
      android:textColor="@color/white" /> 

而且在gradle這個文件,你可以添加:

compile 'com.sromku:simple-fb:4.1.1' 

請檢查。

+0

已棄用。 –

1

我已經使用facebook sdk 4.10.0在我的android應用程序中集成登錄。 教程我跟着是:

Facebook login integration android studio.

您將能夠得到姓,名,電子郵件地址,性別,Facebook的帳號和出生日期從facebbok。

以上教程還介紹瞭如何通過視頻在Facebook開發人員控制檯中創建應用程序。

Gradle.build爲activity_main.xml中

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 23 
    buildToolsVersion "23.0.3" 

    defaultConfig { 
     applicationId "com.demonuts.fblogin" 
     minSdkVersion 16 
     targetSdkVersion 22 
     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.4.0' 
    compile 'com.facebook.android:facebook-android-sdk:4.10.0' 
    compile 'com.github.androidquery:androidquery:0.26.9' 
} 

源代碼

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="com.demonuts.fblogin.MainActivity"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="#000" 
     android:layout_marginLeft="10dp" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:id="@+id/text"/> 

    <ImageView 
     android:layout_width="300dp" 
     android:layout_height="300dp" 
     android:layout_marginTop="10dp" 
     android:layout_marginLeft="10dp" 
     android:id="@+id/ivpic" 
     android:src="@mipmap/ic_launcher"/> 

    <com.facebook.login.widget.LoginButton 
     android:id="@+id/btnfb" 
     android:layout_gravity="center_horizontal" 
     android:layout_marginTop="10dp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> </LinearLayout> 

代碼MainActivity.java

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.ImageView; 
import android.widget.TextView; 
import com.androidquery.AQuery; 
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.JSONException; 
import org.json.JSONObject; 
import java.util.Arrays; 

public class MainActivity extends AppCompatActivity { 



     private AQuery aQuery; 
     private ImageView ivpic; 
     private TextView tvdetails; 
     private CallbackManager callbackManager; 
     private AccessTokenTracker accessTokenTracker; 
     private ProfileTracker profileTracker; 
     private LoginButton loginButton; 
     private FacebookCallback&lt;LoginResult&gt; callback = new FacebookCallback&lt;LoginResult&gt;() { 
      @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()); 

           // Application code 
           try { 
            Log.d("tttttt",object.getString("id")); 
            String birthday=""; 
            if(object.has("birthday")){ 
             birthday = object.getString("birthday"); // 01/31/1980 format 
            } 

            String fnm = object.getString("first_name"); 
            String lnm = object.getString("last_name"); 
            String mail = object.getString("email"); 
            String gender = object.getString("gender"); 
            String fid = object.getString("id"); 
            tvdetails.setText("Name: "+fnm+" "+lnm+" \n"+"Email: "+mail+" \n"+"Gender: "+gender+" \n"+"ID: "+fid+" \n"+"Birth Date: "+birthday); 
            aQuery.id(ivpic).image("https://graph.facebook.com/" + fid + "/picture?type=large"); 
            //https://graph.facebook.com/143990709444026/picture?type=large 
            Log.d("aswwww","https://graph.facebook.com/"+fid+"/picture?type=large"); 

           } catch (JSONException e) { 
            e.printStackTrace(); 
           } 

          } 
         }); 
       Bundle parameters = new Bundle(); 
       parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location"); 
       request.setParameters(parameters); 
       request.executeAsync(); 

      } 

      @Override 
      public void onCancel() { 

      } 

      @Override 
      public void onError(FacebookException error) { 

      } 
     }; 


     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      FacebookSdk.sdkInitialize(this); 
      setContentView(R.layout.activity_main); 

      tvdetails = (TextView) findViewById(R.id.text); 
      ivpic = (ImageView) findViewById(R.id.ivpic); 

      loginButton = (LoginButton) findViewById(R.id.btnfb); 
      aQuery = new AQuery(this); 

      callbackManager = CallbackManager.Factory.create(); 

      accessTokenTracker= new AccessTokenTracker() { 
       @Override 
       protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) { 

       } 
      }; 

      profileTracker = new ProfileTracker() { 
       @Override 
       protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) { 

       } 
      }; 

      accessTokenTracker.startTracking(); 
      profileTracker.startTracking(); 
      loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends")); 
      loginButton.registerCallback(callbackManager, callback); 

     } 

     @Override 
     public void onActivityResult(int requestCode, int resultCode, Intent data) { 
      super.onActivityResult(requestCode, resultCode, data); 
      callbackManager.onActivityResult(requestCode, resultCode, data); 

     } 

     @Override 
     public void onStop() { 
      super.onStop(); 
      accessTokenTracker.stopTracking(); 
      profileTracker.stopTracking(); 
     } 

     @Override 
     public void onResume() { 
      super.onResume(); 
      Profile profile = Profile.getCurrentProfile(); 

     } 

    } 
相關問題