1

我对 facebook 和 android SDK 的所有这些集成有点陌生。我按照 facebook 开发人员的初学者教程执行登录并且它有效,但是当我将它与我的应用程序结合时它没有工作,原因如下:

在我的项目中,我编写了一个从主要活动到另一个正在调用登录片段的 Fragmentactivity (FBProfile) 的调用。在 facebook 的身份验证之后,它将返回到 MainActivity 中的 OnResume,而不是 LoginFragment 中覆盖的 onActivityresult。

我需要创建这个流程(如果可能的话): MainActivity->FBProfile(FragmentActivity)->LoginFragment->Facebook->LoginFragment

MainActivity 调用的活动:

public class FBProfile extends FragmentActivity{


  private LoginFragment loginfragment; 


  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      // TODO Auto-generated method stub
      Log.i(" Facebook: ", "FBProfile->OnCreate");
      if(savedInstanceState==null)
      {
loginfragment=new LoginFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, loginfragment).commit();
}
else
{
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}  
}

从 FBProfile 调用的 LoginFragment:

public class LoginFragment extends Fragment {
 private View login_view;
 private boolean isResumed = false;   
 private static final String TAG="LoginFragment";
 private UiLifecycleHelper uihelper;
 private LoginButton authbutton;
 private TextView userInfoTextView;
 private Session.StatusCallback callback=new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            // TODO Auto-generated method stub
            onSessionStatechange(session, state, exception);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.i(" Facebook: ", "FBProfile->OnCreate->LoginFragment");
        login_view=inflater.inflate(R.layout.profilepage, container,false);
       userInfoTextView = (TextView) login_view.findViewById(R.id.userInfoTextView);

        authbutton=(LoginButton) login_view.findViewById(R.id.login_button);
        authbutton.setFragment(this);
        authbutton.setReadPermissions(Arrays.asList("public_profile","email","user_birthday"));

        return login_view;
    }

    @SuppressWarnings("deprecation")
    private void onSessionStatechange(Session session,SessionState state,Exception exception)
    {
        if (isResumed) {
            if (session != null && session.isOpened()) {
                Intent intent = new Intent(getActivity(),
                        FBProfile.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
        if(state.isOpened()){
            Log.i(" Facebook: ", "LOGGED IN....");
            userInfoTextView.setVisibility(View.VISIBLE);

             // Request user data and show the results
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // TODO Auto-generated method stub
                    if (user != null) {
                        // Display the parsed user info
                        userInfoTextView.setText(buildUserInfoDisplay(user));
                    }
                }
            });


            Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_LONG).show();
        }
        else
        {
             userInfoTextView.setVisibility(View.INVISIBLE);
            if (Session.getActiveSession() != null) {
                Session.getActiveSession().closeAndClearTokenInformation();
            }

            Session.setActiveSession(null);
            Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_LONG).show();
            Log.i(" Facebook: ", "LOGGED OUT....");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        uihelper=new UiLifecycleHelper(getActivity(), callback);
        uihelper.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Session session=Session.getActiveSession();
        if((session!=null)&&(session.isOpened()||session.isClosed()))
        {
            onSessionStatechange(session, session.getState(), null);

        }
        isResumed = true;
        uihelper.onResume();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        uihelper.onPause();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        uihelper.onSaveInstanceState(outState);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        uihelper.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("LoginFragment: ","onActivityResult Called");
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }
    /**
     * 
     * @param user
     * @return
     */
    private String buildUserInfoDisplay(GraphUser user) {
        StringBuilder userInfo = new StringBuilder("");

        // Example: typed access (name)
        // - no special permissions required
        userInfo.append(String.format("Name: %s\n\n", 
            user.getName()));

        // Example: typed access (birthday)
        // - requires user_birthday permission
        userInfo.append(String.format("Birthday: %s\n\n", 
            user.getBirthday()));

        // Example: partially typed access, to location field,
        // name key (location)
        // - requires user_location permission
  //      userInfo.append(String.format("Location: %s\n\n", 
  //          user.getLocation().getProperty("name")));

        // Example: access via property name (locale)
        // - no special permissions required
//        userInfo.append(String.format("Locale: %s\n\n", 
 //           user.getProperty("locale")));

        // Example: access via key for array (languages) 
        // - requires user_likes permission
        JSONArray languages = (JSONArray)user.getProperty("languages");
        if (languages.length() > 0) {
            ArrayList<String> languageNames = new ArrayList<String> ();
            for (int i=0; i < languages.length(); i++) {
                JSONObject language = languages.optJSONObject(i);
                // Add the language name to a list. Use JSON
                // methods to get access to the name field. 
                languageNames.add(language.optString("name"));
            }           
            userInfo.append(String.format("Languages: %s\n\n", 
            languageNames.toString()));
        }

        return userInfo.toString();
    }
}

我的清单设置的一部分:

<uses-sdk android:minSdkVersion="14"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.GET_TASKS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/APP_FB_ID"/>
    <activity
        android:name=".Splash"
        android:label="@string/app_name" >
        <intent-filter>
             <action android:name="android.intent.action.CREATE_SHORTCUT" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:noHistory="false"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEAFULT" />
        </intent-filter>
    </activity>
4

1 回答 1

1

解决了。在 Menifast 中,片段的父亲活动被设定为无历史。我将其更改为 false 并解决了。

于 2014-09-16T09:52:47.507 回答