android - 如何从子 Activity 而不是主 Activity 使用 facebook 登录

标签 android facebook android-fragments android-developer-api

我对 facebook 和 android SDK 的所有这些集成有点陌生。 我按照 facebook 开发人员的初学者教程进行了登录,并且成功了, 但是当我将它与我的应用程序结合时,由于以下原因它不起作用:

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

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

MainActivity 调用的 Activity :

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

我的 list 设置的一部分:

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

最佳答案

已解决。在 Menifast 中, fragment 的父亲 Activity 没有历史记录。 我改成false就解决了。

关于android - 如何从子 Activity 而不是主 Activity 使用 facebook 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831329/

相关文章:

android - 圆形变为椭圆形

authentication - 访问 token 可以超过 255 个字符吗?

php - Facebook SDK PHP 显示用户的电子邮件地址

android - 跨方向更改保留 xml fragment

java - 从 2.3 升级后通过 Android Studio 2.3.3 安装 apk 的未知失败 (UnsatisfiedLinkError)

android - 即使 GPS 关闭,如何使用融合位置 API 获取位置更新?

java - 如何根据android中显示的字母更改字母的样式

ios - Facebook原生广告无法点击,无 react

android - 在提交 FragmentTransaction 之前检查状态是否已保存

java - 调用另一个 fragment 时 ListAdapter 错误