Jose Ignacio Hita
Jose Ignacio Hita

Reputation: 994

Facebook Session.openActiveSessionWithAccessToken is not working even with a valid token in Android

I'm working with Android and the Facebook API, basically, what I want is to create an alarm that do some Facebook stuff every certain time, even when the user has booted his device and the application is not running in the system.

I have my FacebookLoginFragment that is doing the login perfectly with the Facebook Login button this way:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    loginDone = false;

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

    Session.setActiveSession(new Session.Builder(getActivity().getBaseContext()).setApplicationId(getString(R.string.app_id)).build());

    return inflater.inflate(R.layout.fragment_facebook_login, container, false);
}

This is working, and this is the handler:

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (session.isOpened()) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (session.getAccessToken() != null)
            editor.putString("com.facebook.sdk.AccessToken", session.getAccessToken());

        if (session.getExpirationDate()!= null)
            editor.putLong("com.facebook.sdk.AccessTokenExpires", session.getExpirationDate().getTime());

        editor.commit();

        if (!loginDone) {
            loginDone = true;
            startActivity(new Intent(getActivity(), UpdateSnitchListActivity.class));
        }
    }
}

What I'm doing after the user is authorizing the application is to save the auth token. Then, in my BroadcastReceiver I want to access Facebook stuff but it's failing:

public class MyBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            Log.i("ALARM", "MyBootReceiver is executing when device boots");
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

            if (sharedPreferences.getBoolean(context.getString(R.string.preference_use_service), true)) {
                if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened()) {
                    String accessTokenString = sharedPreferences.getString("com.facebook.sdk.AccessToken", null);
                    Long accessTokenExpires = sharedPreferences.getLong("com.facebook.sdk.AccessTokenExpires", 0);

                    Session.setActiveSession(new Session.Builder(context).setApplicationId(context.getString(R.string.app_id)).build());
                    AccessToken accessToken = AccessToken.createFromExistingAccessToken(accessTokenString, new Date(accessTokenExpires), null, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, null);
                    Session.openActiveSessionWithAccessToken(context, accessToken, null);
                    // And then here I get the user's friends list and fail
                }
            }
        }
    }
}

This is the error I am getting every time I try:

Response:  responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 104, errorType: OAuthException, errorMessage: An access token is required to request this resource.}, isFromCache:false

I don't know what's the problem since I'm providing the access token and the access token expires that I'm getting from the user login, and when the user log in normally it works.

Thanks in advance!

Upvotes: 0

Views: 681

Answers (1)

Try to use String to save accessTokenExpires then get it this way:

SimpleDateFormat format = new SimpleDateFormat( "ccc MMM dd HH:mm:ss ZZZZ yyyy", Locale.ENGLISH );
try {
    Date expireDate = format.parse( accessTokenExpires );
} catch ( java.text.ParseException e ) {
    e.printStackTrace();
}

There's my working code:

SimpleDateFormat format = new SimpleDateFormat( "ccc MMM dd HH:mm:ss ZZZZ yyyy", Locale.ENGLISH );

try {
    Date expireDate = format.parse( accessExpireStr );
    AccessToken accessToken = AccessToken.createFromExistingAccessToken( accessTokenStr, expireDate, null, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, mPermissions );
    Session.openActiveSessionWithAccessToken( mActivity, accessToken, mFacebookCallback );
} catch ( java.text.ParseException e ) {
    e.printStackTrace();
}

Where

List<String> mPermissions = new ArrayList<String>();
mPermissions.add( "public_profile" );
mPermissions.add( "email" );

Upvotes: 1

Related Questions