无法在 android 工作室的 android 中导入 facebook 会话 class
Cant import facebook Session class in android in android studio
我是 android 的新手,正在开发登录后获取 facebook 个人资料信息的演示,我已经成功实现登录并想要获取个人资料信息,我得到了代码,但是在添加个人资料信息时它是导入必要的 类(Session) 失败,任何朋友都可以帮我解决这个问题。
java
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;
}
这是 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 Class 即 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) 再创建一个 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);
}
}
看到这个linkhttps://www.simplifiedcoding.net/login-with-facebook-android-studio-using-facebook-sdk-4/
但是我已经对我的代码进行了所有重要更改,您可以在执行上述所有步骤后使用此代码 link。
我是 android 的新手,正在开发登录后获取 facebook 个人资料信息的演示,我已经成功实现登录并想要获取个人资料信息,我得到了代码,但是在添加个人资料信息时它是导入必要的 类(Session) 失败,任何朋友都可以帮我解决这个问题。 java
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;
}
这是 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 Class 即 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) 再创建一个 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);
}
}
看到这个linkhttps://www.simplifiedcoding.net/login-with-facebook-android-studio-using-facebook-sdk-4/
但是我已经对我的代码进行了所有重要更改,您可以在执行上述所有步骤后使用此代码 link。