I've been working with the new Facebook Android SDK (version 3.0) the past two weeks and every time I thought "yes, now I've got it!", I've found something wrong with the integration of it in my apps! But this time I think I've really got it (!!) and I'm gonna do a sequence of three Blog posts to explain (1) how to connect to a Facebook user account and open a Facebook session, (2) how to obtain additional, required Facebook permissions and then perform a Facebook API request like posting to the user's feed, and (3) how to log out and close the Facebook session. I wish the official documentation better explained these core concepts but it doesn't! And this is evident in browsing developer forums like Stack Overflow where almost everybody has a different take on how to perform the above operations!! So here's my two cents...
Firstly, I like to a have single
Activity
(let's call it
BaseFacebookActivity
) that has all my Facebook methods in it and which Activities that do Facebook operations are to extend. Don't forget the
onActivityResult(...)
method!, as follows:
public abstract class BaseFacebookActivity
extends Activity
{
@Override
protected void onActivityResult(
int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(
this,
requestCode,
resultCode,
data);
}
// other methods to follow
}
Secondly, let's define an interface which will help us report back to the user when an attempt to open a Facebook session has been successful or not, as follows:
public interface FacebookConnectHandler
{
/** Method to call when the user's Facebook account
* was connected to
* and a Facebook session was opened successfully.*/
public void onSuccess();
/** Method to call when the user's Facebook account
* was not connected to
* or a Facebook session was not opened successfully.*/
public void onFailure();
}
Thirdly and finally, a method to put in your
BaseFacebookActivity
which will connect to the user's Facebook account and open a Facebook session, as follows:
private void connectFacebookAccount(
final FacebookConnectHandler handler)
{
// safety check
if (!isActiveNetworkConnected())
{
handler.onFailure();
return;
}
// check whether the user already has an active session
// and try opening it if we do
// (note: making a Session.openActiveSessionFromCache(...) call
// instead of simply checking whether the active session is opened
// because of a bug in the Facebook sdk
// where successive calls to update a token
// (requesting additional permissions etc)
// don't result in a session callback)
if (Session.getActiveSession() != null
&& Session.openActiveSessionFromCache(this) != null)
{
handler.onSuccess();
return;
}
// initialise the session status callback
Session.StatusCallback callback = new Session.StatusCallback()
{
@Override
public void call(
Session session,
SessionState state,
Exception exception)
{
// safety check
if (isFinishing())
return;
// check session state
if (state.equals(SessionState.CLOSED)
|| state.equals(SessionState.CLOSED_LOGIN_FAILED))
{
clearFacebookInfoFromSharedPreferences();
// specific action for when the session is closed
// because an open-session request failed
if (state.equals(SessionState.CLOSED_LOGIN_FAILED))
{
cancelProgressDialog();
handler.onFailure();
}
}
else if (state.equals(SessionState.OPENED))
{
cancelProgressDialog();
saveFacebookInfoInSharedPreferences(
session.getAccessToken(),
session.getExpirationDate());
showToast("Succeeded connecting to Facebook");
handler.onSuccess();
}
}
};
// make the call to open the session
showProgressDialog("Connecting to Facebook...");
if (Session.getActiveSession() == null
&& getSharedPreferences().contains("facebookAccessToken")
&& getSharedPreferences().contains("facebookAccessTokenExpires"))
{
// open a session from the access token info
// saved in the app's shared preferences
String accessTokenString = getSharedPreferences().getString(
"facebookAccessToken",
"");
Date accessTokenExpires = new Date(getSharedPreferences().getLong(
"facebookAccessTokenExpires",
0));
AccessToken accessToken = AccessToken.createFromExistingAccessToken(
accessTokenString,
accessTokenExpires,
null,
null,
null);
Session.openActiveSessionWithAccessToken(this, accessToken, callback);
}
else
// open a new session, logging in if necessary
Session.openActiveSession(this, true, callback);
}
Done! In the next Blog post I'll show how to use this
connectFacebookAccount(...)
method prior to making a Facebook API request like posting to the user's feed.