2

在我的 android 应用程序中,我正在使用Android-Facebook Sdk 3.6.0从我的应用程序发布 Facebook 状态。我参考HelloFacebookSample了 sdk 提供的示例。我实现了在 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>
4

3 回答 3

0

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

于 2014-01-08T09:44:35.687 回答
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>

并且在应用程序结束时,您需要 chg 返回旋转

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

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

于 2014-04-23T14:36:48.297 回答
0

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

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

android: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">
于 2014-02-21T00:06:13.947 回答