Session
最新版本的 SDK 已不再提供此課程。
有此級別的更新版本。前往查看 最新版本。

Session is used to authenticate a user and manage the user's session with Facebook.

Sessions must be opened before they can be used to make a Request. When a Session is created, it attempts to initialize itself from a TokenCachingStrategy. Closing the session can optionally clear this cache. The Session lifecycle uses SessionState to indicate its state. Once a Session has been closed, it can't be re-opened; a new Session must be created.

Instances of Session provide state change notification via a callback interface, StatusCallback.

伸延:Object
實作Serializable
套件:facebook
建構函式
Session(Context)

Initializes a new Session with the specified context.

public Session(Context currentContext)
參數說明
currentContextThe Activity or Service creating this Session.
類別方式
saveSession(Session, Bundle)

Save the Session object into the supplied Bundle. This method is intended to be called from an Activity or Fragment's onSaveInstanceState method in order to preserve Sessions across Activity lifecycle events.

public static final void saveSession(Session session, Bundle bundle)
參數說明
sessionThe Session to save
bundleThe Bundle to save the Session to
restoreSession(Context, TokenCachingStrategy, StatusCallback, Bundle)

Restores the saved session from a Bundle, if any. Returns the restored Session or null if it could not be restored. This method is intended to be called from an Activity or Fragment's onCreate method when a Session has previously been saved into a Bundle via saveState to preserve a Session across Activity lifecycle events.

public static final Session restoreSession(Context context, TokenCachingStrategy cachingStrategy, StatusCallback callback, Bundle bundle)
參數說明
contextThe Activity or Service creating the Session, must not be null
cachingStrategyThe TokenCachingStrategy to use to load and store the token. If this is null, a default token cachingStrategy that stores data in SharedPreferences will be used
callbackThe callback to notify for Session state changes, can be null
bundleThe bundle to restore the Session from
Returns
The restored Session, or null
getActiveSession()

Returns the current active Session, or null if there is none.

public static final Session getActiveSession()
Returns
The current active Session, or null if there is none.
setActiveSession(Session)

Sets the current active Session.

The active Session is used implicitly by predefined Request factory methods as well as optionally by UI controls in the sdk.

It is legal to set this to null, or to a Session that is not yet open.

public static final void setActiveSession(Session session)
參數說明
sessionA Session to use as the active Session, or null to indicate that there is no active Session.
openActiveSessionFromCache(Context)

If a cached token is available, creates and opens the session and makes it active without any user interaction, otherwise this does nothing.

public static Session openActiveSessionFromCache(Context context)
參數說明
contextThe Context creating this session
Returns
The new session or null if one could not be created
openActiveSession(Activity, boolean, StatusCallback)

If allowLoginUI is true, this will create a new Session, make it active, and open it. If the default token cache is not available, then this will request basic permissions. If the default token cache is available and cached tokens are loaded, this will use the cached token and associated permissions.

If allowedLoginUI is false, this will only create the active session and open it if it requires no user interaction (i.e. the token cache is available and there are cached tokens).

public static Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback)
參數說明
activityThe Activity that is opening the new Session.
allowLoginUIIf false, only sets the active session and opens it if it does not require user interaction
callbackThe SessionStatusCallback to notify regarding Session state changes. May be null.
Returns
The new Session or null if one could not be created
openActiveSession(Context, Fragment, boolean, StatusCallback)

If allowLoginUI is true, this will create a new Session, make it active, and open it. If the default token cache is not available, then this will request basic permissions. If the default token cache is available and cached tokens are loaded, this will use the cached token and associated permissions.

If allowedLoginUI is false, this will only create the active session and open it if it requires no user interaction (i.e. the token cache is available and there are cached tokens).

public static Session openActiveSession(Context context, Fragment fragment, boolean allowLoginUI, StatusCallback callback)
參數說明
contextThe Activity or Service creating this Session
fragmentThe Fragment that is opening the new Session.
allowLoginUIIf false, only sets the active session and opens it if it does not require user interaction
callbackThe SessionStatusCallback to notify regarding Session state changes.
Returns
The new Session or null if one could not be created
openActiveSessionWithAccessToken(Context, AccessToken, StatusCallback)

Opens a session based on an existing Facebook access token, and also makes this session the currently active session. This method should be used only in instances where an application has previously obtained an access token and wishes to import it into the Session/TokenCachingStrategy-based session-management system. A primary example would be an application which previously did not use the Facebook SDK for Android and implemented its own session-management scheme, but wishes to implement an upgrade path for existing users so they do not need to log in again when upgrading to a version of the app that uses the SDK. In general, this method will be called only once, when the app detects that it has been upgraded -- after that, the usual Session lifecycle methods should be used to manage the session and its associated token.

No validation is done that the token, token source, or permissions are actually valid. It is the caller's responsibility to ensure that these accurately reflect the state of the token that has been passed in, or calls to the Facebook API may fail.

public static Session openActiveSessionWithAccessToken(Context context, AccessToken accessToken, StatusCallback callback)
參數說明
contextThe Context to use for creation the session
accessTokenThe access token obtained from Facebook
callbackA callback that will be called when the session status changes; may be null
Returns
The new Session or null if one could not be created
isPublishPermission(String)
public static boolean isPublishPermission(String permission)
參數說明
permission
執行個體方法
getAuthorizationBundle()

Returns a Bundle containing data that was returned from Facebook during authorization.

public final Bundle getAuthorizationBundle()
Returns
A Bundle containing data that was returned from Facebook during authorization.
isOpened()

Returns a boolean indicating whether the session is opened.

public final boolean isOpened()
Returns
A boolean indicating whether the session is opened.
isClosed()
public final boolean isClosed()
getState()

Returns the current state of the Session. See SessionState for details.

public final SessionState getState()
Returns
The current state of the Session.
getApplicationId()

Returns the application id associated with this Session.

public final String getApplicationId()
Returns
The application id associated with this Session.
getAccessToken()

Returns the access token String.

public final String getAccessToken()
Returns
The access token String, or null if there is no access token
getExpirationDate()

Returns the Date at which the current token will expire.

Note that Session automatically attempts to extend the lifetime of Tokens as needed when Facebook requests are made.

public final Date getExpirationDate()
Returns
The Date at which the current token will expire, or null if there is no access token
getPermissions()

Returns the list of permissions associated with the session.

If there is a valid token, this represents the permissions granted by that token. This can change during calls to Session.requestNewReadPermissions or Session.requestNewPublishPermissions.

public final List getPermissions()
Returns
The list of permissions associated with the session, or null if there is no access token
openForRead(OpenRequest)

Logs a user in to Facebook.

A session may not be used with Request and other classes in the SDK until it is open. If, prior to calling open, the session is in the CREATED_TOKEN_LOADED.CREATED_TOKEN_LOADED state, and the requested permissions are a subset of the previously authorized permissions, then the Session becomes usable immediately with no user interaction.

The permissions associated with the openRequest passed to this method must be read permissions only (or null/empty). It is not allowed to pass publish permissions to this method and will result in an exception being thrown.

Any open method must be called at most once, and cannot be called after the Session is closed. Calling the method at an invalid time will result in UnsuportedOperationException.

public final void openForRead(OpenRequest openRequest)
參數說明
openRequestThe open request, can be null only if the Session is in the CREATED_TOKEN_LOADED.CREATED_TOKEN_LOADED state
openForPublish(OpenRequest)

Logs a user in to Facebook.

A session may not be used with Request and other classes in the SDK until it is open. If, prior to calling open, the session is in the CREATED_TOKEN_LOADED.CREATED_TOKEN_LOADED state, and the requested permissions are a subset of the previously authorized permissions, then the Session becomes usable immediately with no user interaction.

The permissions associated with the openRequest passed to this method must be publish or manage permissions only and must be non-empty. Any read permissions will result in a warning, and may fail during server-side authorization. Also, an application must have at least basic read permissions prior to requesting publish permissions, so this method should only be used if the application knows that the user has already granted read permissions to the application; otherwise, openForRead should be used, followed by a call to requestNewPublishPermissions. For more information on this flow, see https://developers.facebook.com/docs/facebook-login/permissions/.

Any open method must be called at most once, and cannot be called after the Session is closed. Calling the method at an invalid time will result in UnsuportedOperationException.

public final void openForPublish(OpenRequest openRequest)
參數說明
openRequestThe open request, can be null only if the Session is in the CREATED_TOKEN_LOADED.CREATED_TOKEN_LOADED state
open(AccessToken, StatusCallback)

Opens a session based on an existing Facebook access token. This method should be used only in instances where an application has previously obtained an access token and wishes to import it into the Session/TokenCachingStrategy-based session-management system. An example would be an application which previously did not use the Facebook SDK for Android and implemented its own session-management scheme, but wishes to implement an upgrade path for existing users so they do not need to log in again when upgrading to a version of the app that uses the SDK.

No validation is done that the token, token source, or permissions are actually valid. It is the caller's responsibility to ensure that these accurately reflect the state of the token that has been passed in, or calls to the Facebook API may fail.

public final void open(AccessToken accessToken, StatusCallback callback)
參數說明
accessTokenThe access token obtained from Facebook
callbackA callback that will be called when the session status changes; may be null
requestNewReadPermissions(NewPermissionsRequest)

Issues a request to add new read permissions to the Session.

If successful, this will update the set of permissions on this session to match the newPermissions. If this fails, the Session remains unchanged.

The permissions associated with the newPermissionsRequest passed to this method must be read permissions only (or null/empty). It is not allowed to pass publish permissions to this method and will result in an exception being thrown.

public final void requestNewReadPermissions(NewPermissionsRequest newPermissionsRequest)
參數說明
newPermissionsRequestThe new permissions request
requestNewPublishPermissions(NewPermissionsRequest)

Issues a request to add new publish or manage permissions to the Session.

If successful, this will update the set of permissions on this session to match the newPermissions. If this fails, the Session remains unchanged.

The permissions associated with the newPermissionsRequest passed to this method must be publish or manage permissions only and must be non-empty. Any read permissions will result in a warning, and may fail during server-side authorization.

public final void requestNewPublishPermissions(NewPermissionsRequest newPermissionsRequest)
參數說明
newPermissionsRequestThe new permissions request
onActivityResult(Activity, int, int, Intent)

Provides an implementation for onActivityResult.onActivityResult that updates the Session based on information returned during the authorization flow. The Activity that calls open or requestNewPermissions should forward the resulting onActivityResult call here to update the Session state based on the contents of the resultCode and data.

public final boolean onActivityResult(Activity currentActivity, int requestCode, int resultCode, Intent data)
參數說明
currentActivityThe Activity that is forwarding the onActivityResult call.
requestCodeThe requestCode parameter from the forwarded call. When this onActivityResult occurs as part of Facebook authorization flow, this value is the activityCode passed to open or authorize.
resultCodeAn int containing the resultCode parameter from the forwarded call.
dataThe Intent passed as the data parameter from the forwarded call.
Returns
A boolean indicating whether the requestCode matched a pending authorization request for this Session.
close()

Closes the local in-memory Session object, but does not clear the persisted token cache.

public final void close()
closeAndClearTokenInformation()

Closes the local in-memory Session object and clears any persisted token cache related to the Session.

public final void closeAndClearTokenInformation()
addCallback(StatusCallback)

Adds a callback that will be called when the state of this Session changes.

public final void addCallback(StatusCallback callback)
參數說明
callbackThe callback
removeCallback(StatusCallback)

Removes a StatusCallback from this Session.

public final void removeCallback(StatusCallback callback)
參數說明
callbackThe callback
常數
TAG
The logging tag used by Session.
public static final String TAG
DEFAULT_AUTHORIZE_ACTIVITY_CODE
The default activity code used for authorization.
public static final int DEFAULT_AUTHORIZE_ACTIVITY_CODE
WEB_VIEW_ERROR_CODE_KEY
If Session authorization fails and provides a web view error code, the web view error code is stored in the Bundle returned from getAuthorizationBundle.getAuthorizationBundle under this key.
public static final String WEB_VIEW_ERROR_CODE_KEY
WEB_VIEW_FAILING_URL_KEY
If Session authorization fails and provides a failing url, the failing url is stored in the Bundle returned from getAuthorizationBundle.getAuthorizationBundle under this key.
public static final String WEB_VIEW_FAILING_URL_KEY
ACTION_ACTIVE_SESSION_SET
The action used to indicate that the active session has been set. This should be used as an action in an IntentFilter and BroadcastReceiver registered with the LocalBroadcastManager.
public static final String ACTION_ACTIVE_SESSION_SET
ACTION_ACTIVE_SESSION_UNSET
The action used to indicate that the active session has been set to null. This should be used as an action in an IntentFilter and BroadcastReceiver registered with the LocalBroadcastManager.
public static final String ACTION_ACTIVE_SESSION_UNSET
ACTION_ACTIVE_SESSION_OPENED
The action used to indicate that the active session has been opened. This should be used as an action in an IntentFilter and BroadcastReceiver registered with the LocalBroadcastManager.
public static final String ACTION_ACTIVE_SESSION_OPENED
ACTION_ACTIVE_SESSION_CLOSED
The action used to indicate that the active session has been closed. This should be used as an action in an IntentFilter and BroadcastReceiver registered with the LocalBroadcastManager.
public static final String ACTION_ACTIVE_SESSION_CLOSED
APPLICATION_ID_PROPERTY
Session takes application id as a constructor parameter. If this is null, Session will attempt to load the application id from application/meta-data using this String as the key.
public static final String APPLICATION_ID_PROPERTY