Changing orientation open Facebook share dialog twice - Android Facebook sdk

2k views Asked by At

In my android app, i am using Android-Facebook Sdk 3.6.0 to post Facebook status from my app. I referred HelloFacebookSample from samples available with sdk. I implemented everything necessary for posting on facebook but i am facing weird issue related to screen orientation. My entire app is in landscape mode and when i update status from that, it opens Share dialog in portrait mode if device screen orientation is disabled. At that time, on clicking Share button does nothing but reopens that same dialog and then status is not updated. If i do same thing after enabling device screen orientation then it works perfectly. I don't know, why i am facing this issue. Please help me to solve this issue. Thanks.

Code :

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

Menifest :

<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

There are 3 answers

0
user3172609 On
1
user701632 On

I think i had a similar problem on a nexus 4 running android 4.2.2 (this feature worked fine for other devices like the nexus 5 running 4.4.2 and a galaxy s2 running 3.something)

in my application XML, the activity for your share dialog had

android:windowSoftInputMode="adjustResize"

removing this entry made the device able to properly share and return to the main activity.

Here's my diff:

-                <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">
0
SeanOSY On

i found an solution on a stackoverflow

https://stackoverflow.com/a/9720004

using

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

you need to edit your manifest.xml as well

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

and at your end of the apps you need chg back the rotation

else it stay the way you rotate before...

this only can help force all the apps open in the rotation you want but not the best solution...