更改方向打开Facebook共享对话框两次 - Android Facebook sdk

时间:2013-12-14 12:47:14

标签: android facebook facebook-android-sdk android-facebook android-sharing

在我的Android应用程序中,我正在使用Android-Facebook Sdk 3.6.0从我的应用程序发布Facebook状态。我从sdk提供的样本中提到了HelloFacebookSample。我实现了在Facebook上发布所需的一切,但我面临与屏幕方向相关的奇怪问题。我的整个应用都处于landscape模式,当我从中更新状态时,如果设备屏幕方向被禁用,则会以纵向模式打开Share dialog。那时,单击Share按钮除了重新打开相同的对话框之外什么都不做,然后状态不会更新。如果我在启用设备屏幕方向后执行相同的操作,那么它可以正常工作我不知道,为什么我要面对这个问题。请帮我解决这个问题。 感谢。

代码:

ShareScoreActivity.java

public class ShareScoreActivity extends FragmentActivity {

private static final String PERMISSION = "publish_actions";



private final String PENDING_ACTION_BUNDLE_KEY = "com.packg.appname.ShareScoreActivity:PendingAction";

private Button postStatusUpdateButton;

private LoginButton loginButton;

private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;

private enum PendingAction {
    NONE, POST_STATUS_UPDATE // POST_PHOTO
}

private UiLifecycleHelper uiHelper;

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
            Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
    @Override
    public void onError(FacebookDialog.PendingCall pendingCall,
            Exception error, Bundle data) {
        Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
    }

    @Override
    public void onComplete(FacebookDialog.PendingCall pendingCall,
            Bundle data) {
        Log.d("HelloFacebook", "Success!");
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);


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

    if (savedInstanceState != null) {
        String name = savedInstanceState
                .getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }

    setContentView(R.layout.share_screen);

    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton
            .setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
                @Override
                public void onUserInfoFetched(GraphUser user) {
                    ShareScoreActivity.this.user = user;
                    updateUI();
                    // It's possible that we were waiting for this.user to
                    // be populated in order to post a
                    // status update.
                    handlePendingAction();
                }
            });

    postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
    postStatusUpdateButton.setTypeface(Typeface.createFromAsset(
            getAssets(), "RayGun.ttf"));
    postStatusUpdateButton.setTextColor(Color.parseColor("#66863A"));
    postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPostStatusUpdate();
        }
    });

    controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);

    final FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment != null) {
        // If we're being re-created and have a fragment, we need to a) hide
        // the main UI controls and
        // b) hook up its listeners again.
        controlsContainer.setVisibility(View.GONE);

    }

    // Listen for changes in the back stack so we know if a fragment got
    // popped off because the user
    // clicked the back button.
    fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (fm.getBackStackEntryCount() == 0) {
                // We need to re-show our UI.
                controlsContainer.setVisibility(View.VISIBLE);
            }
        }
    });

    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

}

@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();

    // Call the 'activateApp' method to log an app event for use in
    // analytics and advertising reporting. Do so in
    // the onResume methods of the primary Activities that an app may be
    // launched into.
    AppEventsLogger.activateApp(this);

    updateUI();
}

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

    outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}

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

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

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    ShareScoreActivity.this.finish();
    Intent levelIntent = new Intent(ShareScoreActivity.this,
            LevelActivity.class);
    levelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(levelIntent);
}

private void onSessionStateChange(Session session, SessionState state,
        Exception exception) {
    if (pendingAction != PendingAction.NONE
            && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
        new AlertDialog.Builder(ShareScoreActivity.this)
                .setTitle(R.string.cancelled)
                .setMessage(R.string.permission_not_granted)
                .setPositiveButton(R.string.ok, null).show();
        pendingAction = PendingAction.NONE;
    } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
        handlePendingAction();
    }
    updateUI();
}

private void updateUI() {
    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());

    postStatusUpdateButton.setEnabled(enableButtons
            || canPresentShareDialog);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    super.onConfigurationChanged(newConfig);
}

@SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
    PendingAction previouslyPendingAction = pendingAction;
    // These actions may re-set pendingAction if they are still pending, but
    // we assume they
    // will succeed.
    pendingAction = PendingAction.NONE;

    switch (previouslyPendingAction) {

    case POST_STATUS_UPDATE:
        postStatusUpdate();
        break;
    }
}

private interface GraphObjectWithId extends GraphObject {
    String getId();
}

private void showPublishResult(String message, GraphObject result,
        FacebookRequestError error) {
    String title = null;
    String alertMessage = null;
    if (error == null) {
        title = getString(R.string.success);
        String id = result.cast(GraphObjectWithId.class).getId();
        alertMessage = getString(R.string.successfully_posted_post,
                message, id);
    } else {
        title = getString(R.string.error);
        alertMessage = error.getErrorMessage();
    }

    new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
            .setPositiveButton(R.string.ok, null).show();
}

private void onClickPostStatusUpdate() {
    performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}

private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
    return new FacebookDialog.ShareDialogBuilder(this)
            .setName("Egg Catcher")
            .setDescription(
                    "The 'Egg catcher' application Facebook integration")
             .setLink("http://developers.facebook.com/android");                    
}

private void postStatusUpdate() {
    if (canPresentShareDialog) {
        FacebookDialog shareDialog = createShareDialogBuilder().build();
        uiHelper.trackPendingDialogCall(shareDialog.present());
    } else if (user != null && hasPublishPermission()) {
        final String message = getString(R.string.status_update,
                user.getFirstName(), (new Date().toString()));
        Request request = Request.newStatusUpdateRequest(
                Session.getActiveSession(), message, place, tags,
                new Request.Callback() {
                    @Override
                    public void onCompleted(Response response) {
                        showPublishResult(message,
                                response.getGraphObject(),
                                response.getError());
                    }
                });
        request.executeAsync();
    } else {
        pendingAction = PendingAction.POST_STATUS_UPDATE;
    }
}



private boolean hasPublishPermission() {
    Session session = Session.getActiveSession();
    return session != null
            && session.getPermissions().contains("publish_actions");
}

private void performPublish(PendingAction action, boolean allowNoSession) {
    Session session = Session.getActiveSession();
    if (session != null) {
        pendingAction = action;
        if (hasPublishPermission()) {
            // We can do the action right away.
            handlePendingAction();
            return;
        } else if (session.isOpened()) {
            // We need to get new permissions, then complete the action when
            // we get called back.
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                    this, PERMISSION));
            return;
        }
    }

    if (allowNoSession) {
        pendingAction = action;
        handlePendingAction();
    }
}
}

宣言:

<meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
<application>
 <activity
            android:name="com.pakg.appname.ShareScoreActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_score"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:configChanges="orientation|keyboardHidden|screenSize|navigation"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    </application>

3 个答案:

答案 0 :(得分:0)

谢谢Zanky。我在这个问题上向facebook开发者汇报。等他...... https://developers.facebook.com/bugs/577438772347318?browse=external_tasks_search_results_52cd1d37d8cbb8128046135

答案 1 :(得分:0)

我认为我在运行android 4.2.2的nexus 4上遇到了类似的问题(此功能适用于其他设备,例如运行4.4.2的nexus 5和运行3.something的galaxy s2)

在我的应用程序XML中,您的共享对话框的活动已

  

机器人:windowSoftInputMode = “adjustResize”

删除此条目使设备能够正确共享并返回主活动。

这是我的差异:

-                <activity android:name="com.freshplanet.ane.AirFacebook.ShareDialogActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" android:windowSoftInputMode="adjustResize" android:label="@string/app_name">
+                <activity android:name="com.freshplanet.ane.AirFacebook.ShareDialogActivity" android:label="@string/app_name">

答案 2 :(得分:0)

我在stackoverflow上找到了一个解决方案

https://stackoverflow.com/a/9720004

使用

android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.USER_ROTATION,user_rotation);

user_rotation 0 -> ROTATION_0
user_rotation 1 -> ROTATION_90
user_rotation 2 -> ROTATION_180
user_rotation 3 -> ROTATION_270

您还需要编辑manifest.xml

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

在应用程序结束时,你需要回到轮换

否则它会保持你之前旋转的方式......

这只能帮助强制所有应用程序在你想要的轮换中打开,但不是最好的解决方案...