0

我正在创建一个仅包含 java 类的简单库项目。其中不应该有任何活动参与我遵循了 facebook 开发人员页面https://developers.facebook.com/docs/android/中的教程

基于此,我尝试在我的 java 类上实现它,例如

Session.openActiveSession(a,true,new Session.StatusCallback() 
{
                    @Override   
                    public void call(final Session session, final SessionState state, final Exception exception) 
                    {Log.e("Session",session.getAccessToken());
                        Log.e("Session Status",session.toString());
                        if(session.isOpened())
                        {
                            Toast.makeText(c,session.getAccessToken(),Toast.LENGTH_LONG).show();
                            Log.e("Access Token",session.getAccessToken());
                        }
                        else
                        {
                            Log.e("Session","Not Opened");

                        }

                    }
                });

现在,当我使用记录器检查会话值时,结果是

 session {state:OPENING,access_token=ACCESS_TOKEN_REMOVED}

我的要求是:

  1. 仅使用简单 java 类的具有本机登录支持的简单库 无活动
  2. 流程就像如果用户已经登录 facebook 本机应用程序,那么我的库将从会话中检索访问令牌,否则我的 Facebook 网络视图将继续
  3. 我只需要 facebook 访问令牌
4

3 回答 3

2

我以这种方式实现了它。可能这对你有帮助。

//starting facebook session
public void facebookstart() {
    // TODO Auto-generated method stub

    Session.openActiveSession(this, true, new Session.StatusCallback() {

        // callback when session changes state
        @SuppressWarnings("deprecation")
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (session.isOpened()) {
                Log.e("",
                        "session details"
                                + session);
                acesstoken=session.getAccessToken();
                // make request to the /me API
                Request.executeMeRequestAsync(session,
                        new Request.GraphUserCallback() {

                            // callback after Graph API response with user
                            // object
                            @Override
                            public void onCompleted(GraphUser user,
                                    Response response) {
                                if (user != null) {
                                    pv = (ProfilePictureView) findViewById(R.id.profilePictureView1);
                                    pv.setProfileId(user.getId());
                                    welcome = (TextView) findViewById(R.id.name);
                                    welcome.setText("Hi  " + user.getName()+"\n"+""+user.getBirthday()
                                            + "!");
                                    logout.setText("log out");
                                    image();
                                }
                            }
                        });
            }
        }
    });
}
于 2013-11-15T05:16:11.297 回答
2
Try My function It will do wat you want buddy

// Function to signin with Facebook
    private void signInWithFacebook() {
        viewProgressVisible("Loading...");
        SessionTracker mSessionTracker = new SessionTracker(getBaseContext(),
                new StatusCallback() {

                    public void call(Session session, SessionState state,
                            Exception exception) {
                    }
                }, null, false);

        String applicationId = Utility
                .getMetadataApplicationId(getBaseContext());
        mCurrentSession = mSessionTracker.getSession();

        if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
            mSessionTracker.setSession(null);
            Session session = new Session.Builder(getBaseContext())
                    .setApplicationId(applicationId).build();
            Session.setActiveSession(session);
            mCurrentSession = session;
            if (authDialog != null)
                viewProgressGone();

        }
        Log.d("session in login", mCurrentSession + "");
        if (!mCurrentSession.isOpened()) {

            Session.OpenRequest openRequest = null;
            openRequest = new Session.OpenRequest(MainActivity.this);

            if (openRequest != null) {
                if (authDialog != null)
                    viewProgressGone();
                openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
                openRequest.setPermissions(Arrays.asList("email"));

                openRequest
                        .setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
                mCurrentSession.openForRead(openRequest);

            }
        } else {
            Request.executeMeRequestAsync(mCurrentSession,
                    new Request.GraphUserCallback() {

                        @Override
                        public void onCompleted(GraphUser user,
                                Response response) {
                            Log.e("myConsultant",
                                    user.getId() + " " + user.getName() + " "
                                            + user.getInnerJSONObject() + ""
                                            + user.asMap().get("email"));

                            if (authDialog != null)
                                viewProgressGone();

                        }
                    });
        }
    }

    public void viewProgressGone() {
        authDialog.dismiss();
    }

    public void viewProgressVisible(String paramString) {
        authDialog = ProgressDialog.show(this, "", paramString, true, false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode,
                resultCode, data);
        Log.v("the session created",
                ""
                        + Session.getActiveSession().onActivityResult(this,
                                requestCode, resultCode, data));
        signInWithFacebook();
    }

将此添加到清单以及..

   <activity
        android:name="com.facebook.LoginActivity"
        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" />
于 2013-11-15T05:17:02.080 回答
2

试试这个完整的工作解决方案

1) 创建活动

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

public class FacebookLoginActivity extends FragmentActivity {

    private LinearLayout lnrPbr;
    private TextView txtPbr;
    private FacebookLoginMainFragment mainFragment;
    private UiLifecycleHelper uiHelper;

    /**
     * Overrides method
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            // Add the fragment on initial activity setup
            mainFragment = new FacebookLoginMainFragment();
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
        } else {
            // Or set the fragment from restored state info
            mainFragment = (FacebookLoginMainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
        }

        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        lnrPbr = (LinearLayout) findViewById(R.id.lnrPbr);
        txtPbr = (TextView) findViewById(R.id.txtPbr);
        txtPbr.setText("");
        Session session = Session.getActiveSession();
        if (session != null && (session.isOpened() || session.isClosed())) {
            onSessionStateChange(session, session.getState(), null);
        } else {

            if (session == null) {
                session = new Session(this);
                Session.setActiveSession(session);
            }
            OpenRequest openRequest = new OpenRequest(this);
            List<String> readPermissions = new ArrayList<String>();
            readPermissions.add("email");
            openRequest.setPermissions(readPermissions);
            openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
            openRequest.setCallback(callback);
            session.openForRead(openRequest);

        }

        uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            finish();
        } else {
            uiHelper.onActivityResult(requestCode, resultCode, data);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
        try {
            Session.getActiveSession().closeAndClearTokenInformation();
            Session.setActiveSession(null);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

    /**
     * Class method
     */

    /**
     * This method used to after session state change listner.
     * 
     * @param session
     *            represent {@link Session}
     * @param state
     *            represent {@link SessionState}
     * @param exception
     *            represent exception
     */
    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {

            // Your session is opend here

            session.getAccessToken();

        } else if (state.isClosed()) {
            OpenRequest openRequest = new OpenRequest(this);
            List<String> readPermissions = new ArrayList<String>();
            readPermissions.add("email");
            openRequest.setPermissions(readPermissions);
            openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
            openRequest.setCallback(callback);
            session.openForRead(openRequest);
        }
    }

    /**
     * This method used to get session status callback change listner.
     */
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

}

2)创建片段

import java.util.Arrays;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.widget.LoginButton;

public class FacebookLoginMainFragment extends Fragment {

    private static final List<String> PERMISSIONS = Arrays.asList("email");

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

        LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(PERMISSIONS);
        authButton.setApplicationId("123124234234-YourAppID");

        return view;
    }
}

3) Fragment 需要的布局文件

<?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:background="@android:color/white"
    android:orientation="vertical" >

    <com.facebook.widget.LoginButton
        android:id="@+id/authButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:visibility="gone" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:text="Facebook"
        android:textSize="45sp" />

    <LinearLayout
        android:id="@+id/lnrPbr"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_marginBottom="150dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone" >

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtPbr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center" />
    </LinearLayout>

</LinearLayout>
于 2013-11-15T05:45:37.077 回答