2

我是android的新手,並在登錄後獲取facebook profilel信息的演示,我已成功實現登錄,並希望獲取配置文件信息,我得到的代碼,但雖然添加配置文件信息它無法導入必要的類(會話),可以anybudy幫助我做到這一點。 的java不能導入facebook在android工作室的android會話類

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.Session; 
import com.facebook.login.LoginResult; 
import com.facebook.login.widget.LoginButton; 

. 
. 
. 
. 
. 


private Session openActiveSession(Activity activity, boolean allowLoginUI, 
             StatusCallback callback, List<String> permissions, Bundle savedInstanceState) { 
     OpenRequest openRequest = new OpenRequest(activity). 
       setPermissions(permissions).setLoginBehavior(SessionLoginBehavior. 
       SSO_WITH_FALLBACK).setCallback(callback). 
       setDefaultAudience(SessionDefaultAudience.FRIENDS); 

     Session session = Session.getActiveSession(); 
     Log.d(LOG_TAG, "" + session); 
     if (session == null) { 
      Log.d(LOG_TAG, "" + savedInstanceState); 
      if (savedInstanceState != null) { 
       session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState); 
      } 
      if (session == null) { 
       session = new Session(this); 
      } 
      Session.setActiveSession(session); 
      if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) { 
       session.openForRead(openRequest); 
       return session; 
      } 
     } 
     return null; 
    } 

回答

2

這是facebook集成工作代碼:

1)創建一個XML:fragment_main.xml

<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:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:orientation="vertical" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment"> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="New Text" 
     android:id="@+id/textView" 
     android:layout_centerHorizontal="true"/> 


    <com.facebook.login.widget.LoginButton 
     android:id="@+id/login_button" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</LinearLayout> 

2)的Java類即MainFragment.java

package example.com.facebook_integration; 

/** 
* Created by dinesh sharma on 2/22/2016. 
*/ 

import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.TextView; 

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.HttpMethod; 
import com.facebook.Profile; 
import com.facebook.ProfileTracker; 
import com.facebook.login.LoginResult; 
import com.facebook.login.widget.LoginButton; 

import net.simplifiedcoding.androidlogin.R; 

import org.json.JSONArray; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.Arrays; 


/** 
* A placeholder fragment containing a simple view. 
*/ 
public class MainFragment extends Fragment { 

    private CallbackManager callbackManager; 
    private TextView textView; 
    private AccessTokenTracker accessTokenTracker; 
    private ProfileTracker profileTracker; 

    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() { 
     @Override 
     public void onSuccess(LoginResult loginResult) { 
      AccessToken accessToken = loginResult.getAccessToken(); 
      Profile profile = Profile.getCurrentProfile(); 
      displayMessage(profile); 
     } 

     @Override 
     public void onCancel() { 

     } 

     @Override 
     public void onError(FacebookException e) { 

     } 
    }; 

    public MainFragment() { 

    } 


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

     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) { 
       displayMessage(newProfile); 
      } 
     }; 

     accessTokenTracker.startTracking(); 
     profileTracker.startTracking(); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_main, container, false); 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 
     LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button); 
     final ImageView imageView=(ImageView)view.findViewById(R.id.myImage); 
     textView = (TextView) view.findViewById(R.id.textView); 

     //loginButton.setReadPermissions("user_likes"); 
     loginButton.setFragment(this); 
     loginButton.registerCallback(callbackManager, callback); 

     loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday","user_likes","user_friends")); 

     callbackManager = CallbackManager.Factory.create(); 

     // Callback registration 
     loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
      @Override 
      public void onSuccess(LoginResult loginResult) { 
       // App code 
       GraphRequest request = GraphRequest.newMeRequest(
         loginResult.getAccessToken(), 
         new GraphRequest.GraphJSONObjectCallback() { 
          @Override 
          public void onCompleted(final JSONObject object, GraphResponse response) 
          { 
           Log.v("LoginActivity", response.toString()); 
           try 
           { 
            // Application code 
            System.out.println("JSONRESPOMSEEE "+response.toString()); 

            String email = object.getString("email"); 
            String birthday = object.getString("birthday"); // 01/31/1980 format 
            String name = object.getString("name"); 
            Profile profile = Profile.getCurrentProfile(); 
            Uri uri=(Uri)profile.getProfilePictureUri(200,200); 
            System.out.println("Email "+email+" Birthday "+birthday+name); 
            System.out.println("Email " + uri); 
            final ArrayList arrayList=new ArrayList(); 


            new GraphRequest(
              AccessToken.getCurrentAccessToken(), 
              "/me/likes", 
              null, 
              HttpMethod.GET, 
              new GraphRequest.Callback() { 
               public void onCompleted(GraphResponse response) { 
                try { 
                 JSONObject json = new JSONObject(response.getRawResponse()); 
                 JSONArray jarray = json.getJSONArray("data"); 

                 for (int i = 0; i < jarray.length(); i++) { 
                  JSONObject likes = jarray.getJSONObject(i); 
                  String likeId = likes.getString("id"); 
                  String likeName = likes.getString("name"); 
                  String likeCreatedTime = likes.getString("created_time"); 
                  arrayList.add("Page Name "+likeName+" Time= "+likeCreatedTime+" ID= "+likeId); 
                  System.out.println("My Name " + likeName + " " + likeCreatedTime); 
                 } 
                 System.out.println("ArrayList mine "+arrayList); 
                 System.out.println("ArrayList mine size "+arrayList.size()); 


                } 
                catch(Exception e) 
                { 
                 System.out.println("My Exception "+e); 
                } 
               } 

              } 
            ).executeAsync(); 



           } 
           catch (Exception e) 
           { 
            e.printStackTrace(); 
           } 
          } 
         }); 
       Bundle parameters = new Bundle(); 
       parameters.putString("fields", "id,name,email,gender,birthday"); 
       request.setParameters(parameters); 
       request.executeAsync(); 

      } 

      @Override 
      public void onCancel() { 
       // App code 
       Log.v("LoginActivity", "cancel"); 
      } 

      @Override 
      public void onError(FacebookException exception) { 
       // App code 
       Log.v("LoginActivity", exception.getCause().toString()); 
      } 
     }); 
    } 
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 
     callbackManager.onActivityResult(requestCode, resultCode, data); 
    } 

    private void displayMessage(Profile profile) { 
     if(profile != null){ 
      textView.setText(profile.getName()); 
     } 
    } 

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

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

} 

3)Cr eate一個多個XML:activity_main.xml中

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 


    <fragment 
     android:id="@+id/fragment" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:name="example.com.facebook_integration.MainFragment" 
     ></fragment> 
</RelativeLayout> 

4)創建MainActivity.java

package example.com.facebook_integration; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 

import net.simplifiedcoding.androidlogin.R; 

public class MainActivity extends AppCompatActivity 
{ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

請參閱此鏈接https://www.simplifiedcoding.net/login-with-facebook-android-studio-using-facebook-sdk-4/

但我已經做了所有我的代碼,你可以的重要變化遵循上述所有步驟後使用此代碼。

+0

@ danish-well bro bro .. thanks ... –

+0

歡迎brother @sulphuricAcid –