The fb android sdk doc makes this reference:
“However, note that this doesn’t account for the situation where user may have revoked access to your app or if user has changed his password. You will need to always look out for the invalid access_token and redirect user to re-authorize your app. For invalid access token, following error is returned in the ‘response’ parameter of the onComplete() method:”
The docs offers a Shared Preferences solution to hiding the “OKAY” page every time a user launches your app. However, if the user changes their password or logs out of the fb app itself, my app (since a shared preference is set) ignores the login dialog as facebook.authorize()is not called. Given the implementation found on the docs, how does one listen for the access_token error when onComplete() is never called again.
package com.greatapp;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.facebook.android.*;
import com.facebook.android.Facebook.*;
public class MyGreatActivity extends Activity {
Facebook facebook = new Facebook("YOUR_APP_ID");
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* Get existing access_token if any
*/
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if(!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
@Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
@Override
public void onFacebookError(FacebookError error) {}
@Override
public void onError(DialogError e) {}
@Override
public void onCancel() {}
});
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
If you want to keep your app structure (using the Preferences to get the access_token without having to do a user login each time), then you will only find out that the access_token is invalid when you actually try and use the API. For example, if you send a GRAPH API request when the token is invalid, the SDK will send something like the following.
which will return the following JSON (which is pretty clear).
At which point you will know that you need to do an authorize().