code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* An Exception indicating that a Session failed to open or obtain new permissions.
*/
public class FacebookAuthorizationException extends FacebookException {
static final long serialVersionUID = 1;
/**
* Constructs a FacebookAuthorizationException with no additional
* information.
*/
public FacebookAuthorizationException() {
super();
}
/**
* Constructs a FacebookAuthorizationException with a message.
*
* @param message
* A String to be returned from getMessage.
*/
public FacebookAuthorizationException(String message) {
super(message);
}
/**
* Constructs a FacebookAuthorizationException with a message and inner
* error.
*
* @param message
* A String to be returned from getMessage.
* @param throwable
* A Throwable to be returned from getCause.
*/
public FacebookAuthorizationException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a FacebookAuthorizationException with an inner error.
*
* @param throwable
* A Throwable to be returned from getCause.
*/
public FacebookAuthorizationException(Throwable throwable) {
super(throwable);
}
}
| Java |
/**
* Copyright 2012 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
final class FacebookSdkVersion {
public static final String BUILD = "3.0.1";
public static final String MIGRATION_BUNDLE = "fbsdk:20121026";
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.Manifest;
import android.app.Activity;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.*;
import com.facebook.*;
import com.facebook.Session.StatusCallback;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link Session} to manage session state,
* {@link Request} to make API requests, and
* {@link com.facebook.widget.WebDialog} to make dialog requests.
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public class Facebook {
// Strings used in the authorization flow
@Deprecated
public static final String REDIRECT_URI = "fbconnect://success";
@Deprecated
public static final String CANCEL_URI = "fbconnect://cancel";
@Deprecated
public static final String TOKEN = "access_token";
@Deprecated
public static final String EXPIRES = "expires_in";
@Deprecated
public static final String SINGLE_SIGN_ON_DISABLED = "service_disabled";
@Deprecated
public static final Uri ATTRIBUTION_ID_CONTENT_URI =
Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider");
@Deprecated
public static final String ATTRIBUTION_ID_COLUMN_NAME = "aid";
@Deprecated
public static final int FORCE_DIALOG_AUTH = -1;
private static final String LOGIN = "oauth";
// Used as default activityCode by authorize(). See authorize() below.
private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665;
// Facebook server endpoints: may be modified in a subclass for testing
@Deprecated
protected static String DIALOG_BASE_URL = "https://m.facebook.com/dialog/";
@Deprecated
protected static String GRAPH_BASE_URL = "https://graph.facebook.com/";
@Deprecated
protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php";
private final Object lock = new Object();
private String accessToken = null;
private long accessExpiresMillisecondsAfterEpoch = 0;
private long lastAccessUpdateMillisecondsAfterEpoch = 0;
private String mAppId;
private Activity pendingAuthorizationActivity;
private String[] pendingAuthorizationPermissions;
private Session pendingOpeningSession;
private volatile Session session; // must synchronize this.sync to write
private boolean sessionInvalidated; // must synchronize this.sync to access
private SetterTokenCachingStrategy tokenCache;
private volatile Session userSetSession;
// If the last time we extended the access token was more than 24 hours ago
// we try to refresh the access token again.
final private long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L;
/**
* Constructor for Facebook object.
*
* @param appId
* Your Facebook application ID. Found at
* www.facebook.com/developers/apps.php.
*/
@Deprecated
public Facebook(String appId) {
if (appId == null) {
throw new IllegalArgumentException("You must specify your application ID when instantiating "
+ "a Facebook object. See README for details.");
}
mAppId = appId;
}
/**
* Default authorize method. Grants only basic permissions.
* <p/>
* See authorize() below for @params.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorize(Activity activity, final DialogListener listener) {
authorize(activity, new String[]{}, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK,
listener);
}
/**
* Authorize method that grants custom permissions.
* <p/>
* See authorize() below for @params.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorize(Activity activity, String[] permissions, final DialogListener listener) {
authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK, listener);
}
/**
* Full authorize method.
* <p/>
* Starts either an Activity or a dialog which prompts the user to log in to
* Facebook and grant the requested permissions to the given application.
* <p/>
* This method will, when possible, use Facebook's single sign-on for
* Android to obtain an access token. This involves proxying a call through
* the Facebook for Android stand-alone application, which will handle the
* authentication flow, and return an OAuth access token for making API
* calls.
* <p/>
* Because this process will not be available for all users, if single
* sign-on is not possible, this method will automatically fall back to the
* OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
* by Facebook in an embedded WebView, not by the client application. As
* such, the dialog makes a network request and renders HTML content rather
* than a native UI. The access token is retrieved from a redirect to a
* special URL that the WebView handles.
* <p/>
* Note that User credentials could be handled natively using the OAuth 2.0
* Username and Password Flow, but this is not supported by this SDK.
* <p/>
* See http://developers.facebook.com/docs/authentication/ and
* http://wiki.oauth.net/OAuth-2 for more details.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
* <p/>
* Also note that requests may be made to the API without calling authorize
* first, in which case only public information is returned.
* <p/>
* IMPORTANT: Note that single sign-on authentication will not function
* correctly if you do not include a call to the authorizeCallback() method
* in your onActivityResult() function! Please see below for more
* information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
* as the activityCode parameter in your call to authorize().
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param activity
* The Android activity in which we want to display the
* authorization dialog.
* @param permissions
* A list of permissions required for this application: e.g.
* "read_stream", "publish_stream", "offline_access", etc. see
* http://developers.facebook.com/docs/authentication/permissions
* This parameter should not be null -- if you do not require any
* permissions, then pass in an empty String array.
* @param activityCode
* Single sign-on requires an activity result to be called back
* to the client application -- if you are waiting on other
* activities to return data, pass a custom activity code here to
* avoid collisions. If you would like to force the use of legacy
* dialog-based authorization, pass FORCE_DIALOG_AUTH for this
* parameter. Otherwise just omit this parameter and Facebook
* will use a suitable default. See
* http://developer.android.com/reference/android/
* app/Activity.html for more information.
* @param listener
* Callback interface for notifying the calling application when
* the authentication dialog has completed, failed, or been
* canceled.
*/
@Deprecated
public void authorize(Activity activity, String[] permissions, int activityCode, final DialogListener listener) {
SessionLoginBehavior behavior = (activityCode >= 0) ? SessionLoginBehavior.SSO_WITH_FALLBACK
: SessionLoginBehavior.SUPPRESS_SSO;
authorize(activity, permissions, activityCode, behavior, listener);
}
/**
* Full authorize method.
*
* Starts either an Activity or a dialog which prompts the user to log in to
* Facebook and grant the requested permissions to the given application.
*
* This method will, when possible, use Facebook's single sign-on for
* Android to obtain an access token. This involves proxying a call through
* the Facebook for Android stand-alone application, which will handle the
* authentication flow, and return an OAuth access token for making API
* calls.
*
* Because this process will not be available for all users, if single
* sign-on is not possible, this method will automatically fall back to the
* OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
* by Facebook in an embedded WebView, not by the client application. As
* such, the dialog makes a network request and renders HTML content rather
* than a native UI. The access token is retrieved from a redirect to a
* special URL that the WebView handles.
*
* Note that User credentials could be handled natively using the OAuth 2.0
* Username and Password Flow, but this is not supported by this SDK.
*
* See http://developers.facebook.com/docs/authentication/ and
* http://wiki.oauth.net/OAuth-2 for more details.
*
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* Also note that requests may be made to the API without calling authorize
* first, in which case only public information is returned.
*
* IMPORTANT: Note that single sign-on authentication will not function
* correctly if you do not include a call to the authorizeCallback() method
* in your onActivityResult() function! Please see below for more
* information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
* as the activityCode parameter in your call to authorize().
*
* @param activity
* The Android activity in which we want to display the
* authorization dialog.
* @param permissions
* A list of permissions required for this application: e.g.
* "read_stream", "publish_stream", "offline_access", etc. see
* http://developers.facebook.com/docs/authentication/permissions
* This parameter should not be null -- if you do not require any
* permissions, then pass in an empty String array.
* @param activityCode
* Single sign-on requires an activity result to be called back
* to the client application -- if you are waiting on other
* activities to return data, pass a custom activity code here to
* avoid collisions. If you would like to force the use of legacy
* dialog-based authorization, pass FORCE_DIALOG_AUTH for this
* parameter. Otherwise just omit this parameter and Facebook
* will use a suitable default. See
* http://developer.android.com/reference/android/
* app/Activity.html for more information.
* @param behavior
* The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
* @param listener
* Callback interface for notifying the calling application when
* the authentication dialog has completed, failed, or been
* canceled.
*/
private void authorize(Activity activity, String[] permissions, int activityCode,
SessionLoginBehavior behavior, final DialogListener listener) {
checkUserSession("authorize");
pendingOpeningSession = new Session.Builder(activity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
pendingAuthorizationActivity = activity;
pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
StatusCallback callback = new StatusCallback() {
@Override
public void call(Session callbackSession, SessionState state, Exception exception) {
// Invoke user-callback.
onSessionCallback(callbackSession, state, exception, listener);
}
};
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setCallback(callback).
setLoginBehavior(behavior).
setRequestCode(activityCode).
setPermissions(Arrays.asList(permissions));
openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
}
private void openSession(Session session, Session.OpenRequest openRequest, boolean isPublish) {
openRequest.setIsLegacy(true);
if (isPublish) {
session.openForPublish(openRequest);
} else {
session.openForRead(openRequest);
}
}
@SuppressWarnings("deprecation")
private void onSessionCallback(Session callbackSession, SessionState state, Exception exception,
DialogListener listener) {
Bundle extras = callbackSession.getAuthorizationBundle();
if (state == SessionState.OPENED) {
Session sessionToClose = null;
synchronized (Facebook.this.lock) {
if (callbackSession != Facebook.this.session) {
sessionToClose = Facebook.this.session;
Facebook.this.session = callbackSession;
Facebook.this.sessionInvalidated = false;
}
}
if (sessionToClose != null) {
sessionToClose.close();
}
listener.onComplete(extras);
} else if (exception != null) {
if (exception instanceof FacebookOperationCanceledException) {
listener.onCancel();
} else if ((exception instanceof FacebookAuthorizationException) && (extras != null)
&& extras.containsKey(Session.WEB_VIEW_ERROR_CODE_KEY)
&& extras.containsKey(Session.WEB_VIEW_FAILING_URL_KEY)) {
DialogError error = new DialogError(exception.getMessage(),
extras.getInt(Session.WEB_VIEW_ERROR_CODE_KEY),
extras.getString(Session.WEB_VIEW_FAILING_URL_KEY));
listener.onError(error);
} else {
FacebookError error = new FacebookError(exception.getMessage());
listener.onFacebookError(error);
}
}
}
/**
* Helper to validate a service intent by resolving and checking the
* provider's package signature.
*
* @param context
* @param intent
* @return true if the service intent resolution happens successfully and
* the signatures match.
*/
private boolean validateServiceIntent(Context context, Intent intent) {
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return false;
}
return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
}
/**
* Query the signature for the application that would be invoked by the
* given intent and verify that it matches the FB application's signature.
*
* @param context
* @param packageName
* @return true if the app's signature matches the expected signature.
*/
private boolean validateAppSignatureForPackage(Context context, String packageName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
return true;
}
}
return false;
}
/**
* IMPORTANT: If you are using the deprecated authorize() method,
* this method must be invoked at the top of the calling
* activity's onActivityResult() function or Facebook authentication will
* not function properly!
* <p/>
* If your calling activity does not currently implement onActivityResult(),
* you must implement it and include a call to this method if you intend to
* use the authorize() method in this SDK.
* <p/>
* For more information, see
* http://developer.android.com/reference/android/app/
* Activity.html#onActivityResult(int, int, android.content.Intent)
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*/
@Deprecated
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
checkUserSession("authorizeCallback");
Session pending = this.pendingOpeningSession;
if (pending != null) {
if (pending.onActivityResult(this.pendingAuthorizationActivity, requestCode, resultCode, data)) {
this.pendingOpeningSession = null;
this.pendingAuthorizationActivity = null;
this.pendingAuthorizationPermissions = null;
}
}
}
/**
* Refresh OAuth access token method. Binds to Facebook for Android
* stand-alone application application to refresh the access token. This
* method tries to connect to the Facebook App which will handle the
* authentication flow, and return a new OAuth access token. This method
* will automatically replace the old token with a new one. Note that this
* method is asynchronous and the callback will be invoked in the original
* calling thread (not in a background thread).
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param context
* The Android Context that will be used to bind to the Facebook
* RefreshToken Service
* @param serviceListener
* Callback interface for notifying the calling application when
* the refresh request has completed or failed (can be null). In
* case of a success a new token can be found inside the result
* Bundle under Facebook.ACCESS_TOKEN key.
* @return true if the binding to the RefreshToken Service was created
*/
@Deprecated
public boolean extendAccessToken(Context context, ServiceListener serviceListener) {
checkUserSession("extendAccessToken");
Intent intent = new Intent();
intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService");
// Verify that the application whose package name is
// com.facebook.katana
// has the expected FB app signature.
if (!validateServiceIntent(context, intent)) {
return false;
}
return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener),
Context.BIND_AUTO_CREATE);
}
/**
* Calls extendAccessToken if shouldExtendAccessToken returns true.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @return the same value as extendAccessToken if the the token requires
* refreshing, true otherwise
*/
@Deprecated
public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) {
checkUserSession("extendAccessTokenIfNeeded");
if (shouldExtendAccessToken()) {
return extendAccessToken(context, serviceListener);
}
return true;
}
/**
* Check if the access token requires refreshing.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @return true if the last time a new token was obtained was over 24 hours
* ago.
*/
@Deprecated
public boolean shouldExtendAccessToken() {
checkUserSession("shouldExtendAccessToken");
return isSessionValid()
&& (System.currentTimeMillis() - lastAccessUpdateMillisecondsAfterEpoch >= REFRESH_TOKEN_BARRIER);
}
/**
* Handles connection to the token refresh service (this service is a part
* of Facebook App).
*/
private class TokenRefreshServiceConnection implements ServiceConnection {
final Messenger messageReceiver = new Messenger(
new TokenRefreshConnectionHandler(Facebook.this, this));
final ServiceListener serviceListener;
final Context applicationsContext;
Messenger messageSender = null;
public TokenRefreshServiceConnection(Context applicationsContext, ServiceListener serviceListener) {
this.applicationsContext = applicationsContext;
this.serviceListener = serviceListener;
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
messageSender = new Messenger(service);
refreshToken();
}
@Override
public void onServiceDisconnected(ComponentName arg) {
serviceListener.onError(new Error("Service disconnected"));
// We returned an error so there's no point in
// keeping the binding open.
applicationsContext.unbindService(TokenRefreshServiceConnection.this);
}
private void refreshToken() {
Bundle requestData = new Bundle();
requestData.putString(TOKEN, accessToken);
Message request = Message.obtain();
request.setData(requestData);
request.replyTo = messageReceiver;
try {
messageSender.send(request);
} catch (RemoteException e) {
serviceListener.onError(new Error("Service connection error"));
}
}
}
// Creating a static Handler class to reduce the possibility of a memory leak.
// Handler objects for the same thread all share a common Looper object, which they post messages
// to and read from. As messages contain target Handler, as long as there are messages with target
// handler in the message queue, the handler cannot be garbage collected. If handler is not static,
// the instance of the containing class also cannot be garbage collected even if it is destroyed.
private static class TokenRefreshConnectionHandler extends Handler {
WeakReference<Facebook> facebookWeakReference;
WeakReference<TokenRefreshServiceConnection> connectionWeakReference;
TokenRefreshConnectionHandler(Facebook facebook, TokenRefreshServiceConnection connection) {
super();
facebookWeakReference = new WeakReference<Facebook>(facebook);
connectionWeakReference = new WeakReference<TokenRefreshServiceConnection>(connection);
}
@Override
@SuppressWarnings("deprecation")
public void handleMessage(Message msg) {
Facebook facebook = facebookWeakReference.get();
TokenRefreshServiceConnection connection = connectionWeakReference.get();
if (facebook == null || connection == null) {
return;
}
String token = msg.getData().getString(TOKEN);
// Legacy functions in Facebook class (and ServiceListener implementors) expect expires_in in
// milliseconds from epoch
long expiresAtMsecFromEpoch = msg.getData().getLong(EXPIRES) * 1000L;
if (token != null) {
facebook.setAccessToken(token);
facebook.setAccessExpires(expiresAtMsecFromEpoch);
Session refreshSession = facebook.session;
if (refreshSession != null) {
// Session.internalRefreshToken expects the original bundle with expires_in in seconds from
// epoch.
LegacyHelper.extendTokenCompleted(refreshSession, msg.getData());
}
if (connection.serviceListener != null) {
// To avoid confusion we should return the expiration time in
// the same format as the getAccessExpires() function - that
// is in milliseconds.
Bundle resultBundle = (Bundle) msg.getData().clone();
resultBundle.putLong(EXPIRES, expiresAtMsecFromEpoch);
connection.serviceListener.onComplete(resultBundle);
}
} else if (connection.serviceListener != null) { // extract errors only if
// client wants them
String error = msg.getData().getString("error");
if (msg.getData().containsKey("error_code")) {
int errorCode = msg.getData().getInt("error_code");
connection.serviceListener.onFacebookError(new FacebookError(error, null, errorCode));
} else {
connection.serviceListener.onError(new Error(error != null ? error : "Unknown service error"));
}
}
if (connection != null) {
// The refreshToken function should be called rarely,
// so there is no point in keeping the binding open.
connection.applicationsContext.unbindService(connection);
}
}
}
/**
* Invalidate the current user session by removing the access token in
* memory, clearing the browser cookie, and calling auth.expireSession
* through the API.
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param context
* The Android context in which the logout should be called: it
* should be the same context in which the login occurred in
* order to clear any stored cookies
* @throws IOException
* @throws MalformedURLException
* @return JSON string representation of the auth.expireSession response
* ("true" if successful)
*/
@Deprecated
public String logout(Context context) throws MalformedURLException, IOException {
return logoutImpl(context);
}
String logoutImpl(Context context) throws MalformedURLException, IOException {
checkUserSession("logout");
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
String response = request(b);
long currentTimeMillis = System.currentTimeMillis();
Session sessionToClose = null;
synchronized (this.lock) {
sessionToClose = session;
session = null;
accessToken = null;
accessExpiresMillisecondsAfterEpoch = 0;
lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis;
sessionInvalidated = false;
}
if (sessionToClose != null) {
sessionToClose.closeAndClearTokenInformation();
}
return response;
}
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
* <p/>
* See http://developers.facebook.com/docs/reference/rest/
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* Example: <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Request} for more info.
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @throws IOException
* if a network error occurs
* @throws MalformedURLException
* if accessing an invalid endpoint
* @throws IllegalArgumentException
* if one of the parameters is not "method"
* @return JSON string representation of the response
*/
@Deprecated
public String request(Bundle parameters) throws MalformedURLException, IOException {
if (!parameters.containsKey("method")) {
throw new IllegalArgumentException("API method must be specified. "
+ "(parameters must contain key \"method\" and value). See"
+ " http://developers.facebook.com/docs/reference/rest/");
}
return requestImpl(null, parameters, "GET");
}
/**
* Make a request to the Facebook Graph API without any parameters.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @throws IOException
* @throws MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath) throws MalformedURLException, IOException {
return requestImpl(graphPath, new Bundle(), "GET");
}
/**
* Make a request to the Facebook Graph API with the given string parameters
* using an HTTP GET (default method).
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @throws IOException
* @throws MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException {
return requestImpl(graphPath, parameters, "GET");
}
/**
* Synchronously make a request to the Facebook Graph API with the given
* HTTP method and string parameters. Note that binary data parameters (e.g.
* pictures) are not yet supported by this helper function.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param params
* Key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param httpMethod
* http verb, e.g. "GET", "POST", "DELETE"
* @throws IOException
* @throws MalformedURLException
* @return JSON string representation of the response
*/
@Deprecated
public String request(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
return requestImpl(graphPath, params, httpMethod);
}
// Internal call to avoid deprecated warnings.
@SuppressWarnings("deprecation")
String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
}
/**
* Generate a UI dialog for the request action in the given Android context.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* This method is deprecated. See {@link com.facebook.widget.WebDialog}.
*
* @param context
* The Android context in which we will generate this dialog.
* @param action
* String representation of the desired method: e.g. "login",
* "stream.publish", ...
* @param listener
* Callback interface to notify the application when the dialog
* has completed.
*/
@Deprecated
public void dialog(Context context, String action, DialogListener listener) {
dialog(context, action, new Bundle(), listener);
}
/**
* Generate a UI dialog for the request action in the given Android context
* with the provided parameters.
* <p/>
* Note that this method is asynchronous and the callback will be invoked in
* the original calling thread (not in a background thread).
*
* This method is deprecated. See {@link com.facebook.widget.WebDialog}.
*
* @param context
* The Android context in which we will generate this dialog.
* @param action
* String representation of the desired method: e.g. "feed" ...
* @param parameters
* String key-value pairs to be passed as URL parameters.
* @param listener
* Callback interface to notify the application when the dialog
* has completed.
*/
@Deprecated
public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) {
parameters.putString("display", "touch");
parameters.putString("redirect_uri", REDIRECT_URI);
if (action.equals(LOGIN)) {
parameters.putString("type", "user_agent");
parameters.putString("client_id", mAppId);
} else {
parameters.putString("app_id", mAppId);
// We do not want to add an access token when displaying the auth dialog.
if (isSessionValid()) {
parameters.putString(TOKEN, getAccessToken());
}
}
if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
Util.showAlert(context, "Error", "Application requires permission to access the Internet");
} else {
new FbDialog(context, action, parameters, listener).show();
}
}
/**
* Returns whether the current access token is valid
*
* @return boolean - whether this object has an non-expired session token
*/
@Deprecated
public boolean isSessionValid() {
return (getAccessToken() != null)
&& ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires()));
}
/**
* Allows the user to set a Session for the Facebook class to use.
* If a Session is set here, then one should not use the authorize, logout,
* or extendAccessToken methods which alter the Session object since that may
* result in undefined behavior. Using those methods after setting the
* session here will result in exceptions being thrown.
*
* @param session the Session object to use, cannot be null
*/
@Deprecated
public void setSession(Session session) {
if (session == null) {
throw new IllegalArgumentException("session cannot be null");
}
synchronized (this.lock) {
this.userSetSession = session;
}
}
private void checkUserSession(String methodName) {
if (userSetSession != null) {
throw new UnsupportedOperationException(
String.format("Cannot call %s after setSession has been called.", methodName));
}
}
/**
* Get the underlying Session object to use with 3.0 api.
*
* @return Session - underlying session
*/
@Deprecated
public final Session getSession() {
while (true) {
String cachedToken = null;
Session oldSession = null;
synchronized (this.lock) {
if (userSetSession != null) {
return userSetSession;
}
if ((session != null) || !sessionInvalidated) {
return session;
}
cachedToken = accessToken;
oldSession = session;
}
if (cachedToken == null) {
return null;
}
// At this point we do not have a valid session, but mAccessToken is
// non-null.
// So we can try building a session based on that.
List<String> permissions;
if (oldSession != null) {
permissions = oldSession.getPermissions();
} else if (pendingAuthorizationPermissions != null) {
permissions = Arrays.asList(pendingAuthorizationPermissions);
} else {
permissions = Collections.<String>emptyList();
}
Session newSession = new Session.Builder(pendingAuthorizationActivity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
return null;
}
Session.OpenRequest openRequest =
new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
openSession(newSession, openRequest, !permissions.isEmpty());
Session invalidatedSession = null;
Session returnSession = null;
synchronized (this.lock) {
if (sessionInvalidated || (session == null)) {
invalidatedSession = session;
returnSession = session = newSession;
sessionInvalidated = false;
}
}
if (invalidatedSession != null) {
invalidatedSession.close();
}
if (returnSession != null) {
return returnSession;
}
// Else token state changed between the synchronized blocks, so
// retry..
}
}
/**
* Retrieve the OAuth 2.0 access token for API access: treat with care.
* Returns null if no session exists.
*
* @return String - access token
*/
@Deprecated
public String getAccessToken() {
Session s = getSession();
if (s != null) {
return s.getAccessToken();
} else {
return null;
}
}
/**
* Retrieve the current session's expiration time (in milliseconds since
* Unix epoch), or 0 if the session doesn't expire or doesn't exist.
*
* @return long - session expiration time
*/
@Deprecated
public long getAccessExpires() {
Session s = getSession();
if (s != null) {
return s.getExpirationDate().getTime();
} else {
return accessExpiresMillisecondsAfterEpoch;
}
}
/**
* Retrieve the last time the token was updated (in milliseconds since
* the Unix epoch), or 0 if the token has not been set.
*
* @return long - timestamp of the last token update.
*/
@Deprecated
public long getLastAccessUpdate() {
return lastAccessUpdateMillisecondsAfterEpoch;
}
/**
* Restore the token, expiration time, and last update time from cached values.
* These should be values obtained from getAccessToken(), getAccessExpires, and
* getLastAccessUpdate() respectively.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param accessToken - access token
* @param accessExpires - access token expiration time
* @param lastAccessUpdate - timestamp of the last token update
*/
@Deprecated
public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) {
checkUserSession("setTokenFromCache");
synchronized (this.lock) {
this.accessToken = accessToken;
accessExpiresMillisecondsAfterEpoch = accessExpires;
lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate;
}
}
/**
* Set the OAuth 2.0 access token for API access.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param token
* - access token
*/
@Deprecated
public void setAccessToken(String token) {
checkUserSession("setAccessToken");
synchronized (this.lock) {
accessToken = token;
lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
sessionInvalidated = true;
}
}
/**
* Set the current session's expiration time (in milliseconds since Unix
* epoch), or 0 if the session doesn't expire.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param timestampInMsec
* - timestamp in milliseconds
*/
@Deprecated
public void setAccessExpires(long timestampInMsec) {
checkUserSession("setAccessExpires");
synchronized (this.lock) {
accessExpiresMillisecondsAfterEpoch = timestampInMsec;
lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
sessionInvalidated = true;
}
}
/**
* Set the current session's duration (in seconds since Unix epoch), or "0"
* if session doesn't expire.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param expiresInSecsFromNow
* - duration in seconds (or 0 if the session doesn't expire)
*/
@Deprecated
public void setAccessExpiresIn(String expiresInSecsFromNow) {
checkUserSession("setAccessExpiresIn");
if (expiresInSecsFromNow != null) {
long expires = expiresInSecsFromNow.equals("0") ? 0 : System.currentTimeMillis()
+ Long.parseLong(expiresInSecsFromNow) * 1000L;
setAccessExpires(expires);
}
}
/**
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @return the String representing application ID
*/
@Deprecated
public String getAppId() {
return mAppId;
}
/**
* This method is deprecated. See {@link Facebook} and {@link Session} for more info.
*
* @param appId the String representing the application ID
*/
@Deprecated
public void setAppId(String appId) {
checkUserSession("setAppId");
synchronized (this.lock) {
mAppId = appId;
sessionInvalidated = true;
}
}
private TokenCachingStrategy getTokenCache() {
// Intentionally not volatile/synchronized--it is okay if we race to
// create more than one of these.
if (tokenCache == null) {
tokenCache = new SetterTokenCachingStrategy();
}
return tokenCache;
}
private static String[] stringArray(List<String> list) {
String[] array = new String[list.size()];
if (list != null) {
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}
}
return array;
}
private static List<String> stringList(String[] array) {
if (array != null) {
return Arrays.asList(array);
} else {
return Collections.emptyList();
}
}
private class SetterTokenCachingStrategy extends TokenCachingStrategy {
@Override
public Bundle load() {
Bundle bundle = new Bundle();
if (accessToken != null) {
TokenCachingStrategy.putToken(bundle, accessToken);
TokenCachingStrategy.putExpirationMilliseconds(bundle, accessExpiresMillisecondsAfterEpoch);
TokenCachingStrategy.putPermissions(bundle, stringList(pendingAuthorizationPermissions));
TokenCachingStrategy.putSource(bundle, AccessTokenSource.WEB_VIEW);
TokenCachingStrategy.putLastRefreshMilliseconds(bundle, lastAccessUpdateMillisecondsAfterEpoch);
}
return bundle;
}
@Override
public void save(Bundle bundle) {
accessToken = TokenCachingStrategy.getToken(bundle);
accessExpiresMillisecondsAfterEpoch = TokenCachingStrategy.getExpirationMilliseconds(bundle);
pendingAuthorizationPermissions = stringArray(TokenCachingStrategy.getPermissions(bundle));
lastAccessUpdateMillisecondsAfterEpoch = TokenCachingStrategy.getLastRefreshMilliseconds(bundle);
}
@Override
public void clear() {
accessToken = null;
}
}
/**
* Get Attribution ID for app install conversion tracking.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Settings} for more info.
*
* @param contentResolver
* @return Attribution ID that will be used for conversion tracking. It will be null only if
* the user has not installed or logged in to the Facebook app.
*/
@Deprecated
public static String getAttributionId(ContentResolver contentResolver) {
return Settings.getAttributionId(contentResolver);
}
/**
* Get the auto install publish setting. If true, an install event will be published during authorize(), unless
* it has occurred previously or the app does not have install attribution enabled on the application's developer
* config page.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Settings} for more info.
*
* @return a Boolean indicating whether installation of the app should be auto-published.
*/
@Deprecated
public boolean getShouldAutoPublishInstall() {
return Settings.getShouldAutoPublishInstall();
}
/**
* Sets whether auto publishing of installs will occur.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Settings} for more info.
*
* @param value a Boolean indicating whether installation of the app should be auto-published.
*/
@Deprecated
public void setShouldAutoPublishInstall(boolean value) {
Settings.setShouldAutoPublishInstall(value);
}
/**
* Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent
* multiple installs being published to the graph.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link Settings} for more info.
*
* @param context the current Android context
* @return Always false. Earlier versions of the API returned true if it was no longer necessary to call.
* Apps should ignore this value, but for compatibility we will return false to ensure repeat calls (and the
* underlying code will prevent duplicate network traffic).
*/
@Deprecated
public boolean publishInstall(final Context context) {
Settings.publishInstallAsync(context, mAppId);
return false;
}
/**
* Callback interface for dialog requests.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link com.facebook.widget.WebDialog}
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public static interface DialogListener {
/**
* Called when a dialog completes.
*
* Executed by the thread that initiated the dialog.
*
* @param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(Bundle values);
/**
* Called when a Facebook responds to a dialog with an error.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onFacebookError(FacebookError e);
/**
* Called when a dialog has an error.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onError(DialogError e);
/**
* Called when a dialog is canceled by the user.
*
* Executed by the thread that initiated the dialog.
*
*/
public void onCancel();
}
/**
* Callback interface for service requests.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link Session} to manage session state.
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public static interface ServiceListener {
/**
* Called when a service request completes.
*
* @param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(Bundle values);
/**
* Called when a Facebook server responds to the request with an error.
*/
public void onFacebookError(FacebookError e);
/**
* Called when a Facebook Service responds to the request with an error.
*/
public void onError(Error e);
}
@Deprecated
public static final String FB_APP_SIGNATURE =
"30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310"
+ "b3009060355040613025553310b30090603550408130243413112301006035504"
+ "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204"
+ "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504"
+ "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333"
+ "13231353231365a180f32303530303932353231353231365a307a310b30090603"
+ "55040613025553310b30090603550408130243413112301006035504071309506"
+ "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c"
+ "653111300f060355040b130846616365626f6f6b311d301b06035504031314466"
+ "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01"
+ "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa"
+ "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7"
+ "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc"
+ "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603"
+ "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050"
+ "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c"
+ "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6"
+ "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2"
+ "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd"
+ "928a2";
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import com.facebook.internal.Utility;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
/**
* Utility class supporting the Facebook Object.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link com.facebook.Request}
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public final class Util {
private final static String UTF8 = "UTF-8";
/**
* Generate the multi-part post body providing the parameters and boundary
* string
*
* @param parameters the parameters need to be posted
* @param boundary the random string as boundary
* @return a string of the post body
*/
@Deprecated
public static String encodePostBody(Bundle parameters, String boundary) {
if (parameters == null) return "";
StringBuilder sb = new StringBuilder();
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
sb.append("Content-Disposition: form-data; name=\"" + key +
"\"\r\n\r\n" + (String)parameter);
sb.append("\r\n" + "--" + boundary + "\r\n");
}
return sb.toString();
}
@Deprecated
public static String encodeUrl(Bundle parameters) {
if (parameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
if (first) first = false; else sb.append("&");
sb.append(URLEncoder.encode(key) + "=" +
URLEncoder.encode(parameters.getString(key)));
}
return sb.toString();
}
@Deprecated
public static Bundle decodeUrl(String s) {
Bundle params = new Bundle();
if (s != null) {
String array[] = s.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
try {
if (v.length == 2) {
params.putString(URLDecoder.decode(v[0], UTF8),
URLDecoder.decode(v[1], UTF8));
} else if (v.length == 1) {
params.putString(URLDecoder.decode(v[0], UTF8), "");
}
} catch (UnsupportedEncodingException e) {
// shouldn't happen
}
}
}
return params;
}
/**
* Parse a URL query and fragment parameters into a key-value bundle.
*
* @param url the URL to parse
* @return a dictionary bundle of keys and values
*/
@Deprecated
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
}
/**
* Connect to an HTTP URL and return the response as a string.
*
* Note that the HTTP method override is used on non-GET requests. (i.e.
* requests are made as "POST" with method specified in the body).
*
* @param url - the resource to open: must be a welformed URL
* @param method - the HTTP method to use ("GET", "POST", etc.)
* @param params - the query parameter for the URL (e.g. access_token=foo)
* @return the URL contents as a String
* @throws MalformedURLException - if the URL format is invalid
* @throws IOException - if a network problem occurs
*/
@Deprecated
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Utility.logd("Facebook-Util", method + " URL: " + url);
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
Object parameter = params.get(key);
if (parameter instanceof byte[]) {
dataparams.putByteArray(key, (byte[])parameter);
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
if (params.containsKey("access_token")) {
String decoded_token =
URLDecoder.decode(params.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type",
"multipart/form-data;boundary="+strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(("--" + strBoundary +endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key: dataparams.keySet()){
os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine).getBytes());
}
}
os.flush();
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
@Deprecated
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
@Deprecated
public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
}
/**
* Display a simple alert dialog with the given text and title.
*
* @param context
* Android context in which the dialog should be displayed
* @param title
* Alert dialog title
* @param text
* Alert dialog message
*/
@Deprecated
public static void showAlert(Context context, String title, String text) {
Builder alertBuilder = new Builder(context);
alertBuilder.setTitle(title);
alertBuilder.setMessage(text);
alertBuilder.create().show();
}
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
/**
* Encapsulation of Dialog Error.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link com.facebook.FacebookException}
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public class DialogError extends Throwable {
private static final long serialVersionUID = 1L;
/**
* The ErrorCode received by the WebView: see
* http://developer.android.com/reference/android/webkit/WebViewClient.html
*/
private int mErrorCode;
/** The URL that the dialog was trying to load */
private String mFailingUrl;
@Deprecated
public DialogError(String message, int errorCode, String failingUrl) {
super(message);
mErrorCode = errorCode;
mFailingUrl = failingUrl;
}
@Deprecated
public int getErrorCode() {
return mErrorCode;
}
@Deprecated
public String getFailingUrl() {
return mFailingUrl;
}
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
/**
* Encapsulation of a Facebook Error: a Facebook request that could not be
* fulfilled.
* <p/>
* THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
* <p/>
* All public members of this class are intentionally deprecated.
* New code should instead use
* {@link com.facebook.FacebookException}
* <p/>
* Adding @Deprecated to this class causes warnings in other deprecated classes
* that reference this one. That is the only reason this entire class is not
* deprecated.
*
* @devDocDeprecated
*/
public class FacebookError extends RuntimeException {
private static final long serialVersionUID = 1L;
private int mErrorCode = 0;
private String mErrorType;
@Deprecated
public FacebookError(String message) {
super(message);
}
@Deprecated
public FacebookError(String message, String type, int code) {
super(message);
mErrorType = type;
mErrorCode = code;
}
@Deprecated
public int getErrorCode() {
return mErrorCode;
}
@Deprecated
public String getErrorType() {
return mErrorType;
}
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.content.Context;
import android.os.Bundle;
import com.facebook.*;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.widget.WebDialog;
/**
* This class is deprecated. See {@link com.facebook.widget.WebDialog}.
*/
@Deprecated
public class FbDialog extends WebDialog {
private DialogListener mListener;
public FbDialog(Context context, String url, DialogListener listener) {
this(context, url, listener, DEFAULT_THEME);
}
public FbDialog(Context context, String url, DialogListener listener, int theme) {
super(context, url, theme);
setDialogListener(listener);
}
public FbDialog(Context context, String action, Bundle parameters, DialogListener listener) {
super(context, action, parameters, DEFAULT_THEME, null);
setDialogListener(listener);
}
public FbDialog(Context context, String action, Bundle parameters, DialogListener listener,
int theme) {
super(context, action, parameters, theme, null);
setDialogListener(listener);
}
private void setDialogListener(DialogListener listener) {
this.mListener = listener;
setOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Bundle values, FacebookException error) {
callDialogListener(values, error);
}
});
}
private void callDialogListener(Bundle values, FacebookException error) {
if (mListener == null) {
return;
}
if (values != null) {
mListener.onComplete(values);
} else {
if (error instanceof FacebookDialogException) {
FacebookDialogException facebookDialogException = (FacebookDialogException) error;
DialogError dialogError = new DialogError(facebookDialogException.getMessage(),
facebookDialogException.getErrorCode(), facebookDialogException.getFailingUrl());
mListener.onError(dialogError);
} else if (error instanceof FacebookOperationCanceledException) {
mListener.onCancel();
} else {
FacebookError facebookError = new FacebookError(error.getMessage());
mListener.onFacebookError(facebookError);
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.content.Context;
import android.os.Bundle;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
/**
* A sample implementation of asynchronous API requests. This class provides
* the ability to execute API methods and have the call return immediately,
* without blocking the calling thread. This is necessary when accessing the
* API in the UI thread, for instance. The request response is returned to
* the caller via a callback interface, which the developer must implement.
*
* This sample implementation simply spawns a new thread for each request,
* and makes the API call immediately. This may work in many applications,
* but more sophisticated users may re-implement this behavior using a thread
* pool, a network thread, a request queue, or other mechanism. Advanced
* functionality could be built, such as rate-limiting of requests, as per
* a specific application's needs.
*
* @deprecated
*
* @see RequestListener
* The callback interface.
*
* @author Jim Brusstar (jimbru@fb.com),
* Yariv Sadan (yariv@fb.com),
* Luke Shepard (lshepard@fb.com)
*/
@Deprecated
public class AsyncFacebookRunner {
Facebook fb;
public AsyncFacebookRunner(Facebook fb) {
this.fb = fb;
}
/**
* Invalidate the current user session by removing the access token in
* memory, clearing the browser cookies, and calling auth.expireSession
* through the API. The application will be notified when logout is
* complete via the callback interface.
* <p/>
* Note that this method is asynchronous and the callback will be invoked
* in a background thread; operations that affect the UI will need to be
* posted to the UI thread or an appropriate handler.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link com.facebook.Session} for more info.
*
* @param context
* The Android context in which the logout should be called: it
* should be the same context in which the login occurred in
* order to clear any stored cookies
* @param listener
* Callback interface to notify the application when the request
* has completed.
* @param state
* An arbitrary object used to identify the request when it
* returns to the callback. This has no effect on the request
* itself.
*/
@Deprecated
public void logout(final Context context,
final RequestListener listener,
final Object state) {
new Thread() {
@Override public void run() {
try {
String response = fb.logoutImpl(context);
if (response.length() == 0 || response.equals("false")){
listener.onFacebookError(new FacebookError(
"auth.expireSession failed"), state);
return;
}
listener.onComplete(response, state);
} catch (FileNotFoundException e) {
listener.onFileNotFoundException(e, state);
} catch (MalformedURLException e) {
listener.onMalformedURLException(e, state);
} catch (IOException e) {
listener.onIOException(e, state);
}
}
}.start();
}
@Deprecated
public void logout(final Context context, final RequestListener listener) {
logout(context, listener, /* state */ null);
}
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
* <p/>
* See http://developers.facebook.com/docs/reference/rest/
* <p/>
* Note that this method is asynchronous and the callback will be invoked
* in a background thread; operations that affect the UI will need to be
* posted to the UI thread or an appropriate handler.
* <p/>
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession", new Listener());
* String response = request(parameters);
* </code>
* <p/>
* This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info.
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @param listener
* Callback interface to notify the application when the request
* has completed.
* @param state
* An arbitrary object used to identify the request when it
* returns to the callback. This has no effect on the request
* itself.
*/
@Deprecated
public void request(Bundle parameters,
RequestListener listener,
final Object state) {
request(null, parameters, "GET", listener, state);
}
@Deprecated
public void request(Bundle parameters, RequestListener listener) {
request(null, parameters, "GET", listener, /* state */ null);
}
/**
* Make a request to the Facebook Graph API without any parameters.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method is asynchronous and the callback will be invoked
* in a background thread; operations that affect the UI will need to be
* posted to the UI thread or an appropriate handler.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param listener
* Callback interface to notify the application when the request
* has completed.
* @param state
* An arbitrary object used to identify the request when it
* returns to the callback. This has no effect on the request
* itself.
*/
@Deprecated
public void request(String graphPath,
RequestListener listener,
final Object state) {
request(graphPath, new Bundle(), "GET", listener, state);
}
@Deprecated
public void request(String graphPath, RequestListener listener) {
request(graphPath, new Bundle(), "GET", listener, /* state */ null);
}
/**
* Make a request to the Facebook Graph API with the given string parameters
* using an HTTP GET (default method).
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method is asynchronous and the callback will be invoked
* in a background thread; operations that affect the UI will need to be
* posted to the UI thread or an appropriate handler.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param listener
* Callback interface to notify the application when the request
* has completed.
* @param state
* An arbitrary object used to identify the request when it
* returns to the callback. This has no effect on the request
* itself.
*/
@Deprecated
public void request(String graphPath,
Bundle parameters,
RequestListener listener,
final Object state) {
request(graphPath, parameters, "GET", listener, state);
}
@Deprecated
public void request(String graphPath,
Bundle parameters,
RequestListener listener) {
request(graphPath, parameters, "GET", listener, /* state */ null);
}
/**
* Make a request to the Facebook Graph API with the given HTTP method and
* string parameters. Note that binary data parameters (e.g. pictures) are
* not yet supported by this helper function.
* <p/>
* See http://developers.facebook.com/docs/api
* <p/>
* Note that this method is asynchronous and the callback will be invoked
* in a background thread; operations that affect the UI will need to be
* posted to the UI thread or an appropriate handler.
* <p/>
* This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info.
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param httpMethod
* http verb, e.g. "POST", "DELETE"
* @param listener
* Callback interface to notify the application when the request
* has completed.
* @param state
* An arbitrary object used to identify the request when it
* returns to the callback. This has no effect on the request
* itself.
*/
@Deprecated
public void request(final String graphPath,
final Bundle parameters,
final String httpMethod,
final RequestListener listener,
final Object state) {
new Thread() {
@Override public void run() {
try {
String resp = fb.requestImpl(graphPath, parameters, httpMethod);
listener.onComplete(resp, state);
} catch (FileNotFoundException e) {
listener.onFileNotFoundException(e, state);
} catch (MalformedURLException e) {
listener.onMalformedURLException(e, state);
} catch (IOException e) {
listener.onIOException(e, state);
}
}
}.start();
}
/**
* Callback interface for API requests.
* <p/>
* Each method includes a 'state' parameter that identifies the calling
* request. It will be set to the value passed when originally calling the
* request method, or null if none was passed.
* <p/>
* This interface is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info.
*/
@Deprecated
public static interface RequestListener {
/**
* Called when a request completes with the given response.
*
* Executed by a background thread: do not update the UI in this method.
*/
public void onComplete(String response, Object state);
/**
* Called when a request has a network or request error.
*
* Executed by a background thread: do not update the UI in this method.
*/
public void onIOException(IOException e, Object state);
/**
* Called when a request fails because the requested resource is
* invalid or does not exist.
*
* Executed by a background thread: do not update the UI in this method.
*/
public void onFileNotFoundException(FileNotFoundException e,
Object state);
/**
* Called if an invalid graph path is provided (which may result in a
* malformed URL).
*
* Executed by a background thread: do not update the UI in this method.
*/
public void onMalformedURLException(MalformedURLException e,
Object state);
/**
* Called when the server-side Facebook method fails.
*
* Executed by a background thread: do not update the UI in this method.
*/
public void onFacebookError(FacebookError e, Object state);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.os.Handler;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* RequestBatch contains a list of Request objects that can be sent to Facebook in a single round-trip.
*/
public class RequestBatch extends AbstractList<Request> {
private static AtomicInteger idGenerator = new AtomicInteger();
private Handler callbackHandler;
private List<Request> requests = new ArrayList<Request>();
private int timeoutInMilliseconds = 0;
private final String id = Integer.valueOf(idGenerator.incrementAndGet()).toString();
private List<Callback> callbacks = new ArrayList<Callback>();
private String batchApplicationId;
/**
* Constructor. Creates an empty batch.
*/
public RequestBatch() {
this.requests = new ArrayList<Request>();
}
/**
* Constructor.
* @param requests the requests to add to the batch
*/
public RequestBatch(Collection<Request> requests) {
this.requests = new ArrayList<Request>(requests);
}
/**
* Constructor.
* @param requests the requests to add to the batch
*/
public RequestBatch(Request... requests) {
this.requests = Arrays.asList(requests);
}
/**
* Constructor.
* @param requests the requests to add to the batch
*/
public RequestBatch(RequestBatch requests) {
this.requests = new ArrayList<Request>(requests);
this.callbackHandler = requests.callbackHandler;
this.timeoutInMilliseconds = requests.timeoutInMilliseconds;
this.callbacks = new ArrayList<Callback>(requests.callbacks);
}
/**
* Gets the timeout to wait for responses from the server before a timeout error occurs.
* @return the timeout, in milliseconds; 0 (the default) means do not timeout
*/
public int getTimeout() {
return timeoutInMilliseconds;
}
/**
* Sets the timeout to wait for responses from the server before a timeout error occurs.
* @param timeoutInMilliseconds the timeout, in milliseconds; 0 means do not timeout
*/
public void setTimeout(int timeoutInMilliseconds) {
if (timeoutInMilliseconds < 0) {
throw new IllegalArgumentException("Argument timeoutInMilliseconds must be >= 0.");
}
this.timeoutInMilliseconds = timeoutInMilliseconds;
}
/**
* Adds a batch-level callback which will be called when the entire batch has finished executing.
*
* @param callback the callback
*/
public void addCallback(Callback callback) {
if (!callbacks.contains(callback)) {
callbacks.add(callback);
}
}
/**
* Removes a batch-level callback.
*
* @param callback the callback
*/
public void removeCallback(Callback callback) {
callbacks.remove(callback);
}
@Override
public final boolean add(Request request) {
return requests.add(request);
}
@Override
public final void add(int location, Request request) {
requests.add(location, request);
}
@Override
public final void clear() {
requests.clear();
}
@Override
public final Request get(int i) {
return requests.get(i);
}
@Override
public final Request remove(int location) {
return requests.remove(location);
}
@Override
public final Request set(int location, Request request) {
return requests.set(location, request);
}
@Override
public final int size() {
return requests.size();
}
final String getId() {
return id;
}
final Handler getCallbackHandler() {
return callbackHandler;
}
final void setCallbackHandler(Handler callbackHandler) {
this.callbackHandler = callbackHandler;
}
final List<Request> getRequests() {
return requests;
}
final List<Callback> getCallbacks() {
return callbacks;
}
final String getBatchApplicationId() {
return batchApplicationId;
}
final void setBatchApplicationId(String batchApplicationId) {
this.batchApplicationId = batchApplicationId;
}
/**
* Executes this batch on the current thread and returns the responses.
* <p/>
* This should only be used if you have transitioned off the UI thread.
*
* @return a list of Response objects representing the results of the requests; responses are returned in the same
* order as the requests were specified.
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
* @throws IllegalArgumentException if the passed in RequestBatch is empty
* @throws NullPointerException if the passed in RequestBatch or any of its contents are null
*/
public final List<Response> executeAndWait() {
return executeAndWaitImpl();
}
/**
* Executes this batch asynchronously. This function will return immediately, and the batch will
* be processed on a separate thread. In order to process results of a request, or determine
* whether a request succeeded or failed, a callback must be specified (see
* {@link Request#setCallback(com.facebook.Request.Callback)})
* <p/>
* This should only be called from the UI thread.
*
* @return a RequestAsyncTask that is executing the request
*
* @throws IllegalArgumentException if this batch is empty
* @throws NullPointerException if any of the contents of this batch are null
*/
public final RequestAsyncTask executeAsync() {
return executeAsyncImpl();
}
/**
* Specifies the interface that consumers of the RequestBatch class can implement in order to be notified when the
* entire batch completes execution. It will be called after all per-Request callbacks are called.
*/
public interface Callback {
/**
* The method that will be called when a batch completes.
*
* @param batch the RequestBatch containing the Requests which were executed
*/
void onBatchCompleted(RequestBatch batch);
}
List<Response> executeAndWaitImpl() {
return Request.executeBatchAndWait(this);
}
RequestAsyncTask executeAsyncImpl() {
return Request.executeBatchAsync(this);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.app.Activity;
import android.content.*;
import android.content.pm.ResolveInfo;
import android.os.*;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.facebook.internal.SessionAuthorizationType;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
/**
* <p>
* Session is used to authenticate a user and manage the user's session with
* Facebook.
* </p>
* <p>
* 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 {@link SessionState SessionState} to indicate its state.
* </p>
* <p>
* Instances of Session provide state change notification via a callback
* interface, {@link Session.StatusCallback StatusCallback}.
* </p>
*/
public class Session implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The logging tag used by Session.
*/
public static final String TAG = Session.class.getCanonicalName();
/**
* The default activity code used for authorization.
*
* @see #openForRead(OpenRequest)
* open
*/
public static final int DEFAULT_AUTHORIZE_ACTIVITY_CODE = 0xface;
/**
* If Session authorization fails and provides a web view error code, the
* web view error code is stored in the Bundle returned from
* {@link #getAuthorizationBundle getAuthorizationBundle} under this key.
*/
public static final String WEB_VIEW_ERROR_CODE_KEY = "com.facebook.sdk.WebViewErrorCode";
/**
* If Session authorization fails and provides a failing url, the failing
* url is stored in the Bundle returned from {@link #getAuthorizationBundle
* getAuthorizationBundle} under this key.
*/
public static final String WEB_VIEW_FAILING_URL_KEY = "com.facebook.sdk.FailingUrl";
/**
* 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 {@link android.support.v4.content.LocalBroadcastManager}.
*/
public static final String ACTION_ACTIVE_SESSION_SET = "com.facebook.sdk.ACTIVE_SESSION_SET";
/**
* 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 {@link android.support.v4.content.LocalBroadcastManager}.
*/
public static final String ACTION_ACTIVE_SESSION_UNSET = "com.facebook.sdk.ACTIVE_SESSION_UNSET";
/**
* 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 {@link android.support.v4.content.LocalBroadcastManager}.
*/
public static final String ACTION_ACTIVE_SESSION_OPENED = "com.facebook.sdk.ACTIVE_SESSION_OPENED";
/**
* 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 {@link android.support.v4.content.LocalBroadcastManager}.
*/
public static final String ACTION_ACTIVE_SESSION_CLOSED = "com.facebook.sdk.ACTIVE_SESSION_CLOSED";
/**
* 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 = "com.facebook.sdk.ApplicationId";
private static final Object STATIC_LOCK = new Object();
private static Session activeSession;
private static volatile Context staticContext;
// Token extension constants
private static final int TOKEN_EXTEND_THRESHOLD_SECONDS = 24 * 60 * 60; // 1
// day
private static final int TOKEN_EXTEND_RETRY_SECONDS = 60 * 60; // 1 hour
private static final String SESSION_BUNDLE_SAVE_KEY = "com.facebook.sdk.Session.saveSessionKey";
private static final String AUTH_BUNDLE_SAVE_KEY = "com.facebook.sdk.Session.authBundleKey";
private static final String PUBLISH_PERMISSION_PREFIX = "publish";
private static final String MANAGE_PERMISSION_PREFIX = "manage";
@SuppressWarnings("serial")
private static final Set<String> OTHER_PUBLISH_PERMISSIONS = new HashSet<String>() {{
add("ads_management");
add("create_event");
add("rsvp_event");
}};
private String applicationId;
private SessionState state;
private AccessToken tokenInfo;
private Date lastAttemptedTokenExtendDate = new Date(0);
private AuthorizationRequest pendingRequest;
private AuthorizationClient authorizationClient;
// The following are not serialized with the Session object
private volatile Bundle authorizationBundle;
private final List<StatusCallback> callbacks;
private Handler handler;
private AutoPublishAsyncTask autoPublishAsyncTask;
// This is the object that synchronizes access to state and tokenInfo
private final Object lock = new Object();
private TokenCachingStrategy tokenCachingStrategy;
private volatile TokenRefreshRequest currentTokenRefreshRequest;
/**
* Serialization proxy for the Session class. This is version 1 of
* serialization. Future serializations may differ in format. This
* class should not be modified. If serializations formats change,
* create a new class SerializationProxyVx.
*/
private static class SerializationProxyV1 implements Serializable {
private static final long serialVersionUID = 7663436173185080063L;
private final String applicationId;
private final SessionState state;
private final AccessToken tokenInfo;
private final Date lastAttemptedTokenExtendDate;
private final boolean shouldAutoPublish;
private final AuthorizationRequest pendingRequest;
SerializationProxyV1(String applicationId, SessionState state,
AccessToken tokenInfo, Date lastAttemptedTokenExtendDate,
boolean shouldAutoPublish, AuthorizationRequest pendingRequest) {
this.applicationId = applicationId;
this.state = state;
this.tokenInfo = tokenInfo;
this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate;
this.shouldAutoPublish = shouldAutoPublish;
this.pendingRequest = pendingRequest;
}
private Object readResolve() {
return new Session(applicationId, state, tokenInfo,
lastAttemptedTokenExtendDate, shouldAutoPublish, pendingRequest);
}
}
/**
* Used by version 1 of the serialization proxy, do not modify.
*/
private Session(String applicationId, SessionState state,
AccessToken tokenInfo, Date lastAttemptedTokenExtendDate,
boolean shouldAutoPublish, AuthorizationRequest pendingRequest) {
this.applicationId = applicationId;
this.state = state;
this.tokenInfo = tokenInfo;
this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate;
this.pendingRequest = pendingRequest;
handler = new Handler(Looper.getMainLooper());
currentTokenRefreshRequest = null;
tokenCachingStrategy = null;
callbacks = new ArrayList<StatusCallback>();
}
/**
* Initializes a new Session with the specified context.
*
* @param currentContext The Activity or Service creating this Session.
*/
public Session(Context currentContext) {
this(currentContext, null, null, true);
}
Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy) {
this(context, applicationId, tokenCachingStrategy, true);
}
Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy,
boolean loadTokenFromCache) {
// if the application ID passed in is null, try to get it from the
// meta-data in the manifest.
if ((context != null) && (applicationId == null)) {
applicationId = Utility.getMetadataApplicationId(context);
}
Validate.notNull(applicationId, "applicationId");
initializeStaticContext(context);
if (tokenCachingStrategy == null) {
tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(staticContext);
}
this.applicationId = applicationId;
this.tokenCachingStrategy = tokenCachingStrategy;
this.state = SessionState.CREATED;
this.pendingRequest = null;
this.callbacks = new ArrayList<StatusCallback>();
this.handler = new Handler(Looper.getMainLooper());
Bundle tokenState = loadTokenFromCache ? tokenCachingStrategy.load() : null;
if (TokenCachingStrategy.hasTokenInformation(tokenState)) {
Date cachedExpirationDate = TokenCachingStrategy
.getDate(tokenState, TokenCachingStrategy.EXPIRATION_DATE_KEY);
Date now = new Date();
if ((cachedExpirationDate == null) || cachedExpirationDate.before(now)) {
// If expired or we require new permissions, clear out the
// current token cache.
tokenCachingStrategy.clear();
this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList());
} else {
// Otherwise we have a valid token, so use it.
this.tokenInfo = AccessToken.createFromCache(tokenState);
this.state = SessionState.CREATED_TOKEN_LOADED;
}
} else {
this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList());
}
}
/**
* Returns a Bundle containing data that was returned from Facebook during
* authorization.
*
* @return a Bundle containing data that was returned from Facebook during
* authorization.
*/
public final Bundle getAuthorizationBundle() {
synchronized (this.lock) {
return this.authorizationBundle;
}
}
/**
* Returns a boolean indicating whether the session is opened.
*
* @return a boolean indicating whether the session is opened.
*/
public final boolean isOpened() {
synchronized (this.lock) {
return this.state.isOpened();
}
}
public final boolean isClosed() {
synchronized (this.lock) {
return this.state.isClosed();
}
}
/**
* Returns the current state of the Session.
* See {@link SessionState} for details.
*
* @return the current state of the Session.
*/
public final SessionState getState() {
synchronized (this.lock) {
return this.state;
}
}
/**
* Returns the application id associated with this Session.
*
* @return the application id associated with this Session.
*/
public final String getApplicationId() {
return this.applicationId;
}
/**
* Returns the access token String.
*
* @return the access token String, or null if there is no access token
*/
public final String getAccessToken() {
synchronized (this.lock) {
return (this.tokenInfo == null) ? null : this.tokenInfo.getToken();
}
}
/**
* <p>
* Returns the Date at which the current token will expire.
* </p>
* <p>
* Note that Session automatically attempts to extend the lifetime of Tokens
* as needed when Facebook requests are made.
* </p>
*
* @return the Date at which the current token will expire, or null if there is no access token
*/
public final Date getExpirationDate() {
synchronized (this.lock) {
return (this.tokenInfo == null) ? null : this.tokenInfo.getExpires();
}
}
/**
* <p>
* Returns the list of permissions associated with the session.
* </p>
* <p>
* If there is a valid token, this represents the permissions granted by
* that token. This can change during calls to
* {@link #requestNewReadPermissions}
* or {@link #requestNewPublishPermissions}.
* </p>
*
* @return the list of permissions associated with the session, or null if there is no access token
*/
public final List<String> getPermissions() {
synchronized (this.lock) {
return (this.tokenInfo == null) ? null : this.tokenInfo.getPermissions();
}
}
/**
* <p>
* Logs a user in to Facebook.
* </p>
* <p>
* A session may not be used with {@link Request Request} and other classes
* in the SDK until it is open. If, prior to calling open, the session is in
* the {@link SessionState#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.
* </p>
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
*
* @param openRequest the open request, can be null only if the Session is in the
* {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} state
* @throws FacebookException if any publish or manage permissions are requested
*/
public final void openForRead(OpenRequest openRequest) {
open(openRequest, SessionAuthorizationType.READ);
}
/**
* <p>
* Logs a user in to Facebook.
* </p>
* <p>
* A session may not be used with {@link Request Request} and other classes
* in the SDK until it is open. If, prior to calling open, the session is in
* the {@link SessionState#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.
* </p>
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
*
* @param openRequest the open request, can be null only if the Session is in the
* {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} state
* @throws FacebookException if the passed in request is null or has no permissions set.
*/
public final void openForPublish(OpenRequest openRequest) {
open(openRequest, SessionAuthorizationType.PUBLISH);
}
/**
* 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.
* <p/>
* 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.
*
* @param accessToken the access token obtained from Facebook
* @param callback a callback that will be called when the session status changes; may be null
*/
public final void open(AccessToken accessToken, StatusCallback callback) {
synchronized (this.lock) {
if (pendingRequest != null) {
throw new UnsupportedOperationException(
"Session: an attempt was made to open a session that has a pending request.");
}
if (state != SessionState.CREATED && state != SessionState.CREATED_TOKEN_LOADED) {
throw new UnsupportedOperationException(
"Session: an attempt was made to open an already opened session.");
}
if (callback != null) {
addCallback(callback);
}
this.tokenInfo = accessToken;
if (this.tokenCachingStrategy != null) {
this.tokenCachingStrategy.save(accessToken.toCacheBundle());
}
final SessionState oldState = state;
state = SessionState.OPENED;
this.postStateChange(oldState, state, null);
}
autoPublishAsync();
}
/**
* <p>
* Issues a request to add new read permissions to the Session.
* </p>
* <p>
* If successful, this will update the set of permissions on this session to
* match the newPermissions. If this fails, the Session remains unchanged.
* </p>
* <p>
* 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.
* </p>
*
* @param newPermissionsRequest the new permissions request
*/
public final void requestNewReadPermissions(NewPermissionsRequest newPermissionsRequest) {
requestNewPermissions(newPermissionsRequest, SessionAuthorizationType.READ);
}
/**
* <p>
* Issues a request to add new publish or manage permissions to the Session.
* </p>
* <p>
* If successful, this will update the set of permissions on this session to
* match the newPermissions. If this fails, the Session remains unchanged.
* </p>
* <p>
* 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.
* </p>
*
* @param newPermissionsRequest the new permissions request
*/
public final void requestNewPublishPermissions(NewPermissionsRequest newPermissionsRequest) {
requestNewPermissions(newPermissionsRequest, SessionAuthorizationType.PUBLISH);
}
/**
* Provides an implementation for {@link Activity#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.
*
* @param currentActivity The Activity that is forwarding the onActivityResult call.
* @param requestCode The 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.
* @param resultCode An int containing the resultCode parameter from the forwarded
* call.
* @param data The Intent passed as the data parameter from the forwarded
* call.
* @return A boolean indicating whether the requestCode matched a pending
* authorization request for this Session.
*/
public final boolean onActivityResult(Activity currentActivity, int requestCode, int resultCode, Intent data) {
Validate.notNull(currentActivity, "currentActivity");
initializeStaticContext(currentActivity);
synchronized (lock) {
if (pendingRequest == null || (requestCode != pendingRequest.getRequestCode())) {
return false;
}
}
AccessToken newToken = null;
Exception exception = null;
if (data != null) {
AuthorizationClient.Result result = (AuthorizationClient.Result) data.getSerializableExtra(
LoginActivity.RESULT_KEY);
if (result != null) {
// This came from LoginActivity.
handleAuthorizationResult(resultCode, result);
return true;
} else if (authorizationClient != null) {
// Delegate to the auth client.
authorizationClient.onActivityResult(requestCode, resultCode, data);
return true;
}
} else if (resultCode == Activity.RESULT_CANCELED) {
exception = new FacebookOperationCanceledException("User canceled operation.");
}
finishAuthOrReauth(newToken, exception);
return true;
}
/**
* Closes the local in-memory Session object, but does not clear the
* persisted token cache.
*/
@SuppressWarnings("incomplete-switch")
public final void close() {
synchronized (this.lock) {
final SessionState oldState = this.state;
switch (this.state) {
case CREATED:
case OPENING:
this.state = SessionState.CLOSED_LOGIN_FAILED;
postStateChange(oldState, this.state, new FacebookException(
"Log in attempt aborted."));
break;
case CREATED_TOKEN_LOADED:
case OPENED:
case OPENED_TOKEN_UPDATED:
this.state = SessionState.CLOSED;
postStateChange(oldState, this.state, null);
break;
}
}
}
/**
* Closes the local in-memory Session object and clears any persisted token
* cache related to the Session.
*/
public final void closeAndClearTokenInformation() {
if (this.tokenCachingStrategy != null) {
this.tokenCachingStrategy.clear();
}
Utility.clearFacebookCookies(staticContext);
close();
}
/**
* Adds a callback that will be called when the state of this Session changes.
*
* @param callback the callback
*/
public final void addCallback(StatusCallback callback) {
synchronized (callbacks) {
if (callback != null && !callbacks.contains(callback)) {
callbacks.add(callback);
}
}
}
/**
* Removes a StatusCallback from this Session.
*
* @param callback the callback
*/
public final void removeCallback(StatusCallback callback) {
synchronized (callbacks) {
callbacks.remove(callback);
}
}
@Override
public String toString() {
return new StringBuilder().append("{Session").append(" state:").append(this.state).append(", token:")
.append((this.tokenInfo == null) ? "null" : this.tokenInfo).append(", appId:")
.append((this.applicationId == null) ? "null" : this.applicationId).append("}").toString();
}
void extendTokenCompleted(Bundle bundle) {
synchronized (this.lock) {
final SessionState oldState = this.state;
switch (this.state) {
case OPENED:
this.state = SessionState.OPENED_TOKEN_UPDATED;
postStateChange(oldState, this.state, null);
break;
case OPENED_TOKEN_UPDATED:
break;
default:
// Silently ignore attempts to refresh token if we are not open
Log.d(TAG, "refreshToken ignored in state " + this.state);
return;
}
this.tokenInfo = AccessToken.createFromRefresh(this.tokenInfo, bundle);
if (this.tokenCachingStrategy != null) {
this.tokenCachingStrategy.save(this.tokenInfo.toCacheBundle());
}
}
}
private Object writeReplace() {
return new SerializationProxyV1(applicationId, state, tokenInfo,
lastAttemptedTokenExtendDate, false, pendingRequest);
}
// have a readObject that throws to prevent spoofing
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Cannot readObject, serialization proxy required");
}
/**
* Save the Session object into the supplied Bundle.
*
* @param session the Session to save
* @param bundle the Bundle to save the Session to
*/
public static final void saveSession(Session session, Bundle bundle) {
if (bundle != null && session != null && !bundle.containsKey(SESSION_BUNDLE_SAVE_KEY)) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
new ObjectOutputStream(outputStream).writeObject(session);
} catch (IOException e) {
throw new FacebookException("Unable to save session.", e);
}
bundle.putByteArray(SESSION_BUNDLE_SAVE_KEY, outputStream.toByteArray());
bundle.putBundle(AUTH_BUNDLE_SAVE_KEY, session.authorizationBundle);
}
}
/**
* Restores the saved session from a Bundle, if any. Returns the restored Session or
* null if it could not be restored.
*
* @param context the Activity or Service creating the Session, must not be null
* @param cachingStrategy the 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
* @param callback the callback to notify for Session state changes, can be null
* @param bundle the bundle to restore the Session from
* @return the restored Session, or null
*/
public static final Session restoreSession(
Context context, TokenCachingStrategy cachingStrategy, StatusCallback callback, Bundle bundle) {
if (bundle == null) {
return null;
}
byte[] data = bundle.getByteArray(SESSION_BUNDLE_SAVE_KEY);
if (data != null) {
ByteArrayInputStream is = new ByteArrayInputStream(data);
try {
Session session = (Session) (new ObjectInputStream(is)).readObject();
initializeStaticContext(context);
if (cachingStrategy != null) {
session.tokenCachingStrategy = cachingStrategy;
} else {
session.tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(context);
}
if (callback != null) {
session.addCallback(callback);
}
session.authorizationBundle = bundle.getBundle(AUTH_BUNDLE_SAVE_KEY);
return session;
} catch (ClassNotFoundException e) {
Log.w(TAG, "Unable to restore session", e);
} catch (IOException e) {
Log.w(TAG, "Unable to restore session.", e);
}
}
return null;
}
/**
* Returns the current active Session, or null if there is none.
*
* @return the current active Session, or null if there is none.
*/
public static final Session getActiveSession() {
synchronized (Session.STATIC_LOCK) {
return Session.activeSession;
}
}
/**
* <p>
* Sets the current active Session.
* </p>
* <p>
* The active Session is used implicitly by predefined Request factory
* methods as well as optionally by UI controls in the sdk.
* </p>
* <p>
* It is legal to set this to null, or to a Session that is not yet open.
* </p>
*
* @param session A Session to use as the active Session, or null to indicate
* that there is no active Session.
*/
public static final void setActiveSession(Session session) {
synchronized (Session.STATIC_LOCK) {
if (session != Session.activeSession) {
Session oldSession = Session.activeSession;
if (oldSession != null) {
oldSession.close();
}
Session.activeSession = session;
if (oldSession != null) {
postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET);
}
if (session != null) {
postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET);
if (session.isOpened()) {
postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED);
}
}
}
}
}
/**
* Create a new Session, and if a token cache is available, open the
* Session and make it active without any user interaction.
*
* @param context The Context creating this session
* @return The new session or null if one could not be created
*/
public static Session openActiveSessionFromCache(Context context) {
return openActiveSession(context, false, null);
}
/**
* 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.
* <p/>
* 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).
*
* @param activity The Activity that is opening the new Session.
* @param allowLoginUI if false, only sets the active session and opens it if it
* does not require user interaction
* @param callback The {@link StatusCallback SessionStatusCallback} to
* notify regarding Session state changes. May be null.
* @return The new Session or null if one could not be created
*/
public static Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback) {
return openActiveSession(activity, allowLoginUI, new OpenRequest(activity).setCallback(callback));
}
/**
* 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.
* <p/>
* 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).
*
* @param context The Activity or Service creating this Session
* @param fragment The Fragment that is opening the new Session.
* @param allowLoginUI if false, only sets the active session and opens it if it
* does not require user interaction
* @param callback The {@link StatusCallback SessionStatusCallback} to
* notify regarding Session state changes.
* @return The new Session or null if one could not be created
*/
public static Session openActiveSession(Context context, Fragment fragment,
boolean allowLoginUI, StatusCallback callback) {
return openActiveSession(context, allowLoginUI, new OpenRequest(fragment).setCallback(callback));
}
/**
* 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.
* <p/>
* 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.
*
* @param context the Context to use for creation the session
* @param accessToken the access token obtained from Facebook
* @param callback a callback that will be called when the session status changes; may be null
* @return The new Session or null if one could not be created
*/
public static Session openActiveSessionWithAccessToken(Context context, AccessToken accessToken,
StatusCallback callback) {
Session session = new Session(context, null, null, false);
setActiveSession(session);
session.open(accessToken, callback);
return session;
}
private static Session openActiveSession(Context context, boolean allowLoginUI, OpenRequest openRequest) {
Session session = new Builder(context).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
static Context getStaticContext() {
return staticContext;
}
static void initializeStaticContext(Context currentContext) {
if ((currentContext != null) && (staticContext == null)) {
Context applicationContext = currentContext.getApplicationContext();
staticContext = (applicationContext != null) ? applicationContext : currentContext;
}
}
void authorize(AuthorizationRequest request) {
boolean started = false;
request.setApplicationId(applicationId);
autoPublishAsync();
started = tryLoginActivity(request);
if (!started && request.isLegacy) {
started = tryLegacyAuth(request);
}
if (!started) {
synchronized (this.lock) {
final SessionState oldState = this.state;
switch (this.state) {
case CLOSED:
case CLOSED_LOGIN_FAILED:
return;
default:
this.state = SessionState.CLOSED_LOGIN_FAILED;
postStateChange(oldState, this.state, new FacebookException("Log in attempt failed."));
}
}
}
}
private void open(OpenRequest openRequest, SessionAuthorizationType authType) {
validatePermissions(openRequest, authType);
validateLoginBehavior(openRequest);
SessionState newState;
synchronized (this.lock) {
if (pendingRequest != null) {
postStateChange(state, state, new UnsupportedOperationException(
"Session: an attempt was made to open a session that has a pending request."));
return;
}
final SessionState oldState = this.state;
switch (this.state) {
case CREATED:
this.state = newState = SessionState.OPENING;
if (openRequest == null) {
throw new IllegalArgumentException("openRequest cannot be null when opening a new Session");
}
pendingRequest = openRequest;
break;
case CREATED_TOKEN_LOADED:
if (openRequest != null && !Utility.isNullOrEmpty(openRequest.getPermissions())) {
if (!Utility.isSubset(openRequest.getPermissions(), getPermissions())) {
pendingRequest = openRequest;
}
}
if (pendingRequest == null) {
this.state = newState = SessionState.OPENED;
} else {
this.state = newState = SessionState.OPENING;
}
break;
default:
throw new UnsupportedOperationException(
"Session: an attempt was made to open an already opened session.");
}
if (openRequest != null) {
addCallback(openRequest.getCallback());
}
this.postStateChange(oldState, newState, null);
}
if (newState == SessionState.OPENING) {
authorize(openRequest);
}
}
private void requestNewPermissions(NewPermissionsRequest newPermissionsRequest, SessionAuthorizationType authType) {
validatePermissions(newPermissionsRequest, authType);
validateLoginBehavior(newPermissionsRequest);
if (newPermissionsRequest != null) {
synchronized (this.lock) {
if (pendingRequest != null) {
throw new UnsupportedOperationException(
"Session: an attempt was made to request new permissions for a session that has a pending request.");
}
switch (this.state) {
case OPENED:
case OPENED_TOKEN_UPDATED:
pendingRequest = newPermissionsRequest;
break;
default:
throw new UnsupportedOperationException(
"Session: an attempt was made to request new permissions for a session that is not currently open.");
}
}
newPermissionsRequest.setValidateSameFbidAsToken(getAccessToken());
authorize(newPermissionsRequest);
}
}
private void validateLoginBehavior(AuthorizationRequest request) {
if (request != null && !request.isLegacy) {
Intent intent = new Intent();
intent.setClass(getStaticContext(), LoginActivity.class);
if (!resolveIntent(intent)) {
throw new FacebookException(String.format(
"Cannot use SessionLoginBehavior %s when %s is not declared as an activity in AndroidManifest.xml",
request.getLoginBehavior(), LoginActivity.class.getName()));
}
}
}
private void validatePermissions(AuthorizationRequest request, SessionAuthorizationType authType) {
if (request == null || Utility.isNullOrEmpty(request.getPermissions())) {
if (SessionAuthorizationType.PUBLISH.equals(authType)) {
throw new FacebookException("Cannot request publish or manage authorization with no permissions.");
}
return; // nothing to check
}
for (String permission : request.getPermissions()) {
if (isPublishPermission(permission)) {
if (SessionAuthorizationType.READ.equals(authType)) {
throw new FacebookException(
String.format(
"Cannot pass a publish or manage permission (%s) to a request for read authorization",
permission));
}
} else {
if (SessionAuthorizationType.PUBLISH.equals(authType)) {
Log.w(TAG,
String.format(
"Should not pass a read permission (%s) to a request for publish or manage authorization",
permission));
}
}
}
}
static boolean isPublishPermission(String permission) {
return permission != null &&
(permission.startsWith(PUBLISH_PERMISSION_PREFIX) ||
permission.startsWith(MANAGE_PERMISSION_PREFIX) ||
OTHER_PUBLISH_PERMISSIONS.contains(permission));
}
private void handleAuthorizationResult(int resultCode, AuthorizationClient.Result result) {
AccessToken newToken = null;
Exception exception = null;
if (resultCode == Activity.RESULT_OK) {
if (result.code == AuthorizationClient.Result.Code.SUCCESS) {
newToken = result.token;
} else {
exception = new FacebookAuthorizationException(result.errorMessage);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
exception = new FacebookOperationCanceledException(result.errorMessage);
}
authorizationClient = null;
finishAuthOrReauth(newToken, exception);
}
private boolean tryLoginActivity(AuthorizationRequest request) {
Intent intent = getLoginActivityIntent(request);
if (!resolveIntent(intent)) {
return false;
}
try {
request.getStartActivityDelegate().startActivityForResult(intent, request.getRequestCode());
} catch (ActivityNotFoundException e) {
return false;
}
return true;
}
private boolean resolveIntent(Intent intent) {
ResolveInfo resolveInfo = getStaticContext().getPackageManager().resolveActivity(intent, 0);
if (resolveInfo == null) {
return false;
}
return true;
}
private Intent getLoginActivityIntent(AuthorizationRequest request) {
Intent intent = new Intent();
intent.setClass(getStaticContext(), LoginActivity.class);
intent.setAction(request.getLoginBehavior().toString());
// Let LoginActivity populate extras appropriately
AuthorizationClient.AuthorizationRequest authClientRequest = request.getAuthorizationClientRequest();
Bundle extras = LoginActivity.populateIntentExtras(authClientRequest);
intent.putExtras(extras);
return intent;
}
private boolean tryLegacyAuth(final AuthorizationRequest request) {
authorizationClient = new AuthorizationClient();
authorizationClient.setOnCompletedListener(new AuthorizationClient.OnCompletedListener() {
@Override
public void onCompleted(AuthorizationClient.Result result) {
int activityResult;
if (result.code == AuthorizationClient.Result.Code.CANCEL) {
activityResult = Activity.RESULT_CANCELED;
} else {
activityResult = Activity.RESULT_OK;
}
handleAuthorizationResult(activityResult, result);
}
});
authorizationClient.setContext(getStaticContext());
authorizationClient.startOrContinueAuth(request.getAuthorizationClientRequest());
return true;
}
@SuppressWarnings("incomplete-switch")
void finishAuthOrReauth(AccessToken newToken, Exception exception) {
// If the token we came up with is expired/invalid, then auth failed.
if ((newToken != null) && newToken.isInvalid()) {
newToken = null;
exception = new FacebookException("Invalid access token.");
}
synchronized (this.lock) {
switch (this.state) {
case OPENING:
// This means we are authorizing for the first time in this Session.
finishAuthorization(newToken, exception);
break;
case OPENED:
case OPENED_TOKEN_UPDATED:
// This means we are reauthorizing.
finishReauthorization(newToken, exception);
break;
}
}
}
private void finishAuthorization(AccessToken newToken, Exception exception) {
final SessionState oldState = state;
if (newToken != null) {
tokenInfo = newToken;
saveTokenToCache(newToken);
state = SessionState.OPENED;
} else if (exception != null) {
state = SessionState.CLOSED_LOGIN_FAILED;
}
pendingRequest = null;
postStateChange(oldState, state, exception);
}
private void finishReauthorization(final AccessToken newToken, Exception exception) {
final SessionState oldState = state;
if (newToken != null) {
tokenInfo = newToken;
saveTokenToCache(newToken);
state = SessionState.OPENED_TOKEN_UPDATED;
}
pendingRequest = null;
postStateChange(oldState, state, exception);
}
private void saveTokenToCache(AccessToken newToken) {
if (newToken != null && tokenCachingStrategy != null) {
tokenCachingStrategy.save(newToken.toCacheBundle());
}
}
void postStateChange(final SessionState oldState, final SessionState newState, final Exception exception) {
// When we request new permissions, we stay in SessionState.OPENED_TOKEN_UPDATED,
// but we still want notifications of the state change since permissions are
// different now.
if ((oldState == newState) &&
(oldState != SessionState.OPENED_TOKEN_UPDATED) &&
(exception == null)) {
return;
}
if (newState.isClosed()) {
this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList());
}
synchronized (callbacks) {
// Need to schedule the callbacks inside the same queue to preserve ordering.
// Otherwise these callbacks could have been added to the queue before the SessionTracker
// gets the ACTIVE_SESSION_SET action.
Runnable runCallbacks = new Runnable() {
public void run() {
for (final StatusCallback callback : callbacks) {
Runnable closure = new Runnable() {
public void run() {
// This can be called inside a synchronized block.
callback.call(Session.this, newState, exception);
}
};
runWithHandlerOrExecutor(handler, closure);
}
}
};
runWithHandlerOrExecutor(handler, runCallbacks);
}
if (this == Session.activeSession) {
if (oldState.isOpened() != newState.isOpened()) {
if (newState.isOpened()) {
postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED);
} else {
postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
}
}
}
}
static void postActiveSessionAction(String action) {
final Intent intent = new Intent(action);
LocalBroadcastManager.getInstance(getStaticContext()).sendBroadcast(intent);
}
private static void runWithHandlerOrExecutor(Handler handler, Runnable runnable) {
if (handler != null) {
handler.post(runnable);
} else {
Settings.getExecutor().execute(runnable);
}
}
void extendAccessTokenIfNeeded() {
if (shouldExtendAccessToken()) {
extendAccessToken();
}
}
void extendAccessToken() {
TokenRefreshRequest newTokenRefreshRequest = null;
synchronized (this.lock) {
if (currentTokenRefreshRequest == null) {
newTokenRefreshRequest = new TokenRefreshRequest();
currentTokenRefreshRequest = newTokenRefreshRequest;
}
}
if (newTokenRefreshRequest != null) {
newTokenRefreshRequest.bind();
}
}
boolean shouldExtendAccessToken() {
if (currentTokenRefreshRequest != null) {
return false;
}
boolean result = false;
Date now = new Date();
if (state.isOpened() && tokenInfo.getSource().canExtendToken()
&& now.getTime() - lastAttemptedTokenExtendDate.getTime() > TOKEN_EXTEND_RETRY_SECONDS * 1000
&& now.getTime() - tokenInfo.getLastRefresh().getTime() > TOKEN_EXTEND_THRESHOLD_SECONDS * 1000) {
result = true;
}
return result;
}
AccessToken getTokenInfo() {
return tokenInfo;
}
void setTokenInfo(AccessToken tokenInfo) {
this.tokenInfo = tokenInfo;
}
Date getLastAttemptedTokenExtendDate() {
return lastAttemptedTokenExtendDate;
}
void setLastAttemptedTokenExtendDate(Date lastAttemptedTokenExtendDate) {
this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate;
}
void setCurrentTokenRefreshRequest(TokenRefreshRequest request) {
this.currentTokenRefreshRequest = request;
}
class TokenRefreshRequest implements ServiceConnection {
final Messenger messageReceiver = new Messenger(
new TokenRefreshRequestHandler(Session.this, this));
Messenger messageSender = null;
public void bind() {
Intent intent = NativeProtocol.createTokenRefreshIntent(getStaticContext());
if (intent != null
&& staticContext.bindService(intent, new TokenRefreshRequest(), Context.BIND_AUTO_CREATE)) {
setLastAttemptedTokenExtendDate(new Date());
} else {
cleanup();
}
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
messageSender = new Messenger(service);
refreshToken();
}
@Override
public void onServiceDisconnected(ComponentName arg) {
cleanup();
// We returned an error so there's no point in
// keeping the binding open.
staticContext.unbindService(TokenRefreshRequest.this);
}
private void cleanup() {
if (currentTokenRefreshRequest == this) {
currentTokenRefreshRequest = null;
}
}
private void refreshToken() {
Bundle requestData = new Bundle();
requestData.putString(AccessToken.ACCESS_TOKEN_KEY, getTokenInfo().getToken());
Message request = Message.obtain();
request.setData(requestData);
request.replyTo = messageReceiver;
try {
messageSender.send(request);
} catch (RemoteException e) {
cleanup();
}
}
}
// Creating a static Handler class to reduce the possibility of a memory leak.
// Handler objects for the same thread all share a common Looper object, which they post messages
// to and read from. As messages contain target Handler, as long as there are messages with target
// handler in the message queue, the handler cannot be garbage collected. If handler is not static,
// the instance of the containing class also cannot be garbage collected even if it is destroyed.
static class TokenRefreshRequestHandler extends Handler {
private WeakReference<Session> sessionWeakReference;
private WeakReference<TokenRefreshRequest> refreshRequestWeakReference;
TokenRefreshRequestHandler(Session session, TokenRefreshRequest refreshRequest) {
super(Looper.getMainLooper());
sessionWeakReference = new WeakReference<Session>(session);
refreshRequestWeakReference = new WeakReference<TokenRefreshRequest>(refreshRequest);
}
@Override
public void handleMessage(Message msg) {
String token = msg.getData().getString(AccessToken.ACCESS_TOKEN_KEY);
Session session = sessionWeakReference.get();
if (session != null && token != null) {
session.extendTokenCompleted(msg.getData());
}
TokenRefreshRequest request = refreshRequestWeakReference.get();
if (request != null) {
// The refreshToken function should be called rarely,
// so there is no point in keeping the binding open.
staticContext.unbindService(request);
request.cleanup();
}
}
}
/**
* Provides asynchronous notification of Session state changes.
*
* @see Session#open open
*/
public interface StatusCallback {
public void call(Session session, SessionState state, Exception exception);
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object otherObj) {
if (!(otherObj instanceof Session)) {
return false;
}
Session other = (Session) otherObj;
return areEqual(other.applicationId, applicationId) &&
areEqual(other.authorizationBundle, authorizationBundle) &&
areEqual(other.state, state) &&
areEqual(other.getExpirationDate(), getExpirationDate());
}
private static boolean areEqual(Object a, Object b) {
if (a == null) {
return b == null;
} else {
return a.equals(b);
}
}
/**
* Builder class used to create a Session.
*/
public static final class Builder {
private final Context context;
private String applicationId;
private TokenCachingStrategy tokenCachingStrategy;
/**
* Constructs a new Builder associated with the context.
*
* @param context the Activity or Service starting the Session
*/
public Builder(Context context) {
this.context = context;
}
/**
* Sets the application id for the Session.
*
* @param applicationId the application id
* @return the Builder instance
*/
public Builder setApplicationId(final String applicationId) {
this.applicationId = applicationId;
return this;
}
/**
* Sets the TokenCachingStrategy for the Session.
*
* @param tokenCachingStrategy the token cache to use
* @return the Builder instance
*/
public Builder setTokenCachingStrategy(final TokenCachingStrategy tokenCachingStrategy) {
this.tokenCachingStrategy = tokenCachingStrategy;
return this;
}
/**
* Build the Session.
*
* @return a new Session
*/
public Session build() {
return new Session(context, applicationId, tokenCachingStrategy);
}
}
interface StartActivityDelegate {
public void startActivityForResult(Intent intent, int requestCode);
public Activity getActivityContext();
}
private void autoPublishAsync() {
AutoPublishAsyncTask asyncTask = null;
synchronized (this) {
if (autoPublishAsyncTask == null && Settings.getShouldAutoPublishInstall()) {
// copy the application id to guarantee thread safety against our container.
String applicationId = Session.this.applicationId;
// skip publish if we don't have an application id.
if (applicationId != null) {
asyncTask = autoPublishAsyncTask = new AutoPublishAsyncTask(applicationId, staticContext);
}
}
}
if (asyncTask != null) {
asyncTask.execute();
}
}
/**
* Async implementation to allow auto publishing to not block the ui thread.
*/
private class AutoPublishAsyncTask extends AsyncTask<Void, Void, Void> {
private final String mApplicationId;
private final Context mApplicationContext;
public AutoPublishAsyncTask(String applicationId, Context context) {
mApplicationId = applicationId;
mApplicationContext = context.getApplicationContext();
}
@Override
protected Void doInBackground(Void... voids) {
try {
Settings.publishInstallAndWait(mApplicationContext, mApplicationId);
} catch (Exception e) {
Utility.logd("Facebook-publish", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// always clear out the publisher to allow other invocations.
synchronized (Session.this) {
autoPublishAsyncTask = null;
}
}
}
/**
* Base class for authorization requests {@link OpenRequest} and {@link NewPermissionsRequest}.
*/
public static class AuthorizationRequest implements Serializable {
private static final long serialVersionUID = 1L;
private final StartActivityDelegate startActivityDelegate;
private SessionLoginBehavior loginBehavior = SessionLoginBehavior.SSO_WITH_FALLBACK;
private int requestCode = DEFAULT_AUTHORIZE_ACTIVITY_CODE;
private StatusCallback statusCallback;
private boolean isLegacy = false;
private List<String> permissions = Collections.emptyList();
private SessionDefaultAudience defaultAudience = SessionDefaultAudience.FRIENDS;
private String applicationId;
private String validateSameFbidAsToken;
AuthorizationRequest(final Activity activity) {
startActivityDelegate = new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
activity.startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return activity;
}
};
}
AuthorizationRequest(final Fragment fragment) {
startActivityDelegate = new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
fragment.startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return fragment.getActivity();
}
};
}
/**
* Constructor to be used for V1 serialization only, DO NOT CHANGE.
*/
private AuthorizationRequest(SessionLoginBehavior loginBehavior, int requestCode,
List<String> permissions, String defaultAudience, boolean isLegacy, String applicationId,
String validateSameFbidAsToken) {
startActivityDelegate = new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
throw new UnsupportedOperationException(
"Cannot create an AuthorizationRequest without a valid Activity or Fragment");
}
@Override
public Activity getActivityContext() {
throw new UnsupportedOperationException(
"Cannot create an AuthorizationRequest without a valid Activity or Fragment");
}
};
this.loginBehavior = loginBehavior;
this.requestCode = requestCode;
this.permissions = permissions;
this.defaultAudience = SessionDefaultAudience.valueOf(defaultAudience);
this.isLegacy = isLegacy;
this.applicationId = applicationId;
this.validateSameFbidAsToken = validateSameFbidAsToken;
}
/**
* Used for backwards compatibility with Facebook.java only, DO NOT USE.
*
* @param isLegacy
*/
public void setIsLegacy(boolean isLegacy) {
this.isLegacy = isLegacy;
}
boolean isLegacy() {
return isLegacy;
}
AuthorizationRequest setCallback(StatusCallback statusCallback) {
this.statusCallback = statusCallback;
return this;
}
StatusCallback getCallback() {
return statusCallback;
}
AuthorizationRequest setLoginBehavior(SessionLoginBehavior loginBehavior) {
if (loginBehavior != null) {
this.loginBehavior = loginBehavior;
}
return this;
}
SessionLoginBehavior getLoginBehavior() {
return loginBehavior;
}
AuthorizationRequest setRequestCode(int requestCode) {
if (requestCode >= 0) {
this.requestCode = requestCode;
}
return this;
}
int getRequestCode() {
return requestCode;
}
AuthorizationRequest setPermissions(List<String> permissions) {
if (permissions != null) {
this.permissions = permissions;
}
return this;
}
List<String> getPermissions() {
return permissions;
}
AuthorizationRequest setDefaultAudience(SessionDefaultAudience defaultAudience) {
if (defaultAudience != null) {
this.defaultAudience = defaultAudience;
}
return this;
}
SessionDefaultAudience getDefaultAudience() {
return defaultAudience;
}
StartActivityDelegate getStartActivityDelegate() {
return startActivityDelegate;
}
String getApplicationId() {
return applicationId;
}
void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
String getValidateSameFbidAsToken() {
return validateSameFbidAsToken;
}
void setValidateSameFbidAsToken(String validateSameFbidAsToken) {
this.validateSameFbidAsToken = validateSameFbidAsToken;
}
AuthorizationClient.AuthorizationRequest getAuthorizationClientRequest() {
AuthorizationClient.StartActivityDelegate delegate = new AuthorizationClient.StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
startActivityDelegate.startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return startActivityDelegate.getActivityContext();
}
};
return new AuthorizationClient.AuthorizationRequest(loginBehavior, requestCode, isLegacy,
permissions, defaultAudience, applicationId, validateSameFbidAsToken, delegate);
}
// package private so subclasses can use it
Object writeReplace() {
return new AuthRequestSerializationProxyV1(
loginBehavior, requestCode, permissions, defaultAudience.name(), isLegacy, applicationId, validateSameFbidAsToken);
}
// have a readObject that throws to prevent spoofing
// package private so subclasses can use it
void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Cannot readObject, serialization proxy required");
}
private static class AuthRequestSerializationProxyV1 implements Serializable {
private static final long serialVersionUID = -8748347685113614927L;
private final SessionLoginBehavior loginBehavior;
private final int requestCode;
private boolean isLegacy;
private final List<String> permissions;
private final String defaultAudience;
private final String applicationId;
private final String validateSameFbidAsToken;
private AuthRequestSerializationProxyV1(SessionLoginBehavior loginBehavior,
int requestCode, List<String> permissions, String defaultAudience, boolean isLegacy,
String applicationId, String validateSameFbidAsToken) {
this.loginBehavior = loginBehavior;
this.requestCode = requestCode;
this.permissions = permissions;
this.defaultAudience = defaultAudience;
this.isLegacy = isLegacy;
this.applicationId = applicationId;
this.validateSameFbidAsToken = validateSameFbidAsToken;
}
private Object readResolve() {
return new AuthorizationRequest(loginBehavior, requestCode, permissions, defaultAudience, isLegacy,
applicationId, validateSameFbidAsToken);
}
}
}
/**
* A request used to open a Session.
*/
public static final class OpenRequest extends AuthorizationRequest {
private static final long serialVersionUID = 1L;
/**
* Constructs an OpenRequest.
*
* @param activity the Activity to use to open the Session
*/
public OpenRequest(Activity activity) {
super(activity);
}
/**
* Constructs an OpenRequest.
*
* @param fragment the Fragment to use to open the Session
*/
public OpenRequest(Fragment fragment) {
super(fragment);
}
/**
* Sets the StatusCallback for the OpenRequest.
*
* @param statusCallback The {@link StatusCallback SessionStatusCallback} to
* notify regarding Session state changes.
* @return the OpenRequest object to allow for chaining
*/
public final OpenRequest setCallback(StatusCallback statusCallback) {
super.setCallback(statusCallback);
return this;
}
/**
* Sets the login behavior for the OpenRequest.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
* @return the OpenRequest object to allow for chaining
*/
public final OpenRequest setLoginBehavior(SessionLoginBehavior loginBehavior) {
super.setLoginBehavior(loginBehavior);
return this;
}
/**
* Sets the request code for the OpenRequest.
*
* @param requestCode An integer that identifies this request. This integer will be used
* as the request code in {@link Activity#onActivityResult
* onActivityResult}. This integer should be >= 0. If a value < 0 is
* passed in, then a default value will be used.
* @return the OpenRequest object to allow for chaining
*/
public final OpenRequest setRequestCode(int requestCode) {
super.setRequestCode(requestCode);
return this;
}
/**
* Sets the permissions for the OpenRequest.
*
* @param permissions A List<String> representing the permissions to request
* during the authentication flow. A null or empty List
* represents basic permissions.
* @return the OpenRequest object to allow for chaining
*/
public final OpenRequest setPermissions(List<String> permissions) {
super.setPermissions(permissions);
return this;
}
/**
* Sets the defaultAudience for the OpenRequest.
* <p/>
* This is only used during Native login using a sufficiently recent facebook app.
*
* @param defaultAudience A SessionDefaultAudience representing the default audience setting to request.
* @return the OpenRequest object to allow for chaining
*/
public final OpenRequest setDefaultAudience(SessionDefaultAudience defaultAudience) {
super.setDefaultAudience(defaultAudience);
return this;
}
}
/**
* A request to be used to request new permissions for a Session.
*/
public static final class NewPermissionsRequest extends AuthorizationRequest {
private static final long serialVersionUID = 1L;
/**
* Constructs a NewPermissionsRequest.
*
* @param activity the Activity used to issue the request
* @param permissions additional permissions to request
*/
public NewPermissionsRequest(Activity activity, List<String> permissions) {
super(activity);
setPermissions(permissions);
}
/**
* Constructs a NewPermissionsRequest.
*
* @param fragment the Fragment used to issue the request
* @param permissions additional permissions to request
*/
public NewPermissionsRequest(Fragment fragment, List<String> permissions) {
super(fragment);
setPermissions(permissions);
}
/**
* Sets the StatusCallback for the NewPermissionsRequest.
*
* @param statusCallback The {@link StatusCallback SessionStatusCallback} to
* notify regarding Session state changes.
* @return the NewPermissionsRequest object to allow for chaining
*/
public final NewPermissionsRequest setCallback(StatusCallback statusCallback) {
super.setCallback(statusCallback);
return this;
}
/**
* Sets the login behavior for the NewPermissionsRequest.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
* @return the NewPermissionsRequest object to allow for chaining
*/
public final NewPermissionsRequest setLoginBehavior(SessionLoginBehavior loginBehavior) {
super.setLoginBehavior(loginBehavior);
return this;
}
/**
* Sets the request code for the NewPermissionsRequest.
*
* @param requestCode An integer that identifies this request. This integer will be used
* as the request code in {@link Activity#onActivityResult
* onActivityResult}. This integer should be >= 0. If a value < 0 is
* passed in, then a default value will be used.
* @return the NewPermissionsRequest object to allow for chaining
*/
public final NewPermissionsRequest setRequestCode(int requestCode) {
super.setRequestCode(requestCode);
return this;
}
/**
* Sets the defaultAudience for the OpenRequest.
*
* @param defaultAudience A SessionDefaultAudience representing the default audience setting to request.
* @return the NewPermissionsRequest object to allow for chaining
*/
public final NewPermissionsRequest setDefaultAudience(SessionDefaultAudience defaultAudience) {
super.setDefaultAudience(defaultAudience);
return this;
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* An Exception indicating that an operation was canceled before it completed.
*/
public class FacebookOperationCanceledException extends FacebookException {
static final long serialVersionUID = 1;
/**
* Constructs a FacebookOperationCanceledException with no additional information.
*/
public FacebookOperationCanceledException() {
super();
}
/**
* Constructs a FacebookOperationCanceledException with a message.
*
* @param message A String to be returned from getMessage.
*/
public FacebookOperationCanceledException(String message) {
super(message);
}
/**
* Constructs a FacebookOperationCanceledException with a message and inner error.
*
* @param message A String to be returned from getMessage.
* @param throwable A Throwable to be returned from getCause.
*/
public FacebookOperationCanceledException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a FacebookOperationCanceledException with an inner error.
*
* @param throwable A Throwable to be returned from getCause.
*/
public FacebookOperationCanceledException(Throwable throwable) {
super(throwable);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* <p>
* Identifies the state of a Session.
* </p>
* <p>
* Session objects implement a state machine that controls their lifecycle. This
* enum represents the states of the state machine.
* </p>
*/
public enum SessionState {
/**
* Indicates that the Session has not yet been opened and has no cached
* token. Opening a Session in this state will involve user interaction.
*/
CREATED(Category.CREATED_CATEGORY),
/**
* <p>
* Indicates that the Session has not yet been opened and has a cached
* token. Opening a Session in this state will not involve user interaction.
* </p>
* <p>
* If you are using Session from an Android Service, you must provide a
* TokenCachingStrategy implementation that contains a valid token to the Session
* constructor. The resulting Session will be created in this state, and you
* can then safely call open, passing null for the Activity.
* </p>
*/
CREATED_TOKEN_LOADED(Category.CREATED_CATEGORY),
/**
* Indicates that the Session is in the process of opening.
*/
OPENING(Category.CREATED_CATEGORY),
/**
* Indicates that the Session is opened. In this state, the Session may be
* used with a {@link Request}.
*/
OPENED(Category.OPENED_CATEGORY),
/**
* <p>
* Indicates that the Session is opened and that the token has changed. In
* this state, the Session may be used with {@link Request}.
* </p>
* <p>
* Every time the token is updated, {@link Session.StatusCallback
* StatusCallback} is called with this value.
* </p>
*/
OPENED_TOKEN_UPDATED(Category.OPENED_CATEGORY),
/**
* Indicates that the Session is closed, and that it was not closed
* normally. Typically this means that the open call failed, and the
* Exception parameter to {@link Session.StatusCallback StatusCallback} will
* be non-null.
*/
CLOSED_LOGIN_FAILED(Category.CLOSED_CATEGORY),
/**
* Indicates that the Session was closed normally.
*/
CLOSED(Category.CLOSED_CATEGORY);
private final Category category;
SessionState(Category category) {
this.category = category;
}
/**
* Returns a boolean indicating whether the state represents a successfully
* opened state in which the Session can be used with a {@link Request}.
*
* @return a boolean indicating whether the state represents a successfully
* opened state in which the Session can be used with a
* {@link Request}.
*/
public boolean isOpened() {
return this.category == Category.OPENED_CATEGORY;
}
/**
* Returns a boolean indicating whether the state represents a closed
* Session that can no longer be used with a {@link Request}.
*
* @return a boolean indicating whether the state represents a closed
* Session that can no longer be used with a {@link Request}.
*/
public boolean isClosed() {
return this.category == Category.CLOSED_CATEGORY;
}
private enum Category {
CREATED_CATEGORY, OPENED_CATEGORY, CLOSED_CATEGORY
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.CookieSyncManager;
import com.facebook.android.R;
import com.facebook.internal.ServerProtocol;
import com.facebook.internal.Utility;
import com.facebook.model.GraphMultiResult;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class AuthorizationClient implements Serializable {
private static final long serialVersionUID = 1L;
private static final String TAG = "Facebook-AuthorizationClient";
private static final String WEB_VIEW_AUTH_HANDLER_STORE =
"com.facebook.AuthorizationClient.WebViewAuthHandler.TOKEN_STORE_KEY";
private static final String WEB_VIEW_AUTH_HANDLER_TOKEN_KEY = "TOKEN";
List<AuthHandler> handlersToTry;
AuthHandler currentHandler;
transient Context context;
transient StartActivityDelegate startActivityDelegate;
transient OnCompletedListener onCompletedListener;
transient BackgroundProcessingListener backgroundProcessingListener;
transient boolean checkedInternetPermission;
AuthorizationRequest pendingRequest;
interface OnCompletedListener {
void onCompleted(Result result);
}
interface BackgroundProcessingListener {
void onBackgroundProcessingStarted();
void onBackgroundProcessingStopped();
}
interface StartActivityDelegate {
public void startActivityForResult(Intent intent, int requestCode);
public Activity getActivityContext();
}
void setContext(final Context context) {
this.context = context;
// We rely on individual requests to tell us how to start an activity.
startActivityDelegate = null;
}
void setContext(final Activity activity) {
this.context = activity;
// If we are used in the context of an activity, we will always use that activity to
// call startActivityForResult.
startActivityDelegate = new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
activity.startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return activity;
}
};
}
void startOrContinueAuth(AuthorizationRequest request) {
if (getInProgress()) {
continueAuth();
} else {
authorize(request);
}
}
void authorize(AuthorizationRequest request) {
if (request == null) {
return;
}
if (pendingRequest != null) {
throw new FacebookException("Attempted to authorize while a request is pending.");
}
if (request.needsNewTokenValidation() && !checkInternetPermission()) {
// We're going to need INTERNET permission later and don't have it, so fail early.
return;
}
pendingRequest = request;
handlersToTry = getHandlerTypes(request);
tryNextHandler();
}
void continueAuth() {
if (pendingRequest == null || currentHandler == null) {
throw new FacebookException("Attempted to continue authorization without a pending request.");
}
if (currentHandler.needsRestart()) {
currentHandler.cancel();
tryCurrentHandler();
}
}
boolean getInProgress() {
return pendingRequest != null && currentHandler != null;
}
void cancelCurrentHandler() {
if (currentHandler != null) {
currentHandler.cancel();
}
}
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == pendingRequest.getRequestCode()) {
return currentHandler.onActivityResult(requestCode, resultCode, data);
}
return false;
}
private List<AuthHandler> getHandlerTypes(AuthorizationRequest request) {
ArrayList<AuthHandler> handlers = new ArrayList<AuthHandler>();
final SessionLoginBehavior behavior = request.getLoginBehavior();
if (behavior.allowsKatanaAuth()) {
if (!request.isLegacy()) {
handlers.add(new GetTokenAuthHandler());
handlers.add(new KatanaLoginDialogAuthHandler());
}
handlers.add(new KatanaProxyAuthHandler());
}
if (behavior.allowsWebViewAuth()) {
handlers.add(new WebViewAuthHandler());
}
return handlers;
}
boolean checkInternetPermission() {
if (checkedInternetPermission) {
return true;
}
int permissionCheck = checkPermission(Manifest.permission.INTERNET);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
String errorType = context.getString(R.string.com_facebook_internet_permission_error_title);
String errorDescription = context.getString(R.string.com_facebook_internet_permission_error_message);
complete(Result.createErrorResult(errorType, errorDescription));
return false;
}
checkedInternetPermission = true;
return true;
}
void tryNextHandler() {
while (handlersToTry != null && !handlersToTry.isEmpty()) {
currentHandler = handlersToTry.remove(0);
boolean started = tryCurrentHandler();
if (started) {
return;
}
}
if (pendingRequest != null) {
// We went through all handlers without successfully attempting an auth.
completeWithFailure();
}
}
private void completeWithFailure() {
complete(Result.createErrorResult("Login attempt failed.", null));
}
boolean tryCurrentHandler() {
if (currentHandler.needsInternetPermission() && !checkInternetPermission()) {
return false;
}
return currentHandler.tryAuthorize(pendingRequest);
}
void completeAndValidate(Result outcome) {
// Do we need to validate a successful result (as in the case of a reauth)?
if (outcome.token != null && pendingRequest.needsNewTokenValidation()) {
validateSameFbidAndFinish(outcome);
} else {
// We're done, just notify the listener.
complete(outcome);
}
}
void complete(Result outcome) {
handlersToTry = null;
currentHandler = null;
pendingRequest = null;
notifyOnCompleteListener(outcome);
}
OnCompletedListener getOnCompletedListener() {
return onCompletedListener;
}
void setOnCompletedListener(OnCompletedListener onCompletedListener) {
this.onCompletedListener = onCompletedListener;
}
BackgroundProcessingListener getBackgroundProcessingListener() {
return backgroundProcessingListener;
}
void setBackgroundProcessingListener(BackgroundProcessingListener backgroundProcessingListener) {
this.backgroundProcessingListener = backgroundProcessingListener;
}
StartActivityDelegate getStartActivityDelegate() {
if (startActivityDelegate != null) {
return startActivityDelegate;
} else if (pendingRequest != null) {
// Wrap the request's delegate in our own.
return new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
pendingRequest.getStartActivityDelegate().startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return pendingRequest.getStartActivityDelegate().getActivityContext();
}
};
}
return null;
}
int checkPermission(String permission) {
return context.checkCallingOrSelfPermission(permission);
}
void validateSameFbidAndFinish(Result pendingResult) {
if (pendingResult.token == null) {
throw new FacebookException("Can't validate without a token");
}
RequestBatch batch = createReauthValidationBatch(pendingResult);
notifyBackgroundProcessingStart();
batch.executeAsync();
}
RequestBatch createReauthValidationBatch(final Result pendingResult) {
// We need to ensure that the token we got represents the same fbid as the old one. We issue
// a "me" request using the current token, a "me" request using the new token, and a "me/permissions"
// request using the current token to get the permissions of the user.
final ArrayList<String> fbids = new ArrayList<String>();
final ArrayList<String> tokenPermissions = new ArrayList<String>();
final String newToken = pendingResult.token.getToken();
Request.Callback meCallback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphUser user = response.getGraphObjectAs(GraphUser.class);
if (user != null) {
fbids.add(user.getId());
}
} catch (Exception ex) {
}
}
};
String validateSameFbidAsToken = pendingRequest.getPreviousAccessToken();
Request requestCurrentTokenMe = createGetProfileIdRequest(validateSameFbidAsToken);
requestCurrentTokenMe.setCallback(meCallback);
Request requestNewTokenMe = createGetProfileIdRequest(newToken);
requestNewTokenMe.setCallback(meCallback);
Request requestCurrentTokenPermissions = createGetPermissionsRequest(validateSameFbidAsToken);
requestCurrentTokenPermissions.setCallback(new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class);
if (result != null) {
GraphObjectList<GraphObject> data = result.getData();
if (data != null && data.size() == 1) {
GraphObject permissions = data.get(0);
// The keys are the permission names.
tokenPermissions.addAll(permissions.asMap().keySet());
}
}
} catch (Exception ex) {
}
}
});
RequestBatch batch = new RequestBatch(requestCurrentTokenMe, requestNewTokenMe,
requestCurrentTokenPermissions);
batch.setBatchApplicationId(pendingRequest.getApplicationId());
batch.addCallback(new RequestBatch.Callback() {
@Override
public void onBatchCompleted(RequestBatch batch) {
try {
Result result = null;
if (fbids.size() == 2 && fbids.get(0) != null && fbids.get(1) != null &&
fbids.get(0).equals(fbids.get(1))) {
// Modify the token to have the right permission set.
AccessToken tokenWithPermissions = AccessToken
.createFromTokenWithRefreshedPermissions(pendingResult.token,
tokenPermissions);
result = Result.createTokenResult(tokenWithPermissions);
} else {
result = Result
.createErrorResult("User logged in as different Facebook user.", null);
}
complete(result);
} catch (Exception ex) {
complete(Result.createErrorResult("Caught exception", ex.getMessage()));
} finally {
notifyBackgroundProcessingStop();
}
}
});
return batch;
}
Request createGetPermissionsRequest(String accessToken) {
Bundle parameters = new Bundle();
parameters.putString("fields", "id");
parameters.putString("access_token", accessToken);
return new Request(null, "me/permissions", parameters, HttpMethod.GET, null);
}
Request createGetProfileIdRequest(String accessToken) {
Bundle parameters = new Bundle();
parameters.putString("fields", "id");
parameters.putString("access_token", accessToken);
return new Request(null, "me", parameters, HttpMethod.GET, null);
}
private void notifyOnCompleteListener(Result outcome) {
if (onCompletedListener != null) {
onCompletedListener.onCompleted(outcome);
}
}
private void notifyBackgroundProcessingStart() {
if (backgroundProcessingListener != null) {
backgroundProcessingListener.onBackgroundProcessingStarted();
}
}
private void notifyBackgroundProcessingStop() {
if (backgroundProcessingListener != null) {
backgroundProcessingListener.onBackgroundProcessingStopped();
}
}
abstract class AuthHandler implements Serializable {
private static final long serialVersionUID = 1L;
abstract boolean tryAuthorize(AuthorizationRequest request);
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
return false;
}
boolean needsRestart() {
return false;
}
boolean needsInternetPermission() {
return false;
}
void cancel() {
}
}
class WebViewAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
private transient WebDialog loginDialog;
@Override
boolean needsRestart() {
// Because we are presenting WebView UI within the current context, we need to explicitly
// restart the process if the context goes away and is recreated.
return true;
}
@Override
boolean needsInternetPermission() {
return true;
}
@Override
void cancel() {
if (loginDialog != null) {
loginDialog.dismiss();
loginDialog = null;
}
}
@Override
boolean tryAuthorize(final AuthorizationRequest request) {
String applicationId = request.getApplicationId();
Bundle parameters = new Bundle();
if (!Utility.isNullOrEmpty(request.getPermissions())) {
parameters.putString(ServerProtocol.DIALOG_PARAM_SCOPE, TextUtils.join(",", request.getPermissions()));
}
String previousToken = request.getPreviousAccessToken();
if (!Utility.isNullOrEmpty(previousToken) && (previousToken.equals(loadCookieToken()))) {
parameters.putString(ServerProtocol.DIALOG_PARAM_ACCESS_TOKEN, previousToken);
} else {
// The call to clear cookies will create the first instance of CookieSyncManager if necessary
Utility.clearFacebookCookies(context);
}
WebDialog.OnCompleteListener listener = new WebDialog.OnCompleteListener() {
@Override
public void onComplete(Bundle values, FacebookException error) {
onWebDialogComplete(request, values, error);
}
};
WebDialog.Builder builder =
new AuthDialogBuilder(getStartActivityDelegate().getActivityContext(), applicationId, parameters)
.setOnCompleteListener(listener);
loginDialog = builder.build();
loginDialog.show();
return true;
}
void onWebDialogComplete(AuthorizationRequest request, Bundle values,
FacebookException error) {
Result outcome;
if (values != null) {
AccessToken token = AccessToken
.createFromWebBundle(request.getPermissions(), values, AccessTokenSource.WEB_VIEW);
outcome = Result.createTokenResult(token);
// Ensure any cookies set by the dialog are saved
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
saveCookieToken(token.getToken());
} else {
if (error instanceof FacebookOperationCanceledException) {
outcome = Result.createCancelResult("User canceled log in.");
} else {
outcome = Result.createErrorResult(error.getMessage(), null);
}
}
completeAndValidate(outcome);
}
private void saveCookieToken(String token) {
Context context = getStartActivityDelegate().getActivityContext();
SharedPreferences sharedPreferences = context.getSharedPreferences(
WEB_VIEW_AUTH_HANDLER_STORE,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, token);
if (!editor.commit()) {
Utility.logd(TAG, "Could not update saved web view auth handler token.");
}
}
private String loadCookieToken() {
Context context = getStartActivityDelegate().getActivityContext();
SharedPreferences sharedPreferences = context.getSharedPreferences(
WEB_VIEW_AUTH_HANDLER_STORE,
Context.MODE_PRIVATE);
return sharedPreferences.getString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, "");
}
}
class GetTokenAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
private transient GetTokenClient getTokenClient;
@Override
void cancel() {
if (getTokenClient != null) {
getTokenClient.cancel();
getTokenClient = null;
}
}
boolean tryAuthorize(final AuthorizationRequest request) {
getTokenClient = new GetTokenClient(context, request.getApplicationId());
if (!getTokenClient.start()) {
return false;
}
notifyBackgroundProcessingStart();
GetTokenClient.CompletedListener callback = new GetTokenClient.CompletedListener() {
@Override
public void completed(Bundle result) {
getTokenCompleted(request, result);
}
};
getTokenClient.setCompletedListener(callback);
return true;
}
void getTokenCompleted(AuthorizationRequest request, Bundle result) {
getTokenClient = null;
notifyBackgroundProcessingStop();
if (result != null) {
ArrayList<String> currentPermissions = result.getStringArrayList(NativeProtocol.EXTRA_PERMISSIONS);
List<String> permissions = request.getPermissions();
if ((currentPermissions != null) &&
((permissions == null) || currentPermissions.containsAll(permissions))) {
// We got all the permissions we needed, so we can complete the auth now.
AccessToken token = AccessToken
.createFromNativeLogin(result, AccessTokenSource.FACEBOOK_APPLICATION_SERVICE);
Result outcome = Result.createTokenResult(token);
completeAndValidate(outcome);
return;
}
// We didn't get all the permissions we wanted, so update the request with just the permissions
// we still need.
ArrayList<String> newPermissions = new ArrayList<String>();
for (String permission : permissions) {
if (!currentPermissions.contains(permission)) {
newPermissions.add(permission);
}
}
request.setPermissions(newPermissions);
}
tryNextHandler();
}
}
abstract class KatanaAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
protected boolean tryIntent(Intent intent, int requestCode) {
if (intent == null) {
return false;
}
try {
getStartActivityDelegate().startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
return false;
}
return true;
}
}
class KatanaLoginDialogAuthHandler extends KatanaAuthHandler {
private static final long serialVersionUID = 1L;
@Override
boolean tryAuthorize(AuthorizationRequest request) {
Intent intent = NativeProtocol.createLoginDialog20121101Intent(context, request.getApplicationId(),
new ArrayList<String>(request.getPermissions()),
request.getDefaultAudience().getNativeProtocolAudience());
return tryIntent(intent, request.getRequestCode());
}
@Override
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
Result outcome;
if (data == null) {
// This happens if the user presses 'Back'.
outcome = Result.createCancelResult("Operation canceled");
} else if (NativeProtocol.isServiceDisabledResult20121101(data)) {
outcome = null;
} else if (resultCode == Activity.RESULT_CANCELED) {
outcome = Result.createCancelResult(
data.getStringExtra(NativeProtocol.STATUS_ERROR_DESCRIPTION));
} else if (resultCode != Activity.RESULT_OK) {
outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null);
} else {
outcome = handleResultOk(data);
}
if (outcome != null) {
completeAndValidate(outcome);
} else {
tryNextHandler();
}
return true;
}
private Result handleResultOk(Intent data) {
Bundle extras = data.getExtras();
String errorType = extras.getString(NativeProtocol.STATUS_ERROR_TYPE);
if (errorType == null) {
return Result.createTokenResult(
AccessToken.createFromNativeLogin(extras, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE));
} else if (NativeProtocol.ERROR_SERVICE_DISABLED.equals(errorType)) {
return null;
} else if (NativeProtocol.ERROR_USER_CANCELED.equals(errorType)) {
return Result.createCancelResult(null);
} else {
return Result.createErrorResult(errorType, extras.getString("error_description"));
}
}
}
class KatanaProxyAuthHandler extends KatanaAuthHandler {
private static final long serialVersionUID = 1L;
@Override
boolean tryAuthorize(AuthorizationRequest request) {
Intent intent = NativeProtocol.createProxyAuthIntent(context,
request.getApplicationId(), request.getPermissions());
return tryIntent(intent, request.getRequestCode());
}
@Override
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
// Handle stuff
Result outcome;
if (data == null) {
// This happens if the user presses 'Back'.
outcome = Result.createCancelResult("Operation canceled");
} else if (resultCode == Activity.RESULT_CANCELED) {
outcome = Result.createCancelResult(data.getStringExtra("error"));
} else if (resultCode != Activity.RESULT_OK) {
outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null);
} else {
outcome = handleResultOk(data);
}
if (outcome != null) {
completeAndValidate(outcome);
} else {
tryNextHandler();
}
return true;
}
private Result handleResultOk(Intent data) {
Bundle extras = data.getExtras();
String error = extras.getString("error");
if (error == null) {
error = extras.getString("error_type");
}
if (error == null) {
AccessToken token = AccessToken.createFromWebBundle(pendingRequest.getPermissions(), extras,
AccessTokenSource.FACEBOOK_APPLICATION_WEB);
return Result.createTokenResult(token);
} else if (ServerProtocol.errorsProxyAuthDisabled.contains(error)) {
return null;
} else if (ServerProtocol.errorsUserCanceled.contains(error)) {
return Result.createCancelResult(null);
} else {
return Result.createErrorResult(error, extras.getString("error_description"));
}
}
}
static class AuthDialogBuilder extends WebDialog.Builder {
private static final String OAUTH_DIALOG = "oauth";
static final String REDIRECT_URI = "fbconnect://success";
public AuthDialogBuilder(Context context, String applicationId, Bundle parameters) {
super(context, applicationId, OAUTH_DIALOG, parameters);
}
@Override
public WebDialog build() {
Bundle parameters = getParameters();
parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI);
parameters.putString(ServerProtocol.DIALOG_PARAM_CLIENT_ID, getApplicationId());
return new WebDialog(getContext(), OAUTH_DIALOG, parameters, getTheme(), getListener());
}
}
static class AuthorizationRequest implements Serializable {
private static final long serialVersionUID = 1L;
private transient final StartActivityDelegate startActivityDelegate;
private SessionLoginBehavior loginBehavior;
private int requestCode;
private boolean isLegacy = false;
private List<String> permissions;
private SessionDefaultAudience defaultAudience;
private String applicationId;
private String previousAccessToken;
AuthorizationRequest(SessionLoginBehavior loginBehavior, int requestCode, boolean isLegacy,
List<String> permissions, SessionDefaultAudience defaultAudience, String applicationId,
String validateSameFbidAsToken, StartActivityDelegate startActivityDelegate) {
this.loginBehavior = loginBehavior;
this.requestCode = requestCode;
this.isLegacy = isLegacy;
this.permissions = permissions;
this.defaultAudience = defaultAudience;
this.applicationId = applicationId;
this.previousAccessToken = validateSameFbidAsToken;
this.startActivityDelegate = startActivityDelegate;
}
StartActivityDelegate getStartActivityDelegate() {
return startActivityDelegate;
}
List<String> getPermissions() {
return permissions;
}
void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
SessionLoginBehavior getLoginBehavior() {
return loginBehavior;
}
int getRequestCode() {
return requestCode;
}
SessionDefaultAudience getDefaultAudience() {
return defaultAudience;
}
String getApplicationId() {
return applicationId;
}
boolean isLegacy() {
return isLegacy;
}
void setIsLegacy(boolean isLegacy) {
this.isLegacy = isLegacy;
}
String getPreviousAccessToken() {
return previousAccessToken;
}
boolean needsNewTokenValidation() {
return previousAccessToken != null && !isLegacy;
}
}
static class Result implements Serializable {
private static final long serialVersionUID = 1L;
enum Code {
SUCCESS,
CANCEL,
ERROR
}
final Code code;
final AccessToken token;
final String errorMessage;
private Result(Code code, AccessToken token, String errorMessage) {
this.token = token;
this.errorMessage = errorMessage;
this.code = code;
}
static Result createTokenResult(AccessToken token) {
return new Result(Code.SUCCESS, token, null);
}
static Result createCancelResult(String message) {
return new Result(Code.CANCEL, null, message);
}
static Result createErrorResult(String errorType, String errorDescription) {
String message = errorType;
if (errorDescription != null) {
message += ": " + errorDescription;
}
return new Result(Code.ERROR, null, message);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.facebook.android.R;
/**
* This Activity is a necessary part of the overall Facebook login process
* but is not meant to be used directly. Add this activity to your
* AndroidManifest.xml to ensure proper handling of Facebook login.
* <pre>
* {@code
* <activity android:name="com.facebook.LoginActivity"
* android:theme="@android:style/Theme.Translucent.NoTitleBar"
* android:label="@string/app_name" />
* }
* </pre>
* Do not start this activity directly.
*/
public class LoginActivity extends Activity {
static final String RESULT_KEY = "com.facebook.LoginActivity:Result";
private static final String NULL_CALLING_PKG_ERROR_MSG =
"Cannot call LoginActivity with a null calling package. " +
"This can occur if the launchMode of the caller is singleInstance.";
private static final String SAVED_CALLING_PKG_KEY = "callingPackage";
private static final String SAVED_AUTH_CLIENT = "authorizationClient";
private static final String EXTRA_REQUEST = "request";
private String callingPackage;
private AuthorizationClient authorizationClient;
private AuthorizationClient.AuthorizationRequest request;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.com_facebook_login_activity_layout);
if (savedInstanceState != null) {
callingPackage = savedInstanceState.getString(SAVED_CALLING_PKG_KEY);
authorizationClient = (AuthorizationClient) savedInstanceState.getSerializable(SAVED_AUTH_CLIENT);
} else {
callingPackage = getCallingPackage();
authorizationClient = new AuthorizationClient();
request = (AuthorizationClient.AuthorizationRequest) getIntent().getSerializableExtra(EXTRA_REQUEST);
}
authorizationClient.setContext(this);
authorizationClient.setOnCompletedListener(new AuthorizationClient.OnCompletedListener() {
@Override
public void onCompleted(AuthorizationClient.Result outcome) {
onAuthClientCompleted(outcome);
}
});
authorizationClient.setBackgroundProcessingListener(new AuthorizationClient.BackgroundProcessingListener() {
@Override
public void onBackgroundProcessingStarted() {
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.VISIBLE);
}
@Override
public void onBackgroundProcessingStopped() {
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE);
}
});
}
private void onAuthClientCompleted(AuthorizationClient.Result outcome) {
request = null;
int resultCode = (outcome.code == AuthorizationClient.Result.Code.CANCEL) ?
RESULT_CANCELED : RESULT_OK;
Bundle bundle = new Bundle();
bundle.putSerializable(RESULT_KEY, outcome);
Intent resultIntent = new Intent();
resultIntent.putExtras(bundle);
setResult(resultCode, resultIntent);
finish();
}
@Override
public void onResume() {
super.onResume();
// If the calling package is null, this generally means that the callee was started
// with a launchMode of singleInstance. Unfortunately, Android does not allow a result
// to be set when the callee is a singleInstance, so we throw an exception here.
if (callingPackage == null) {
throw new FacebookException(NULL_CALLING_PKG_ERROR_MSG);
}
authorizationClient.startOrContinueAuth(request);
}
@Override
public void onPause() {
super.onPause();
authorizationClient.cancelCurrentHandler();
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVED_CALLING_PKG_KEY, callingPackage);
outState.putSerializable(SAVED_AUTH_CLIENT, authorizationClient);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
authorizationClient.onActivityResult(requestCode, resultCode, data);
}
static Bundle populateIntentExtras(AuthorizationClient.AuthorizationRequest request) {
Bundle extras = new Bundle();
extras.putSerializable(EXTRA_REQUEST, request);
return extras;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.content.Context;
import com.facebook.internal.*;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Encapsulates the response, successful or otherwise, of a call to the Facebook platform.
*/
public class Response {
private final HttpURLConnection connection;
private final GraphObject graphObject;
private final GraphObjectList<GraphObject> graphObjectList;
private final boolean isFromCache;
private final FacebookRequestError error;
private final Request request;
/**
* Property name of non-JSON results in the GraphObject. Certain calls to Facebook result in a non-JSON response
* (e.g., the string literal "true" or "false"). To present a consistent way of accessing results, these are
* represented as a GraphObject with a single string property with this name.
*/
public static final String NON_JSON_RESPONSE_PROPERTY = "FACEBOOK_NON_JSON_RESULT";
private static final int INVALID_SESSION_FACEBOOK_ERROR_CODE = 190;
private static final String CODE_KEY = "code";
private static final String BODY_KEY = "body";
private static final String RESPONSE_LOG_TAG = "Response";
private static final String RESPONSE_CACHE_TAG = "ResponseCache";
private static FileLruCache responseCache;
Response(Request request, HttpURLConnection connection, GraphObject graphObject, boolean isFromCache) {
this.request = request;
this.connection = connection;
this.graphObject = graphObject;
this.graphObjectList = null;
this.isFromCache = isFromCache;
this.error = null;
}
Response(Request request, HttpURLConnection connection, GraphObjectList<GraphObject> graphObjects,
boolean isFromCache) {
this.request = request;
this.connection = connection;
this.graphObject = null;
this.graphObjectList = graphObjects;
this.isFromCache = isFromCache;
this.error = null;
}
Response(Request request, HttpURLConnection connection, FacebookRequestError error) {
this.request = request;
this.connection = connection;
this.graphObject = null;
this.graphObjectList = null;
this.isFromCache = false;
this.error = error;
}
/**
* Returns information about any errors that may have occurred during the request.
*
* @return the error from the server, or null if there was no server error
*/
public final FacebookRequestError getError() {
return error;
}
/**
* The single graph object returned for this request, if any.
*
* @return the graph object returned, or null if none was returned (or if the result was a list)
*/
public final GraphObject getGraphObject() {
return graphObject;
}
/**
* The single graph object returned for this request, if any, cast into a particular type of GraphObject.
*
* @param graphObjectClass the GraphObject-derived interface to cast the graph object into
* @return the graph object returned, or null if none was returned (or if the result was a list)
* @throws FacebookException If the passed in Class is not a valid GraphObject interface
*/
public final <T extends GraphObject> T getGraphObjectAs(Class<T> graphObjectClass) {
if (graphObject == null) {
return null;
}
if (graphObjectClass == null) {
throw new NullPointerException("Must pass in a valid interface that extends GraphObject");
}
return graphObject.cast(graphObjectClass);
}
/**
* The list of graph objects returned for this request, if any.
*
* @return the list of graph objects returned, or null if none was returned (or if the result was not a list)
*/
public final GraphObjectList<GraphObject> getGraphObjectList() {
return graphObjectList;
}
/**
* The list of graph objects returned for this request, if any, cast into a particular type of GraphObject.
*
* @param graphObjectClass the GraphObject-derived interface to cast the graph objects into
* @return the list of graph objects returned, or null if none was returned (or if the result was not a list)
* @throws FacebookException If the passed in Class is not a valid GraphObject interface
*/
public final <T extends GraphObject> GraphObjectList<T> getGraphObjectListAs(Class<T> graphObjectClass) {
if (graphObjectList == null) {
return null;
}
return graphObjectList.castToListOf(graphObjectClass);
}
/**
* Returns the HttpURLConnection that this response was generated from. If the response was retrieved
* from the cache, this will be null.
*
* @return the connection, or null
*/
public final HttpURLConnection getConnection() {
return connection;
}
/**
* Returns the request that this response is for.
*
* @return the request that this response is for
*/
public Request getRequest() {
return request;
}
/**
* Indicates whether paging is being done forward or backward.
*/
public enum PagingDirection {
/**
* Indicates that paging is being performed in the forward direction.
*/
NEXT,
/**
* Indicates that paging is being performed in the backward direction.
*/
PREVIOUS
}
/**
* If a Response contains results that contain paging information, returns a new
* Request that will retrieve the next page of results, in whichever direction
* is desired. If no paging information is available, returns null.
*
* @param direction enum indicating whether to page forward or backward
* @return a Request that will retrieve the next page of results in the desired
* direction, or null if no paging information is available
*/
public Request getRequestForPagedResults(PagingDirection direction) {
String link = null;
if (graphObject != null) {
PagedResults pagedResults = graphObject.cast(PagedResults.class);
PagingInfo pagingInfo = pagedResults.getPaging();
if (pagingInfo != null) {
if (direction == PagingDirection.NEXT) {
link = pagingInfo.getNext();
} else {
link = pagingInfo.getPrevious();
}
}
}
if (Utility.isNullOrEmpty(link)) {
return null;
}
if (link != null && link.equals(request.getUrlForSingleRequest())) {
// We got the same "next" link as we just tried to retrieve. This could happen if cached
// data is invalid. All we can do in this case is pretend we have finished.
return null;
}
Request pagingRequest;
try {
pagingRequest = new Request(request.getSession(), new URL(link));
} catch (MalformedURLException e) {
return null;
}
return pagingRequest;
}
/**
* Provides a debugging string for this response.
*/
@Override
public String toString() {
String responseCode;
try {
responseCode = String.format("%d", (connection != null) ? connection.getResponseCode() : 200);
} catch (IOException e) {
responseCode = "unknown";
}
return new StringBuilder().append("{Response: ").append(" responseCode: ").append(responseCode)
.append(", graphObject: ").append(graphObject).append(", error: ").append(error)
.append(", isFromCache:").append(isFromCache).append("}")
.toString();
}
/**
* Indicates whether the response was retrieved from a local cache or from the server.
*
* @return true if the response was cached locally, false if it was retrieved from the server
*/
public final boolean getIsFromCache() {
return isFromCache;
}
static FileLruCache getResponseCache() {
if (responseCache == null) {
Context applicationContext = Session.getStaticContext();
if (applicationContext != null) {
responseCache = new FileLruCache(applicationContext, RESPONSE_CACHE_TAG, new FileLruCache.Limits());
}
}
return responseCache;
}
@SuppressWarnings("resource")
static List<Response> fromHttpConnection(HttpURLConnection connection, RequestBatch requests) {
InputStream stream = null;
FileLruCache cache = null;
String cacheKey = null;
if (requests instanceof CacheableRequestBatch) {
CacheableRequestBatch cacheableRequestBatch = (CacheableRequestBatch) requests;
cache = getResponseCache();
cacheKey = cacheableRequestBatch.getCacheKeyOverride();
if (Utility.isNullOrEmpty(cacheKey)) {
if (requests.size() == 1) {
// Default for single requests is to use the URL.
cacheKey = requests.get(0).getUrlForSingleRequest();
} else {
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_CACHE_TAG,
"Not using cache for cacheable request because no key was specified");
}
}
// Try loading from cache. If that fails, load from the network.
if (!cacheableRequestBatch.getForceRoundTrip() && cache != null && !Utility.isNullOrEmpty(cacheKey)) {
try {
stream = cache.get(cacheKey);
if (stream != null) {
return createResponsesFromStream(stream, null, requests, true);
}
} catch (FacebookException exception) { // retry via roundtrip below
} catch (JSONException exception) {
} catch (IOException exception) {
} finally {
Utility.closeQuietly(stream);
}
}
}
// Load from the network, and cache the result if not an error.
try {
if (connection.getResponseCode() >= 400) {
stream = connection.getErrorStream();
} else {
stream = connection.getInputStream();
if ((cache != null) && (cacheKey != null) && (stream != null)) {
InputStream interceptStream = cache.interceptAndPut(cacheKey, stream);
if (interceptStream != null) {
stream = interceptStream;
}
}
}
return createResponsesFromStream(stream, connection, requests, false);
} catch (FacebookException facebookException) {
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException);
return constructErrorResponses(requests, connection, facebookException);
} catch (JSONException exception) {
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
return constructErrorResponses(requests, connection, new FacebookException(exception));
} catch (IOException exception) {
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
return constructErrorResponses(requests, connection, new FacebookException(exception));
} finally {
Utility.closeQuietly(stream);
}
}
static List<Response> createResponsesFromStream(InputStream stream, HttpURLConnection connection,
RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
String responseString = Utility.readStreamToString(stream);
Logger.log(LoggingBehavior.INCLUDE_RAW_RESPONSES, RESPONSE_LOG_TAG,
"Response (raw)\n Size: %d\n Response:\n%s\n", responseString.length(),
responseString);
return createResponsesFromString(responseString, connection, requests, isFromCache);
}
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
JSONTokener tokener = new JSONTokener(responseString);
Object resultObject = tokener.nextValue();
List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n",
requests.getId(), responseString.length(), responses);
return responses;
}
private static List<Response> createResponsesFromObject(HttpURLConnection connection, List<Request> requests,
Object object, boolean isFromCache) throws FacebookException, JSONException {
assert (connection != null) || isFromCache;
int numRequests = requests.size();
List<Response> responses = new ArrayList<Response>(numRequests);
Object originalResult = object;
if (numRequests == 1) {
Request request = requests.get(0);
try {
// Single request case -- the entire response is the result, wrap it as "body" so we can handle it
// the same as we do in the batched case. We get the response code from the actual HTTP response,
// as opposed to the batched case where it is returned as a "code" element.
JSONObject jsonObject = new JSONObject();
jsonObject.put(BODY_KEY, object);
int responseCode = (connection != null) ? connection.getResponseCode() : 200;
jsonObject.put(CODE_KEY, responseCode);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
// Pretend we got an array of 1 back.
object = jsonArray;
} catch (JSONException e) {
responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
} catch (IOException e) {
responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
}
}
if (!(object instanceof JSONArray) || ((JSONArray) object).length() != numRequests) {
FacebookException exception = new FacebookException("Unexpected number of results");
throw exception;
}
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length(); ++i) {
Request request = requests.get(i);
try {
Object obj = jsonArray.get(i);
responses.add(createResponseFromObject(request, connection, obj, isFromCache, originalResult));
} catch (JSONException e) {
responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
} catch (FacebookException e) {
responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
}
}
return responses;
}
private static Response createResponseFromObject(Request request, HttpURLConnection connection, Object object,
boolean isFromCache, Object originalResult) throws JSONException {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
FacebookRequestError error =
FacebookRequestError.checkResponseAndCreateError(jsonObject, originalResult, connection);
if (error != null) {
if (error.getErrorCode() == INVALID_SESSION_FACEBOOK_ERROR_CODE) {
Session session = request.getSession();
if (session != null) {
session.closeAndClearTokenInformation();
}
}
return new Response(request, connection, error);
}
Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY);
if (body instanceof JSONObject) {
GraphObject graphObject = GraphObject.Factory.create((JSONObject) body);
return new Response(request, connection, graphObject, isFromCache);
} else if (body instanceof JSONArray) {
GraphObjectList<GraphObject> graphObjectList = GraphObject.Factory.createList(
(JSONArray) body, GraphObject.class);
return new Response(request, connection, graphObjectList, isFromCache);
}
// We didn't get a body we understand how to handle, so pretend we got nothing.
object = JSONObject.NULL;
}
if (object == JSONObject.NULL) {
return new Response(request, connection, (GraphObject)null, isFromCache);
} else {
throw new FacebookException("Got unexpected object type in response, class: "
+ object.getClass().getSimpleName());
}
}
static List<Response> constructErrorResponses(List<Request> requests, HttpURLConnection connection,
FacebookException error) {
int count = requests.size();
List<Response> responses = new ArrayList<Response>(count);
for (int i = 0; i < count; ++i) {
Response response = new Response(requests.get(i), connection, new FacebookRequestError(connection, error));
responses.add(response);
}
return responses;
}
interface PagingInfo extends GraphObject {
String getNext();
String getPrevious();
}
interface PagedResults extends GraphObject {
GraphObjectList<GraphObject> getData();
PagingInfo getPaging();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.os.Bundle;
import android.text.TextUtils;
import com.facebook.internal.Utility;
import java.util.ArrayList;
import java.util.List;
final class NativeProtocol {
static final String KATANA_PACKAGE = "com.facebook.katana";
static final String KATANA_PROXY_AUTH_ACTIVITY = "com.facebook.katana.ProxyAuth";
static final String KATANA_TOKEN_REFRESH_ACTIVITY = "com.facebook.katana.platform.TokenRefreshService";
static final String KATANA_SIGNATURE =
"30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310"
+ "b3009060355040613025553310b30090603550408130243413112301006035504"
+ "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204"
+ "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504"
+ "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333"
+ "13231353231365a180f32303530303932353231353231365a307a310b30090603"
+ "55040613025553310b30090603550408130243413112301006035504071309506"
+ "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c"
+ "653111300f060355040b130846616365626f6f6b311d301b06035504031314466"
+ "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01"
+ "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa"
+ "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7"
+ "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc"
+ "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603"
+ "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050"
+ "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c"
+ "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6"
+ "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2"
+ "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd"
+ "928a2";
private static final String BASIC_INFO = "basic_info";
public static final String KATANA_PROXY_AUTH_PERMISSIONS_KEY = "scope";
public static final String KATANA_PROXY_AUTH_APP_ID_KEY = "client_id";
static final boolean validateSignature(Context context, String packageName) {
PackageInfo packageInfo = null;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(KATANA_SIGNATURE)) {
return true;
}
}
return false;
}
static Intent validateKatanaActivityIntent(Context context, Intent intent) {
if (intent == null) {
return null;
}
ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
if (!validateSignature(context, resolveInfo.activityInfo.packageName)) {
return null;
}
return intent;
}
static Intent validateKatanaServiceIntent(Context context, Intent intent) {
if (intent == null) {
return null;
}
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return null;
}
if (!validateSignature(context, resolveInfo.serviceInfo.packageName)) {
return null;
}
return intent;
}
static Intent createProxyAuthIntent(Context context, String applicationId, List<String> permissions) {
Intent intent = new Intent()
.setClassName(KATANA_PACKAGE, KATANA_PROXY_AUTH_ACTIVITY)
.putExtra(KATANA_PROXY_AUTH_APP_ID_KEY, applicationId);
if (!Utility.isNullOrEmpty(permissions)) {
intent.putExtra(KATANA_PROXY_AUTH_PERMISSIONS_KEY, TextUtils.join(",", permissions));
}
return validateKatanaActivityIntent(context, intent);
}
static Intent createTokenRefreshIntent(Context context) {
Intent intent = new Intent();
intent.setClassName(KATANA_PACKAGE, KATANA_TOKEN_REFRESH_ACTIVITY);
return validateKatanaServiceIntent(context, intent);
}
// ---------------------------------------------------------------------------------------------
// Native Protocol updated 2012-11
static final String INTENT_ACTION_PLATFORM_ACTIVITY = "com.facebook.platform.PLATFORM_ACTIVITY";
static final String INTENT_ACTION_PLATFORM_SERVICE = "com.facebook.platform.PLATFORM_SERVICE";
static final int PROTOCOL_VERSION_20121101 = 20121101;
static final String EXTRA_PROTOCOL_VERSION = "com.facebook.platform.protocol.PROTOCOL_VERSION";
static final String EXTRA_PROTOCOL_ACTION = "com.facebook.platform.protocol.PROTOCOL_ACTION";
// Messages supported by PlatformService:
static final int MESSAGE_GET_ACCESS_TOKEN_REQUEST = 0x10000;
static final int MESSAGE_GET_ACCESS_TOKEN_REPLY = 0x10001;
// MESSAGE_ERROR_REPLY data keys:
// See STATUS_*
// MESSAGE_GET_ACCESS_TOKEN_REQUEST data keys:
// EXTRA_APPLICATION_ID
// MESSAGE_GET_ACCESS_TOKEN_REPLY data keys:
// EXTRA_ACCESS_TOKEN
// EXTRA_EXPIRES_SECONDS_SINCE_EPOCH
// EXTRA_PERMISSIONS
// Values of EXTRA_PROTOCOL_ACTION supported by PlatformActivity:
static final String ACTION_LOGIN_DIALOG = "com.facebook.platform.action.request.LOGIN_DIALOG";
// Values of EXTRA_PROTOCOL_ACTION values returned by PlatformActivity:
static final String ACTION_LOGIN_DIALOG_REPLY =
"com.facebook.platform.action.reply.LOGIN_DIALOG";
// Extras supported for ACTION_LOGIN_DIALOG:
static final String EXTRA_PERMISSIONS = "com.facebook.platform.extra.PERMISSIONS";
static final String EXTRA_WRITE_PRIVACY = "com.facebook.platform.extra.WRITE_PRIVACY";
static final String EXTRA_APPLICATION_ID = "com.facebook.platform.extra.APPLICATION_ID";
// Extras returned by setResult() for ACTION_LOGIN_DIALOG
static final String EXTRA_ACCESS_TOKEN = "com.facebook.platform.extra.ACCESS_TOKEN";
static final String EXTRA_EXPIRES_SECONDS_SINCE_EPOCH =
"com.facebook.platform.extra.EXPIRES_SECONDS_SINCE_EPOCH";
// EXTRA_PERMISSIONS
// Keys for status data in MESSAGE_ERROR_REPLY from PlatformService and for error
// extras returned by PlatformActivity's setResult() in case of errors:
static final String STATUS_ERROR_TYPE = "com.facebook.platform.status.ERROR_TYPE";
static final String STATUS_ERROR_DESCRIPTION =
"com.facebook.platform.status.ERROR_DESCRIPTION";
static final String STATUS_ERROR_CODE = "com.facebook.platform.status.ERROR_CODE";
static final String STATUS_ERROR_SUBCODE = "com.facebook.platform.status.ERROR_SUBCODE";
static final String STATUS_ERROR_JSON = "com.facebook.platform.status.ERROR_JSON";
// Expected values for ERROR_KEY_TYPE. Clients should tolerate other values:
static final String ERROR_UNKNOWN_ERROR = "UnknownError";
static final String ERROR_PROTOCOL_ERROR = "ProtocolError";
static final String ERROR_USER_CANCELED = "UserCanceled";
static final String ERROR_APPLICATION_ERROR = "ApplicationError";
static final String ERROR_NETWORK_ERROR = "NetworkError";
static final String ERROR_PERMISSION_DENIED = "PermissionDenied";
static final String ERROR_SERVICE_DISABLED = "ServiceDisabled";
static final String AUDIENCE_ME = "SELF";
static final String AUDIENCE_FRIENDS = "ALL_FRIENDS";
static final String AUDIENCE_EVERYONE = "EVERYONE";
static Intent createLoginDialog20121101Intent(Context context, String applicationId, ArrayList<String> permissions,
String audience) {
Intent intent = new Intent()
.setAction(INTENT_ACTION_PLATFORM_ACTIVITY)
.addCategory(Intent.CATEGORY_DEFAULT)
.putExtra(EXTRA_PROTOCOL_VERSION, PROTOCOL_VERSION_20121101)
.putExtra(EXTRA_PROTOCOL_ACTION, ACTION_LOGIN_DIALOG)
.putExtra(EXTRA_APPLICATION_ID, applicationId)
.putStringArrayListExtra(EXTRA_PERMISSIONS, ensureDefaultPermissions(permissions))
.putExtra(EXTRA_WRITE_PRIVACY, ensureDefaultAudience(audience));
return validateKatanaActivityIntent(context, intent);
}
private static String ensureDefaultAudience(String audience) {
if (Utility.isNullOrEmpty(audience)) {
return AUDIENCE_ME;
} else {
return audience;
}
}
private static ArrayList<String> ensureDefaultPermissions(ArrayList<String> permissions) {
ArrayList<String> updated;
// Return if we are doing publish, or if basic_info is already included
if (Utility.isNullOrEmpty(permissions)) {
updated = new ArrayList<String>();
} else {
for (String permission : permissions) {
if (Session.isPublishPermission(permission) || BASIC_INFO.equals(permission)) {
return permissions;
}
}
updated = new ArrayList<String>(permissions);
}
updated.add(BASIC_INFO);
return updated;
}
static boolean isServiceDisabledResult20121101(Intent data) {
int protocolVersion = data.getIntExtra(EXTRA_PROTOCOL_VERSION, 0);
String errorType = data.getStringExtra(STATUS_ERROR_TYPE);
return ((PROTOCOL_VERSION_20121101 == protocolVersion) && ERROR_SERVICE_DISABLED.equals(errorType));
}
static AccessTokenSource getAccessTokenSourceFromNative(Bundle extras) {
long expected = PROTOCOL_VERSION_20121101;
long actual = extras.getInt(EXTRA_PROTOCOL_VERSION, 0);
if (expected == actual) {
return AccessTokenSource.FACEBOOK_APPLICATION_NATIVE;
} else {
return AccessTokenSource.FACEBOOK_APPLICATION_WEB;
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Represents an error condition specific to the Facebook SDK for Android.
*/
public class FacebookException extends RuntimeException {
static final long serialVersionUID = 1;
/**
* Constructs a new FacebookException.
*/
public FacebookException() {
super();
}
/**
* Constructs a new FacebookException.
*
* @param message
* the detail message of this exception
*/
public FacebookException(String message) {
super(message);
}
/**
* Constructs a new FacebookException.
*
* @param message
* the detail message of this exception
* @param throwable
* the cause of this exception
*/
public FacebookException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a new FacebookException.
*
* @param throwable
* the cause of this exception
*/
public FacebookException(Throwable throwable) {
super(throwable);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.os.Bundle;
import com.facebook.internal.Validate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>
* A base class for implementations of a {@link Session Session} token cache.
* </p>
* <p>
* The Session constructor optionally takes a TokenCachingStrategy, from which it will
* attempt to load a cached token during construction. Also, whenever the
* Session updates its token, it will also save the token and associated state
* to the TokenCachingStrategy.
* </p>
* <p>
* This is the only mechanism supported for an Android service to use Session.
* The service can create a custom TokenCachingStrategy that returns the Session provided
* by an Activity through which the user logged in to Facebook.
* </p>
*/
public abstract class TokenCachingStrategy {
/**
* The key used by Session to store the token value in the Bundle during
* load and save.
*/
public static final String TOKEN_KEY = "com.facebook.TokenCachingStrategy.Token";
/**
* The key used by Session to store the expiration date value in the Bundle
* during load and save.
*/
public static final String EXPIRATION_DATE_KEY = "com.facebook.TokenCachingStrategy.ExpirationDate";
/**
* The key used by Session to store the last refresh date value in the
* Bundle during load and save.
*/
public static final String LAST_REFRESH_DATE_KEY = "com.facebook.TokenCachingStrategy.LastRefreshDate";
/**
* The key used by Session to store the user's id value in the Bundle during
* load and save.
*/
public static final String USER_FBID_KEY = "com.facebook.TokenCachingStrategy.UserFBID";
/**
* The key used by Session to store an enum indicating the source of the token
* in the Bundle during load and save.
*/
public static final String TOKEN_SOURCE_KEY = "com.facebook.TokenCachingStrategy.AccessTokenSource";
/**
* The key used by Session to store the list of permissions granted by the
* token in the Bundle during load and save.
*/
public static final String PERMISSIONS_KEY = "com.facebook.TokenCachingStrategy.Permissions";
private static final long INVALID_BUNDLE_MILLISECONDS = Long.MIN_VALUE;
private static final String IS_SSO_KEY = "com.facebook.TokenCachingStrategy.IsSSO";
/**
* Called during Session construction to get the token state. Typically this
* is loaded from a persistent store that was previously initialized via
* save. The caller may choose to keep a reference to the returned Bundle
* indefinitely. Therefore the TokenCachingStrategy should not store the returned Bundle
* and should return a new Bundle on every call to this method.
*
* @return A Bundle that represents the token state that was loaded.
*/
public abstract Bundle load();
/**
* Called when a Session updates its token. This is passed a Bundle of
* values that should be stored durably for the purpose of being returned
* from a later call to load. Some implementations may choose to store
* bundle beyond the scope of this call, so the caller should keep no
* references to the bundle to ensure that it is not modified later.
*
* @param bundle
* A Bundle that represents the token state to be saved.
*/
public abstract void save(Bundle bundle);
/**
* Called when a Session learns its token is no longer valid or during a
* call to {@link Session#closeAndClearTokenInformation
* closeAndClearTokenInformation} to clear the durable state associated with
* the token.
*/
public abstract void clear();
/**
* Returns a boolean indicating whether a Bundle contains properties that
* could be a valid saved token.
*
* @param bundle
* A Bundle to check for token information.
* @return a boolean indicating whether a Bundle contains properties that
* could be a valid saved token.
*/
public static boolean hasTokenInformation(Bundle bundle) {
if (bundle == null) {
return false;
}
String token = bundle.getString(TOKEN_KEY);
if ((token == null) || (token.length() == 0)) {
return false;
}
long expiresMilliseconds = bundle.getLong(EXPIRATION_DATE_KEY, 0L);
if (expiresMilliseconds == 0L) {
return false;
}
return true;
}
/**
* Gets the cached token value from a Bundle.
*
* @param bundle
* A Bundle in which the token value was stored.
* @return the cached token value, or null.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static String getToken(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return bundle.getString(TOKEN_KEY);
}
/**
* Puts the token value into a Bundle.
*
* @param bundle
* A Bundle in which the token value should be stored.
* @param value
* The String representing the token value, or null.
*
* @throws NullPointerException if the passed in Bundle or token value are null
*/
public static void putToken(Bundle bundle, String value) {
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
bundle.putString(TOKEN_KEY, value);
}
/**
* Gets the cached expiration date from a Bundle.
*
* @param bundle
* A Bundle in which the expiration date was stored.
* @return the cached expiration date, or null.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static Date getExpirationDate(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return getDate(bundle, EXPIRATION_DATE_KEY);
}
/**
* Puts the expiration date into a Bundle.
*
* @param bundle
* A Bundle in which the expiration date should be stored.
* @param value
* The Date representing the expiration date.
*
* @throws NullPointerException if the passed in Bundle or date value are null
*/
public static void putExpirationDate(Bundle bundle, Date value) {
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
putDate(bundle, EXPIRATION_DATE_KEY, value);
}
/**
* Gets the cached expiration date from a Bundle.
*
* @param bundle
* A Bundle in which the expiration date was stored.
* @return the long representing the cached expiration date in milliseconds
* since the epoch, or 0.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static long getExpirationMilliseconds(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return bundle.getLong(EXPIRATION_DATE_KEY);
}
/**
* Puts the expiration date into a Bundle.
*
* @param bundle
* A Bundle in which the expiration date should be stored.
* @param value
* The long representing the expiration date in milliseconds
* since the epoch.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static void putExpirationMilliseconds(Bundle bundle, long value) {
Validate.notNull(bundle, "bundle");
bundle.putLong(EXPIRATION_DATE_KEY, value);
}
/**
* Gets the cached list of permissions from a Bundle.
*
* @param bundle
* A Bundle in which the list of permissions was stored.
* @return the cached list of permissions.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static List<String> getPermissions(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return bundle.getStringArrayList(PERMISSIONS_KEY);
}
/**
* Puts the list of permissions into a Bundle.
*
* @param bundle
* A Bundle in which the list of permissions should be stored.
* @param value
* The List<String> representing the list of permissions,
* or null.
*
* @throws NullPointerException if the passed in Bundle or permissions list are null
*/
public static void putPermissions(Bundle bundle, List<String> value) {
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
ArrayList<String> arrayList;
if (value instanceof ArrayList<?>) {
arrayList = (ArrayList<String>) value;
} else {
arrayList = new ArrayList<String>(value);
}
bundle.putStringArrayList(PERMISSIONS_KEY, arrayList);
}
/**
* Gets the cached enum indicating the source of the token from the Bundle.
*
* @param bundle
* A Bundle in which the enum was stored.
* @return enum indicating the source of the token
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static AccessTokenSource getSource(Bundle bundle) {
Validate.notNull(bundle, "bundle");
if (bundle.containsKey(TokenCachingStrategy.TOKEN_SOURCE_KEY)) {
return (AccessTokenSource) bundle.getSerializable(TokenCachingStrategy.TOKEN_SOURCE_KEY);
} else {
boolean isSSO = bundle.getBoolean(TokenCachingStrategy.IS_SSO_KEY);
return isSSO ? AccessTokenSource.FACEBOOK_APPLICATION_WEB : AccessTokenSource.WEB_VIEW;
}
}
/**
* Puts the enum indicating the source of the token into a Bundle.
*
* @param bundle
* A Bundle in which the enum should be stored.
* @param value
* enum indicating the source of the token
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static void putSource(Bundle bundle, AccessTokenSource value) {
Validate.notNull(bundle, "bundle");
bundle.putSerializable(TOKEN_SOURCE_KEY, value);
}
/**
* Gets the cached last refresh date from a Bundle.
*
* @param bundle
* A Bundle in which the last refresh date was stored.
* @return the cached last refresh Date, or null.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static Date getLastRefreshDate(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return getDate(bundle, LAST_REFRESH_DATE_KEY);
}
/**
* Puts the last refresh date into a Bundle.
*
* @param bundle
* A Bundle in which the last refresh date should be stored.
* @param value
* The Date representing the last refresh date, or null.
*
* @throws NullPointerException if the passed in Bundle or date value are null
*/
public static void putLastRefreshDate(Bundle bundle, Date value) {
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
putDate(bundle, LAST_REFRESH_DATE_KEY, value);
}
/**
* Gets the cached last refresh date from a Bundle.
*
* @param bundle
* A Bundle in which the last refresh date was stored.
* @return the cached last refresh date in milliseconds since the epoch.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static long getLastRefreshMilliseconds(Bundle bundle) {
Validate.notNull(bundle, "bundle");
return bundle.getLong(LAST_REFRESH_DATE_KEY);
}
/**
* Puts the last refresh date into a Bundle.
*
* @param bundle
* A Bundle in which the last refresh date should be stored.
* @param value
* The long representing the last refresh date in milliseconds
* since the epoch.
*
* @throws NullPointerException if the passed in Bundle is null
*/
public static void putLastRefreshMilliseconds(Bundle bundle, long value) {
Validate.notNull(bundle, "bundle");
bundle.putLong(LAST_REFRESH_DATE_KEY, value);
}
static Date getDate(Bundle bundle, String key) {
if (bundle == null) {
return null;
}
long n = bundle.getLong(key, INVALID_BUNDLE_MILLISECONDS);
if (n == INVALID_BUNDLE_MILLISECONDS) {
return null;
}
return new Date(n);
}
static void putDate(Bundle bundle, String key, Date date) {
bundle.putLong(key, date.getTime());
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Represents an error returned from the Facebook service in response to a request.
*/
public class FacebookServiceException extends FacebookException {
private final FacebookRequestError error;
private static final long serialVersionUID = 1;
/**
* Constructs a new FacebookServiceException.
*
* @param error the error from the request
*/
public FacebookServiceException(FacebookRequestError error, String errorMessage) {
super(errorMessage);
this.error = error;
}
/**
* Returns an object that encapsulates complete information representing the error returned by Facebook.
*
* @return complete information representing the error.
*/
public final FacebookRequestError getRequestError() {
return error;
}
@Override
public final String toString() {
return new StringBuilder()
.append("{FacebookServiceException: ")
.append("httpResponseCode: ")
.append(error.getRequestStatusCode())
.append(", facebookErrorCode: ")
.append(error.getErrorCode())
.append(", facebookErrorType: ")
.append(error.getErrorType())
.append(", message: ")
.append(error.getErrorMessage())
.append("}")
.toString();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Represents an error specific to the {@link com.facebook.model.GraphObject GraphObject} class.
*/
public class FacebookGraphObjectException extends FacebookException {
static final long serialVersionUID = 1;
/**
* Constructs a new FacebookGraphObjectException.
*/
public FacebookGraphObjectException() {
super();
}
/**
* Constructs a new FacebookGraphObjectException.
*
* @param message
* the detail message of this exception
*/
public FacebookGraphObjectException(String message) {
super(message);
}
/**
* Constructs a new FacebookGraphObjectException.
*
* @param message
* the detail message of this exception
* @param throwable
* the cause of this exception
*/
public FacebookGraphObjectException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a new FacebookGraphObjectException.
*
* @param throwable
* the cause of this exception
*/
public FacebookGraphObjectException(Throwable throwable) {
super(throwable);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.*;
final class GetTokenClient implements ServiceConnection {
final Context context;
final String applicationId;
final Handler handler;
CompletedListener listener;
boolean running;
Messenger sender;
GetTokenClient(Context context, String applicationId) {
Context applicationContext = context.getApplicationContext();
this.context = (applicationContext != null) ? applicationContext : context;
this.applicationId = applicationId;
handler = new Handler() {
@Override
public void handleMessage(Message message) {
GetTokenClient.this.handleMessage(message);
}
};
}
void setCompletedListener(CompletedListener listener) {
this.listener = listener;
}
boolean start() {
Intent intent = new Intent(NativeProtocol.INTENT_ACTION_PLATFORM_SERVICE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent = NativeProtocol.validateKatanaServiceIntent(context, intent);
if (intent == null) {
callback(null);
return false;
} else {
running = true;
context.bindService(intent, this, Context.BIND_AUTO_CREATE);
return true;
}
}
void cancel() {
running = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
sender = new Messenger(service);
getToken();
}
@Override
public void onServiceDisconnected(ComponentName name) {
sender = null;
context.unbindService(this);
callback(null);
}
private void getToken() {
Bundle data = new Bundle();
data.putString(NativeProtocol.EXTRA_APPLICATION_ID, applicationId);
Message request = Message.obtain(null, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST);
request.arg1 = NativeProtocol.PROTOCOL_VERSION_20121101;
request.setData(data);
request.replyTo = new Messenger(handler);
try {
sender.send(request);
} catch (RemoteException e) {
callback(null);
}
}
private void handleMessage(Message message) {
if (message.what == NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REPLY) {
Bundle extras = message.getData();
String errorType = extras.getString(NativeProtocol.STATUS_ERROR_TYPE);
if (errorType != null) {
callback(null);
} else {
callback(extras);
}
context.unbindService(this);
}
}
private void callback(Bundle result) {
if (!running) {
return;
}
running = false;
CompletedListener callback = listener;
if (callback != null) {
callback.completed(result);
}
}
interface CompletedListener {
void completed(Bundle result);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.util.Log;
import com.facebook.internal.Logger;
import com.facebook.LoggingBehavior;
import com.facebook.internal.Utility;
import com.facebook.internal.FileLruCache;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
class ImageResponseCache {
static final String TAG = ImageResponseCache.class.getSimpleName();
private volatile static FileLruCache imageCache;
synchronized static FileLruCache getCache(Context context) throws IOException{
if (imageCache == null) {
imageCache = new FileLruCache(context.getApplicationContext(), TAG, new FileLruCache.Limits());
}
return imageCache;
}
// Get stream from cache, or return null if the image is not cached.
// Does not throw if there was an error.
static InputStream getCachedImageStream(URL url, Context context) {
InputStream imageStream = null;
if (url != null) {
if (isCDNURL(url)) {
try {
FileLruCache cache = getCache(context);
imageStream = cache.get(url.toString());
} catch (IOException e) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, e.toString());
}
}
}
return imageStream;
}
static InputStream interceptAndCacheImageStream(Context context, HttpURLConnection connection) throws IOException {
InputStream stream = null;
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
URL url = connection.getURL();
stream = connection.getInputStream(); // Default stream in case caching fails
if (isCDNURL(url)) {
try {
FileLruCache cache = getCache(context);
// Wrap stream with a caching stream
stream = cache.interceptAndPut(
url.toString(),
new BufferedHttpInputStream(stream, connection));
} catch (IOException e) {
// Caching is best effort
}
}
}
return stream;
}
private static boolean isCDNURL(URL url) {
if (url != null) {
String uriHost = url.getHost();
if (uriHost.endsWith("fbcdn.net")) {
return true;
}
if (uriHost.startsWith("fbcdn") && uriHost.endsWith("akamaihd.net")) {
return true;
}
}
return false;
}
private static class BufferedHttpInputStream extends BufferedInputStream {
HttpURLConnection connection;
BufferedHttpInputStream(InputStream stream, HttpURLConnection connection) {
super(stream, Utility.DEFAULT_STREAM_BUFFER_SIZE);
this.connection = connection;
}
@Override
public void close() throws IOException {
super.close();
Utility.disconnectQuietly(connection);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.os.Handler;
import android.support.v4.content.Loader;
import com.facebook.*;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.internal.CacheableRequestBatch;
class GraphObjectPagingLoader<T extends GraphObject> extends Loader<SimpleGraphObjectCursor<T>> {
private final Class<T> graphObjectClass;
private boolean skipRoundtripIfCached;
private Request originalRequest;
private Request currentRequest;
private Request nextRequest;
private OnErrorListener onErrorListener;
private SimpleGraphObjectCursor<T> cursor;
private boolean appendResults = false;
private boolean loading = false;
public interface OnErrorListener {
public void onError(FacebookException error, GraphObjectPagingLoader<?> loader);
}
public GraphObjectPagingLoader(Context context, Class<T> graphObjectClass) {
super(context);
this.graphObjectClass = graphObjectClass;
}
public OnErrorListener getOnErrorListener() {
return onErrorListener;
}
public void setOnErrorListener(OnErrorListener listener) {
this.onErrorListener = listener;
}
public SimpleGraphObjectCursor<T> getCursor() {
return cursor;
}
public void clearResults() {
nextRequest = null;
originalRequest = null;
currentRequest = null;
deliverResult(null);
}
public boolean isLoading() {
return loading;
}
public void startLoading(Request request, boolean skipRoundtripIfCached) {
originalRequest = request;
startLoading(request, skipRoundtripIfCached, 0);
}
public void refreshOriginalRequest(long afterDelay) {
if (originalRequest == null) {
throw new FacebookException(
"refreshOriginalRequest may not be called until after startLoading has been called.");
}
startLoading(originalRequest, false, afterDelay);
}
public void followNextLink() {
if (nextRequest != null) {
appendResults = true;
currentRequest = nextRequest;
currentRequest.setCallback(new Request.Callback() {
@Override
public void onCompleted(Response response) {
requestCompleted(response);
}
});
loading = true;
CacheableRequestBatch batch = putRequestIntoBatch(currentRequest, skipRoundtripIfCached);
Request.executeBatchAsync(batch);
}
}
@Override
public void deliverResult(SimpleGraphObjectCursor<T> cursor) {
SimpleGraphObjectCursor<T> oldCursor = this.cursor;
this.cursor = cursor;
if (isStarted()) {
super.deliverResult(cursor);
if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
oldCursor.close();
}
}
}
@Override
protected void onStartLoading() {
super.onStartLoading();
if (cursor != null) {
deliverResult(cursor);
}
}
private void startLoading(Request request, boolean skipRoundtripIfCached, long afterDelay) {
this.skipRoundtripIfCached = skipRoundtripIfCached;
appendResults = false;
nextRequest = null;
currentRequest = request;
currentRequest.setCallback(new Request.Callback() {
@Override
public void onCompleted(Response response) {
requestCompleted(response);
}
});
// We are considered loading even if we have a delay.
loading = true;
final RequestBatch batch = putRequestIntoBatch(request, skipRoundtripIfCached);
Runnable r = new Runnable() {
@Override
public void run() {
Request.executeBatchAsync(batch);
}
};
if (afterDelay == 0) {
r.run();
} else {
Handler handler = new Handler();
handler.postDelayed(r, afterDelay);
}
}
private CacheableRequestBatch putRequestIntoBatch(Request request, boolean skipRoundtripIfCached) {
// We just use the request URL as the cache key.
CacheableRequestBatch batch = new CacheableRequestBatch(request);
// We use the default cache key (request URL).
batch.setForceRoundTrip(!skipRoundtripIfCached);
return batch;
}
private void requestCompleted(Response response) {
Request request = response.getRequest();
if (request != currentRequest) {
return;
}
loading = false;
currentRequest = null;
FacebookRequestError requestError = response.getError();
FacebookException exception = (requestError == null) ? null : requestError.getException();
if (response.getGraphObject() == null && exception == null) {
exception = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
}
if (exception != null) {
nextRequest = null;
if (onErrorListener != null) {
onErrorListener.onError(exception, this);
}
} else {
addResults(response);
}
}
private void addResults(Response response) {
SimpleGraphObjectCursor<T> cursorToModify = (cursor == null || !appendResults) ? new SimpleGraphObjectCursor<T>() :
new SimpleGraphObjectCursor<T>(cursor);
PagedResults result = response.getGraphObjectAs(PagedResults.class);
boolean fromCache = response.getIsFromCache();
GraphObjectList<T> data = result.getData().castToListOf(graphObjectClass);
boolean haveData = data.size() > 0;
if (haveData) {
nextRequest = response.getRequestForPagedResults(Response.PagingDirection.NEXT);
cursorToModify.addGraphObjects(data, fromCache);
cursorToModify.setMoreObjectsAvailable(true);
}
if (!haveData) {
cursorToModify.setMoreObjectsAvailable(false);
cursorToModify.setFromCache(fromCache);
nextRequest = null;
}
// Once we get any set of results NOT from the cache, stop trying to get any future ones
// from it.
if (!fromCache) {
skipRoundtripIfCached = false;
}
deliverResult(cursorToModify);
}
interface PagedResults extends GraphObject {
GraphObjectList<GraphObject> getData();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphPlace;
import com.facebook.internal.Logger;
import com.facebook.internal.Utility;
import java.util.*;
public class PlacePickerFragment extends PickerFragment<GraphPlace> {
/**
* The key for an int parameter in the fragment's Intent bundle to indicate the radius in meters around
* the center point to search. The default is 1000 meters.
*/
public static final String RADIUS_IN_METERS_BUNDLE_KEY = "com.facebook.widget.PlacePickerFragment.RadiusInMeters";
/**
* The key for an int parameter in the fragment's Intent bundle to indicate what how many results to
* return at a time. The default is 100 results.
*/
public static final String RESULTS_LIMIT_BUNDLE_KEY = "com.facebook.widget.PlacePickerFragment.ResultsLimit";
/**
* The key for a String parameter in the fragment's Intent bundle to indicate what search text should
* be sent to the service. The default is to have no search text.
*/
public static final String SEARCH_TEXT_BUNDLE_KEY = "com.facebook.widget.PlacePickerFragment.SearchText";
/**
* The key for a Location parameter in the fragment's Intent bundle to indicate what geographical
* location should be the center of the search.
*/
public static final String LOCATION_BUNDLE_KEY = "com.facebook.widget.PlacePickerFragment.Location";
/**
* The key for a boolean parameter in the fragment's Intent bundle to indicate that the fragment
* should display a search box and automatically update the search text as it changes.
*/
public static final String SHOW_SEARCH_BOX_BUNDLE_KEY = "com.facebook.widget.PlacePickerFragment.ShowSearchBox";
/**
* The default radius around the center point to search.
*/
public static final int DEFAULT_RADIUS_IN_METERS = 1000;
/**
* The default number of results to retrieve.
*/
public static final int DEFAULT_RESULTS_LIMIT = 100;
private static final int searchTextTimerDelayInMilliseconds = 2 * 1000;
private static final String ID = "id";
private static final String NAME = "name";
private static final String LOCATION = "location";
private static final String CATEGORY = "category";
private static final String WERE_HERE_COUNT = "were_here_count";
private static final String TAG = "PlacePickerFragment";
private Location location;
private int radiusInMeters = DEFAULT_RADIUS_IN_METERS;
private int resultsLimit = DEFAULT_RESULTS_LIMIT;
private String searchText;
private Timer searchTextTimer;
private boolean hasSearchTextChangedSinceLastQuery;
private boolean showSearchBox = true;
private EditText searchBox;
/**
* Default constructor. Creates a Fragment with all default properties.
*/
public PlacePickerFragment() {
this(null);
}
/**
* Constructor.
*
* @param args a Bundle that optionally contains one or more values containing additional
* configuration information for the Fragment.
*/
public PlacePickerFragment(Bundle args) {
super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, args);
setPlacePickerSettingsFromBundle(args);
}
/**
* Gets the location to search around. Either the location or the search text (or both) must be specified.
*
* @return the Location to search around
*/
public Location getLocation() {
return location;
}
/**
* Sets the location to search around. Either the location or the search text (or both) must be specified.
*
* @param location the Location to search around
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Gets the radius in meters around the location to search.
*
* @return the radius in meters
*/
public int getRadiusInMeters() {
return radiusInMeters;
}
/**
* Sets the radius in meters around the location to search.
*
* @param radiusInMeters the radius in meters
*/
public void setRadiusInMeters(int radiusInMeters) {
this.radiusInMeters = radiusInMeters;
}
/**
* Gets the number of results to retrieve.
*
* @return the number of results to retrieve
*/
public int getResultsLimit() {
return resultsLimit;
}
/**
* Sets the number of results to retrieve.
*
* @param resultsLimit the number of results to retrieve
*/
public void setResultsLimit(int resultsLimit) {
this.resultsLimit = resultsLimit;
}
/**
* Gets the search text (e.g., category, name) to search for. Either the location or the search
* text (or both) must be specified.
*
* @return the search text
*/
public String getSearchText() {
return searchText;
}
/**
* Sets the search text (e.g., category, name) to search for. Either the location or the search
* text (or both) must be specified. If a search box is displayed, this will update its contents
* to the specified text.
*
* @param searchText the search text
*/
public void setSearchText(String searchText) {
if (TextUtils.isEmpty(searchText)) {
searchText = null;
}
this.searchText = searchText;
if (this.searchBox != null) {
this.searchBox.setText(searchText);
}
}
/**
* Sets the search text and reloads the data in the control. This is used to provide search-box
* functionality where the user may be typing or editing text rapidly. It uses a timer to avoid repeated
* requerying, preferring to wait until the user pauses typing to refresh the data. Note that this
* method will NOT update the text in the search box, if any, as it is intended to be called as a result
* of changes to the search box (and is public to enable applications to provide their own search box
* UI instead of the default one).
*
* @param searchText the search text
* @param forceReloadEventIfSameText if true, will reload even if the search text has not changed; if false,
* identical search text will not force a reload
*/
public void onSearchBoxTextChanged(String searchText, boolean forceReloadEventIfSameText) {
if (!forceReloadEventIfSameText && Utility.stringsEqualOrEmpty(this.searchText, searchText)) {
return;
}
if (TextUtils.isEmpty(searchText)) {
searchText = null;
}
this.searchText = searchText;
// If search text is being set in response to user input, it is wasteful to send a new request
// with every keystroke. Send a request the first time the search text is set, then set up a 2-second timer
// and send whatever changes the user has made since then. (If nothing has changed
// in 2 seconds, we reset so the next change will cause an immediate re-query.)
hasSearchTextChangedSinceLastQuery = true;
if (searchTextTimer == null) {
searchTextTimer = createSearchTextTimer();
}
}
/**
* Gets the currently-selected place.
*
* @return the currently-selected place, or null if there is none
*/
public GraphPlace getSelection() {
Collection<GraphPlace> selection = getSelectedGraphObjects();
return (selection != null && selection.size() > 0) ? selection.iterator().next() : null;
}
public void setSettingsFromBundle(Bundle inState) {
super.setSettingsFromBundle(inState);
setPlacePickerSettingsFromBundle(inState);
}
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.com_facebook_place_picker_fragment);
setRadiusInMeters(a.getInt(R.styleable.com_facebook_place_picker_fragment_radius_in_meters, radiusInMeters));
setResultsLimit(a.getInt(R.styleable.com_facebook_place_picker_fragment_results_limit, resultsLimit));
if (a.hasValue(R.styleable.com_facebook_place_picker_fragment_results_limit)) {
setSearchText(a.getString(R.styleable.com_facebook_place_picker_fragment_search_text));
}
showSearchBox = a.getBoolean(R.styleable.com_facebook_place_picker_fragment_show_search_box, showSearchBox);
a.recycle();
}
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ViewGroup view = (ViewGroup) getView();
if (showSearchBox) {
ViewStub stub = (ViewStub) view.findViewById(R.id.com_facebook_placepickerfragment_search_box_stub);
if (stub != null) {
searchBox = (EditText) stub.inflate();
// Put the list under the search box
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
layoutParams.addRule(RelativeLayout.BELOW, R.id.search_box);
ListView listView = (ListView) view.findViewById(R.id.com_facebook_picker_list_view);
listView.setLayoutParams(layoutParams);
// If we need to, put the search box under the title bar.
if (view.findViewById(R.id.com_facebook_picker_title_bar) != null) {
layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, R.id.com_facebook_picker_title_bar);
searchBox.setLayoutParams(layoutParams);
}
searchBox.addTextChangedListener(new SearchTextWatcher());
if (!TextUtils.isEmpty(searchText)) {
searchBox.setText(searchText);
}
}
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (searchBox != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
}
}
@Override
public void onDetach() {
super.onDetach();
if (searchBox != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchBox.getWindowToken(), 0);
}
}
void saveSettingsToBundle(Bundle outState) {
super.saveSettingsToBundle(outState);
outState.putInt(RADIUS_IN_METERS_BUNDLE_KEY, radiusInMeters);
outState.putInt(RESULTS_LIMIT_BUNDLE_KEY, resultsLimit);
outState.putString(SEARCH_TEXT_BUNDLE_KEY, searchText);
outState.putParcelable(LOCATION_BUNDLE_KEY, location);
outState.putBoolean(SHOW_SEARCH_BOX_BUNDLE_KEY, showSearchBox);
}
@Override
void onLoadingData() {
hasSearchTextChangedSinceLastQuery = false;
}
@Override
Request getRequestForLoadData(Session session) {
return createRequest(location, radiusInMeters, resultsLimit, searchText, extraFields, session);
}
@Override
String getDefaultTitleText() {
return getString(R.string.com_facebook_nearby);
}
@Override
PickerFragmentAdapter<GraphPlace> createAdapter() {
PickerFragmentAdapter<GraphPlace> adapter = new PickerFragmentAdapter<GraphPlace>(
this.getActivity()) {
@Override
protected CharSequence getSubTitleOfGraphObject(GraphPlace graphObject) {
String category = graphObject.getCategory();
Integer wereHereCount = (Integer) graphObject.getProperty(WERE_HERE_COUNT);
String result = null;
if (category != null && wereHereCount != null) {
result = getString(R.string.com_facebook_placepicker_subtitle_format, category, wereHereCount);
} else if (category == null && wereHereCount != null) {
result = getString(R.string.com_facebook_placepicker_subtitle_were_here_only_format, wereHereCount);
} else if (category != null && wereHereCount == null) {
result = getString(R.string.com_facebook_placepicker_subtitle_catetory_only_format, category);
}
return result;
}
@Override
protected int getGraphObjectRowLayoutId(GraphPlace graphObject) {
return R.layout.com_facebook_placepickerfragment_list_row;
}
@Override
protected int getDefaultPicture() {
return R.drawable.com_facebook_place_default_icon;
}
};
adapter.setShowCheckbox(false);
adapter.setShowPicture(getShowPictures());
return adapter;
}
@Override
LoadingStrategy createLoadingStrategy() {
return new AsNeededLoadingStrategy();
}
@Override
SelectionStrategy createSelectionStrategy() {
return new SingleSelectionStrategy();
}
private Request createRequest(Location location, int radiusInMeters, int resultsLimit, String searchText,
Set<String> extraFields,
Session session) {
Request request = Request.newPlacesSearchRequest(session, location, radiusInMeters, resultsLimit, searchText,
null);
Set<String> fields = new HashSet<String>(extraFields);
String[] requiredFields = new String[]{
ID,
NAME,
LOCATION,
CATEGORY,
WERE_HERE_COUNT
};
fields.addAll(Arrays.asList(requiredFields));
String pictureField = adapter.getPictureFieldSpecifier();
if (pictureField != null) {
fields.add(pictureField);
}
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
private void setPlacePickerSettingsFromBundle(Bundle inState) {
// We do this in a separate non-overridable method so it is safe to call from the constructor.
if (inState != null) {
setRadiusInMeters(inState.getInt(RADIUS_IN_METERS_BUNDLE_KEY, radiusInMeters));
setResultsLimit(inState.getInt(RESULTS_LIMIT_BUNDLE_KEY, resultsLimit));
if (inState.containsKey(SEARCH_TEXT_BUNDLE_KEY)) {
setSearchText(inState.getString(SEARCH_TEXT_BUNDLE_KEY));
}
if (inState.containsKey(LOCATION_BUNDLE_KEY)) {
Location location = inState.getParcelable(LOCATION_BUNDLE_KEY);
setLocation(location);
}
showSearchBox = inState.getBoolean(SHOW_SEARCH_BOX_BUNDLE_KEY, showSearchBox);
}
}
private Timer createSearchTextTimer() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
onSearchTextTimerTriggered();
}
}, 0, searchTextTimerDelayInMilliseconds);
return timer;
}
private void onSearchTextTimerTriggered() {
if (hasSearchTextChangedSinceLastQuery) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
FacebookException error = null;
try {
loadData(true);
} catch (FacebookException fe) {
error = fe;
} catch (Exception e) {
error = new FacebookException(e);
} finally {
if (error != null) {
OnErrorListener onErrorListener = getOnErrorListener();
if (onErrorListener != null) {
onErrorListener.onError(PlacePickerFragment.this, error);
} else {
Logger.log(LoggingBehavior.REQUESTS, TAG, "Error loading data : %s", error);
}
}
}
}
});
} else {
// Nothing has changed in 2 seconds. Invalidate and forget about this timer.
// Next time the user types, we will fire a query immediately again.
searchTextTimer.cancel();
searchTextTimer = null;
}
}
private class AsNeededLoadingStrategy extends LoadingStrategy {
@Override
public void attach(GraphObjectAdapter<GraphPlace> adapter) {
super.attach(adapter);
this.adapter.setDataNeededListener(new GraphObjectAdapter.DataNeededListener() {
@Override
public void onDataNeeded() {
// Do nothing if we are currently loading data . We will get notified again when that load finishes if the adapter still
// needs more data. Otherwise, follow the next link.
if (!loader.isLoading()) {
loader.followNextLink();
}
}
});
}
@Override
protected void onLoadFinished(GraphObjectPagingLoader<GraphPlace> loader,
SimpleGraphObjectCursor<GraphPlace> data) {
super.onLoadFinished(loader, data);
// We could be called in this state if we are clearing data or if we are being re-attached
// in the middle of a query.
if (data == null || loader.isLoading()) {
return;
}
hideActivityCircle();
if (data.isFromCache()) {
// Only the first page can be cached, since all subsequent pages will be round-tripped. Force
// a refresh of the first page before we allow paging to begin. If the first page produced
// no data, launch the refresh immediately, otherwise schedule it for later.
loader.refreshOriginalRequest(data.areMoreObjectsAvailable() ? CACHED_RESULT_REFRESH_DELAY : 0);
}
}
}
private class SearchTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
onSearchBoxTextChanged(s.toString(), false);
}
@Override
public void afterTextChanged(Editable s) {
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.AlphaAnimation;
import android.widget.*;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphObject;
import com.facebook.internal.SessionTracker;
import java.util.*;
/**
* Provides functionality common to SDK UI elements that allow the user to pick one or more
* graph objects (e.g., places, friends) from a list of possibilities. The UI is exposed as a
* Fragment to allow to it to be included in an Activity along with other Fragments. The Fragments
* can be configured by passing parameters as part of their Intent bundle, or (for certain
* properties) by specifying attributes in their XML layout files.
* <br/>
* PickerFragments support callbacks that will be called in the event of an error, when the
* underlying data has been changed, or when the set of selected graph objects changes.
*/
public abstract class PickerFragment<T extends GraphObject> extends Fragment {
/**
* The key for a boolean parameter in the fragment's Intent bundle to indicate whether the
* picker should show pictures (if available) for the graph objects.
*/
public static final String SHOW_PICTURES_BUNDLE_KEY = "com.facebook.widget.PickerFragment.ShowPictures";
/**
* The key for a String parameter in the fragment's Intent bundle to indicate which extra fields
* beyond the default fields should be retrieved for any graph objects in the results.
*/
public static final String EXTRA_FIELDS_BUNDLE_KEY = "com.facebook.widget.PickerFragment.ExtraFields";
/**
* The key for a boolean parameter in the fragment's Intent bundle to indicate whether the
* picker should display a title bar with a Done button.
*/
public static final String SHOW_TITLE_BAR_BUNDLE_KEY = "com.facebook.widget.PickerFragment.ShowTitleBar";
/**
* The key for a String parameter in the fragment's Intent bundle to indicate the text to
* display in the title bar.
*/
public static final String TITLE_TEXT_BUNDLE_KEY = "com.facebook.widget.PickerFragment.TitleText";
/**
* The key for a String parameter in the fragment's Intent bundle to indicate the text to
* display in the Done btuton.
*/
public static final String DONE_BUTTON_TEXT_BUNDLE_KEY = "com.facebook.widget.PickerFragment.DoneButtonText";
private static final String SELECTION_BUNDLE_KEY = "com.facebook.android.PickerFragment.Selection";
private static final String ACTIVITY_CIRCLE_SHOW_KEY = "com.facebook.android.PickerFragment.ActivityCircleShown";
private static final int PROFILE_PICTURE_PREFETCH_BUFFER = 5;
private final int layout;
private OnErrorListener onErrorListener;
private OnDataChangedListener onDataChangedListener;
private OnSelectionChangedListener onSelectionChangedListener;
private OnDoneButtonClickedListener onDoneButtonClickedListener;
private GraphObjectFilter<T> filter;
private boolean showPictures = true;
private boolean showTitleBar = true;
private ListView listView;
HashSet<String> extraFields = new HashSet<String>();
GraphObjectAdapter<T> adapter;
private final Class<T> graphObjectClass;
private LoadingStrategy loadingStrategy;
private SelectionStrategy selectionStrategy;
private ProgressBar activityCircle;
private SessionTracker sessionTracker;
private String titleText;
private String doneButtonText;
private TextView titleTextView;
private Button doneButton;
private Drawable titleBarBackground;
private Drawable doneButtonBackground;
PickerFragment(Class<T> graphObjectClass, int layout, Bundle args) {
this.graphObjectClass = graphObjectClass;
this.layout = layout;
setPickerFragmentSettingsFromBundle(args);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = createAdapter();
adapter.setFilter(new GraphObjectAdapter.Filter<T>() {
@Override
public boolean includeItem(T graphObject) {
return filterIncludesItem(graphObject);
}
});
}
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.com_facebook_picker_fragment);
setShowPictures(a.getBoolean(R.styleable.com_facebook_picker_fragment_show_pictures, showPictures));
String extraFieldsString = a.getString(R.styleable.com_facebook_picker_fragment_extra_fields);
if (extraFieldsString != null) {
String[] strings = extraFieldsString.split(",");
setExtraFields(Arrays.asList(strings));
}
showTitleBar = a.getBoolean(R.styleable.com_facebook_picker_fragment_show_title_bar, showTitleBar);
titleText = a.getString(R.styleable.com_facebook_picker_fragment_title_text);
doneButtonText = a.getString(R.styleable.com_facebook_picker_fragment_done_button_text);
titleBarBackground = a.getDrawable(R.styleable.com_facebook_picker_fragment_title_bar_background);
doneButtonBackground = a.getDrawable(R.styleable.com_facebook_picker_fragment_done_button_background);
a.recycle();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup view = (ViewGroup) inflater.inflate(layout, container, false);
listView = (ListView) view.findViewById(R.id.com_facebook_picker_list_view);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
onListItemClick((ListView) parent, v, position);
}
});
listView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// We don't actually do anything differently on long-clicks, but setting the listener
// enables the selector transition that we have for visual consistency with the
// Facebook app's pickers.
return false;
}
});
listView.setOnScrollListener(onScrollListener);
listView.setAdapter(adapter);
activityCircle = (ProgressBar) view.findViewById(R.id.com_facebook_picker_activity_circle);
return view;
}
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sessionTracker = new SessionTracker(getActivity(), new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (!session.isOpened()) {
// When a session is closed, we want to clear out our data so it is not visible to subsequent users
clearResults();
}
}
});
setSettingsFromBundle(savedInstanceState);
loadingStrategy = createLoadingStrategy();
loadingStrategy.attach(adapter);
selectionStrategy = createSelectionStrategy();
selectionStrategy.readSelectionFromBundle(savedInstanceState, SELECTION_BUNDLE_KEY);
// Should we display a title bar? (We need to do this after we've retrieved our bundle settings.)
if (showTitleBar) {
inflateTitleBar((ViewGroup) getView());
}
if (activityCircle != null && savedInstanceState != null) {
boolean shown = savedInstanceState.getBoolean(ACTIVITY_CIRCLE_SHOW_KEY, false);
if (shown) {
displayActivityCircle();
} else {
// Should be hidden already, but just to be sure.
hideActivityCircle();
}
}
}
@Override
public void onDetach() {
super.onDetach();
listView.setOnScrollListener(null);
listView.setAdapter(null);
loadingStrategy.detach();
sessionTracker.stopTracking();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveSettingsToBundle(outState);
selectionStrategy.saveSelectionToBundle(outState, SELECTION_BUNDLE_KEY);
if (activityCircle != null) {
outState.putBoolean(ACTIVITY_CIRCLE_SHOW_KEY, activityCircle.getVisibility() == View.VISIBLE);
}
}
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
setSettingsFromBundle(args);
}
/**
* Gets the current OnDataChangedListener for this fragment, which will be called whenever
* the underlying data being displaying in the picker has changed.
*
* @return the OnDataChangedListener, or null if there is none
*/
public OnDataChangedListener getOnDataChangedListener() {
return onDataChangedListener;
}
/**
* Sets the current OnDataChangedListener for this fragment, which will be called whenever
* the underlying data being displaying in the picker has changed.
*
* @param onDataChangedListener the OnDataChangedListener, or null if there is none
*/
public void setOnDataChangedListener(OnDataChangedListener onDataChangedListener) {
this.onDataChangedListener = onDataChangedListener;
}
/**
* Gets the current OnSelectionChangedListener for this fragment, which will be called
* whenever the user selects or unselects a graph object in the list.
*
* @return the OnSelectionChangedListener, or null if there is none
*/
public OnSelectionChangedListener getOnSelectionChangedListener() {
return onSelectionChangedListener;
}
/**
* Sets the current OnSelectionChangedListener for this fragment, which will be called
* whenever the user selects or unselects a graph object in the list.
*
* @param onSelectionChangedListener the OnSelectionChangedListener, or null if there is none
*/
public void setOnSelectionChangedListener(
OnSelectionChangedListener onSelectionChangedListener) {
this.onSelectionChangedListener = onSelectionChangedListener;
}
/**
* Gets the current OnDoneButtonClickedListener for this fragment, which will be called
* when the user clicks the Done button.
*
* @return the OnDoneButtonClickedListener, or null if there is none
*/
public OnDoneButtonClickedListener getOnDoneButtonClickedListener() {
return onDoneButtonClickedListener;
}
/**
* Sets the current OnDoneButtonClickedListener for this fragment, which will be called
* when the user clicks the Done button. This will only be possible if the title bar is
* being shown in this fragment.
*
* @param onDoneButtonClickedListener the OnDoneButtonClickedListener, or null if there is none
*/
public void setOnDoneButtonClickedListener(OnDoneButtonClickedListener onDoneButtonClickedListener) {
this.onDoneButtonClickedListener = onDoneButtonClickedListener;
}
/**
* Gets the current OnErrorListener for this fragment, which will be called in the event
* of network or other errors encountered while populating the graph objects in the list.
*
* @return the OnErrorListener, or null if there is none
*/
public OnErrorListener getOnErrorListener() {
return onErrorListener;
}
/**
* Sets the current OnErrorListener for this fragment, which will be called in the event
* of network or other errors encountered while populating the graph objects in the list.
*
* @param onErrorListener the OnErrorListener, or null if there is none
*/
public void setOnErrorListener(OnErrorListener onErrorListener) {
this.onErrorListener = onErrorListener;
}
/**
* Gets the current filter for this fragment, which will be called for each graph object
* returned from the service to determine if it should be displayed in the list.
* If no filter is specified, all retrieved graph objects will be displayed.
*
* @return the GraphObjectFilter, or null if there is none
*/
public GraphObjectFilter<T> getFilter() {
return filter;
}
/**
* Sets the current filter for this fragment, which will be called for each graph object
* returned from the service to determine if it should be displayed in the list.
* If no filter is specified, all retrieved graph objects will be displayed.
*
* @param filter the GraphObjectFilter, or null if there is none
*/
public void setFilter(GraphObjectFilter<T> filter) {
this.filter = filter;
}
/**
* Gets the Session to use for any Facebook requests this fragment will make.
*
* @return the Session that will be used for any Facebook requests, or null if there is none
*/
public Session getSession() {
return sessionTracker.getSession();
}
/**
* Sets the Session to use for any Facebook requests this fragment will make. If the
* parameter is null, the fragment will use the current active session, if any.
*
* @param session the Session to use for Facebook requests, or null to use the active session
*/
public void setSession(Session session) {
sessionTracker.setSession(session);
}
/**
* Gets whether to display pictures, if available, for displayed graph objects.
*
* @return true if pictures should be displayed, false if not
*/
public boolean getShowPictures() {
return showPictures;
}
/**
* Sets whether to display pictures, if available, for displayed graph objects.
*
* @param showPictures true if pictures should be displayed, false if not
*/
public void setShowPictures(boolean showPictures) {
this.showPictures = showPictures;
}
/**
* Gets the extra fields to request for the retrieved graph objects.
*
* @return the extra fields to request
*/
public Set<String> getExtraFields() {
return new HashSet<String>(extraFields);
}
/**
* Sets the extra fields to request for the retrieved graph objects.
*
* @param fields the extra fields to request
*/
public void setExtraFields(Collection<String> fields) {
extraFields = new HashSet<String>();
if (fields != null) {
extraFields.addAll(fields);
}
}
/**
* Sets whether to show a title bar with a Done button. This must be
* called prior to the Fragment going through its creation lifecycle to have an effect.
*
* @param showTitleBar true if a title bar should be displayed, false if not
*/
public void setShowTitleBar(boolean showTitleBar) {
this.showTitleBar = showTitleBar;
}
/**
* Gets whether to show a title bar with a Done button. The default is true.
*
* @return true if a title bar will be shown, false if not.
*/
public boolean getShowTitleBar() {
return showTitleBar;
}
/**
* Sets the text to show in the title bar, if a title bar is to be shown. This must be
* called prior to the Fragment going through its creation lifecycle to have an effect, or
* the default will be used.
*
* @param titleText the text to show in the title bar
*/
public void setTitleText(String titleText) {
this.titleText = titleText;
}
/**
* Gets the text to show in the title bar, if a title bar is to be shown.
*
* @return the text to show in the title bar
*/
public String getTitleText() {
if (titleText == null) {
titleText = getDefaultTitleText();
}
return titleText;
}
/**
* Sets the text to show in the Done button, if a title bar is to be shown. This must be
* called prior to the Fragment going through its creation lifecycle to have an effect, or
* the default will be used.
*
* @param doneButtonText the text to show in the Done button
*/
public void setDoneButtonText(String doneButtonText) {
this.doneButtonText = doneButtonText;
}
/**
* Gets the text to show in the Done button, if a title bar is to be shown.
*
* @return the text to show in the Done button
*/
public String getDoneButtonText() {
if (doneButtonText == null) {
doneButtonText = getDefaultDoneButtonText();
}
return doneButtonText;
}
/**
* Causes the picker to load data from the service and display it to the user.
*
* @param forceReload if true, data will be loaded even if there is already data being displayed (or loading);
* if false, data will not be re-loaded if it is already displayed (or loading)
*/
public void loadData(boolean forceReload) {
if (!forceReload && loadingStrategy.isDataPresentOrLoading()) {
return;
}
loadDataSkippingRoundTripIfCached();
}
/**
* Updates the properties of the PickerFragment based on the contents of the supplied Bundle;
* calling Activities may use this to pass additional configuration information to the
* PickerFragment beyond what is specified in its XML layout.
*
* @param inState a Bundle containing keys corresponding to properties of the PickerFragment
*/
public void setSettingsFromBundle(Bundle inState) {
setPickerFragmentSettingsFromBundle(inState);
}
boolean filterIncludesItem(T graphObject) {
if (filter != null) {
return filter.includeItem(graphObject);
}
return true;
}
List<T> getSelectedGraphObjects() {
return adapter.getGraphObjectsById(selectionStrategy.getSelectedIds());
}
void saveSettingsToBundle(Bundle outState) {
outState.putBoolean(SHOW_PICTURES_BUNDLE_KEY, showPictures);
if (!extraFields.isEmpty()) {
outState.putString(EXTRA_FIELDS_BUNDLE_KEY, TextUtils.join(",", extraFields));
}
outState.putBoolean(SHOW_TITLE_BAR_BUNDLE_KEY, showTitleBar);
outState.putString(TITLE_TEXT_BUNDLE_KEY, titleText);
outState.putString(DONE_BUTTON_TEXT_BUNDLE_KEY, doneButtonText);
}
abstract Request getRequestForLoadData(Session session);
abstract PickerFragmentAdapter<T> createAdapter();
abstract LoadingStrategy createLoadingStrategy();
abstract SelectionStrategy createSelectionStrategy();
void onLoadingData() {
}
String getDefaultTitleText() {
return null;
}
String getDefaultDoneButtonText() {
return getString(R.string.com_facebook_picker_done_button_text);
}
void displayActivityCircle() {
if (activityCircle != null) {
layoutActivityCircle();
activityCircle.setVisibility(View.VISIBLE);
}
}
void layoutActivityCircle() {
// If we've got no data, make the activity circle full-opacity. Otherwise we'll dim it to avoid
// cluttering the UI.
float alpha = (!adapter.isEmpty()) ? .25f : 1.0f;
setAlpha(activityCircle, alpha);
}
void hideActivityCircle() {
if (activityCircle != null) {
// We use an animation to dim the activity circle; need to clear this or it will remain visible.
activityCircle.clearAnimation();
activityCircle.setVisibility(View.INVISIBLE);
}
}
void setSelectionStrategy(SelectionStrategy selectionStrategy) {
if (selectionStrategy != this.selectionStrategy) {
this.selectionStrategy = selectionStrategy;
if (adapter != null) {
// Adapter should cause a re-render.
adapter.notifyDataSetChanged();
}
}
}
private static void setAlpha(View view, float alpha) {
// Set the alpha appropriately (setAlpha is API >= 11, this technique works on all API levels).
AlphaAnimation alphaAnimation = new AlphaAnimation(alpha, alpha);
alphaAnimation.setDuration(0);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
}
private void setPickerFragmentSettingsFromBundle(Bundle inState) {
// We do this in a separate non-overridable method so it is safe to call from the constructor.
if (inState != null) {
showPictures = inState.getBoolean(SHOW_PICTURES_BUNDLE_KEY, showPictures);
String extraFieldsString = inState.getString(EXTRA_FIELDS_BUNDLE_KEY);
if (extraFieldsString != null) {
String[] strings = extraFieldsString.split(",");
setExtraFields(Arrays.asList(strings));
}
showTitleBar = inState.getBoolean(SHOW_TITLE_BAR_BUNDLE_KEY, showTitleBar);
String titleTextString = inState.getString(TITLE_TEXT_BUNDLE_KEY);
if (titleTextString != null) {
titleText = titleTextString;
if (titleTextView != null) {
titleTextView.setText(titleText);
}
}
String doneButtonTextString = inState.getString(DONE_BUTTON_TEXT_BUNDLE_KEY);
if (doneButtonTextString != null) {
doneButtonText = doneButtonTextString;
if (doneButton != null) {
doneButton.setText(doneButtonText);
}
}
}
}
private void inflateTitleBar(ViewGroup view) {
ViewStub stub = (ViewStub) view.findViewById(R.id.com_facebook_picker_title_bar_stub);
if (stub != null) {
View titleBar = stub.inflate();
final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
layoutParams.addRule(RelativeLayout.BELOW, R.id.com_facebook_picker_title_bar);
listView.setLayoutParams(layoutParams);
if (titleBarBackground != null) {
titleBar.setBackgroundDrawable(titleBarBackground);
}
doneButton = (Button) view.findViewById(R.id.com_facebook_picker_done_button);
if (doneButton != null) {
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onDoneButtonClickedListener != null) {
onDoneButtonClickedListener.onDoneButtonClicked(PickerFragment.this);
}
}
});
if (getDoneButtonText() != null) {
doneButton.setText(getDoneButtonText());
}
if (doneButtonBackground != null) {
doneButton.setBackgroundDrawable(doneButtonBackground);
}
}
titleTextView = (TextView) view.findViewById(R.id.com_facebook_picker_title);
if (titleTextView != null) {
if (getTitleText() != null) {
titleTextView.setText(getTitleText());
}
}
}
}
private void onListItemClick(ListView listView, View v, int position) {
@SuppressWarnings("unchecked")
T graphObject = (T) listView.getItemAtPosition(position);
String id = adapter.getIdOfGraphObject(graphObject);
selectionStrategy.toggleSelection(id);
adapter.notifyDataSetChanged();
if (onSelectionChangedListener != null) {
onSelectionChangedListener.onSelectionChanged(PickerFragment.this);
}
}
private void loadDataSkippingRoundTripIfCached() {
clearResults();
Request request = getRequestForLoadData(getSession());
if (request != null) {
onLoadingData();
loadingStrategy.startLoading(request);
}
}
private void clearResults() {
if (adapter != null) {
boolean wasSelection = !selectionStrategy.isEmpty();
boolean wasData = !adapter.isEmpty();
loadingStrategy.clearResults();
selectionStrategy.clear();
adapter.notifyDataSetChanged();
// Tell anyone who cares the data and selection has changed, if they have.
if (wasData && onDataChangedListener != null) {
onDataChangedListener.onDataChanged(PickerFragment.this);
}
if (wasSelection && onSelectionChangedListener != null) {
onSelectionChangedListener.onSelectionChanged(PickerFragment.this);
}
}
}
void updateAdapter(SimpleGraphObjectCursor<T> data) {
if (adapter != null) {
// As we fetch additional results and add them to the table, we do not
// want the items displayed jumping around seemingly at random, frustrating the user's
// attempts at scrolling, etc. Since results may be added anywhere in
// the table, we choose to try to keep the first visible row in a fixed
// position (from the user's perspective). We try to keep it positioned at
// the same offset from the top of the screen so adding new items seems
// smoother, as opposed to having it "snap" to a multiple of row height
// We use the second row, to give context above and below it and avoid
// cases where the first row is only barely visible, thus providing little context.
// The exception is where the very first row is visible, in which case we use that.
View view = listView.getChildAt(1);
int anchorPosition = listView.getFirstVisiblePosition();
if (anchorPosition > 0) {
anchorPosition++;
}
GraphObjectAdapter.SectionAndItem<T> anchorItem = adapter.getSectionAndItem(anchorPosition);
final int top = (view != null &&
anchorItem.getType() != GraphObjectAdapter.SectionAndItem.Type.ACTIVITY_CIRCLE) ?
view.getTop() : 0;
// Now actually add the results.
boolean dataChanged = adapter.changeCursor(data);
if (view != null && anchorItem != null) {
// Put the item back in the same spot it was.
final int newPositionOfItem = adapter.getPosition(anchorItem.sectionKey, anchorItem.graphObject);
if (newPositionOfItem != -1) {
listView.setSelectionFromTop(newPositionOfItem, top);
}
}
if (dataChanged && onDataChangedListener != null) {
onDataChangedListener.onDataChanged(PickerFragment.this);
}
}
}
private void reprioritizeDownloads() {
int lastVisibleItem = listView.getLastVisiblePosition();
if (lastVisibleItem >= 0) {
int firstVisibleItem = listView.getFirstVisiblePosition();
adapter.prioritizeViewRange(firstVisibleItem, lastVisibleItem, PROFILE_PICTURE_PREFETCH_BUFFER);
}
}
private ListView.OnScrollListener onScrollListener = new ListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
reprioritizeDownloads();
}
};
/**
* Callback interface that will be called when a network or other error is encountered
* while retrieving graph objects.
*/
public interface OnErrorListener {
/**
* Called when a network or other error is encountered.
*
* @param error a FacebookException representing the error that was encountered.
*/
void onError(PickerFragment<?> fragment, FacebookException error);
}
/**
* Callback interface that will be called when the underlying data being displayed in the
* picker has been updated.
*/
public interface OnDataChangedListener {
/**
* Called when the set of data being displayed in the picker has changed.
*/
void onDataChanged(PickerFragment<?> fragment);
}
/**
* Callback interface that will be called when the user selects or unselects graph objects
* in the picker.
*/
public interface OnSelectionChangedListener {
/**
* Called when the user selects or unselects graph objects in the picker.
*/
void onSelectionChanged(PickerFragment<?> fragment);
}
/**
* Callback interface that will be called when the user clicks the Done button on the
* title bar.
*/
public interface OnDoneButtonClickedListener {
/**
* Called when the user clicks the Done button.
*/
void onDoneButtonClicked(PickerFragment<?> fragment);
}
/**
* Callback interface that will be called to determine if a graph object should be displayed.
*
* @param <T>
*/
public interface GraphObjectFilter<T> {
/**
* Called to determine if a graph object should be displayed.
*
* @param graphObject the graph object
* @return true to display the graph object, false to hide it
*/
boolean includeItem(T graphObject);
}
abstract class LoadingStrategy {
protected final static int CACHED_RESULT_REFRESH_DELAY = 2 * 1000;
protected GraphObjectPagingLoader<T> loader;
protected GraphObjectAdapter<T> adapter;
public void attach(GraphObjectAdapter<T> adapter) {
loader = (GraphObjectPagingLoader<T>) getLoaderManager().initLoader(0, null,
new LoaderManager.LoaderCallbacks<SimpleGraphObjectCursor<T>>() {
@Override
public Loader<SimpleGraphObjectCursor<T>> onCreateLoader(int id, Bundle args) {
return LoadingStrategy.this.onCreateLoader();
}
@Override
public void onLoadFinished(Loader<SimpleGraphObjectCursor<T>> loader,
SimpleGraphObjectCursor<T> data) {
if (loader != LoadingStrategy.this.loader) {
throw new FacebookException("Received callback for unknown loader.");
}
LoadingStrategy.this.onLoadFinished((GraphObjectPagingLoader<T>) loader, data);
}
@Override
public void onLoaderReset(Loader<SimpleGraphObjectCursor<T>> loader) {
if (loader != LoadingStrategy.this.loader) {
throw new FacebookException("Received callback for unknown loader.");
}
LoadingStrategy.this.onLoadReset((GraphObjectPagingLoader<T>) loader);
}
});
loader.setOnErrorListener(new GraphObjectPagingLoader.OnErrorListener() {
@Override
public void onError(FacebookException error, GraphObjectPagingLoader<?> loader) {
hideActivityCircle();
if (onErrorListener != null) {
onErrorListener.onError(PickerFragment.this, error);
}
}
});
this.adapter = adapter;
// Tell the adapter about any data we might already have.
this.adapter.changeCursor(loader.getCursor());
this.adapter.setOnErrorListener(new GraphObjectAdapter.OnErrorListener() {
@Override
public void onError(GraphObjectAdapter<?> adapter, FacebookException error) {
if (onErrorListener != null) {
onErrorListener.onError(PickerFragment.this, error);
}
}
});
}
public void detach() {
adapter.setDataNeededListener(null);
adapter.setOnErrorListener(null);
loader.setOnErrorListener(null);
loader = null;
adapter = null;
}
public void clearResults() {
if (loader != null) {
loader.clearResults();
}
}
public void startLoading(Request request) {
if (loader != null) {
loader.startLoading(request, true);
onStartLoading(loader, request);
}
}
public boolean isDataPresentOrLoading() {
return !adapter.isEmpty() || loader.isLoading();
}
protected GraphObjectPagingLoader<T> onCreateLoader() {
return new GraphObjectPagingLoader<T>(getActivity(), graphObjectClass);
}
protected void onStartLoading(GraphObjectPagingLoader<T> loader, Request request) {
displayActivityCircle();
}
protected void onLoadReset(GraphObjectPagingLoader<T> loader) {
adapter.changeCursor(null);
}
protected void onLoadFinished(GraphObjectPagingLoader<T> loader, SimpleGraphObjectCursor<T> data) {
updateAdapter(data);
}
}
abstract class SelectionStrategy {
abstract boolean isSelected(String id);
abstract void toggleSelection(String id);
abstract Collection<String> getSelectedIds();
abstract void clear();
abstract boolean isEmpty();
abstract boolean shouldShowCheckBoxIfUnselected();
abstract void saveSelectionToBundle(Bundle outBundle, String key);
abstract void readSelectionFromBundle(Bundle inBundle, String key);
}
class SingleSelectionStrategy extends SelectionStrategy {
private String selectedId;
public Collection<String> getSelectedIds() {
return Arrays.asList(new String[]{selectedId});
}
@Override
boolean isSelected(String id) {
return selectedId != null && id != null && selectedId.equals(id);
}
@Override
void toggleSelection(String id) {
if (selectedId != null && selectedId.equals(id)) {
selectedId = null;
} else {
selectedId = id;
}
}
@Override
void saveSelectionToBundle(Bundle outBundle, String key) {
if (!TextUtils.isEmpty(selectedId)) {
outBundle.putString(key, selectedId);
}
}
@Override
void readSelectionFromBundle(Bundle inBundle, String key) {
if (inBundle != null) {
selectedId = inBundle.getString(key);
}
}
@Override
public void clear() {
selectedId = null;
}
@Override
boolean isEmpty() {
return selectedId == null;
}
@Override
boolean shouldShowCheckBoxIfUnselected() {
return false;
}
}
class MultiSelectionStrategy extends SelectionStrategy {
private Set<String> selectedIds = new HashSet<String>();
public Collection<String> getSelectedIds() {
return selectedIds;
}
@Override
boolean isSelected(String id) {
return id != null && selectedIds.contains(id);
}
@Override
void toggleSelection(String id) {
if (id != null) {
if (selectedIds.contains(id)) {
selectedIds.remove(id);
} else {
selectedIds.add(id);
}
}
}
@Override
void saveSelectionToBundle(Bundle outBundle, String key) {
if (!selectedIds.isEmpty()) {
String ids = TextUtils.join(",", selectedIds);
outBundle.putString(key, ids);
}
}
@Override
void readSelectionFromBundle(Bundle inBundle, String key) {
if (inBundle != null) {
String ids = inBundle.getString(key);
if (ids != null) {
String[] splitIds = TextUtils.split(ids, ",");
selectedIds.clear();
Collections.addAll(selectedIds, splitIds);
}
}
}
@Override
public void clear() {
selectedIds.clear();
}
@Override
boolean isEmpty() {
return selectedIds.isEmpty();
}
@Override
boolean shouldShowCheckBoxIfUnselected() {
return true;
}
}
abstract class PickerFragmentAdapter<U extends GraphObject> extends GraphObjectAdapter<T> {
public PickerFragmentAdapter(Context context) {
super(context);
}
@Override
boolean isGraphObjectSelected(String graphObjectId) {
return selectionStrategy.isSelected(graphObjectId);
}
@Override
void updateCheckboxState(CheckBox checkBox, boolean graphObjectSelected) {
checkBox.setChecked(graphObjectSelected);
int visible = (graphObjectSelected || selectionStrategy
.shouldShowCheckBoxIfUnselected()) ? View.VISIBLE : View.GONE;
checkBox.setVisibility(visible);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.facebook.*;
import com.facebook.android.*;
import com.facebook.internal.Logger;
import com.facebook.internal.ServerProtocol;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
/**
* This class provides a mechanism for displaying Facebook Web dialogs inside a Dialog. Helper
* methods are provided to construct commonly-used dialogs, or a caller can specify arbitrary
* parameters to call other dialogs.
*/
public class WebDialog extends Dialog {
private static final String LOG_TAG = Logger.LOG_TAG_BASE + "WebDialog";
private static final String DISPLAY_TOUCH = "touch";
private static final String USER_AGENT = "user_agent";
static final String REDIRECT_URI = "fbconnect://success";
static final String CANCEL_URI = "fbconnect://cancel";
static final boolean DISABLE_SSL_CHECK_FOR_TESTING = false;
public static final int DEFAULT_THEME = android.R.style.Theme_Translucent_NoTitleBar;
private String url;
private OnCompleteListener onCompleteListener;
private WebView webView;
private ProgressDialog spinner;
private ImageView crossImageView;
private FrameLayout contentFrameLayout;
private boolean listenerCalled = false;
private boolean isDetached = false;
/**
* Interface that implements a listener to be called when the user's interaction with the
* dialog completes, whether because the dialog finished successfully, or it was cancelled,
* or an error was encountered.
*/
public interface OnCompleteListener {
/**
* Called when the dialog completes.
*
* @param values on success, contains the values returned by the dialog
* @param error on an error, contains an exception describing the error
*/
void onComplete(Bundle values, FacebookException error);
}
/**
* Constructor which can be used to display a dialog with an already-constructed URL.
*
* @param context the context to use to display the dialog
* @param url the URL of the Web Dialog to display; no validation is done on this URL, but it should
* be a valid URL pointing to a Facebook Web Dialog
*/
public WebDialog(Context context, String url) {
this(context, url, DEFAULT_THEME);
}
/**
* Constructor which can be used to display a dialog with an already-constructed URL and a custom theme.
*
* @param context the context to use to display the dialog
* @param url the URL of the Web Dialog to display; no validation is done on this URL, but it should
* be a valid URL pointing to a Facebook Web Dialog
* @param theme identifier of a theme to pass to the Dialog class
*/
public WebDialog(Context context, String url, int theme) {
super(context, theme);
this.url = url;
}
/**
* Constructor which will construct the URL of the Web dialog based on the specified parameters.
*
* @param context the context to use to display the dialog
* @param action the portion of the dialog URL following "dialog/"
* @param parameters parameters which will be included as part of the URL
* @param theme identifier of a theme to pass to the Dialog class
* @param listener the listener to notify, or null if no notification is desired
*/
public WebDialog(Context context, String action, Bundle parameters, int theme, OnCompleteListener listener) {
super(context, theme);
if (parameters == null) {
parameters = new Bundle();
}
parameters.putString(ServerProtocol.DIALOG_PARAM_DISPLAY, DISPLAY_TOUCH);
parameters.putString(ServerProtocol.DIALOG_PARAM_TYPE, USER_AGENT);
Uri uri = Utility.buildUri(ServerProtocol.DIALOG_AUTHORITY, ServerProtocol.DIALOG_PATH + action, parameters);
this.url = uri.toString();
onCompleteListener = listener;
}
/**
* Sets the listener which will be notified when the dialog finishes.
*
* @param listener the listener to notify, or null if no notification is desired
*/
public void setOnCompleteListener(OnCompleteListener listener) {
onCompleteListener = listener;
}
/**
* Gets the listener which will be notified when the dialog finishes.
*
* @return the listener, or null if none has been specified
*/
public OnCompleteListener getOnCompleteListener() {
return onCompleteListener;
}
@Override
public void dismiss() {
if (webView != null) {
webView.stopLoading();
}
if (!isDetached) {
if (spinner.isShowing()) {
spinner.dismiss();
}
super.dismiss();
}
}
@Override
public void onDetachedFromWindow() {
isDetached = true;
super.onDetachedFromWindow();
}
@Override
public void onAttachedToWindow() {
isDetached = false;
super.onAttachedToWindow();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
sendCancelToListener();
}
});
spinner = new ProgressDialog(getContext());
spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
spinner.setMessage(getContext().getString(R.string.com_facebook_loading));
spinner.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
sendCancelToListener();
WebDialog.this.dismiss();
}
});
requestWindowFeature(Window.FEATURE_NO_TITLE);
contentFrameLayout = new FrameLayout(getContext());
/* Create the 'x' image, but don't add to the contentFrameLayout layout yet
* at this point, we only need to know its drawable width and height
* to place the webview
*/
createCrossImage();
/* Now we know 'x' drawable width and height,
* layout the webivew and add it the contentFrameLayout layout
*/
int crossWidth = crossImageView.getDrawable().getIntrinsicWidth();
setUpWebView(crossWidth / 2);
/* Finally add the 'x' image to the contentFrameLayout layout and
* add contentFrameLayout to the Dialog view
*/
contentFrameLayout.addView(crossImageView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addContentView(contentFrameLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void sendSuccessToListener(Bundle values) {
if (onCompleteListener != null && !listenerCalled) {
listenerCalled = true;
onCompleteListener.onComplete(values, null);
}
}
private void sendErrorToListener(Throwable error) {
if (onCompleteListener != null && !listenerCalled) {
listenerCalled = true;
FacebookException facebookException = null;
if (error instanceof FacebookException) {
facebookException = (FacebookException) error;
} else {
facebookException = new FacebookException(error);
}
onCompleteListener.onComplete(null, facebookException);
}
}
private void sendCancelToListener() {
sendErrorToListener(new FacebookOperationCanceledException());
}
private void createCrossImage() {
crossImageView = new ImageView(getContext());
// Dismiss the dialog when user click on the 'x'
crossImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendCancelToListener();
WebDialog.this.dismiss();
}
});
Drawable crossDrawable = getContext().getResources().getDrawable(R.drawable.com_facebook_close);
crossImageView.setImageDrawable(crossDrawable);
/* 'x' should not be visible while webview is loading
* make it visible only after webview has fully loaded
*/
crossImageView.setVisibility(View.INVISIBLE);
}
@SuppressLint("SetJavaScriptEnabled")
private void setUpWebView(int margin) {
LinearLayout webViewContainer = new LinearLayout(getContext());
webView = new WebView(getContext());
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new DialogWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
webView.setVisibility(View.INVISIBLE);
webView.getSettings().setSavePassword(false);
webViewContainer.setPadding(margin, margin, margin, margin);
webViewContainer.addView(webView);
contentFrameLayout.addView(webViewContainer);
}
private class DialogWebViewClient extends WebViewClient {
@Override
@SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Utility.logd(LOG_TAG, "Redirect URL: " + url);
if (url.startsWith(WebDialog.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
String errorMessage = values.getString("error_msg");
if (errorMessage == null) {
errorMessage = values.getString("error_description");
}
String errorCodeString = values.getString("error_code");
int errorCode = FacebookRequestError.INVALID_ERROR_CODE;
if (!Utility.isNullOrEmpty(errorCodeString)) {
try {
errorCode = Integer.parseInt(errorCodeString);
} catch (NumberFormatException ex) {
errorCode = FacebookRequestError.INVALID_ERROR_CODE;
}
}
if (Utility.isNullOrEmpty(error) && Utility
.isNullOrEmpty(errorMessage) && errorCode == FacebookRequestError.INVALID_ERROR_CODE) {
sendSuccessToListener(values);
} else if (error != null && (error.equals("access_denied") ||
error.equals("OAuthAccessDeniedException"))) {
sendCancelToListener();
} else {
FacebookRequestError requestError = new FacebookRequestError(errorCode, error, errorMessage);
sendErrorToListener(new FacebookServiceException(requestError, errorMessage));
}
WebDialog.this.dismiss();
return true;
} else if (url.startsWith(WebDialog.CANCEL_URI)) {
sendCancelToListener();
WebDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_TOUCH)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
sendErrorToListener(new FacebookDialogException(description, errorCode, failingUrl));
WebDialog.this.dismiss();
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (DISABLE_SSL_CHECK_FOR_TESTING) {
handler.proceed();
} else {
super.onReceivedSslError(view, handler, error);
sendErrorToListener(new FacebookDialogException(null, ERROR_FAILED_SSL_HANDSHAKE, null));
handler.cancel();
WebDialog.this.dismiss();
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Utility.logd(LOG_TAG, "Webview loading URL: " + url);
super.onPageStarted(view, url, favicon);
if (!isDetached) {
spinner.show();
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!isDetached) {
spinner.dismiss();
}
/*
* Once web view is fully loaded, set the contentFrameLayout background to be transparent
* and make visible the 'x' image.
*/
contentFrameLayout.setBackgroundColor(Color.TRANSPARENT);
webView.setVisibility(View.VISIBLE);
crossImageView.setVisibility(View.VISIBLE);
}
}
private static class BuilderBase<CONCRETE extends BuilderBase<?>> {
private Context context;
private Session session;
private String applicationId;
private String action;
private int theme = DEFAULT_THEME;
private OnCompleteListener listener;
private Bundle parameters;
protected BuilderBase(Context context, Session session, String action, Bundle parameters) {
Validate.notNull(session, "session");
if (!session.isOpened()) {
throw new FacebookException("Attempted to use a Session that was not open.");
}
this.session = session;
finishInit(context, action, parameters);
}
protected BuilderBase(Context context, String applicationId, String action, Bundle parameters) {
Validate.notNullOrEmpty(applicationId, "applicationId");
this.applicationId = applicationId;
finishInit(context, action, parameters);
}
/**
* Sets a theme identifier which will be passed to the underlying Dialog.
*
* @param theme a theme identifier which will be passed to the Dialog class
* @return the builder
*/
public CONCRETE setTheme(int theme) {
this.theme = theme;
@SuppressWarnings("unchecked")
CONCRETE result = (CONCRETE) this;
return result;
}
/**
* Sets the listener which will be notified when the dialog finishes.
*
* @param listener the listener to notify, or null if no notification is desired
* @return the builder
*/
public CONCRETE setOnCompleteListener(OnCompleteListener listener) {
this.listener = listener;
@SuppressWarnings("unchecked")
CONCRETE result = (CONCRETE) this;
return result;
}
/**
* Constructs a WebDialog using the parameters provided. The dialog is not shown,
* but is ready to be shown by calling Dialog.show().
*
* @return the WebDialog
*/
public WebDialog build() {
if (session != null && session.isOpened()) {
parameters.putString(ServerProtocol.DIALOG_PARAM_APP_ID, session.getApplicationId());
parameters.putString(ServerProtocol.DIALOG_PARAM_ACCESS_TOKEN, session.getAccessToken());
} else {
parameters.putString(ServerProtocol.DIALOG_PARAM_APP_ID, applicationId);
}
if (!parameters.containsKey(ServerProtocol.DIALOG_PARAM_REDIRECT_URI)) {
parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI);
}
return new WebDialog(context, action, parameters, theme, listener);
}
protected String getApplicationId() {
return applicationId;
}
protected Context getContext() {
return context;
}
protected int getTheme() {
return theme;
}
protected Bundle getParameters() {
return parameters;
}
protected WebDialog.OnCompleteListener getListener() {
return listener;
}
private void finishInit(Context context, String action, Bundle parameters) {
this.context = context;
this.action = action;
if (parameters != null) {
this.parameters = parameters;
} else {
this.parameters = new Bundle();
}
}
}
/**
* Provides a builder that allows construction of an arbitary Facebook web dialog.
*/
public static class Builder extends BuilderBase<Builder> {
/**
* Constructor that builds a dialog for an authenticated user.
*
* @param context the Context within which the dialog will be shown.
* @param session the Session representing an authenticating user to use for
* showing the dialog; must not be null, and must be opened.
* @param action the portion of the dialog URL following www.facebook.com/dialog/.
* See https://developers.facebook.com/docs/reference/dialogs/ for details.
* @param parameters a Bundle containing parameters to pass as part of the URL.
*/
public Builder(Context context, Session session, String action, Bundle parameters) {
super(context, session, action, parameters);
}
/**
* Constructor that builds a dialog without an authenticated user.
*
* @param context the Context within which the dialog will be shown.
* @param applicationId the application ID to be included in the dialog URL.
* @param action the portion of the dialog URL following www.facebook.com/dialog/.
* See https://developers.facebook.com/docs/reference/dialogs/ for details.
* @param parameters a Bundle containing parameters to pass as part of the URL.
*/
public Builder(Context context, String applicationId, String action, Bundle parameters) {
super(context, applicationId, action, parameters);
}
}
/**
* Provides a builder that allows construction of the parameters for showing
* the Feed Dialog (https://developers.facebook.com/docs/reference/dialogs/feed/).
*/
public static class FeedDialogBuilder extends BuilderBase<FeedDialogBuilder> {
private static final String FEED_DIALOG = "feed";
private static final String FROM_PARAM = "from";
private static final String TO_PARAM = "to";
private static final String LINK_PARAM = "link";
private static final String PICTURE_PARAM = "picture";
private static final String SOURCE_PARAM = "source";
private static final String NAME_PARAM = "name";
private static final String CAPTION_PARAM = "caption";
private static final String DESCRIPTION_PARAM = "description";
/**
* Constructor.
*
* @param context the Context within which the dialog will be shown.
* @param session the Session representing an authenticating user to use for
* showing the dialog; must not be null, and must be opened.
*/
public FeedDialogBuilder(Context context, Session session) {
super(context, session, FEED_DIALOG, null);
}
/**
* Constructor.
*
* @param context the Context within which the dialog will be shown.
* @param parameters a Bundle containing parameters to pass as part of the
* dialog URL. No validation is done on these parameters; it is
* the caller's responsibility to ensure they are valid.
* @param session the Session representing an authenticating user to use for
* showing the dialog; must not be null, and must be opened.
*/
public FeedDialogBuilder(Context context, Session session, Bundle parameters) {
super(context, session, FEED_DIALOG, parameters);
}
/**
* Sets the ID of the profile that is posting to Facebook. If none is specified,
* the default is "me". This profile must be either the authenticated user or a
* Page that the user is an administrator of.
*
* @param id Facebook ID of the profile to post from
* @return the builder
*/
public FeedDialogBuilder setFrom(String id) {
getParameters().putString(FROM_PARAM, id);
return this;
}
/**
* Sets the ID of the profile that the story will be published to. If not specified, it
* will default to the same profile that the story is being published from.
*
* @param id Facebook ID of the profile to post to
* @return the builder
*/
public FeedDialogBuilder setTo(String id) {
getParameters().putString(TO_PARAM, id);
return this;
}
/**
* Sets the URL of a link to be shared.
*
* @param link the URL
* @return the builder
*/
public FeedDialogBuilder setLink(String link) {
getParameters().putString(LINK_PARAM, link);
return this;
}
/**
* Sets the URL of a picture to be shared.
*
* @param picture the URL of the picture
* @return the builder
*/
public FeedDialogBuilder setPicture(String picture) {
getParameters().putString(PICTURE_PARAM, picture);
return this;
}
/**
* Sets the URL of a media file attached to this post. If this is set, any picture
* set via setPicture will be ignored.
*
* @param source the URL of the media file
* @return the builder
*/
public FeedDialogBuilder setSource(String source) {
getParameters().putString(SOURCE_PARAM, source);
return this;
}
/**
* Sets the name of the item being shared.
*
* @param name the name
* @return the builder
*/
public FeedDialogBuilder setName(String name) {
getParameters().putString(NAME_PARAM, name);
return this;
}
/**
* Sets the caption to be displayed.
*
* @param caption the caption
* @return the builder
*/
public FeedDialogBuilder setCaption(String caption) {
getParameters().putString(CAPTION_PARAM, caption);
return this;
}
/**
* Sets the description to be displayed.
*
* @param description the description
* @return the builder
*/
public FeedDialogBuilder setDescription(String description) {
getParameters().putString(DESCRIPTION_PARAM, description);
return this;
}
}
/**
* Provides a builder that allows construction of the parameters for showing
* the Feed Dialog (https://developers.facebook.com/docs/reference/dialogs/feed/).
*/
public static class RequestsDialogBuilder extends BuilderBase<RequestsDialogBuilder> {
private static final String APPREQUESTS_DIALOG = "apprequests";
private static final String MESSAGE_PARAM = "message";
private static final String TO_PARAM = "to";
private static final String DATA_PARAM = "data";
private static final String TITLE_PARAM = "title";
/**
* Constructor.
*
* @param context the Context within which the dialog will be shown.
* @param session the Session representing an authenticating user to use for
* showing the dialog; must not be null, and must be opened.
*/
public RequestsDialogBuilder(Context context, Session session) {
super(context, session, APPREQUESTS_DIALOG, null);
}
/**
* Constructor.
*
* @param context the Context within which the dialog will be shown.
* @param parameters a Bundle containing parameters to pass as part of the
* dialog URL. No validation is done on these parameters; it is
* the caller's responsibility to ensure they are valid.
* @param session the Session representing an authenticating user to use for
* showing the dialog; must not be null, and must be opened.
*/
public RequestsDialogBuilder(Context context, Session session, Bundle parameters) {
super(context, session, APPREQUESTS_DIALOG, parameters);
}
/**
* Sets the string users receiving the request will see. The maximum length
* is 60 characters.
*
* @param message the message
* @return the builder
*/
public RequestsDialogBuilder setMessage(String message) {
getParameters().putString(MESSAGE_PARAM, message);
return this;
}
/**
* Sets the user ID or user name the request will be sent to. If this is not
* specified, a friend selector will be displayed and the user can select up
* to 50 friends.
*
* @param id the id or user name to send the request to
* @return the builder
*/
public RequestsDialogBuilder setTo(String id) {
getParameters().putString(TO_PARAM, id);
return this;
}
/**
* Sets optional data which can be used for tracking; maximum length is 255
* characters.
*
* @param data the data
* @return the builder
*/
public RequestsDialogBuilder setData(String data) {
getParameters().putString(DATA_PARAM, data);
return this;
}
/**
* Sets an optional title for the dialog; maximum length is 50 characters.
*
* @param title the title
* @return the builder
*/
public RequestsDialogBuilder setTitle(String title) {
getParameters().putString(TITLE_PARAM, title);
return this;
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import com.facebook.internal.FileLruCache;
import com.facebook.internal.Utility;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
class UrlRedirectCache {
static final String TAG = UrlRedirectCache.class.getSimpleName();
private static final String REDIRECT_CONTENT_TAG = TAG + "_Redirect";
private volatile static FileLruCache urlRedirectCache;
synchronized static FileLruCache getCache(Context context) throws IOException{
if (urlRedirectCache == null) {
urlRedirectCache = new FileLruCache(context.getApplicationContext(), TAG, new FileLruCache.Limits());
}
return urlRedirectCache;
}
static URL getRedirectedUrl(Context context, URL url) {
if (url == null) {
return null;
}
String urlString = url.toString();
URL finalUrl = null;
InputStreamReader reader = null;
try {
InputStream stream;
FileLruCache cache = getCache(context);
boolean redirectExists = false;
while ((stream = cache.get(urlString, REDIRECT_CONTENT_TAG)) != null) {
redirectExists = true;
// Get the redirected url
reader = new InputStreamReader(stream);
char[] buffer = new char[128];
int bufferLength;
StringBuilder urlBuilder = new StringBuilder();
while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) {
urlBuilder.append(buffer, 0, bufferLength);
}
Utility.closeQuietly(reader);
// Iterate to the next url in the redirection
urlString = urlBuilder.toString();
}
if (redirectExists) {
finalUrl = new URL(urlString);
}
} catch (MalformedURLException e) {
// caching is best effort, so ignore the exception
} catch (IOException ioe) {
} finally {
Utility.closeQuietly(reader);
}
return finalUrl;
}
static void cacheUrlRedirect(Context context, URL fromUrl, URL toUrl) {
if (fromUrl == null || toUrl == null) {
return;
}
OutputStream redirectStream = null;
try {
FileLruCache cache = getCache(context);
redirectStream = cache.openPutStream(fromUrl.toString(), REDIRECT_CONTENT_TAG);
redirectStream.write(toUrl.toString().getBytes());
} catch (IOException e) {
// Caching is best effort
} finally {
Utility.closeQuietly(redirectStream);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import com.facebook.FacebookException;
import com.facebook.internal.Utility;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
class ImageDownloader {
private static final int DOWNLOAD_QUEUE_MAX_CONCURRENT = WorkQueue.DEFAULT_MAX_CONCURRENT;
private static final int CACHE_READ_QUEUE_MAX_CONCURRENT = 2;
private static final Handler handler = new Handler();
private static WorkQueue downloadQueue = new WorkQueue(DOWNLOAD_QUEUE_MAX_CONCURRENT);
private static WorkQueue cacheReadQueue = new WorkQueue(CACHE_READ_QUEUE_MAX_CONCURRENT);
private static final Map<RequestKey, DownloaderContext> pendingRequests = new HashMap<RequestKey, DownloaderContext>();
/**
* Downloads the image specified in the passed in request.
* If a callback is specified, it is guaranteed to be invoked on the calling thread.
* @param request Request to process
*/
static void downloadAsync(ImageRequest request) {
if (request == null) {
return;
}
// NOTE: This is the ONLY place where the original request's Url is read. From here on,
// we will keep track of the Url separately. This is because we might be dealing with a
// redirect response and the Url might change. We can't create our own new ImageRequests
// for these changed Urls since the caller might be doing some book-keeping with the request's
// object reference. So we keep the old references and just map them to new urls in the downloader
RequestKey key = new RequestKey(request.getImageUrl(), request.getCallerTag());
synchronized (pendingRequests) {
DownloaderContext downloaderContext = pendingRequests.get(key);
if (downloaderContext != null) {
downloaderContext.request = request;
downloaderContext.isCancelled = false;
downloaderContext.workItem.moveToFront();
} else {
enqueueCacheRead(request, key, request.isCachedRedirectAllowed());
}
}
}
static boolean cancelRequest(ImageRequest request) {
boolean cancelled = false;
RequestKey key = new RequestKey(request.getImageUrl(), request.getCallerTag());
synchronized (pendingRequests) {
DownloaderContext downloaderContext = pendingRequests.get(key);
if (downloaderContext != null) {
// If we were able to find the request in our list of pending requests, then we will
// definitely be able to prevent an ImageResponse from being issued. This is regardless
// of whether a cache-read or network-download is underway for this request.
cancelled = true;
if (downloaderContext.workItem.cancel()) {
pendingRequests.remove(key);
} else {
// May be attempting a cache-read right now. So keep track of the cancellation
// to prevent network calls etc
downloaderContext.isCancelled = true;
}
}
}
return cancelled;
}
static void prioritizeRequest(ImageRequest request) {
RequestKey key = new RequestKey(request.getImageUrl(), request.getCallerTag());
synchronized (pendingRequests) {
DownloaderContext downloaderContext = pendingRequests.get(key);
if (downloaderContext != null) {
downloaderContext.workItem.moveToFront();
}
}
}
private static void enqueueCacheRead(ImageRequest request, RequestKey key, boolean allowCachedRedirects) {
enqueueRequest(
request,
key,
cacheReadQueue,
new CacheReadWorkItem(request.getContext(), key, allowCachedRedirects));
}
private static void enqueueDownload(ImageRequest request, RequestKey key) {
enqueueRequest(
request,
key,
downloadQueue,
new DownloadImageWorkItem(request.getContext(), key));
}
private static void enqueueRequest(
ImageRequest request,
RequestKey key,
WorkQueue workQueue,
Runnable workItem) {
synchronized (pendingRequests) {
DownloaderContext downloaderContext = new DownloaderContext();
downloaderContext.request = request;
pendingRequests.put(key, downloaderContext);
// The creation of the WorkItem should be done after the pending request has been registered.
// This is necessary since the WorkItem might kick off right away and attempt to retrieve
// the request's DownloaderContext prior to it being ready for access.
//
// It is also necessary to hold on to the lock until after the workItem is created, since
// calls to cancelRequest or prioritizeRequest might come in and expect a registered
// request to have a workItem available as well.
downloaderContext.workItem = workQueue.addActiveWorkItem(workItem);
}
}
private static void issueResponse(
RequestKey key,
final Exception error,
final Bitmap bitmap,
final boolean isCachedRedirect) {
// Once the old downloader context is removed, we are thread-safe since this is the
// only reference to it
DownloaderContext completedRequestContext = removePendingRequest(key);
if (completedRequestContext != null && !completedRequestContext.isCancelled) {
final ImageRequest request = completedRequestContext.request;
final ImageRequest.Callback callback = request.getCallback();
if (callback != null) {
handler.post(new Runnable() {
@Override
public void run() {
ImageResponse response = new ImageResponse(
request,
error,
isCachedRedirect,
bitmap);
callback.onCompleted(response);
}
});
}
}
}
private static void readFromCache(RequestKey key, Context context, boolean allowCachedRedirects) {
InputStream cachedStream = null;
boolean isCachedRedirect = false;
if (allowCachedRedirects) {
URL redirectUrl = UrlRedirectCache.getRedirectedUrl(context, key.url);
if (redirectUrl != null) {
cachedStream = ImageResponseCache.getCachedImageStream(redirectUrl, context);
isCachedRedirect = cachedStream != null;
}
}
if (!isCachedRedirect) {
cachedStream = ImageResponseCache.getCachedImageStream(key.url, context);
}
if (cachedStream != null) {
// We were able to find a cached image.
Bitmap bitmap = BitmapFactory.decodeStream(cachedStream);
Utility.closeQuietly(cachedStream);
issueResponse(key, null, bitmap, isCachedRedirect);
} else {
// Once the old downloader context is removed, we are thread-safe since this is the
// only reference to it
DownloaderContext downloaderContext = removePendingRequest(key);
if (downloaderContext != null && !downloaderContext.isCancelled) {
enqueueDownload(downloaderContext.request, key);
}
}
}
private static void download(RequestKey key, Context context) {
HttpURLConnection connection = null;
InputStream stream = null;
Exception error = null;
Bitmap bitmap = null;
boolean issueResponse = true;
try {
connection = (HttpURLConnection) key.url.openConnection();
connection.setInstanceFollowRedirects(false);
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
// redirect. So we need to perform further requests
issueResponse = false;
String redirectLocation = connection.getHeaderField("location");
if (!Utility.isNullOrEmpty(redirectLocation)) {
URL redirectUrl = new URL(redirectLocation);
UrlRedirectCache.cacheUrlRedirect(context, key.url, redirectUrl);
// Once the old downloader context is removed, we are thread-safe since this is the
// only reference to it
DownloaderContext downloaderContext = removePendingRequest(key);
if (downloaderContext != null && !downloaderContext.isCancelled) {
enqueueCacheRead(
downloaderContext.request,
new RequestKey(redirectUrl, key.tag),
false);
}
}
break;
case HttpURLConnection.HTTP_OK:
// image should be available
stream = ImageResponseCache.interceptAndCacheImageStream(context, connection);
bitmap = BitmapFactory.decodeStream(stream);
break;
default:
stream = connection.getErrorStream();
InputStreamReader reader = new InputStreamReader(stream);
char[] buffer = new char[128];
int bufferLength;
StringBuilder errorMessageBuilder = new StringBuilder();
while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) {
errorMessageBuilder.append(buffer, 0, bufferLength);
}
Utility.closeQuietly(reader);
error = new FacebookException(errorMessageBuilder.toString());
break;
}
} catch (IOException e) {
error = e;
} finally {
Utility.closeQuietly(stream);
Utility.disconnectQuietly(connection);
}
if (issueResponse) {
issueResponse(key, error, bitmap, false);
}
}
private static DownloaderContext removePendingRequest(RequestKey key) {
synchronized (pendingRequests) {
return pendingRequests.remove(key);
}
}
private static class RequestKey {
private static final int HASH_SEED = 29; // Some random prime number
private static final int HASH_MULTIPLIER = 37; // Some random prime number
URL url;
Object tag;
RequestKey(URL url, Object tag) {
this.url = url;
this.tag = tag;
}
@Override
public int hashCode() {
int result = HASH_SEED;
result = (result * HASH_MULTIPLIER) + url.hashCode();
result = (result * HASH_MULTIPLIER) + tag.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
boolean isEqual = false;
if (o != null && o instanceof RequestKey) {
RequestKey compareTo = (RequestKey)o;
isEqual = compareTo.url == url && compareTo.tag == tag;
}
return isEqual;
}
}
private static class DownloaderContext {
WorkQueue.WorkItem workItem;
ImageRequest request;
boolean isCancelled;
}
private static class CacheReadWorkItem implements Runnable {
private Context context;
private RequestKey key;
private boolean allowCachedRedirects;
CacheReadWorkItem(Context context, RequestKey key, boolean allowCachedRedirects) {
this.context = context;
this.key = key;
this.allowCachedRedirects = allowCachedRedirects;
}
@Override
public void run() {
readFromCache(key, context, allowCachedRedirects);
}
}
private static class DownloadImageWorkItem implements Runnable {
private Context context;
private RequestKey key;
DownloadImageWorkItem(Context context, RequestKey key) {
this.context = context;
this.key = key;
}
@Override
public void run() {
download(key, context);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.graphics.Bitmap;
class ImageResponse {
private ImageRequest request;
private Exception error;
private boolean isCachedRedirect;
private Bitmap bitmap;
ImageResponse(ImageRequest request, Exception error, boolean isCachedRedirect, Bitmap bitmap) {
this.request = request;
this.error = error;
this.bitmap = bitmap;
this.isCachedRedirect = isCachedRedirect;
}
ImageRequest getRequest() {
return request;
}
Exception getError() {
return error;
}
Bitmap getBitmap() {
return bitmap;
}
boolean isCachedRedirect() {
return isCachedRedirect;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.net.Uri;
import com.facebook.internal.Validate;
import java.net.MalformedURLException;
import java.net.URL;
class ImageRequest {
interface Callback {
/**
* This method should always be called on the UI thread. ImageDownloader makes
* sure to do this when it is responsible for issuing the ImageResponse
* @param response
*/
void onCompleted(ImageResponse response);
}
static final int UNSPECIFIED_DIMENSION = 0;
private static final String PROFILEPIC_URL_FORMAT =
"https://graph.facebook.com/%s/picture";
private static final String HEIGHT_PARAM = "height";
private static final String WIDTH_PARAM = "width";
private static final String MIGRATION_PARAM = "migration_overrides";
private static final String MIGRATION_VALUE = "{october_2012:true}";
private Context context;
private URL imageUrl;
private Callback callback;
private boolean allowCachedRedirects;
private Object callerTag;
static URL getProfilePictureUrl(
String userId,
int width,
int height)
throws MalformedURLException {
Validate.notNullOrEmpty(userId, "userId");
width = Math.max(width, UNSPECIFIED_DIMENSION);
height = Math.max(height, UNSPECIFIED_DIMENSION);
if (width == UNSPECIFIED_DIMENSION && height == UNSPECIFIED_DIMENSION) {
throw new IllegalArgumentException("Either width or height must be greater than 0");
}
Uri.Builder builder = new Uri.Builder().encodedPath(String.format(PROFILEPIC_URL_FORMAT, userId));
if (height != UNSPECIFIED_DIMENSION) {
builder.appendQueryParameter(HEIGHT_PARAM, String.valueOf(height));
}
if (width != UNSPECIFIED_DIMENSION) {
builder.appendQueryParameter(WIDTH_PARAM, String.valueOf(width));
}
builder.appendQueryParameter(MIGRATION_PARAM, MIGRATION_VALUE);
return new URL(builder.toString());
}
private ImageRequest(Builder builder) {
this.context = builder.context;
this.imageUrl = builder.imageUrl;
this.callback = builder.callback;
this.allowCachedRedirects = builder.allowCachedRedirects;
this.callerTag = builder.callerTag == null ? new Object() : builder.callerTag;
}
Context getContext() {
return context;
}
URL getImageUrl() {
return imageUrl;
}
Callback getCallback() {
return callback;
}
boolean isCachedRedirectAllowed() {
return allowCachedRedirects;
}
Object getCallerTag() {
return callerTag;
}
static class Builder {
// Required
private Context context;
private URL imageUrl;
// Optional
private Callback callback;
private boolean allowCachedRedirects;
private Object callerTag;
Builder(Context context, URL imageUrl) {
Validate.notNull(imageUrl, "imageUrl");
this.context = context;
this.imageUrl = imageUrl;
}
Builder setCallback(Callback callback) {
this.callback = callback;
return this;
}
Builder setCallerTag(Object callerTag) {
this.callerTag = callerTag;
return this;
}
Builder setAllowCachedRedirects(boolean allowCachedRedirects) {
this.allowCachedRedirects = allowCachedRedirects;
return this;
}
ImageRequest build() {
return new ImageRequest(this);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphUser;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Provides a Fragment that displays a list of a user's friends and allows one or more of the
* friends to be selected.
*/
public class FriendPickerFragment extends PickerFragment<GraphUser> {
/**
* The key for a String parameter in the fragment's Intent bundle to indicate what user's
* friends should be shown. The default is to display the currently authenticated user's friends.
*/
public static final String USER_ID_BUNDLE_KEY = "com.facebook.widget.FriendPickerFragment.UserId";
/**
* The key for a boolean parameter in the fragment's Intent bundle to indicate whether the
* picker should allow more than one friend to be selected or not.
*/
public static final String MULTI_SELECT_BUNDLE_KEY = "com.facebook.widget.FriendPickerFragment.MultiSelect";
private static final String ID = "id";
private static final String NAME = "name";
private String userId;
private boolean multiSelect = true;
/**
* Default constructor. Creates a Fragment with all default properties.
*/
public FriendPickerFragment() {
this(null);
}
/**
* Constructor.
* @param args a Bundle that optionally contains one or more values containing additional
* configuration information for the Fragment.
*/
@SuppressLint("ValidFragment")
public FriendPickerFragment(Bundle args) {
super(GraphUser.class, R.layout.com_facebook_friendpickerfragment, args);
setFriendPickerSettingsFromBundle(args);
}
/**
* Gets the ID of the user whose friends should be displayed. If null, the default is to
* show the currently authenticated user's friends.
* @return the user ID, or null
*/
public String getUserId() {
return userId;
}
/**
* Sets the ID of the user whose friends should be displayed. If null, the default is to
* show the currently authenticated user's friends.
* @param userId the user ID, or null
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets whether the user can select multiple friends, or only one friend.
* @return true if the user can select multiple friends, false if only one friend
*/
public boolean getMultiSelect() {
return multiSelect;
}
/**
* Sets whether the user can select multiple friends, or only one friend.
* @param multiSelect true if the user can select multiple friends, false if only one friend
*/
public void setMultiSelect(boolean multiSelect) {
if (this.multiSelect != multiSelect) {
this.multiSelect = multiSelect;
setSelectionStrategy(createSelectionStrategy());
}
}
/**
* Gets the currently-selected list of users.
* @return the currently-selected list of users
*/
public List<GraphUser> getSelection() {
return getSelectedGraphObjects();
}
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.com_facebook_friend_picker_fragment);
setMultiSelect(a.getBoolean(R.styleable.com_facebook_friend_picker_fragment_multi_select, multiSelect));
a.recycle();
}
public void setSettingsFromBundle(Bundle inState) {
super.setSettingsFromBundle(inState);
setFriendPickerSettingsFromBundle(inState);
}
void saveSettingsToBundle(Bundle outState) {
super.saveSettingsToBundle(outState);
outState.putString(USER_ID_BUNDLE_KEY, userId);
outState.putBoolean(MULTI_SELECT_BUNDLE_KEY, multiSelect);
}
@Override
PickerFragmentAdapter<GraphUser> createAdapter() {
PickerFragmentAdapter<GraphUser> adapter = new PickerFragmentAdapter<GraphUser>(
this.getActivity()) {
@Override
protected int getGraphObjectRowLayoutId(GraphUser graphObject) {
return R.layout.com_facebook_picker_list_row;
}
@Override
protected int getDefaultPicture() {
return R.drawable.com_facebook_profile_default_icon;
}
};
adapter.setShowCheckbox(true);
adapter.setShowPicture(getShowPictures());
adapter.setSortFields(Arrays.asList(new String[]{NAME}));
adapter.setGroupByField(NAME);
return adapter;
}
@Override
LoadingStrategy createLoadingStrategy() {
return new ImmediateLoadingStrategy();
}
@Override
SelectionStrategy createSelectionStrategy() {
return multiSelect ? new MultiSelectionStrategy() : new SingleSelectionStrategy();
}
@Override
Request getRequestForLoadData(Session session) {
if (adapter == null) {
throw new FacebookException("Can't issue requests until Fragment has been created.");
}
String userToFetch = (userId != null) ? userId : "me";
return createRequest(userToFetch, extraFields, session);
}
@Override
String getDefaultTitleText() {
return getString(R.string.com_facebook_choose_friends);
}
private Request createRequest(String userID, Set<String> extraFields, Session session) {
Request request = Request.newGraphPathRequest(session, userID + "/friends", null);
Set<String> fields = new HashSet<String>(extraFields);
String[] requiredFields = new String[]{
ID,
NAME
};
fields.addAll(Arrays.asList(requiredFields));
String pictureField = adapter.getPictureFieldSpecifier();
if (pictureField != null) {
fields.add(pictureField);
}
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
private void setFriendPickerSettingsFromBundle(Bundle inState) {
// We do this in a separate non-overridable method so it is safe to call from the constructor.
if (inState != null) {
if (inState.containsKey(USER_ID_BUNDLE_KEY)) {
setUserId(inState.getString(USER_ID_BUNDLE_KEY));
}
setMultiSelect(inState.getBoolean(MULTI_SELECT_BUNDLE_KEY, multiSelect));
}
}
private class ImmediateLoadingStrategy extends LoadingStrategy {
@Override
protected void onLoadFinished(GraphObjectPagingLoader<GraphUser> loader,
SimpleGraphObjectCursor<GraphUser> data) {
super.onLoadFinished(loader, data);
// We could be called in this state if we are clearing data or if we are being re-attached
// in the middle of a query.
if (data == null || loader.isLoading()) {
return;
}
if (data.areMoreObjectsAvailable()) {
// We got results, but more are available.
followNextLink();
} else {
// We finished loading results.
hideActivityCircle();
// If this was from the cache, schedule a delayed refresh query (unless we got no results
// at all, in which case refresh immediately.
if (data.isFromCache()) {
loader.refreshOriginalRequest(data.getCount() == 0 ? CACHED_RESULT_REFRESH_DELAY : 0);
}
}
}
private void followNextLink() {
// This may look redundant, but this causes the circle to be alpha-dimmed if we have results.
displayActivityCircle();
loader.followNextLink();
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphUser;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* A Fragment that displays a Login/Logout button as well as the user's
* profile picture and name when logged in.
* <p/>
* This Fragment will create and use the active session upon construction
* if it has the available data (if the app ID is specified in the manifest).
* It will also open the active session if it does not require user interaction
* (i.e. if the session is in the {@link com.facebook.SessionState#CREATED_TOKEN_LOADED} state.
* Developers can override the use of the active session by calling
* the {@link #setSession(com.facebook.Session)} method.
*/
public class UserSettingsFragment extends FacebookFragment {
private static final String NAME = "name";
private static final String ID = "id";
private static final String PICTURE = "picture";
private static final String FIELDS = "fields";
private static final String REQUEST_FIELDS = TextUtils.join(",", new String[] {ID, NAME, PICTURE});
private LoginButton loginButton;
private LoginButton.LoginButtonProperties loginButtonProperties = new LoginButton.LoginButtonProperties();
private TextView connectedStateLabel;
private GraphUser user;
private Session userInfoSession; // the Session used to fetch the current user info
private Drawable userProfilePic;
private String userProfilePicID;
private Session.StatusCallback sessionStatusCallback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.com_facebook_usersettingsfragment, container, false);
loginButton = (LoginButton) view.findViewById(R.id.com_facebook_usersettingsfragment_login_button);
loginButton.setProperties(loginButtonProperties);
loginButton.setFragment(this);
Session session = getSession();
if (session != null && !session.equals(Session.getActiveSession())) {
loginButton.setSession(session);
}
connectedStateLabel = (TextView) view.findViewById(R.id.com_facebook_usersettingsfragment_profile_name);
// if no background is set for some reason, then default to Facebook blue
if (view.getBackground() == null) {
view.setBackgroundColor(getResources().getColor(R.color.com_facebook_blue));
} else {
view.getBackground().setDither(true);
}
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
/**
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void onResume() {
super.onResume();
fetchUserInfo();
updateUI();
}
/**
* Set the Session object to use instead of the active Session. Since a Session
* cannot be reused, if the user logs out from this Session, and tries to
* log in again, a new Active Session will be used instead.
* <p/>
* If the passed in session is currently opened, this method will also attempt to
* load some user information for display (if needed).
*
* @param newSession the Session object to use
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void setSession(Session newSession) {
super.setSession(newSession);
if (loginButton != null) {
loginButton.setSession(newSession);
}
fetchUserInfo();
updateUI();
}
/**
* Sets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @param defaultAudience the default audience value to use
*/
public void setDefaultAudience(SessionDefaultAudience defaultAudience) {
loginButtonProperties.setDefaultAudience(defaultAudience);
}
/**
* Gets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @return the default audience value to use
*/
public SessionDefaultAudience getDefaultAudience() {
return loginButtonProperties.getDefaultAudience();
}
/**
* Set the permissions to use when the session is opened. The permissions here
* can only be read permissions. If any publish permissions are included, the login
* attempt by the user will fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the UserSettingsFragment is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setPublishPermissions has been called
*/
public void setReadPermissions(List<String> permissions) {
loginButtonProperties.setReadPermissions(permissions, getSession());
}
/**
* Set the permissions to use when the session is opened. The permissions here
* should only be publish permissions. If any read permissions are included, the login
* attempt by the user may fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the LoginButton is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setReadPermissions has been called
* @throws IllegalArgumentException if permissions is null or empty
*/
public void setPublishPermissions(List<String> permissions) {
loginButtonProperties.setPublishPermissions(permissions, getSession());
}
/**
* Clears the permissions currently associated with this LoginButton.
*/
public void clearPermissions() {
loginButtonProperties.clearPermissions();
}
/**
* Sets the login behavior for the session that will be opened. If null is specified,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public void setLoginBehavior(SessionLoginBehavior loginBehavior) {
loginButtonProperties.setLoginBehavior(loginBehavior);
}
/**
* Gets the login behavior for the session that will be opened. If null is returned,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @return loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public SessionLoginBehavior getLoginBehavior() {
return loginButtonProperties.getLoginBehavior();
}
/**
* Sets an OnErrorListener for this instance of UserSettingsFragment to call into when
* certain exceptions occur.
*
* @param onErrorListener The listener object to set
*/
public void setOnErrorListener(LoginButton.OnErrorListener onErrorListener) {
loginButtonProperties.setOnErrorListener(onErrorListener);
}
/**
* Returns the current OnErrorListener for this instance of UserSettingsFragment.
*
* @return The OnErrorListener
*/
public LoginButton.OnErrorListener getOnErrorListener() {
return loginButtonProperties.getOnErrorListener();
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
*
* @param callback the callback interface
*/
public void setSessionStatusCallback(Session.StatusCallback callback) {
this.sessionStatusCallback = callback;
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
* @return the callback interface
*/
public Session.StatusCallback getSessionStatusCallback() {
return sessionStatusCallback;
}
@Override
protected void onSessionStateChange(SessionState state, Exception exception) {
fetchUserInfo();
updateUI();
if (sessionStatusCallback != null) {
sessionStatusCallback.call(getSession(), state, exception);
}
}
// For Testing Only
List<String> getPermissions() {
return loginButtonProperties.getPermissions();
}
private void fetchUserInfo() {
final Session currentSession = getSession();
if (currentSession != null && currentSession.isOpened()) {
if (currentSession != userInfoSession) {
Request request = Request.newMeRequest(currentSession, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser me, Response response) {
if (currentSession == getSession()) {
user = me;
updateUI();
}
if (response.getError() != null) {
loginButton.handleError(response.getError().getException());
}
}
});
Bundle parameters = new Bundle();
parameters.putString(FIELDS, REQUEST_FIELDS);
request.setParameters(parameters);
Request.executeBatchAsync(request);
userInfoSession = currentSession;
}
} else {
user = null;
}
}
private void updateUI() {
if (!isAdded()) {
return;
}
if (isSessionOpen()) {
connectedStateLabel.setTextColor(getResources().getColor(R.color.com_facebook_usersettingsfragment_connected_text_color));
connectedStateLabel.setShadowLayer(1f, 0f, -1f,
getResources().getColor(R.color.com_facebook_usersettingsfragment_connected_shadow_color));
if (user != null) {
ImageRequest request = getImageRequest();
if (request != null) {
URL requestUrl = request.getImageUrl();
// Do we already have the right picture? If so, leave it alone.
if (!requestUrl.equals(connectedStateLabel.getTag())) {
if (user.getId().equals(userProfilePicID)) {
connectedStateLabel.setCompoundDrawables(null, userProfilePic, null, null);
connectedStateLabel.setTag(requestUrl);
} else {
ImageDownloader.downloadAsync(request);
}
}
}
connectedStateLabel.setText(user.getName());
} else {
connectedStateLabel.setText(getResources().getString(
R.string.com_facebook_usersettingsfragment_logged_in));
Drawable noProfilePic = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
noProfilePic.setBounds(0, 0,
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_width),
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_height));
connectedStateLabel.setCompoundDrawables(null, noProfilePic, null, null);
}
} else {
int textColor = getResources().getColor(R.color.com_facebook_usersettingsfragment_not_connected_text_color);
connectedStateLabel.setTextColor(textColor);
connectedStateLabel.setShadowLayer(0f, 0f, 0f, textColor);
connectedStateLabel.setText(getResources().getString(
R.string.com_facebook_usersettingsfragment_not_logged_in));
connectedStateLabel.setCompoundDrawables(null, null, null, null);
connectedStateLabel.setTag(null);
}
}
private ImageRequest getImageRequest() {
ImageRequest request = null;
try {
ImageRequest.Builder requestBuilder = new ImageRequest.Builder(
getActivity(),
ImageRequest.getProfilePictureUrl(
user.getId(),
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_width),
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_height)));
request = requestBuilder.setCallerTag(this)
.setCallback(
new ImageRequest.Callback() {
@Override
public void onCompleted(ImageResponse response) {
processImageResponse(user.getId(), response);
}
})
.build();
} catch (MalformedURLException e) {
}
return request;
}
private void processImageResponse(String id, ImageResponse response) {
if (response != null) {
Bitmap bitmap = response.getBitmap();
if (bitmap != null) {
BitmapDrawable drawable = new BitmapDrawable(UserSettingsFragment.this.getResources(), bitmap);
drawable.setBounds(0, 0,
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_width),
getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_height));
userProfilePic = drawable;
userProfilePicID = id;
connectedStateLabel.setCompoundDrawables(null, drawable, null, null);
connectedStateLabel.setTag(response.getRequest().getImageUrl());
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.internal.SessionAuthorizationType;
import com.facebook.internal.SessionTracker;
import java.util.Date;
import java.util.List;
/**
* <p>Basic implementation of a Fragment that uses a Session to perform
* Single Sign On (SSO). This class is package private, and is not intended
* to be consumed by external applications.</p>
*
* <p>The method {@link android.support.v4.app.Fragment#onActivityResult} is
* used to manage the session information, so if you override it in a subclass,
* be sure to call {@code super.onActivityResult}.</p>
*
* <p>The methods in this class are not thread-safe.</p>
*/
class FacebookFragment extends Fragment {
private SessionTracker sessionTracker;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sessionTracker = new SessionTracker(getActivity(), new DefaultSessionStatusCallback());
}
/**
* Called when the activity that was launched exits. This method manages session
* information when a session is opened. If this method is overridden in subclasses,
* be sure to call {@code super.onActivityResult(...)} first.
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sessionTracker.getSession().onActivityResult(this.getActivity(), requestCode, resultCode, data);
}
@Override
public void onDestroy() {
super.onDestroy();
sessionTracker.stopTracking();
}
/**
* Use the supplied Session object instead of the active Session.
*
* @param newSession the Session object to use
*/
public void setSession(Session newSession) {
if (sessionTracker != null) {
sessionTracker.setSession(newSession);
}
}
// METHOD TO BE OVERRIDDEN
/**
* Called when the session state changes. Override this method to take action
* on session state changes.
*
* @param state the new state
* @param exception any exceptions that occurred during the state change
*/
protected void onSessionStateChange(SessionState state, Exception exception) {
}
// ACCESSORS (CANNOT BE OVERRIDDEN)
/**
* Gets the current Session.
*
* @return the current Session object.
*/
protected final Session getSession() {
if (sessionTracker != null) {
return sessionTracker.getSession();
}
return null;
}
/**
* Determines whether the current session is open.
*
* @return true if the current session is open
*/
protected final boolean isSessionOpen() {
if (sessionTracker != null) {
return sessionTracker.getOpenSession() != null;
}
return false;
}
/**
* Gets the current state of the session or null if no session has been created.
*
* @return the current state of the session
*/
protected final SessionState getSessionState() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getState() : null;
}
return null;
}
/**
* Gets the access token associated with the current session or null if no
* session has been created.
*
* @return the access token
*/
protected final String getAccessToken() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getAccessToken() : null;
}
return null;
}
/**
* Gets the date at which the current session will expire or null if no session
* has been created.
*
* @return the date at which the current session will expire
*/
protected final Date getExpirationDate() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getExpirationDate() : null;
}
return null;
}
/**
* Closes the current session.
*/
protected final void closeSession() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
currentSession.close();
}
}
}
/**
* Closes the current session as well as clearing the token cache.
*/
protected final void closeSessionAndClearTokenInformation() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
}
}
}
/**
* Gets the permissions associated with the current session or null if no session
* has been created.
*
* @return the permissions associated with the current session
*/
protected final List<String> getSessionPermissions() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getPermissions() : null;
}
return null;
}
/**
* Opens a new session. This method will use the application id from
* the associated meta-data value and an empty list of permissions.
*/
protected final void openSession() {
openSessionForRead(null, null);
}
/**
* Opens a new session with read permissions. If either applicationID or permissions
* is null, this method will default to using the values from the associated
* meta-data value and an empty list respectively.
*
* @param applicationId the applicationID, can be null
* @param permissions the permissions list, can be null
*/
protected final void openSessionForRead(String applicationId, List<String> permissions) {
openSessionForRead(applicationId, permissions, SessionLoginBehavior.SSO_WITH_FALLBACK,
Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
}
/**
* Opens a new session with read permissions. If either applicationID or permissions
* is null, this method will default to using the values from the associated
* meta-data value and an empty list respectively.
*
* @param applicationId the applicationID, can be null
* @param permissions the permissions list, can be null
* @param behavior the login behavior to use with the session
* @param activityCode the activity code to use for the SSO activity
*/
protected final void openSessionForRead(String applicationId, List<String> permissions,
SessionLoginBehavior behavior, int activityCode) {
openSession(applicationId, permissions, behavior, activityCode, SessionAuthorizationType.READ);
}
/**
* Opens a new session with publish permissions. If either applicationID is null,
* this method will default to using the value from the associated
* meta-data value. The permissions list cannot be null.
*
* @param applicationId the applicationID, can be null
* @param permissions the permissions list, cannot be null
*/
protected final void openSessionForPublish(String applicationId, List<String> permissions) {
openSessionForPublish(applicationId, permissions, SessionLoginBehavior.SSO_WITH_FALLBACK,
Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
}
/**
* Opens a new session with publish permissions. If either applicationID is null,
* this method will default to using the value from the associated
* meta-data value. The permissions list cannot be null.
*
* @param applicationId the applicationID, can be null
* @param permissions the permissions list, cannot be null
* @param behavior the login behavior to use with the session
* @param activityCode the activity code to use for the SSO activity
*/
protected final void openSessionForPublish(String applicationId, List<String> permissions,
SessionLoginBehavior behavior, int activityCode) {
openSession(applicationId, permissions, behavior, activityCode, SessionAuthorizationType.PUBLISH);
}
private void openSession(String applicationId, List<String> permissions,
SessionLoginBehavior behavior, int activityCode, SessionAuthorizationType authType) {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getActivity()).setApplicationId(applicationId).build();
Session.setActiveSession(session);
currentSession = session;
}
if (!currentSession.isOpened()) {
Session.OpenRequest openRequest = new Session.OpenRequest(this).
setPermissions(permissions).
setLoginBehavior(behavior).
setRequestCode(activityCode);
if (SessionAuthorizationType.PUBLISH.equals(authType)) {
currentSession.openForPublish(openRequest);
} else {
currentSession.openForRead(openRequest);
}
}
}
}
/**
* The default callback implementation for the session.
*/
private class DefaultSessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session,
SessionState state,
Exception exception) {
FacebookFragment.this.onSessionStateChange(state, exception);
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import com.facebook.model.GraphObject;
interface GraphObjectCursor<T extends GraphObject> {
boolean isFromCache();
boolean areMoreObjectsAvailable();
int getCount();
int getPosition();
boolean move(int offset);
boolean moveToPosition(int position);
boolean moveToFirst();
boolean moveToLast();
boolean moveToNext();
boolean moveToPrevious();
boolean isFirst();
boolean isLast();
boolean isBeforeFirst();
boolean isAfterLast();
T getGraphObject();
void close();
boolean isClosed();
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import com.facebook.Settings;
import java.util.concurrent.Executor;
class WorkQueue {
public static final int DEFAULT_MAX_CONCURRENT = 8;
private final Object workLock = new Object();
private WorkNode pendingJobs;
private final int maxConcurrent;
private final Executor executor;
private WorkNode runningJobs = null;
private int runningCount = 0;
WorkQueue() {
this(DEFAULT_MAX_CONCURRENT);
}
WorkQueue(int maxConcurrent) {
this(maxConcurrent, Settings.getExecutor());
}
WorkQueue(int maxConcurrent, Executor executor) {
this.maxConcurrent = maxConcurrent;
this.executor = executor;
}
WorkItem addActiveWorkItem(Runnable callback) {
return addActiveWorkItem(callback, true);
}
WorkItem addActiveWorkItem(Runnable callback, boolean addToFront) {
WorkNode node = new WorkNode(callback);
synchronized (workLock) {
pendingJobs = node.addToList(pendingJobs, addToFront);
}
startItem();
return node;
}
void validate() {
synchronized (workLock) {
// Verify that all running items know they are running, and counts match
int count = 0;
if (runningJobs != null) {
WorkNode walk = runningJobs;
do {
walk.verify(true);
count++;
walk = walk.getNext();
} while (walk != runningJobs);
}
assert runningCount == count;
}
}
private void startItem() {
finishItemAndStartNew(null);
}
private void finishItemAndStartNew(WorkNode finished) {
WorkNode ready = null;
synchronized (workLock) {
if (finished != null) {
runningJobs = finished.removeFromList(runningJobs);
runningCount--;
}
if (runningCount < maxConcurrent) {
ready = pendingJobs; // Head of the pendingJobs queue
if (ready != null) {
// The Queue reassignments are necessary since 'ready' might have been
// added / removed from the front of either queue, which changes its
// respective head.
pendingJobs = ready.removeFromList(pendingJobs);
runningJobs = ready.addToList(runningJobs, false);
runningCount++;
ready.setIsRunning(true);
}
}
}
if (ready != null) {
execute(ready);
}
}
private void execute(final WorkNode node) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
node.getCallback().run();
} finally {
finishItemAndStartNew(node);
}
}
});
}
private class WorkNode implements WorkItem {
private final Runnable callback;
private WorkNode next;
private WorkNode prev;
private boolean isRunning;
WorkNode(Runnable callback) {
this.callback = callback;
}
@Override
public boolean cancel() {
synchronized (workLock) {
if (!isRunning()) {
pendingJobs = removeFromList(pendingJobs);
return true;
}
}
return false;
}
@Override
public void moveToFront() {
synchronized (workLock) {
if (!isRunning()) {
pendingJobs = removeFromList(pendingJobs);
pendingJobs = addToList(pendingJobs, true);
}
}
}
@Override
public boolean isRunning() {
return isRunning;
}
Runnable getCallback() {
return callback;
}
WorkNode getNext() {
return next;
}
void setIsRunning(boolean isRunning) {
this.isRunning = isRunning;
}
WorkNode addToList(WorkNode list, boolean addToFront) {
assert next == null;
assert prev == null;
if (list == null) {
list = next = prev = this;
} else {
next = list;
prev = list.prev;
next.prev = prev.next = this;
}
return addToFront ? this : list;
}
WorkNode removeFromList(WorkNode list) {
assert next != null;
assert prev != null;
if (list == this) {
if (next == this) {
list = null;
} else {
list = next;
}
}
next.prev = prev;
prev.next = next;
next = prev = null;
return list;
}
void verify(boolean shouldBeRunning) {
assert prev.next == this;
assert next.prev == this;
assert isRunning() == shouldBeRunning;
}
}
interface WorkItem {
boolean cancel();
boolean isRunning();
void moveToFront();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphUser;
import com.facebook.internal.SessionAuthorizationType;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import java.util.Collections;
import java.util.List;
/**
* A Log In/Log Out button that maintains session state and logs
* in/out for the app.
* <p/>
* This control will create and use the active session upon construction
* if it has the available data (if the app ID is specified in the manifest).
* It will also open the active session if it does not require user interaction
* (i.e. if the session is in the {@link com.facebook.SessionState#CREATED_TOKEN_LOADED} state.
* Developers can override the use of the active session by calling
* the {@link #setSession(com.facebook.Session)} method.
*/
public class LoginButton extends Button {
private static final String TAG = LoginButton.class.getName();
private String applicationId = null;
private SessionTracker sessionTracker;
private GraphUser user = null;
private Session userInfoSession = null; // the Session used to fetch the current user info
private boolean confirmLogout;
private boolean fetchUserInfo;
private String loginText;
private String logoutText;
private UserInfoChangedCallback userInfoChangedCallback;
private Fragment parentFragment;
private LoginButtonProperties properties = new LoginButtonProperties();
static class LoginButtonProperties {
private SessionDefaultAudience defaultAudience = SessionDefaultAudience.FRIENDS;
private List<String> permissions = Collections.<String>emptyList();
private SessionAuthorizationType authorizationType = null;
private OnErrorListener onErrorListener;
private SessionLoginBehavior loginBehavior = SessionLoginBehavior.SSO_WITH_FALLBACK;
private Session.StatusCallback sessionStatusCallback;
public void setOnErrorListener(OnErrorListener onErrorListener) {
this.onErrorListener = onErrorListener;
}
public OnErrorListener getOnErrorListener() {
return onErrorListener;
}
public void setDefaultAudience(SessionDefaultAudience defaultAudience) {
this.defaultAudience = defaultAudience;
}
public SessionDefaultAudience getDefaultAudience() {
return defaultAudience;
}
public void setReadPermissions(List<String> permissions, Session session) {
if (SessionAuthorizationType.PUBLISH.equals(authorizationType)) {
throw new UnsupportedOperationException(
"Cannot call setReadPermissions after setPublishPermissions has been called.");
}
if (validatePermissions(permissions, SessionAuthorizationType.READ, session)) {
this.permissions = permissions;
authorizationType = SessionAuthorizationType.READ;
}
}
public void setPublishPermissions(List<String> permissions, Session session) {
if (SessionAuthorizationType.READ.equals(authorizationType)) {
throw new UnsupportedOperationException(
"Cannot call setPublishPermissions after setReadPermissions has been called.");
}
if (validatePermissions(permissions, SessionAuthorizationType.PUBLISH, session)) {
this.permissions = permissions;
authorizationType = SessionAuthorizationType.PUBLISH;
}
}
private boolean validatePermissions(List<String> permissions,
SessionAuthorizationType authType, Session currentSession) {
if (SessionAuthorizationType.PUBLISH.equals(authType)) {
if (Utility.isNullOrEmpty(permissions)) {
throw new IllegalArgumentException("Permissions for publish actions cannot be null or empty.");
}
}
if (currentSession != null && currentSession.isOpened()) {
if (!Utility.isSubset(permissions, currentSession.getPermissions())) {
Log.e(TAG, "Cannot set additional permissions when session is already open.");
return false;
}
}
return true;
}
List<String> getPermissions() {
return permissions;
}
public void clearPermissions() {
permissions = null;
authorizationType = null;
}
public void setLoginBehavior(SessionLoginBehavior loginBehavior) {
this.loginBehavior = loginBehavior;
}
public SessionLoginBehavior getLoginBehavior() {
return loginBehavior;
}
public void setSessionStatusCallback(Session.StatusCallback callback) {
this.sessionStatusCallback = callback;
}
public Session.StatusCallback getSessionStatusCallback() {
return sessionStatusCallback;
}
}
/**
* Specifies a callback interface that will be called when the button's notion of the current
* user changes (if the fetch_user_info attribute is true for this control).
*/
public interface UserInfoChangedCallback {
/**
* Called when the current user changes.
* @param user the current user, or null if there is no user
*/
void onUserInfoFetched(GraphUser user);
}
/**
* Callback interface that will be called when a network or other error is encountered
* while logging in.
*/
public interface OnErrorListener {
/**
* Called when a network or other error is encountered.
* @param error a FacebookException representing the error that was encountered.
*/
void onError(FacebookException error);
}
/**
* Create the LoginButton.
*
* @see View#View(Context)
*/
public LoginButton(Context context) {
super(context);
initializeActiveSessionWithCachedToken(context);
// since onFinishInflate won't be called, we need to finish initialization ourselves
finishInit();
}
/**
* Create the LoginButton by inflating from XML
*
* @see View#View(Context, AttributeSet)
*/
public LoginButton(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs.getStyleAttribute() == 0) {
// apparently there's no method of setting a default style in xml,
// so in case the users do not explicitly specify a style, we need
// to use sensible defaults.
this.setTextColor(getResources().getColor(R.color.com_facebook_loginview_text_color));
this.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.com_facebook_loginview_text_size));
this.setPadding(getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_padding_left),
getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_padding_top),
getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_padding_right),
getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_padding_bottom));
this.setWidth(getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_width));
this.setHeight(getResources().getDimensionPixelSize(R.dimen.com_facebook_loginview_height));
this.setGravity(Gravity.CENTER);
if (isInEditMode()) {
// cannot use a drawable in edit mode, so setting the background color instead
// of a background resource.
this.setBackgroundColor(getResources().getColor(R.color.com_facebook_blue));
// hardcoding in edit mode as getResources().getString() doesn't seem to work in IntelliJ
loginText = "Log in";
} else {
this.setBackgroundResource(R.drawable.com_facebook_loginbutton_blue);
}
}
parseAttributes(attrs);
if (!isInEditMode()) {
initializeActiveSessionWithCachedToken(context);
}
}
/**
* Create the LoginButton by inflating from XML and applying a style.
*
* @see View#View(Context, AttributeSet, int)
*/
public LoginButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
parseAttributes(attrs);
initializeActiveSessionWithCachedToken(context);
}
/**
* Sets an OnErrorListener for this instance of LoginButton to call into when
* certain exceptions occur.
*
* @param onErrorListener The listener object to set
*/
public void setOnErrorListener(OnErrorListener onErrorListener) {
properties.setOnErrorListener(onErrorListener);
}
/**
* Returns the current OnErrorListener for this instance of LoginButton.
*
* @return The OnErrorListener
*/
public OnErrorListener getOnErrorListener() {
return properties.getOnErrorListener();
}
/**
* Sets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @param defaultAudience the default audience value to use
*/
public void setDefaultAudience(SessionDefaultAudience defaultAudience) {
properties.setDefaultAudience(defaultAudience);
}
/**
* Gets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @return the default audience value to use
*/
public SessionDefaultAudience getDefaultAudience() {
return properties.getDefaultAudience();
}
/**
* Set the permissions to use when the session is opened. The permissions here
* can only be read permissions. If any publish permissions are included, the login
* attempt by the user will fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the LoginButton is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setPublishPermissions has been called
*/
public void setReadPermissions(List<String> permissions) {
properties.setReadPermissions(permissions, sessionTracker.getSession());
}
/**
* Set the permissions to use when the session is opened. The permissions here
* should only be publish permissions. If any read permissions are included, the login
* attempt by the user may fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the LoginButton is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setReadPermissions has been called
* @throws IllegalArgumentException if permissions is null or empty
*/
public void setPublishPermissions(List<String> permissions) {
properties.setPublishPermissions(permissions, sessionTracker.getSession());
}
/**
* Clears the permissions currently associated with this LoginButton.
*/
public void clearPermissions() {
properties.clearPermissions();
}
/**
* Sets the login behavior for the session that will be opened. If null is specified,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public void setLoginBehavior(SessionLoginBehavior loginBehavior) {
properties.setLoginBehavior(loginBehavior);
}
/**
* Gets the login behavior for the session that will be opened. If null is returned,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @return loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public SessionLoginBehavior getLoginBehavior() {
return properties.getLoginBehavior();
}
/**
* Set the application ID to be used to open the session.
*
* @param applicationId the application ID to use
*/
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
/**
* Gets the callback interface that will be called when the current user changes.
* @return the callback interface
*/
public UserInfoChangedCallback getUserInfoChangedCallback() {
return userInfoChangedCallback;
}
/**
* Sets the callback interface that will be called when the current user changes.
*
* @param userInfoChangedCallback the callback interface
*/
public void setUserInfoChangedCallback(UserInfoChangedCallback userInfoChangedCallback) {
this.userInfoChangedCallback = userInfoChangedCallback;
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes. Note that updates will only be sent to the
* callback while the LoginButton is actually attached to a window.
*
* @param callback the callback interface
*/
public void setSessionStatusCallback(Session.StatusCallback callback) {
properties.setSessionStatusCallback(callback);
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
* @return the callback interface
*/
public Session.StatusCallback getSessionStatusCallback() {
return properties.getSessionStatusCallback();
}
/**
* Provides an implementation for {@link Activity#onActivityResult
* onActivityResult} that updates the Session based on information returned
* during the authorization flow. The Activity containing this view
* should forward the resulting onActivityResult call here to
* update the Session state based on the contents of the resultCode and
* data.
*
* @param requestCode
* The 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.
* @param resultCode
* An int containing the resultCode parameter from the forwarded
* call.
* @param data
* The Intent passed as the data parameter from the forwarded
* call.
* @return A boolean indicating whether the requestCode matched a pending
* authorization request for this Session.
* @see Session#onActivityResult(Activity, int, int, Intent)
*/
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
Session session = sessionTracker.getSession();
if (session != null) {
return session.onActivityResult((Activity)getContext(), requestCode,
resultCode, data);
} else {
return false;
}
}
/**
* Set the Session object to use instead of the active Session. Since a Session
* cannot be reused, if the user logs out from this Session, and tries to
* log in again, a new Active Session will be used instead.
* <p/>
* If the passed in session is currently opened, this method will also attempt to
* load some user information for display (if needed).
*
* @param newSession the Session object to use
* @throws FacebookException if errors occur during the loading of user information
*/
public void setSession(Session newSession) {
sessionTracker.setSession(newSession);
fetchUserInfo();
setButtonText();
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
finishInit();
}
private void finishInit() {
setOnClickListener(new LoginClickListener());
setButtonText();
if (!isInEditMode()) {
sessionTracker = new SessionTracker(getContext(), new LoginButtonCallback(), null, false);
fetchUserInfo();
}
}
/**
* Sets the fragment that contains this control. This allows the LoginButton to be
* embedded inside a Fragment, and will allow the fragment to receive the
* {@link Fragment#onActivityResult(int, int, android.content.Intent) onActivityResult}
* call rather than the Activity.
*
* @param fragment the fragment that contains this control
*/
public void setFragment(Fragment fragment) {
parentFragment = fragment;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (sessionTracker != null && !sessionTracker.isTracking()) {
sessionTracker.startTracking();
fetchUserInfo();
setButtonText();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (sessionTracker != null) {
sessionTracker.stopTracking();
}
}
// For testing purposes only
List<String> getPermissions() {
return properties.getPermissions();
}
void setProperties(LoginButtonProperties properties) {
this.properties = properties;
}
private void parseAttributes(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.com_facebook_login_view);
confirmLogout = a.getBoolean(R.styleable.com_facebook_login_view_confirm_logout, true);
fetchUserInfo = a.getBoolean(R.styleable.com_facebook_login_view_fetch_user_info, true);
loginText = a.getString(R.styleable.com_facebook_login_view_login_text);
logoutText = a.getString(R.styleable.com_facebook_login_view_logout_text);
a.recycle();
}
private void setButtonText() {
if (sessionTracker != null && sessionTracker.getOpenSession() != null) {
setText((logoutText != null) ? logoutText :
getResources().getString(R.string.com_facebook_loginview_log_out_button));
} else {
setText((loginText != null) ? loginText :
getResources().getString(R.string.com_facebook_loginview_log_in_button));
}
}
private boolean initializeActiveSessionWithCachedToken(Context context) {
if (context == null) {
return false;
}
Session session = Session.getActiveSession();
if (session != null) {
return session.isOpened();
}
String applicationId = Utility.getMetadataApplicationId(context);
if (applicationId == null) {
return false;
}
return Session.openActiveSessionFromCache(context) != null;
}
private void fetchUserInfo() {
if (fetchUserInfo) {
final Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
if (currentSession != userInfoSession) {
Request request = Request.newMeRequest(currentSession, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser me, Response response) {
if (currentSession == sessionTracker.getOpenSession()) {
user = me;
if (userInfoChangedCallback != null) {
userInfoChangedCallback.onUserInfoFetched(user);
}
}
if (response.getError() != null) {
handleError(response.getError().getException());
}
}
});
Request.executeBatchAsync(request);
userInfoSession = currentSession;
}
} else {
user = null;
if (userInfoChangedCallback != null) {
userInfoChangedCallback.onUserInfoFetched(user);
}
}
}
}
private class LoginClickListener implements OnClickListener {
@Override
public void onClick(View v) {
Context context = getContext();
final Session openSession = sessionTracker.getOpenSession();
if (openSession != null) {
// If the Session is currently open, it must mean we need to log out
if (confirmLogout) {
// Create a confirmation dialog
String logout = getResources().getString(R.string.com_facebook_loginview_log_out_action);
String cancel = getResources().getString(R.string.com_facebook_loginview_cancel_action);
String message;
if (user != null && user.getName() != null) {
message = String.format(getResources().getString(R.string.com_facebook_loginview_logged_in_as), user.getName());
} else {
message = getResources().getString(R.string.com_facebook_loginview_logged_in_using_facebook);
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
}
})
.setNegativeButton(cancel, null);
builder.create().show();
} else {
openSession.closeAndClearTokenInformation();
}
} else {
Session currentSession = sessionTracker.getSession();
if (currentSession == null || currentSession.getState().isClosed()) {
sessionTracker.setSession(null);
Session session = new Session.Builder(context).setApplicationId(applicationId).build();
Session.setActiveSession(session);
currentSession = session;
}
if (!currentSession.isOpened()) {
Session.OpenRequest openRequest = null;
if (parentFragment != null) {
openRequest = new Session.OpenRequest(parentFragment);
} else if (context instanceof Activity) {
openRequest = new Session.OpenRequest((Activity)context);
}
if (openRequest != null) {
openRequest.setDefaultAudience(properties.defaultAudience);
openRequest.setPermissions(properties.permissions);
openRequest.setLoginBehavior(properties.loginBehavior);
if (SessionAuthorizationType.PUBLISH.equals(properties.authorizationType)) {
currentSession.openForPublish(openRequest);
} else {
currentSession.openForRead(openRequest);
}
}
}
}
}
}
private class LoginButtonCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
fetchUserInfo();
setButtonText();
if (exception != null) {
handleError(exception);
}
if (properties.sessionStatusCallback != null) {
properties.sessionStatusCallback.call(session, state, exception);
}
}
};
void handleError(Exception exception) {
if (properties.onErrorListener != null) {
if (exception instanceof FacebookException) {
properties.onErrorListener.onError((FacebookException)exception);
} else {
properties.onErrorListener.onError(new FacebookException(exception));
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.facebook.FacebookException;
import com.facebook.LoggingBehavior;
import com.facebook.android.R;
import com.facebook.internal.Logger;
import com.facebook.internal.Utility;
import java.net.MalformedURLException;
/**
* View that displays the profile photo of a supplied profile ID, while conforming
* to user specified dimensions.
*/
public class ProfilePictureView extends FrameLayout {
/**
* Callback interface that will be called when a network or other error is encountered
* while retrieving profile pictures.
*/
public interface OnErrorListener {
/**
* Called when a network or other error is encountered.
* @param error a FacebookException representing the error that was encountered.
*/
void onError(FacebookException error);
}
/**
* Tag used when logging calls are made by ProfilePictureView
*/
public static final String TAG = ProfilePictureView.class.getSimpleName();
/**
* Indicates that the specific size of the View will be set via layout params.
* ProfilePictureView will default to NORMAL X NORMAL, if the layout params set on
* this instance do not have a fixed size.
* Used in calls to setPresetSize() and getPresetSize().
* Corresponds with the preset_size Xml attribute that can be set on ProfilePictureView.
*/
public static final int CUSTOM = -1;
/**
* Indicates that the profile image should fit in a SMALL X SMALL space, regardless
* of whether the cropped or un-cropped version is chosen.
* Used in calls to setPresetSize() and getPresetSize().
* Corresponds with the preset_size Xml attribute that can be set on ProfilePictureView.
*/
public static final int SMALL = -2;
/**
* Indicates that the profile image should fit in a NORMAL X NORMAL space, regardless
* of whether the cropped or un-cropped version is chosen.
* Used in calls to setPresetSize() and getPresetSize().
* Corresponds with the preset_size Xml attribute that can be set on ProfilePictureView.
*/
public static final int NORMAL = -3;
/**
* Indicates that the profile image should fit in a LARGE X LARGE space, regardless
* of whether the cropped or un-cropped version is chosen.
* Used in calls to setPresetSize() and getPresetSize().
* Corresponds with the preset_size Xml attribute that can be set on ProfilePictureView.
*/
public static final int LARGE = -4;
private static final int MIN_SIZE = 1;
private static final boolean IS_CROPPED_DEFAULT_VALUE = true;
private static final String SUPER_STATE_KEY = "ProfilePictureView_superState";
private static final String PROFILE_ID_KEY = "ProfilePictureView_profileId";
private static final String PRESET_SIZE_KEY = "ProfilePictureView_presetSize";
private static final String IS_CROPPED_KEY = "ProfilePictureView_isCropped";
private static final String BITMAP_KEY = "ProfilePictureView_bitmap";
private static final String BITMAP_WIDTH_KEY = "ProfilePictureView_width";
private static final String BITMAP_HEIGHT_KEY = "ProfilePictureView_height";
private static final String PENDING_REFRESH_KEY = "ProfilePictureView_refresh";
private String profileId;
private int queryHeight = ImageRequest.UNSPECIFIED_DIMENSION;
private int queryWidth = ImageRequest.UNSPECIFIED_DIMENSION;
private boolean isCropped = IS_CROPPED_DEFAULT_VALUE;
private Bitmap imageContents;
private ImageView image;
private int presetSizeType = CUSTOM;
private ImageRequest lastRequest;
private OnErrorListener onErrorListener;
/**
* Constructor
*
* @param context Context for this View
*/
public ProfilePictureView(Context context) {
super(context);
initialize(context);
}
/**
* Constructor
*
* @param context Context for this View
* @param attrs AttributeSet for this View.
* The attribute 'preset_size' is processed here
*/
public ProfilePictureView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
parseAttributes(attrs);
}
/**
* Constructor
*
* @param context Context for this View
* @param attrs AttributeSet for this View.
* The attribute 'preset_size' is processed here
* @param defStyle Default style for this View
*/
public ProfilePictureView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize(context);
parseAttributes(attrs);
}
/**
* Gets the current preset size type
*
* @return The current preset size type, if set; CUSTOM if not
*/
public final int getPresetSize() {
return presetSizeType;
}
/**
* Apply a preset size to this profile photo
*
* @param sizeType The size type to apply: SMALL, NORMAL or LARGE
*/
public final void setPresetSize(int sizeType) {
switch (sizeType) {
case SMALL:
case NORMAL:
case LARGE:
case CUSTOM:
this.presetSizeType = sizeType;
break;
default:
throw new IllegalArgumentException("Must use a predefined preset size");
}
requestLayout();
}
/**
* Indicates whether the cropped version of the profile photo has been chosen
*
* @return True if the cropped version is chosen, false if not.
*/
public final boolean isCropped() {
return isCropped;
}
/**
* Sets the profile photo to be the cropped version, or the original version
*
* @param showCroppedVersion True to select the cropped version
* False to select the standard version
*/
public final void setCropped(boolean showCroppedVersion) {
isCropped = showCroppedVersion;
// No need to force the refresh since we will catch the change in required dimensions
refreshImage(false);
}
/**
* Returns the profile Id for the current profile photo
*
* @return The profile Id
*/
public final String getProfileId() {
return profileId;
}
/**
* Sets the profile Id for this profile photo
*
* @param profileId The profileId
* NULL/Empty String will show the blank profile photo
*/
public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture();
force = true;
}
this.profileId = profileId;
refreshImage(force);
}
/**
* Returns the current OnErrorListener for this instance of ProfilePictureView
*
* @return The OnErrorListener
*/
public final OnErrorListener getOnErrorListener() {
return onErrorListener;
}
/**
* Sets an OnErrorListener for this instance of ProfilePictureView to call into when
* certain exceptions occur.
*
* @param onErrorListener The listener object to set
*/
public final void setOnErrorListener(OnErrorListener onErrorListener) {
this.onErrorListener = onErrorListener;
}
/**
* Overriding onMeasure to handle the case where WRAP_CONTENT might be
* specified in the layout. Since we don't know the dimensions of the profile
* photo, we need to handle this case specifically.
* <p/>
* The approach is to default to a NORMAL sized amount of space in the case that
* a preset size is not specified. This logic is applied to both width and height
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
ViewGroup.LayoutParams params = getLayoutParams();
boolean customMeasure = false;
int newHeight = MeasureSpec.getSize(heightMeasureSpec);
int newWidth = MeasureSpec.getSize(widthMeasureSpec);
if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY &&
params.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
newHeight = getPresetSizeInPixels(true); // Default to a preset size
heightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
customMeasure = true;
}
if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY &&
params.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
newWidth = getPresetSizeInPixels(true); // Default to a preset size
widthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
customMeasure = true;
}
if (customMeasure) {
// Since we are providing custom dimensions, we need to handle the measure
// phase from here
setMeasuredDimension(newWidth, newHeight);
measureChildren(widthMeasureSpec, heightMeasureSpec);
} else {
// Rely on FrameLayout to do the right thing
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* In addition to calling super.Layout(), we also attempt to get a new image that
* is properly size for the layout dimensions
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// See if the image needs redrawing
refreshImage(false);
}
/**
* Some of the current state is returned as a Bundle to allow quick restoration
* of the ProfilePictureView object in scenarios like orientation changes.
* @return a Parcelable containing the current state
*/
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle instanceState = new Bundle();
instanceState.putParcelable(SUPER_STATE_KEY, superState);
instanceState.putString(PROFILE_ID_KEY, profileId);
instanceState.putInt(PRESET_SIZE_KEY, presetSizeType);
instanceState.putBoolean(IS_CROPPED_KEY, isCropped);
instanceState.putParcelable(BITMAP_KEY, imageContents);
instanceState.putInt(BITMAP_WIDTH_KEY, queryWidth);
instanceState.putInt(BITMAP_HEIGHT_KEY, queryHeight);
instanceState.putBoolean(PENDING_REFRESH_KEY, lastRequest != null);
return instanceState;
}
/**
* If the passed in state is a Bundle, an attempt is made to restore from it.
* @param state a Parcelable containing the current state
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state.getClass() != Bundle.class) {
super.onRestoreInstanceState(state);
} else {
Bundle instanceState = (Bundle)state;
super.onRestoreInstanceState(instanceState.getParcelable(SUPER_STATE_KEY));
profileId = instanceState.getString(PROFILE_ID_KEY);
presetSizeType = instanceState.getInt(PRESET_SIZE_KEY);
isCropped = instanceState.getBoolean(IS_CROPPED_KEY);
queryWidth = instanceState.getInt(BITMAP_WIDTH_KEY);
queryHeight = instanceState.getInt(BITMAP_HEIGHT_KEY);
setImageBitmap((Bitmap)instanceState.getParcelable(BITMAP_KEY));
if (instanceState.getBoolean(PENDING_REFRESH_KEY)) {
refreshImage(true);
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Null out lastRequest. This way, when the response is returned, we can ascertain
// that the view is detached and hence should not attempt to update its contents.
lastRequest = null;
}
private void initialize(Context context) {
// We only want our ImageView in here. Nothing else is permitted
removeAllViews();
image = new ImageView(context);
LayoutParams imageLayout = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
image.setLayoutParams(imageLayout);
// We want to prevent up-scaling the image, but still have it fit within
// the layout bounds as best as possible.
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
addView(image);
}
private void parseAttributes(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.com_facebook_profile_picture_view);
setPresetSize(a.getInt(R.styleable.com_facebook_profile_picture_view_preset_size, CUSTOM));
isCropped = a.getBoolean(R.styleable.com_facebook_profile_picture_view_is_cropped, IS_CROPPED_DEFAULT_VALUE);
a.recycle();
}
private void refreshImage(boolean force) {
boolean changed = updateImageQueryParameters();
// Note: do not use Utility.isNullOrEmpty here as this will cause the Eclipse
// Graphical Layout editor to fail in some cases
if (profileId == null || profileId.length() == 0 ||
((queryWidth == ImageRequest.UNSPECIFIED_DIMENSION) &&
(queryHeight == ImageRequest.UNSPECIFIED_DIMENSION))) {
setBlankProfilePicture();
} else if (changed || force) {
sendImageRequest(true);
}
}
private void setBlankProfilePicture() {
int blankImageResource = isCropped() ?
R.drawable.com_facebook_profile_picture_blank_square :
R.drawable.com_facebook_profile_picture_blank_portrait;
setImageBitmap( BitmapFactory.decodeResource(getResources(), blankImageResource));
}
private void setImageBitmap(Bitmap imageBitmap) {
if (image != null && imageBitmap != null) {
imageContents = imageBitmap; // Hold for save-restore cycles
image.setImageBitmap(imageBitmap);
}
}
private void sendImageRequest(boolean allowCachedResponse) {
try {
ImageRequest.Builder requestBuilder = new ImageRequest.Builder(
getContext(),
ImageRequest.getProfilePictureUrl(profileId, queryWidth, queryHeight));
ImageRequest request = requestBuilder.setAllowCachedRedirects(allowCachedResponse)
.setCallerTag(this)
.setCallback(
new ImageRequest.Callback() {
@Override
public void onCompleted(ImageResponse response) {
processResponse(response);
}
})
.build();
// Make sure to cancel the old request before sending the new one to prevent
// accidental cancellation of the new request. This could happen if the URL and
// caller tag stayed the same.
if (lastRequest != null) {
ImageDownloader.cancelRequest(lastRequest);
}
lastRequest = request;
ImageDownloader.downloadAsync(request);
} catch (MalformedURLException e) {
Logger.log(LoggingBehavior.REQUESTS, Log.ERROR, TAG, e.toString());
}
}
private void processResponse(ImageResponse response) {
// First check if the response is for the right request. We may have:
// 1. Sent a new request, thus super-ceding this one.
// 2. Detached this view, in which case the response should be discarded.
if (response.getRequest() == lastRequest) {
lastRequest = null;
Bitmap responseImage = response.getBitmap();
Exception error = response.getError();
if (error != null) {
OnErrorListener listener = onErrorListener;
if (listener != null) {
listener.onError(new FacebookException(
"Error in downloading profile picture for profileId: " + getProfileId(), error));
} else {
Logger.log(LoggingBehavior.REQUESTS, Log.ERROR, TAG, error.toString());
}
} else if (responseImage != null) {
setImageBitmap(responseImage);
if (response.isCachedRedirect()) {
sendImageRequest(false);
}
}
}
}
private boolean updateImageQueryParameters() {
int newHeightPx = getHeight();
int newWidthPx = getWidth();
if (newWidthPx < MIN_SIZE || newHeightPx < MIN_SIZE) {
// Not enough space laid out for this View yet. Or something else is awry.
return false;
}
int presetSize = getPresetSizeInPixels(false);
if (presetSize != ImageRequest.UNSPECIFIED_DIMENSION) {
newWidthPx = presetSize;
newHeightPx = presetSize;
}
// The cropped version is square
// If full version is desired, then only one dimension is required.
if (newWidthPx <= newHeightPx) {
newHeightPx = isCropped() ? newWidthPx : ImageRequest.UNSPECIFIED_DIMENSION;
} else {
newWidthPx = isCropped() ? newHeightPx : ImageRequest.UNSPECIFIED_DIMENSION;
}
boolean changed = (newWidthPx != queryWidth) || (newHeightPx != queryHeight);
queryWidth = newWidthPx;
queryHeight = newHeightPx;
return changed;
}
private int getPresetSizeInPixels(boolean forcePreset) {
int dimensionId;
switch (presetSizeType) {
case SMALL:
dimensionId = R.dimen.com_facebook_profilepictureview_preset_size_small;
break;
case NORMAL:
dimensionId = R.dimen.com_facebook_profilepictureview_preset_size_normal;
break;
case LARGE:
dimensionId = R.dimen.com_facebook_profilepictureview_preset_size_large;
break;
case CUSTOM:
if (!forcePreset) {
return ImageRequest.UNSPECIFIED_DIMENSION;
} else {
dimensionId = R.dimen.com_facebook_profilepictureview_preset_size_normal;
break;
}
default:
return ImageRequest.UNSPECIFIED_DIMENSION;
}
return getResources().getDimensionPixelSize(dimensionId);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.*;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphObject;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Collator;
import java.util.*;
class GraphObjectAdapter<T extends GraphObject> extends BaseAdapter implements SectionIndexer {
private static final int DISPLAY_SECTIONS_THRESHOLD = 1;
private static final int HEADER_VIEW_TYPE = 0;
private static final int GRAPH_OBJECT_VIEW_TYPE = 1;
private static final int ACTIVITY_CIRCLE_VIEW_TYPE = 2;
private static final int MAX_PREFETCHED_PICTURES = 20;
private static final String ID = "id";
private static final String NAME = "name";
private static final String PICTURE = "picture";
private final Map<String, ImageRequest> pendingRequests = new HashMap<String, ImageRequest>();
private final LayoutInflater inflater;
private List<String> sectionKeys = new ArrayList<String>();
private Map<String, ArrayList<T>> graphObjectsBySection = new HashMap<String, ArrayList<T>>();
private Map<String, T> graphObjectsById = new HashMap<String, T>();
private boolean displaySections;
private List<String> sortFields;
private String groupByField;
private boolean showPicture;
private boolean showCheckbox;
private Filter<T> filter;
private DataNeededListener dataNeededListener;
private GraphObjectCursor<T> cursor;
private Context context;
private Map<String, ImageResponse> prefetchedPictureCache = new HashMap<String, ImageResponse>();
private ArrayList<String> prefetchedProfilePictureIds = new ArrayList<String>();
private OnErrorListener onErrorListener;
public interface DataNeededListener {
public void onDataNeeded();
}
public interface OnErrorListener {
void onError(GraphObjectAdapter<?> adapter, FacebookException error);
}
public static class SectionAndItem<T extends GraphObject> {
public String sectionKey;
public T graphObject;
public enum Type {
GRAPH_OBJECT,
SECTION_HEADER,
ACTIVITY_CIRCLE
}
public SectionAndItem(String sectionKey, T graphObject) {
this.sectionKey = sectionKey;
this.graphObject = graphObject;
}
public Type getType() {
if (sectionKey == null) {
return Type.ACTIVITY_CIRCLE;
} else if (graphObject == null) {
return Type.SECTION_HEADER;
} else {
return Type.GRAPH_OBJECT;
}
}
}
interface Filter<T> {
boolean includeItem(T graphObject);
}
public GraphObjectAdapter(Context context) {
this.context = context;
this.inflater = LayoutInflater.from(context);
}
public List<String> getSortFields() {
return sortFields;
}
public void setSortFields(List<String> sortFields) {
this.sortFields = sortFields;
}
public String getGroupByField() {
return groupByField;
}
public void setGroupByField(String groupByField) {
this.groupByField = groupByField;
}
public boolean getShowPicture() {
return showPicture;
}
public void setShowPicture(boolean showPicture) {
this.showPicture = showPicture;
}
public boolean getShowCheckbox() {
return showCheckbox;
}
public void setShowCheckbox(boolean showCheckbox) {
this.showCheckbox = showCheckbox;
}
public DataNeededListener getDataNeededListener() {
return dataNeededListener;
}
public void setDataNeededListener(DataNeededListener dataNeededListener) {
this.dataNeededListener = dataNeededListener;
}
public OnErrorListener getOnErrorListener() {
return onErrorListener;
}
public void setOnErrorListener(OnErrorListener onErrorListener) {
this.onErrorListener = onErrorListener;
}
public GraphObjectCursor<T> getCursor() {
return cursor;
}
public boolean changeCursor(GraphObjectCursor<T> cursor) {
if (this.cursor == cursor) {
return false;
}
if (this.cursor != null) {
this.cursor.close();
}
this.cursor = cursor;
rebuildAndNotify();
return true;
}
public void rebuildAndNotify() {
rebuildSections();
notifyDataSetChanged();
}
public void prioritizeViewRange(int firstVisibleItem, int lastVisibleItem, int prefetchBuffer) {
if (lastVisibleItem < firstVisibleItem) {
return;
}
// We want to prioritize requests for items which are visible but do not have pictures
// loaded yet. We also want to pre-fetch pictures for items which are not yet visible
// but are within a buffer on either side of the visible items, on the assumption that
// they will be visible soon. For these latter items, we'll store the images in memory
// in the hopes we can immediately populate their image view when needed.
// Prioritize the requests in reverse order since each call to prioritizeRequest will just
// move it to the front of the queue. And we want the earliest ones in the range to be at
// the front of the queue, so all else being equal, the list will appear to populate from
// the top down.
for (int i = lastVisibleItem; i >= 0; i--) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
if (sectionAndItem.graphObject != null) {
String id = getIdOfGraphObject(sectionAndItem.graphObject);
ImageRequest request = pendingRequests.get(id);
if (request != null) {
ImageDownloader.prioritizeRequest(request);
}
}
}
// For items which are not visible, but within the buffer on either side, we want to
// fetch those items and store them in a small in-memory cache of bitmaps.
int start = Math.max(0, firstVisibleItem - prefetchBuffer);
int end = Math.min(lastVisibleItem + prefetchBuffer, getCount() - 1);
ArrayList<T> graphObjectsToPrefetchPicturesFor = new ArrayList<T>();
// Add the IDs before and after the visible range.
for (int i = start; i < firstVisibleItem; ++i) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
if (sectionAndItem.graphObject != null) {
graphObjectsToPrefetchPicturesFor.add(sectionAndItem.graphObject);
}
}
for (int i = lastVisibleItem + 1; i <= end; ++i) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
if (sectionAndItem.graphObject != null) {
graphObjectsToPrefetchPicturesFor.add(sectionAndItem.graphObject);
}
}
for (T graphObject : graphObjectsToPrefetchPicturesFor) {
URL url = getPictureUrlOfGraphObject(graphObject);
final String id = getIdOfGraphObject(graphObject);
// This URL already have been requested for pre-fetching, but we want to act in an LRU manner, so move
// it to the end of the list regardless.
boolean alreadyPrefetching = prefetchedProfilePictureIds.remove(id);
prefetchedProfilePictureIds.add(id);
// If we've already requested it for pre-fetching, no need to do so again.
if (!alreadyPrefetching) {
downloadProfilePicture(id, url, null);
}
}
}
protected String getSectionKeyOfGraphObject(T graphObject) {
String result = null;
if (groupByField != null) {
result = (String) graphObject.getProperty(groupByField);
if (result != null && result.length() > 0) {
result = result.substring(0, 1).toUpperCase();
}
}
return (result != null) ? result : "";
}
protected CharSequence getTitleOfGraphObject(T graphObject) {
return (String) graphObject.getProperty(NAME);
}
protected CharSequence getSubTitleOfGraphObject(T graphObject) {
return null;
}
protected URL getPictureUrlOfGraphObject(T graphObject) {
String url = null;
Object o = graphObject.getProperty(PICTURE);
if (o instanceof String) {
url = (String) o;
} else if (o instanceof JSONObject) {
ItemPicture itemPicture = GraphObject.Factory.create((JSONObject) o).cast(ItemPicture.class);
ItemPictureData data = itemPicture.getData();
if (data != null) {
url = data.getUrl();
}
}
if (url != null) {
try {
return new URL(url);
} catch (MalformedURLException e) {
}
}
return null;
}
protected View getSectionHeaderView(String sectionHeader, View convertView, ViewGroup parent) {
TextView result = (TextView) convertView;
if (result == null) {
result = (TextView) inflater.inflate(R.layout.com_facebook_picker_list_section_header, null);
}
result.setText(sectionHeader);
return result;
}
protected View getGraphObjectView(T graphObject, View convertView, ViewGroup parent) {
View result = convertView;
if (result == null) {
result = createGraphObjectView(graphObject, convertView);
}
populateGraphObjectView(result, graphObject);
return result;
}
private View getActivityCircleView(View convertView, ViewGroup parent) {
View result = convertView;
if (result == null) {
result = inflater.inflate(R.layout.com_facebook_picker_activity_circle_row, null);
}
ProgressBar activityCircle = (ProgressBar) result.findViewById(R.id.com_facebook_picker_row_activity_circle);
activityCircle.setVisibility(View.VISIBLE);
return result;
}
protected int getGraphObjectRowLayoutId(T graphObject) {
return R.layout.com_facebook_picker_list_row;
}
protected int getDefaultPicture() {
return R.drawable.com_facebook_profile_default_icon;
}
protected View createGraphObjectView(T graphObject, View convertView) {
View result = inflater.inflate(getGraphObjectRowLayoutId(graphObject), null);
ViewStub checkboxStub = (ViewStub) result.findViewById(R.id.com_facebook_picker_checkbox_stub);
if (checkboxStub != null) {
if (!getShowCheckbox()) {
checkboxStub.setVisibility(View.GONE);
} else {
CheckBox checkBox = (CheckBox) checkboxStub.inflate();
updateCheckboxState(checkBox, false);
}
}
ViewStub profilePicStub = (ViewStub) result.findViewById(R.id.com_facebook_picker_profile_pic_stub);
if (!getShowPicture()) {
profilePicStub.setVisibility(View.GONE);
} else {
ImageView imageView = (ImageView) profilePicStub.inflate();
imageView.setVisibility(View.VISIBLE);
}
return result;
}
protected void populateGraphObjectView(View view, T graphObject) {
String id = getIdOfGraphObject(graphObject);
view.setTag(id);
CharSequence title = getTitleOfGraphObject(graphObject);
TextView titleView = (TextView) view.findViewById(R.id.com_facebook_picker_title);
if (titleView != null) {
titleView.setText(title, TextView.BufferType.SPANNABLE);
}
CharSequence subtitle = getSubTitleOfGraphObject(graphObject);
TextView subtitleView = (TextView) view.findViewById(R.id.picker_subtitle);
if (subtitleView != null) {
if (subtitle != null) {
subtitleView.setText(subtitle, TextView.BufferType.SPANNABLE);
subtitleView.setVisibility(View.VISIBLE);
} else {
subtitleView.setVisibility(View.GONE);
}
}
if (getShowCheckbox()) {
CheckBox checkBox = (CheckBox) view.findViewById(R.id.com_facebook_picker_checkbox);
updateCheckboxState(checkBox, isGraphObjectSelected(id));
}
if (getShowPicture()) {
URL pictureURL = getPictureUrlOfGraphObject(graphObject);
if (pictureURL != null) {
ImageView profilePic = (ImageView) view.findViewById(R.id.com_facebook_picker_image);
// See if we have already pre-fetched this; if not, download it.
if (prefetchedPictureCache.containsKey(id)) {
ImageResponse response = prefetchedPictureCache.get(id);
profilePic.setImageBitmap(response.getBitmap());
profilePic.setTag(response.getRequest().getImageUrl());
} else {
downloadProfilePicture(id, pictureURL, profilePic);
}
}
}
}
/**
* @throws FacebookException if the GraphObject doesn't have an ID.
*/
String getIdOfGraphObject(T graphObject) {
if (graphObject.asMap().containsKey(ID)) {
Object obj = graphObject.getProperty(ID);
if (obj instanceof String) {
return (String) obj;
}
}
throw new FacebookException("Received an object without an ID.");
}
boolean filterIncludesItem(T graphObject) {
return filter == null || filter.includeItem(graphObject);
}
Filter<T> getFilter() {
return filter;
}
void setFilter(Filter<T> filter) {
this.filter = filter;
}
boolean isGraphObjectSelected(String graphObjectId) {
return false;
}
void updateCheckboxState(CheckBox checkBox, boolean graphObjectSelected) {
// Default is no-op
}
String getPictureFieldSpecifier() {
// How big is our image?
View view = createGraphObjectView(null, null);
ImageView picture = (ImageView) view.findViewById(R.id.com_facebook_picker_image);
if (picture == null) {
return null;
}
// Note: these dimensions are in pixels, not dips
ViewGroup.LayoutParams layoutParams = picture.getLayoutParams();
return String.format("picture.height(%d).width(%d)", layoutParams.height, layoutParams.width);
}
private boolean shouldShowActivityCircleCell() {
// We show the "more data" activity circle cell if we have a listener to request more data,
// we are expecting more data, and we have some data already (i.e., not on a fresh query).
return (cursor != null) && cursor.areMoreObjectsAvailable() && (dataNeededListener != null) && !isEmpty();
}
private void rebuildSections() {
sectionKeys = new ArrayList<String>();
graphObjectsBySection = new HashMap<String, ArrayList<T>>();
graphObjectsById = new HashMap<String, T>();
displaySections = false;
if (cursor == null || cursor.getCount() == 0) {
return;
}
int objectsAdded = 0;
cursor.moveToFirst();
do {
T graphObject = cursor.getGraphObject();
if (!filterIncludesItem(graphObject)) {
continue;
}
objectsAdded++;
String sectionKeyOfItem = getSectionKeyOfGraphObject(graphObject);
if (!graphObjectsBySection.containsKey(sectionKeyOfItem)) {
sectionKeys.add(sectionKeyOfItem);
graphObjectsBySection.put(sectionKeyOfItem, new ArrayList<T>());
}
List<T> section = graphObjectsBySection.get(sectionKeyOfItem);
section.add(graphObject);
graphObjectsById.put(getIdOfGraphObject(graphObject), graphObject);
} while (cursor.moveToNext());
if (sortFields != null) {
final Collator collator = Collator.getInstance();
for (List<T> section : graphObjectsBySection.values()) {
Collections.sort(section, new Comparator<GraphObject>() {
@Override
public int compare(GraphObject a, GraphObject b) {
return compareGraphObjects(a, b, sortFields, collator);
}
});
}
}
Collections.sort(sectionKeys, Collator.getInstance());
displaySections = sectionKeys.size() > 1 && objectsAdded > DISPLAY_SECTIONS_THRESHOLD;
}
SectionAndItem<T> getSectionAndItem(int position) {
if (sectionKeys.size() == 0) {
return null;
}
String sectionKey = null;
T graphObject = null;
if (!displaySections) {
sectionKey = sectionKeys.get(0);
List<T> section = graphObjectsBySection.get(sectionKey);
if (position >= 0 && position < section.size()) {
graphObject = graphObjectsBySection.get(sectionKey).get(position);
} else {
// We are off the end; we must be adding an activity circle to indicate more data is coming.
assert dataNeededListener != null && cursor.areMoreObjectsAvailable();
// We return null for both to indicate this.
return new SectionAndItem<T>(null, null);
}
} else {
// Count through the sections; the "0" position in each section is the header. We decrement
// position each time we skip forward a certain number of elements, including the header.
for (String key : sectionKeys) {
// Decrement if we skip over the header
if (position-- == 0) {
sectionKey = key;
break;
}
List<T> section = graphObjectsBySection.get(key);
if (position < section.size()) {
// The position is somewhere in this section. Get the corresponding graph object.
sectionKey = key;
graphObject = section.get(position);
break;
}
// Decrement by as many items as we skipped over
position -= section.size();
}
}
if (sectionKey != null) {
// Note: graphObject will be null if this represents a section header.
return new SectionAndItem<T>(sectionKey, graphObject);
} else {
throw new IndexOutOfBoundsException("position");
}
}
int getPosition(String sectionKey, T graphObject) {
int position = 0;
boolean found = false;
// First find the section key and increment position one for each header we will render;
// increment by the size of each section prior to the one we want.
for (String key : sectionKeys) {
if (displaySections) {
position++;
}
if (key.equals(sectionKey)) {
found = true;
break;
} else {
position += graphObjectsBySection.get(key).size();
}
}
if (!found) {
return -1;
} else if (graphObject == null) {
// null represents the header for a section; we counted this header in position earlier,
// so subtract it back out.
return position - (displaySections ? 1 : 0);
}
// Now find index of this item within that section.
for (T t : graphObjectsBySection.get(sectionKey)) {
if (GraphObject.Factory.hasSameId(t, graphObject)) {
return position;
}
position++;
}
return -1;
}
@Override
public boolean isEmpty() {
// We'll never populate sectionKeys unless we have at least one object.
return sectionKeys.size() == 0;
}
@Override
public int getCount() {
if (sectionKeys.size() == 0) {
return 0;
}
// If we are not displaying sections, we don't display a header; otherwise, we have one header per item in
// addition to the actual items.
int count = (displaySections) ? sectionKeys.size() : 0;
for (List<T> section : graphObjectsBySection.values()) {
count += section.size();
}
// If we should show a cell with an activity circle indicating more data is coming, add it to the count.
if (shouldShowActivityCircleCell()) {
++count;
}
return count;
}
@Override
public boolean areAllItemsEnabled() {
return displaySections;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEnabled(int position) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
return sectionAndItem.getType() == SectionAndItem.Type.GRAPH_OBJECT;
}
@Override
public Object getItem(int position) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
return (sectionAndItem.getType() == SectionAndItem.Type.GRAPH_OBJECT) ? sectionAndItem.graphObject : null;
}
@Override
public long getItemId(int position) {
// We assume IDs that can be converted to longs. If this is not the case for certain types of
// GraphObjects, subclasses should override this to return, e.g., position, and override hasStableIds
// to return false.
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
if (sectionAndItem != null && sectionAndItem.graphObject != null) {
String id = getIdOfGraphObject(sectionAndItem.graphObject);
if (id != null) {
return Long.parseLong(id);
}
}
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType(int position) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
switch (sectionAndItem.getType()) {
case SECTION_HEADER:
return HEADER_VIEW_TYPE;
case GRAPH_OBJECT:
return GRAPH_OBJECT_VIEW_TYPE;
case ACTIVITY_CIRCLE:
return ACTIVITY_CIRCLE_VIEW_TYPE;
default:
throw new FacebookException("Unexpected type of section and item.");
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
switch (sectionAndItem.getType()) {
case SECTION_HEADER:
return getSectionHeaderView(sectionAndItem.sectionKey, convertView, parent);
case GRAPH_OBJECT:
return getGraphObjectView(sectionAndItem.graphObject, convertView, parent);
case ACTIVITY_CIRCLE:
// If we get a request for this view, it means we need more data.
assert cursor.areMoreObjectsAvailable() && (dataNeededListener != null);
dataNeededListener.onDataNeeded();
return getActivityCircleView(convertView, parent);
default:
throw new FacebookException("Unexpected type of section and item.");
}
}
@Override
public Object[] getSections() {
if (displaySections) {
return sectionKeys.toArray();
} else {
return new Object[0];
}
}
@Override
public int getPositionForSection(int section) {
if (displaySections) {
section = Math.max(0, Math.min(section, sectionKeys.size() - 1));
if (section < sectionKeys.size()) {
return getPosition(sectionKeys.get(section), null);
}
}
return 0;
}
@Override
public int getSectionForPosition(int position) {
SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
if (sectionAndItem != null &&
sectionAndItem.getType() != SectionAndItem.Type.ACTIVITY_CIRCLE) {
return Math.max(0, Math.min(sectionKeys.indexOf(sectionAndItem.sectionKey), sectionKeys.size() - 1));
}
return 0;
}
public List<T> getGraphObjectsById(Collection<String> ids) {
Set<String> idSet = new HashSet<String>();
idSet.addAll(ids);
ArrayList<T> result = new ArrayList<T>(idSet.size());
for (String id : idSet) {
T graphObject = graphObjectsById.get(id);
if (graphObject != null) {
result.add(graphObject);
}
}
return result;
}
private void downloadProfilePicture(final String profileId, URL pictureURL, final ImageView imageView) {
if (pictureURL == null) {
return;
}
// If we don't have an imageView, we are pre-fetching this image to store in-memory because we
// think the user might scroll to its corresponding list row. If we do have an imageView, we
// only want to queue a download if the view's tag isn't already set to the URL (which would mean
// it's already got the correct picture).
boolean prefetching = imageView == null;
if (prefetching || !pictureURL.equals(imageView.getTag())) {
if (!prefetching) {
// Setting the tag to the profile ID indicates that we're currently downloading the
// picture for this profile; we'll set it to the actual picture URL when complete.
imageView.setTag(profileId);
imageView.setImageResource(getDefaultPicture());
}
ImageRequest.Builder builder = new ImageRequest.Builder(context.getApplicationContext(), pictureURL)
.setCallerTag(this)
.setCallback(
new ImageRequest.Callback() {
@Override
public void onCompleted(ImageResponse response) {
processImageResponse(response, profileId, imageView);
}
});
ImageRequest newRequest = builder.build();
pendingRequests.put(profileId, newRequest);
ImageDownloader.downloadAsync(newRequest);
}
}
private void callOnErrorListener(Exception exception) {
if (onErrorListener != null) {
if (!(exception instanceof FacebookException)) {
exception = new FacebookException(exception);
}
onErrorListener.onError(this, (FacebookException) exception);
}
}
private void processImageResponse(ImageResponse response, String graphObjectId, ImageView imageView) {
pendingRequests.remove(graphObjectId);
if (response.getError() != null) {
callOnErrorListener(response.getError());
}
if (imageView == null) {
// This was a pre-fetch request.
if (response.getBitmap() != null) {
// Is the cache too big?
if (prefetchedPictureCache.size() >= MAX_PREFETCHED_PICTURES) {
// Find the oldest one and remove it.
String oldestId = prefetchedProfilePictureIds.remove(0);
prefetchedPictureCache.remove(oldestId);
}
prefetchedPictureCache.put(graphObjectId, response);
}
} else if (imageView != null && graphObjectId.equals(imageView.getTag())) {
Exception error = response.getError();
Bitmap bitmap = response.getBitmap();
if (error == null && bitmap != null) {
imageView.setImageBitmap(bitmap);
imageView.setTag(response.getRequest().getImageUrl());
}
}
}
private static int compareGraphObjects(GraphObject a, GraphObject b, Collection<String> sortFields,
Collator collator) {
for (String sortField : sortFields) {
String sa = (String) a.getProperty(sortField);
String sb = (String) b.getProperty(sortField);
if (sa != null && sb != null) {
int result = collator.compare(sa, sb);
if (result != 0) {
return result;
}
} else if (!(sa == null && sb == null)) {
return (sa == null) ? -1 : 1;
}
}
return 0;
}
// Graph object type to navigate the JSON that sometimes comes back instead of a URL string
private interface ItemPicture extends GraphObject {
ItemPictureData getData();
}
// Graph object type to navigate the JSON that sometimes comes back instead of a URL string
private interface ItemPictureData extends GraphObject {
String getUrl();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.database.CursorIndexOutOfBoundsException;
import com.facebook.model.GraphObject;
import java.util.ArrayList;
import java.util.Collection;
class SimpleGraphObjectCursor<T extends GraphObject> implements GraphObjectCursor<T> {
private int pos = -1;
private boolean closed = false;
private ArrayList<T> graphObjects = new ArrayList<T>();
private boolean moreObjectsAvailable = false;
private boolean fromCache = false;
SimpleGraphObjectCursor() {
}
SimpleGraphObjectCursor(SimpleGraphObjectCursor<T> other) {
pos = other.pos;
closed = other.closed;
graphObjects = new ArrayList<T>();
graphObjects.addAll(other.graphObjects);
fromCache = other.fromCache;
// We do not copy observers.
}
public void addGraphObjects(Collection<T> graphObjects, boolean fromCache) {
this.graphObjects.addAll(graphObjects);
// We consider this cached if ANY results were from the cache.
this.fromCache |= fromCache;
}
public boolean isFromCache() {
return fromCache;
}
public void setFromCache(boolean fromCache) {
this.fromCache = fromCache;
}
public boolean areMoreObjectsAvailable() {
return moreObjectsAvailable;
}
public void setMoreObjectsAvailable(boolean moreObjectsAvailable) {
this.moreObjectsAvailable = moreObjectsAvailable;
}
@Override
public int getCount() {
return graphObjects.size();
}
@Override
public int getPosition() {
return pos;
}
@Override
public boolean move(int offset) {
return moveToPosition(pos + offset);
}
@Override
public boolean moveToPosition(int position) {
final int count = getCount();
if (position >= count) {
pos = count;
return false;
}
if (position < 0) {
pos = -1;
return false;
}
pos = position;
return true;
}
@Override
public boolean moveToFirst() {
return moveToPosition(0);
}
@Override
public boolean moveToLast() {
return moveToPosition(getCount() - 1);
}
@Override
public boolean moveToNext() {
return moveToPosition(pos + 1);
}
@Override
public boolean moveToPrevious() {
return moveToPosition(pos - 1);
}
@Override
public boolean isFirst() {
return (pos == 0) && (getCount() != 0);
}
@Override
public boolean isLast() {
final int count = getCount();
return (pos == (count - 1)) && (count != 0);
}
@Override
public boolean isBeforeFirst() {
return (getCount() == 0) || (pos == -1);
}
@Override
public boolean isAfterLast() {
final int count = getCount();
return (count == 0) || (pos == count);
}
@Override
public T getGraphObject() {
if (pos < 0) {
throw new CursorIndexOutOfBoundsException("Before first object.");
}
if (pos >= graphObjects.size()) {
throw new CursorIndexOutOfBoundsException("After last object.");
}
return graphObjects.get(pos);
}
@Override
public void close() {
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Certain operations such as publishing a status or publishing a photo require an audience. When the user
* grants an application permission to perform a publish operation, a default audience is selected as the
* publication ceiling for the application. This enumerated value allows the application to select which
* audience to ask the user to grant publish permission for.
*/
public enum SessionDefaultAudience {
/**
* Represents an invalid default audience value, can be used when only reading.
*/
NONE(null),
/**
* Indicates only the user is able to see posts made by the application.
*/
ONLY_ME(NativeProtocol.AUDIENCE_ME),
/**
* Indicates that the user's friends are able to see posts made by the application.
*/
FRIENDS(NativeProtocol.AUDIENCE_FRIENDS),
/**
* Indicates that all Facebook users are able to see posts made by the application.
*/
EVERYONE(NativeProtocol.AUDIENCE_EVERYONE);
private final String nativeProtocolAudience;
private SessionDefaultAudience(String protocol) {
nativeProtocolAudience = protocol;
}
String getNativeProtocolAudience() {
return nativeProtocolAudience;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Represents an error condition relating to displaying a Facebook Web dialog.
*/
public class FacebookDialogException extends FacebookException {
static final long serialVersionUID = 1;
private int errorCode;
private String failingUrl;
/**
* Constructs a new FacebookException.
*/
public FacebookDialogException(String message, int errorCode, String failingUrl) {
super(message);
this.errorCode = errorCode;
this.failingUrl = failingUrl;
}
/**
* Gets the error code received by the WebView. See:
* http://developer.android.com/reference/android/webkit/WebViewClient.html
*
* @return the error code
*/
public int getErrorCode() {
return errorCode;
}
/**
* Gets the URL that the dialog was trying to load.
* @return the URL
*/
public String getFailingUrl() {
return failingUrl;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.os.Bundle;
/**
* LegacyHelper is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the methods in this class is unsupported, and they may be modified or removed without warning at
* any time.
*/
public class LegacyHelper {
@Deprecated
public static void extendTokenCompleted(Session session, Bundle bundle) {
session.extendTokenCompleted(bundle);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.os.Bundle;
/**
* Implements a trivial {@link TokenCachingStrategy} that does not actually cache any tokens.
* It is intended for use when an access token may be used on a temporary basis but should not be
* cached for future use (for instance, when handling a deep link).
*/
public class NonCachingTokenCachingStrategy extends TokenCachingStrategy {
@Override
public Bundle load() {
return null;
}
@Override
public void save(Bundle bundle) {
}
@Override
public void clear() {
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.facebook.internal.Logger;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
* <p>
* An implementation of {@link TokenCachingStrategy TokenCachingStrategy} that uses Android SharedPreferences
* to persist information.
* </p>
* <p>
* The data to be cached is passed in via a Bundle. Only non-null key-value-pairs where
* the value is one of the following types (or an array of the same) are persisted:
* boolean, byte, int, long, float, double, char. In addition, String and List<String>
* are also supported.
* </p>
*/
public class SharedPreferencesTokenCachingStrategy extends TokenCachingStrategy {
private static final String DEFAULT_CACHE_KEY = "com.facebook.SharedPreferencesTokenCachingStrategy.DEFAULT_KEY";
private static final String TAG = SharedPreferencesTokenCachingStrategy.class.getSimpleName();
private static final String JSON_VALUE_TYPE = "valueType";
private static final String JSON_VALUE = "value";
private static final String JSON_VALUE_ENUM_TYPE = "enumType";
private static final String TYPE_BOOLEAN = "bool";
private static final String TYPE_BOOLEAN_ARRAY = "bool[]";
private static final String TYPE_BYTE = "byte";
private static final String TYPE_BYTE_ARRAY = "byte[]";
private static final String TYPE_SHORT = "short";
private static final String TYPE_SHORT_ARRAY = "short[]";
private static final String TYPE_INTEGER = "int";
private static final String TYPE_INTEGER_ARRAY = "int[]";
private static final String TYPE_LONG = "long";
private static final String TYPE_LONG_ARRAY = "long[]";
private static final String TYPE_FLOAT = "float";
private static final String TYPE_FLOAT_ARRAY = "float[]";
private static final String TYPE_DOUBLE = "double";
private static final String TYPE_DOUBLE_ARRAY = "double[]";
private static final String TYPE_CHAR = "char";
private static final String TYPE_CHAR_ARRAY = "char[]";
private static final String TYPE_STRING = "string";
private static final String TYPE_STRING_LIST = "stringList";
private static final String TYPE_ENUM = "enum";
private String cacheKey;
private SharedPreferences cache;
/**
* Creates a default {@link SharedPreferencesTokenCachingStrategy SharedPreferencesTokenCachingStrategy}
* instance that provides access to a single set of token information.
*
* @param context
* The Context object to use to get the SharedPreferences object.
*
* @throws NullPointerException if the passed in Context is null
*/
public SharedPreferencesTokenCachingStrategy(Context context) {
this(context, null);
}
/**
* Creates a {@link SharedPreferencesTokenCachingStrategy SharedPreferencesTokenCachingStrategy} instance
* that is distinct for the passed in cacheKey.
*
* @param context
* The Context object to use to get the SharedPreferences object.
*
* @param cacheKey
* Identifies a distinct set of token information.
*
* @throws NullPointerException if the passed in Context is null
*/
public SharedPreferencesTokenCachingStrategy(Context context, String cacheKey) {
Validate.notNull(context, "context");
this.cacheKey = Utility.isNullOrEmpty(cacheKey) ? DEFAULT_CACHE_KEY : cacheKey;
// If the application context is available, use that. However, if it isn't
// available (possibly because of a context that was created manually), use
// the passed in context directly.
Context applicationContext = context.getApplicationContext();
context = applicationContext != null ? applicationContext : context;
this.cache = context.getSharedPreferences(
this.cacheKey,
Context.MODE_PRIVATE);
}
/**
* Returns a Bundle that contains the information stored in this cache
*
* @return A Bundle with the information contained in this cache
*/
public Bundle load() {
Bundle settings = new Bundle();
Map<String, ?> allCachedEntries = cache.getAll();
for (String key : allCachedEntries.keySet()) {
try {
deserializeKey(key, settings);
} catch (JSONException e) {
// Error in the cache. So consider it corrupted and return null
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG,
"Error reading cached value for key: '" + key + "' -- " + e);
return null;
}
}
return settings;
}
/**
* Persists all supported data types present in the passed in Bundle, to the
* cache
*
* @param bundle
* The Bundle containing information to be cached
*/
public void save(Bundle bundle) {
Validate.notNull(bundle, "bundle");
SharedPreferences.Editor editor = cache.edit();
for (String key : bundle.keySet()) {
try {
serializeKey(key, bundle, editor);
} catch (JSONException e) {
// Error in the bundle. Don't store a partial cache.
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "Error processing value for key: '" + key + "' -- " + e);
// Bypass the commit and just return. This cancels the entire edit transaction
return;
}
}
boolean successfulCommit = editor.commit();
if (!successfulCommit) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "SharedPreferences.Editor.commit() was not successful");
}
}
/**
* Clears out all token information stored in this cache.
*/
public void clear() {
cache.edit().clear().commit();
}
private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)
throws JSONException {
Object value = bundle.get(key);
if (value == null) {
// Cannot serialize null values.
return;
}
String supportedType = null;
JSONArray jsonArray = null;
JSONObject json = new JSONObject();
if (value instanceof Byte) {
supportedType = TYPE_BYTE;
json.put(JSON_VALUE, ((Byte)value).intValue());
} else if (value instanceof Short) {
supportedType = TYPE_SHORT;
json.put(JSON_VALUE, ((Short)value).intValue());
} else if (value instanceof Integer) {
supportedType = TYPE_INTEGER;
json.put(JSON_VALUE, ((Integer)value).intValue());
} else if (value instanceof Long) {
supportedType = TYPE_LONG;
json.put(JSON_VALUE, ((Long)value).longValue());
} else if (value instanceof Float) {
supportedType = TYPE_FLOAT;
json.put(JSON_VALUE, ((Float)value).doubleValue());
} else if (value instanceof Double) {
supportedType = TYPE_DOUBLE;
json.put(JSON_VALUE, ((Double)value).doubleValue());
} else if (value instanceof Boolean) {
supportedType = TYPE_BOOLEAN;
json.put(JSON_VALUE, ((Boolean)value).booleanValue());
} else if (value instanceof Character) {
supportedType = TYPE_CHAR;
json.put(JSON_VALUE, value.toString());
} else if (value instanceof String) {
supportedType = TYPE_STRING;
json.put(JSON_VALUE, (String)value);
} else if (value instanceof Enum<?>) {
supportedType = TYPE_ENUM;
json.put(JSON_VALUE, value.toString());
json.put(JSON_VALUE_ENUM_TYPE, value.getClass().getName());
} else {
// Optimistically create a JSONArray. If not an array type, we can null
// it out later
jsonArray = new JSONArray();
if (value instanceof byte[]) {
supportedType = TYPE_BYTE_ARRAY;
for (byte v : (byte[])value) {
jsonArray.put((int)v);
}
} else if (value instanceof short[]) {
supportedType = TYPE_SHORT_ARRAY;
for (short v : (short[])value) {
jsonArray.put((int)v);
}
} else if (value instanceof int[]) {
supportedType = TYPE_INTEGER_ARRAY;
for (int v : (int[])value) {
jsonArray.put(v);
}
} else if (value instanceof long[]) {
supportedType = TYPE_LONG_ARRAY;
for (long v : (long[])value) {
jsonArray.put(v);
}
} else if (value instanceof float[]) {
supportedType = TYPE_FLOAT_ARRAY;
for (float v : (float[])value) {
jsonArray.put((double)v);
}
} else if (value instanceof double[]) {
supportedType = TYPE_DOUBLE_ARRAY;
for (double v : (double[])value) {
jsonArray.put(v);
}
} else if (value instanceof boolean[]) {
supportedType = TYPE_BOOLEAN_ARRAY;
for (boolean v : (boolean[])value) {
jsonArray.put(v);
}
} else if (value instanceof char[]) {
supportedType = TYPE_CHAR_ARRAY;
for (char v : (char[])value) {
jsonArray.put(String.valueOf(v));
}
} else if (value instanceof List<?>) {
supportedType = TYPE_STRING_LIST;
@SuppressWarnings("unchecked")
List<String> stringList = (List<String>)value;
for (String v : stringList) {
jsonArray.put((v == null) ? JSONObject.NULL : v);
}
} else {
// Unsupported type. Clear out the array as a precaution even though
// it is redundant with the null supportedType.
jsonArray = null;
}
}
if (supportedType != null) {
json.put(JSON_VALUE_TYPE, supportedType);
if (jsonArray != null) {
// If we have an array, it has already been converted to JSON. So use
// that instead.
json.putOpt(JSON_VALUE, jsonArray);
}
String jsonString = json.toString();
editor.putString(key, jsonString);
}
}
private void deserializeKey(String key, Bundle bundle)
throws JSONException {
String jsonString = cache.getString(key, "{}");
JSONObject json = new JSONObject(jsonString);
String valueType = json.getString(JSON_VALUE_TYPE);
if (valueType.equals(TYPE_BOOLEAN)) {
bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
} else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
boolean[] array = new boolean[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getBoolean(i);
}
bundle.putBooleanArray(key, array);
} else if (valueType.equals(TYPE_BYTE)) {
bundle.putByte(key, (byte)json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_BYTE_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
byte[] array = new byte[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (byte)jsonArray.getInt(i);
}
bundle.putByteArray(key, array);
} else if (valueType.equals(TYPE_SHORT)) {
bundle.putShort(key, (short)json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_SHORT_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
short[] array = new short[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (short)jsonArray.getInt(i);
}
bundle.putShortArray(key, array);
} else if (valueType.equals(TYPE_INTEGER)) {
bundle.putInt(key, json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
int[] array = new int[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getInt(i);
}
bundle.putIntArray(key, array);
} else if (valueType.equals(TYPE_LONG)) {
bundle.putLong(key, json.getLong(JSON_VALUE));
} else if (valueType.equals(TYPE_LONG_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
long[] array = new long[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getLong(i);
}
bundle.putLongArray(key, array);
} else if (valueType.equals(TYPE_FLOAT)) {
bundle.putFloat(key, (float)json.getDouble(JSON_VALUE));
} else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
float[] array = new float[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (float)jsonArray.getDouble(i);
}
bundle.putFloatArray(key, array);
} else if (valueType.equals(TYPE_DOUBLE)) {
bundle.putDouble(key, json.getDouble(JSON_VALUE));
} else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
double[] array = new double[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getDouble(i);
}
bundle.putDoubleArray(key, array);
} else if (valueType.equals(TYPE_CHAR)) {
String charString = json.getString(JSON_VALUE);
if (charString != null && charString.length() == 1) {
bundle.putChar(key, charString.charAt(0));
}
} else if (valueType.equals(TYPE_CHAR_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
char[] array = new char[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
String charString = jsonArray.getString(i);
if (charString != null && charString.length() == 1) {
array[i] = charString.charAt(0);
}
}
bundle.putCharArray(key, array);
} else if (valueType.equals(TYPE_STRING)) {
bundle.putString(key, json.getString(JSON_VALUE));
} else if (valueType.equals(TYPE_STRING_LIST)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
int numStrings = jsonArray.length();
ArrayList<String> stringList = new ArrayList<String>(numStrings);
for (int i = 0; i < numStrings; i++) {
Object jsonStringValue = jsonArray.get(i);
stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue);
}
bundle.putStringArrayList(key, stringList);
} else if (valueType.equals(TYPE_ENUM)) {
try {
String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
@SuppressWarnings({ "unchecked", "rawtypes" })
Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
@SuppressWarnings("unchecked")
Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
bundle.putSerializable(key, enumValue);
} catch (ClassNotFoundException e) {
} catch (IllegalArgumentException e) {
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import com.facebook.Request;
import com.facebook.RequestBatch;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public class CacheableRequestBatch extends RequestBatch {
private String cacheKey;
private boolean forceRoundTrip;
public CacheableRequestBatch() {
}
public CacheableRequestBatch(Request... requests) {
super(requests);
}
public final String getCacheKeyOverride() {
return cacheKey;
}
// If this is set, the provided string will override the default key (the URL) for single requests.
// There is no default for multi-request batches, so no caching will be done unless the override is
// specified.
public final void setCacheKeyOverride(String cacheKey) {
this.cacheKey = cacheKey;
}
public final boolean getForceRoundTrip() {
return forceRoundTrip;
}
public final void setForceRoundTrip(boolean forceRoundTrip) {
this.forceRoundTrip = forceRoundTrip;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.facebook.*;
import com.facebook.android.BuildConfig;
import com.facebook.model.GraphObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public final class Utility {
static final String LOG_TAG = "FacebookSDK";
private static final String HASH_ALGORITHM_MD5 = "MD5";
private static final String URL_SCHEME = "https";
private static final String SUPPORTS_ATTRIBUTION = "supports_attribution";
private static final String APPLICATION_FIELDS = "fields";
// This is the default used by the buffer streams, but they trace a warning if you do not specify.
public static final int DEFAULT_STREAM_BUFFER_SIZE = 8192;
private static final Object LOCK = new Object();
private static volatile boolean attributionAllowedForLastAppChecked = false;
private static volatile String lastAppCheckedForAttributionStatus = "";
// Returns true iff all items in subset are in superset, treating null and
// empty collections as
// the same.
public static <T> boolean isSubset(Collection<T> subset, Collection<T> superset) {
if ((superset == null) || (superset.size() == 0)) {
return ((subset == null) || (subset.size() == 0));
}
HashSet<T> hash = new HashSet<T>(superset);
for (T t : subset) {
if (!hash.contains(t)) {
return false;
}
}
return true;
}
public static <T> boolean isNullOrEmpty(Collection<T> c) {
return (c == null) || (c.size() == 0);
}
public static boolean isNullOrEmpty(String s) {
return (s == null) || (s.length() == 0);
}
public static <T> Collection<T> unmodifiableCollection(T... ts) {
return Collections.unmodifiableCollection(Arrays.asList(ts));
}
public static <T> ArrayList<T> arrayList(T... ts) {
ArrayList<T> arrayList = new ArrayList<T>(ts.length);
for (T t : ts) {
arrayList.add(t);
}
return arrayList;
}
static String md5hash(String key) {
MessageDigest hash = null;
try {
hash = MessageDigest.getInstance(HASH_ALGORITHM_MD5);
} catch (NoSuchAlgorithmException e) {
return null;
}
hash.update(key.getBytes());
byte[] digest = hash.digest();
StringBuilder builder = new StringBuilder();
for (int b : digest) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString((b >> 0) & 0xf));
}
return builder.toString();
}
public static Uri buildUri(String authority, String path, Bundle parameters) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(URL_SCHEME);
builder.authority(authority);
builder.path(path);
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (parameter instanceof String) {
builder.appendQueryParameter(key, (String) parameter);
}
}
return builder.build();
}
public static void putObjectInBundle(Bundle bundle, String key, Object value) {
if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Parcelable) {
bundle.putParcelable(key, (Parcelable) value);
} else if (value instanceof byte[]) {
bundle.putByteArray(key, (byte[]) value);
} else {
throw new FacebookException("attempted to add unsupported type to Bundle");
}
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}
public static void disconnectQuietly(URLConnection connection) {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection)connection).disconnect();
}
}
public static String getMetadataApplicationId(Context context) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (ai.metaData != null) {
return ai.metaData.getString(Session.APPLICATION_ID_PROPERTY);
}
} catch (PackageManager.NameNotFoundException e) {
// if we can't find it in the manifest, just return null
}
return null;
}
static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONArray keys = jsonObject.names();
for (int i = 0; i < keys.length(); ++i) {
String key;
try {
key = keys.getString(i);
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
value = convertJSONObjectToHashMap((JSONObject) value);
}
map.put(key, value);
} catch (JSONException e) {
}
}
return map;
}
// Returns either a JSONObject or JSONArray representation of the 'key' property of 'jsonObject'.
public static Object getStringPropertyAsJSON(JSONObject jsonObject, String key, String nonJSONPropertyKey)
throws JSONException {
Object value = jsonObject.opt(key);
if (value != null && value instanceof String) {
JSONTokener tokener = new JSONTokener((String) value);
value = tokener.nextValue();
}
if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
if (nonJSONPropertyKey != null) {
// Facebook sometimes gives us back a non-JSON value such as
// literal "true" or "false" as a result.
// If we got something like that, we present it to the caller as
// a GraphObject with a single
// property. We only do this if the caller wants that behavior.
jsonObject = new JSONObject();
jsonObject.putOpt(nonJSONPropertyKey, value);
return jsonObject;
} else {
throw new FacebookException("Got an unexpected non-JSON object.");
}
}
return value;
}
public static String readStreamToString(InputStream inputStream) throws IOException {
BufferedInputStream bufferedInputStream = null;
InputStreamReader reader = null;
try {
bufferedInputStream = new BufferedInputStream(inputStream);
reader = new InputStreamReader(bufferedInputStream);
StringBuilder stringBuilder = new StringBuilder();
final int bufferSize = 1024 * 2;
char[] buffer = new char[bufferSize];
int n = 0;
while ((n = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, n);
}
return stringBuilder.toString();
} finally {
closeQuietly(bufferedInputStream);
closeQuietly(reader);
}
}
public static boolean stringsEqualOrEmpty(String a, String b) {
boolean aEmpty = TextUtils.isEmpty(a);
boolean bEmpty = TextUtils.isEmpty(b);
if (aEmpty && bEmpty) {
// Both null or empty, they match.
return true;
}
if (!aEmpty && !bEmpty) {
// Both non-empty, check equality.
return a.equals(b);
}
// One empty, one non-empty, can't match.
return false;
}
private static void clearCookiesForDomain(Context context, String domain) {
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(domain);
if (cookies == null) {
return;
}
String[] splitCookies = cookies.split(";");
for (String cookie : splitCookies) {
String[] cookieParts = cookie.split("=");
if (cookieParts.length > 0) {
String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
cookieManager.setCookie(domain, newCookie);
}
}
cookieManager.removeExpiredCookie();
}
public static void clearFacebookCookies(Context context) {
// setCookie acts differently when trying to expire cookies between builds of Android that are using
// Chromium HTTP stack and those that are not. Using both of these domains to ensure it works on both.
clearCookiesForDomain(context, "facebook.com");
clearCookiesForDomain(context, ".facebook.com");
clearCookiesForDomain(context, "https://facebook.com");
clearCookiesForDomain(context, "https://.facebook.com");
}
public static void logd(String tag, Exception e) {
if (BuildConfig.DEBUG && tag != null && e != null) {
Log.d(tag, e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
public static void logd(String tag, String msg) {
if (BuildConfig.DEBUG && tag != null && msg != null) {
Log.d(tag, msg);
}
}
public static boolean queryAppAttributionSupportAndWait(final String applicationId) {
synchronized (LOCK) {
// Cache the last app checked results.
if (applicationId.equals(lastAppCheckedForAttributionStatus)) {
return attributionAllowedForLastAppChecked;
}
Bundle supportsAttributionParams = new Bundle();
supportsAttributionParams.putString(APPLICATION_FIELDS, SUPPORTS_ATTRIBUTION);
Request pingRequest = Request.newGraphPathRequest(null, applicationId, null);
pingRequest.setParameters(supportsAttributionParams);
GraphObject supportResponse = pingRequest.executeAndWait().getGraphObject();
Object doesSupportAttribution = false;
if (supportResponse != null) {
doesSupportAttribution = supportResponse.getProperty(SUPPORTS_ATTRIBUTION);
}
if (!(doesSupportAttribution instanceof Boolean)) {
// Should never happen, but be safe in case server returns non-Boolean
doesSupportAttribution = false;
}
lastAppCheckedForAttributionStatus = applicationId;
attributionAllowedForLastAppChecked = ((Boolean)doesSupportAttribution == true);
return attributionAllowedForLastAppChecked;
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public enum SessionAuthorizationType {
READ,
PUBLISH
}
| Java |
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
package com.facebook.internal;
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import java.util.Collection;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public final class Validate {
public static void notNull(Object arg, String name) {
if (arg == null) {
throw new NullPointerException("Argument '" + name + "' cannot be null");
}
}
public static <T> void notEmpty(Collection<T> container, String name) {
if (container.isEmpty()) {
throw new IllegalArgumentException("Container '" + name + "' cannot be empty");
}
}
public static <T> void containsNoNulls(Collection<T> container, String name) {
Validate.notNull(container, name);
for (T item : container) {
if (item == null) {
throw new NullPointerException("Container '" + name + "' cannot contain null values");
}
}
}
public static <T> void notEmptyAndContainsNoNulls(Collection<T> container, String name) {
Validate.containsNoNulls(container, name);
Validate.notEmpty(container, name);
}
public static void notNullOrEmpty(String arg, String name) {
if (Utility.isNullOrEmpty(arg)) {
throw new IllegalArgumentException("Argument '" + name + "' cannot be null or empty");
}
}
public static void oneOf(Object arg, String name, Object... values) {
for (Object value : values) {
if (value != null) {
if (value.equals(arg)) {
return;
}
} else {
if (arg == null) {
return;
}
}
}
throw new IllegalArgumentException("Argument '" + name + "' was not one of the allowed values");
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import android.util.Log;
import com.facebook.LoggingBehavior;
import com.facebook.Settings;
import java.util.HashMap;
import java.util.Map;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public class Logger {
public static final String LOG_TAG_BASE = "FacebookSDK.";
private static final HashMap<String, String> stringsToReplace = new HashMap<String, String>();
private final LoggingBehavior behavior;
private final String tag;
private StringBuilder contents;
private int priority = Log.DEBUG;
// Note that the mapping of replaced strings is never emptied, so it should be used only for things that
// are not expected to be too numerous, such as access tokens.
public synchronized static void registerStringToReplace(String original, String replace) {
stringsToReplace.put(original, replace);
}
public synchronized static void registerAccessToken(String accessToken) {
if (Settings.isLoggingBehaviorEnabled(LoggingBehavior.INCLUDE_ACCESS_TOKENS) == false) {
registerStringToReplace(accessToken, "ACCESS_TOKEN_REMOVED");
}
}
public static void log(LoggingBehavior behavior, String tag, String string) {
log(behavior, Log.DEBUG, tag, string);
}
public static void log(LoggingBehavior behavior, String tag, String format, Object... args) {
if (Settings.isLoggingBehaviorEnabled(behavior)) {
String string = String.format(format, args);
log(behavior, Log.DEBUG, tag, string);
}
}
public static void log(LoggingBehavior behavior, int priority, String tag, String string) {
if (Settings.isLoggingBehaviorEnabled(behavior)) {
string = replaceStrings(string);
if (tag.startsWith(LOG_TAG_BASE) == false) {
tag = LOG_TAG_BASE + tag;
}
Log.println(priority, tag, string);
// Developer errors warrant special treatment by printing out a stack trace, to make both more noticeable,
// and let the source of the problem be more easily pinpointed.
if (behavior == LoggingBehavior.DEVELOPER_ERRORS) {
(new Exception()).printStackTrace();
}
}
}
private synchronized static String replaceStrings(String string) {
for (Map.Entry<String, String> entry : stringsToReplace.entrySet()) {
string = string.replace(entry.getKey(), entry.getValue());
}
return string;
}
public Logger(LoggingBehavior behavior, String tag) {
Validate.notNullOrEmpty(tag, "tag");
this.behavior = behavior;
this.tag = LOG_TAG_BASE + tag;
this.contents = new StringBuilder();
}
public int getPriority() {
return priority;
}
public void setPriority(int value) {
Validate.oneOf(value, "value", Log.ASSERT, Log.DEBUG, Log.ERROR, Log.INFO, Log.VERBOSE, Log.WARN);
priority = value;
}
public String getContents() {
return replaceStrings(contents.toString());
}
// Writes the accumulated contents, then clears contents to start again.
public void log() {
logString(contents.toString());
contents = new StringBuilder();
}
// Immediately logs a string, ignoring any accumulated contents, which are left unchanged.
public void logString(String string) {
log(behavior, priority, tag, string);
}
public void append(StringBuilder stringBuilder) {
if (shouldLog()) {
contents.append(stringBuilder);
}
}
public void append(String string) {
if (shouldLog()) {
contents.append(string);
}
}
public void append(String format, Object... args) {
if (shouldLog()) {
contents.append(String.format(format, args));
}
}
public void appendKeyValue(String key, Object value) {
append(" %s:\t%s\n", key, value);
}
private boolean shouldLog() {
return Settings.isLoggingBehaviorEnabled(behavior);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import android.content.Context;
import android.util.Log;
import com.facebook.LoggingBehavior;
import com.facebook.Settings;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.*;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicLong;
// This class is intended to be thread-safe.
//
// There are two classes of files: buffer files and cache files:
// - A buffer file is in the process of being written, and there is an open stream on the file. These files are
// named as "bufferN" where N is an incrementing integer. On startup, we delete all existing files of this form.
// Once the stream is closed, we rename the buffer file to a cache file or attempt to delete if this fails. We
// do not otherwise ever attempt to delete these files.
// - A cache file is a non-changing file that is named by the md5 hash of the cache key. We monitor the size of
// these files in aggregate and remove the oldest one(s) to stay under quota. This process does not block threads
// calling into this class, so theoretically we could go arbitrarily over quota but in practice this should not
// happen because deleting files should be much cheaper than downloading new file content.
//
// Since there can only ever be one thread accessing a particular buffer file, we do not synchronize access to these.
// We do assume that file rename is atomic when converting a buffer file to a cache file, and that if multiple files
// are renamed to a single target that exactly one of them continues to exist.
//
// Standard POSIX file semantics guarantee being able to continue to use a file handle even after the
// corresponding file has been deleted. Given this and that cache files never change other than deleting in trim(),
// we only have to ensure that there is at most one trim() process deleting files at any given time.
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public final class FileLruCache {
static final String TAG = FileLruCache.class.getSimpleName();
private static final String HEADER_CACHEKEY_KEY = "key";
private static final String HEADER_CACHE_CONTENT_TAG_KEY = "tag";
private static final AtomicLong bufferIndex = new AtomicLong();
private final String tag;
private final Limits limits;
private final File directory;
private boolean isTrimPending;
private final Object lock;
// The value of tag should be a final String that works as a directory name.
public FileLruCache(Context context, String tag, Limits limits) {
this.tag = tag;
this.limits = limits;
this.directory = new File(context.getCacheDir(), tag);
this.lock = new Object();
// Ensure the cache dir exists
this.directory.mkdirs();
// Remove any stale partially-written files from a previous run
BufferFile.deleteAll(this.directory);
}
// Other code in this class is not necessarily robust to having buffer files deleted concurrently.
// If this is ever used for non-test code, we should make sure the synchronization is correct. See
// the threading notes at the top of this class.
public void clearForTest() throws IOException {
for (File file : this.directory.listFiles()) {
file.delete();
}
}
// This is not robust to files changing dynamically underneath it and should therefore only be used
// for test code. If we ever need this for product code we need to think through synchronization.
// See the threading notes at the top of this class.
//
// Also, since trim() runs asynchronously now, this blocks until any pending trim has completed.
long sizeInBytesForTest() {
synchronized (lock) {
while (isTrimPending) {
try {
lock.wait();
} catch (InterruptedException e) {
// intentional no-op
}
}
}
File[] files = this.directory.listFiles();
long total = 0;
for (File file : files) {
total += file.length();
}
return total;
}
public InputStream get(String key) throws IOException {
return get(key, null);
}
public InputStream get(String key, String contentTag) throws IOException {
File file = new File(this.directory, Utility.md5hash(key));
FileInputStream input = null;
try {
input = new FileInputStream(file);
} catch (IOException e) {
return null;
}
BufferedInputStream buffered = new BufferedInputStream(input, Utility.DEFAULT_STREAM_BUFFER_SIZE);
boolean success = false;
try {
JSONObject header = StreamHeader.readHeader(buffered);
if (header == null) {
return null;
}
String foundKey = header.optString(HEADER_CACHEKEY_KEY);
if ((foundKey == null) || !foundKey.equals(key)) {
return null;
}
String headerContentTag = header.optString(HEADER_CACHE_CONTENT_TAG_KEY, null);
if ((contentTag == null && headerContentTag != null) ||
(contentTag != null && !contentTag.equals(headerContentTag))) {
return null;
}
long accessTime = new Date().getTime();
Logger.log(LoggingBehavior.CACHE, TAG, "Setting lastModified to " + Long.valueOf(accessTime) + " for "
+ file.getName());
file.setLastModified(accessTime);
success = true;
return buffered;
} finally {
if (!success) {
buffered.close();
}
}
}
OutputStream openPutStream(final String key) throws IOException {
return openPutStream(key, null);
}
public OutputStream openPutStream(final String key, String contentTag) throws IOException {
final File buffer = BufferFile.newFile(this.directory);
buffer.delete();
if (!buffer.createNewFile()) {
throw new IOException("Could not create file at " + buffer.getAbsolutePath());
}
FileOutputStream file = null;
try {
file = new FileOutputStream(buffer);
} catch (FileNotFoundException e) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "Error creating buffer output stream: " + e);
throw new IOException(e.getMessage());
}
StreamCloseCallback renameToTargetCallback = new StreamCloseCallback() {
@Override
public void onClose() {
renameToTargetAndTrim(key, buffer);
}
};
CloseCallbackOutputStream cleanup = new CloseCallbackOutputStream(file, renameToTargetCallback);
BufferedOutputStream buffered = new BufferedOutputStream(cleanup, Utility.DEFAULT_STREAM_BUFFER_SIZE);
boolean success = false;
try {
// Prefix the stream with the actual key, since there could be collisions
JSONObject header = new JSONObject();
header.put(HEADER_CACHEKEY_KEY, key);
if (!Utility.isNullOrEmpty(contentTag)) {
header.put(HEADER_CACHE_CONTENT_TAG_KEY, contentTag);
}
StreamHeader.writeHeader(buffered, header);
success = true;
return buffered;
} catch (JSONException e) {
// JSON is an implementation detail of the cache, so don't let JSON exceptions out.
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "Error creating JSON header for cache file: " + e);
throw new IOException(e.getMessage());
} finally {
if (!success) {
buffered.close();
}
}
}
private void renameToTargetAndTrim(String key, File buffer) {
final File target = new File(directory, Utility.md5hash(key));
// This is triggered by close(). By the time close() returns, the file should be cached, so this needs to
// happen synchronously on this thread.
//
// However, it does not need to be synchronized, since in the race we will just start an unnecesary trim
// operation. Avoiding the cost of holding the lock across the file operation seems worth this cost.
if (!buffer.renameTo(target)) {
buffer.delete();
}
postTrim();
}
// Opens an output stream for the key, and creates an input stream wrapper to copy
// the contents of input into the new output stream. The effect is to store a
// copy of input, and associate that data with key.
public InputStream interceptAndPut(String key, InputStream input) throws IOException {
OutputStream output = openPutStream(key);
return new CopyingInputStream(input, output);
}
public String toString() {
return "{FileLruCache:" + " tag:" + this.tag + " file:" + this.directory.getName() + "}";
}
private void postTrim() {
synchronized (lock) {
if (!isTrimPending) {
isTrimPending = true;
Settings.getExecutor().execute(new Runnable() {
@Override
public void run() {
trim();
}
});
}
}
}
private void trim() {
try {
Logger.log(LoggingBehavior.CACHE, TAG, "trim started");
PriorityQueue<ModifiedFile> heap = new PriorityQueue<ModifiedFile>();
long size = 0;
long count = 0;
for (File file : this.directory.listFiles(BufferFile.excludeBufferFiles())) {
ModifiedFile modified = new ModifiedFile(file);
heap.add(modified);
Logger.log(LoggingBehavior.CACHE, TAG, " trim considering time=" + Long.valueOf(modified.getModified())
+ " name=" + modified.getFile().getName());
size += file.length();
count++;
}
while ((size > limits.getByteCount()) || (count > limits.getFileCount())) {
File file = heap.remove().getFile();
Logger.log(LoggingBehavior.CACHE, TAG, " trim removing " + file.getName());
size -= file.length();
count--;
file.delete();
}
} finally {
synchronized (lock) {
isTrimPending = false;
lock.notifyAll();
}
}
}
private static class BufferFile {
private static final String FILE_NAME_PREFIX = "buffer";
private static final FilenameFilter filterExcludeBufferFiles = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return !filename.startsWith(FILE_NAME_PREFIX);
}
};
private static final FilenameFilter filterExcludeNonBufferFiles = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith(FILE_NAME_PREFIX);
}
};
static void deleteAll(final File root) {
for (File file : root.listFiles(excludeNonBufferFiles())) {
file.delete();
}
}
static FilenameFilter excludeBufferFiles() {
return filterExcludeBufferFiles;
}
static FilenameFilter excludeNonBufferFiles() {
return filterExcludeNonBufferFiles;
}
static File newFile(final File root) {
String name = FILE_NAME_PREFIX + Long.valueOf(bufferIndex.incrementAndGet()).toString();
return new File(root, name);
}
}
// Treats the first part of a stream as a header, reads/writes it as a JSON blob, and
// leaves the stream positioned exactly after the header.
//
// The format is as follows:
// byte: meaning
// ---------------------------------
// 0: version number
// 1-3: big-endian JSON header blob size
// 4-size+4: UTF-8 JSON header blob
// ...: stream data
private static final class StreamHeader {
private static final int HEADER_VERSION = 0;
static void writeHeader(OutputStream stream, JSONObject header) throws IOException {
String headerString = header.toString();
byte[] headerBytes = headerString.getBytes();
// Write version number and big-endian header size
stream.write(HEADER_VERSION);
stream.write((headerBytes.length >> 16) & 0xff);
stream.write((headerBytes.length >> 8) & 0xff);
stream.write((headerBytes.length >> 0) & 0xff);
stream.write(headerBytes);
}
static JSONObject readHeader(InputStream stream) throws IOException {
int version = stream.read();
if (version != HEADER_VERSION) {
return null;
}
int headerSize = 0;
for (int i = 0; i < 3; i++) {
int b = stream.read();
if (b == -1) {
Logger.log(LoggingBehavior.CACHE, TAG,
"readHeader: stream.read returned -1 while reading header size");
return null;
}
headerSize <<= 8;
headerSize += b & 0xff;
}
byte[] headerBytes = new byte[headerSize];
int count = 0;
while (count < headerBytes.length) {
int readCount = stream.read(headerBytes, count, headerBytes.length - count);
if (readCount < 1) {
Logger.log(LoggingBehavior.CACHE, TAG,
"readHeader: stream.read stopped at " + Integer.valueOf(count) + " when expected "
+ headerBytes.length);
return null;
}
count += readCount;
}
String headerString = new String(headerBytes);
JSONObject header = null;
JSONTokener tokener = new JSONTokener(headerString);
try {
Object parsed = tokener.nextValue();
if (!(parsed instanceof JSONObject)) {
Logger.log(LoggingBehavior.CACHE, TAG, "readHeader: expected JSONObject, got " + parsed.getClass().getCanonicalName());
return null;
}
header = (JSONObject) parsed;
} catch (JSONException e) {
throw new IOException(e.getMessage());
}
return header;
}
}
private static class CloseCallbackOutputStream extends OutputStream {
final OutputStream innerStream;
final StreamCloseCallback callback;
CloseCallbackOutputStream(OutputStream innerStream, StreamCloseCallback callback) {
this.innerStream = innerStream;
this.callback = callback;
}
@Override
public void close() throws IOException {
try {
this.innerStream.close();
} finally {
this.callback.onClose();
}
}
@Override
public void flush() throws IOException {
this.innerStream.flush();
}
@Override
public void write(byte[] buffer, int offset, int count) throws IOException {
this.innerStream.write(buffer, offset, count);
}
@Override
public void write(byte[] buffer) throws IOException {
this.innerStream.write(buffer);
}
@Override
public void write(int oneByte) throws IOException {
this.innerStream.write(oneByte);
}
}
private static final class CopyingInputStream extends InputStream {
final InputStream input;
final OutputStream output;
CopyingInputStream(final InputStream input, final OutputStream output) {
this.input = input;
this.output = output;
}
@Override
public int available() throws IOException {
return input.available();
}
@Override
public void close() throws IOException {
// According to http://www.cs.cornell.edu/andru/javaspec/11.doc.html:
// "If a finally clause is executed because of abrupt completion of a try block and the finally clause
// itself completes abruptly, then the reason for the abrupt completion of the try block is discarded
// and the new reason for abrupt completion is propagated from there."
//
// Android does appear to behave like this.
try {
this.input.close();
} finally {
this.output.close();
}
}
@Override
public void mark(int readlimit) {
throw new UnsupportedOperationException();
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int read(byte[] buffer) throws IOException {
int count = input.read(buffer);
if (count > 0) {
output.write(buffer, 0, count);
}
return count;
}
@Override
public int read() throws IOException {
int b = input.read();
if (b >= 0) {
output.write(b);
}
return b;
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int count = input.read(buffer, offset, length);
if (count > 0) {
output.write(buffer, offset, count);
}
return count;
}
@Override
public synchronized void reset() {
throw new UnsupportedOperationException();
}
@Override
public long skip(long byteCount) throws IOException {
byte[] buffer = new byte[1024];
long total = 0;
while (total < byteCount) {
int count = read(buffer, 0, (int)Math.min(byteCount - total, buffer.length));
if (count < 0) {
return total;
}
total += count;
}
return total;
}
}
public static final class Limits {
private int byteCount;
private int fileCount;
public Limits() {
// A Samsung Galaxy Nexus can create 1k files in half a second. By the time
// it gets to 5k files it takes 5 seconds. 10k files took 15 seconds. This
// continues to slow down as files are added. This assumes all files are in
// a single directory.
//
// Following a git-like strategy where we partition MD5-named files based on
// the first 2 characters is slower across the board.
this.fileCount = 1024;
this.byteCount = 1024 * 1024;
}
int getByteCount() {
return byteCount;
}
int getFileCount() {
return fileCount;
}
void setByteCount(int n) {
if (n < 0) {
throw new InvalidParameterException("Cache byte-count limit must be >= 0");
}
byteCount = n;
}
void setFileCount(int n) {
if (n < 0) {
throw new InvalidParameterException("Cache file count limit must be >= 0");
}
fileCount = n;
}
}
// Caches the result of lastModified during sort/heap operations
private final static class ModifiedFile implements Comparable<ModifiedFile> {
private final File file;
private final long modified;
ModifiedFile(File file) {
this.file = file;
this.modified = file.lastModified();
}
File getFile() {
return file;
}
long getModified() {
return modified;
}
@Override
public int compareTo(ModifiedFile another) {
if (getModified() < another.getModified()) {
return -1;
} else if (getModified() > another.getModified()) {
return 1;
} else {
return getFile().compareTo(another.getFile());
}
}
@Override
public boolean equals(Object another) {
return
(another instanceof ModifiedFile) &&
(compareTo((ModifiedFile)another) == 0);
}
}
private interface StreamCloseCallback {
void onClose();
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import com.facebook.internal.Utility;
import java.util.Collection;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public final class ServerProtocol {
static final String FACEBOOK_COM = "facebook.com";
public static final String DIALOG_AUTHORITY = "m." + FACEBOOK_COM;
public static final String DIALOG_PATH = "dialog/";
public static final String DIALOG_PARAM_SCOPE = "scope";
public static final String DIALOG_PARAM_CLIENT_ID = "client_id";
public static final String DIALOG_PARAM_DISPLAY = "display";
public static final String DIALOG_PARAM_REDIRECT_URI = "redirect_uri";
public static final String DIALOG_PARAM_TYPE = "type";
public static final String DIALOG_PARAM_ACCESS_TOKEN = "access_token";
public static final String DIALOG_PARAM_APP_ID = "app_id";
// URL components
public static final String GRAPH_URL = "https://graph." + FACEBOOK_COM;
public static final String GRAPH_URL_BASE = "https://graph." + FACEBOOK_COM + "/";
public static final String REST_URL_BASE = "https://api." + FACEBOOK_COM + "/method/";
public static final String BATCHED_REST_METHOD_URL_BASE = "method/";
public static final Collection<String> errorsProxyAuthDisabled =
Utility.unmodifiableCollection("service_disabled", "AndroidAuthKillSwitchException");
public static final Collection<String> errorsUserCanceled =
Utility.unmodifiableCollection("access_denied", "OAuthAccessDeniedException");
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import com.facebook.Session;
import com.facebook.SessionState;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*/
public class SessionTracker {
private Session session;
private final Session.StatusCallback callback;
private final BroadcastReceiver receiver;
private final LocalBroadcastManager broadcastManager;
private boolean isTracking = false;
/**
* Constructs a SessionTracker to track the active Session object.
*
* @param context the context object.
* @param callback the callback to use whenever the active Session's
* state changes
*/
public SessionTracker(Context context, Session.StatusCallback callback) {
this(context, callback, null);
}
/**
* Constructs a SessionTracker to track the Session object passed in.
* If the Session is null, then it will track the active Session instead.
*
* @param context the context object.
* @param callback the callback to use whenever the Session's state changes
* @param session the Session object to track
*/
SessionTracker(Context context, Session.StatusCallback callback, Session session) {
this(context, callback, session, true);
}
/**
* Constructs a SessionTracker to track the Session object passed in.
* If the Session is null, then it will track the active Session instead.
*
* @param context the context object.
* @param callback the callback to use whenever the Session's state changes
* @param session the Session object to track
* @param startTracking whether to start tracking the Session right away
*/
public SessionTracker(Context context, Session.StatusCallback callback, Session session, boolean startTracking) {
this.callback = new CallbackWrapper(callback);
this.session = session;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(context);
if (startTracking) {
startTracking();
}
}
/**
* Returns the current Session that's being tracked.
*
* @return the current Session associated with this tracker
*/
public Session getSession() {
return (session == null) ? Session.getActiveSession() : session;
}
/**
* Returns the current Session that's being tracked if it's open,
* otherwise returns null.
*
* @return the current Session if it's open, otherwise returns null
*/
public Session getOpenSession() {
Session openSession = getSession();
if (openSession != null && openSession.isOpened()) {
return openSession;
}
return null;
}
/**
* Set the Session object to track.
*
* @param newSession the new Session object to track
*/
public void setSession(Session newSession) {
if (newSession == null) {
if (session != null) {
// We're current tracking a Session. Remove the callback
// and start tracking the active Session.
session.removeCallback(callback);
session = null;
addBroadcastReceiver();
if (getSession() != null) {
getSession().addCallback(callback);
}
}
} else {
if (session == null) {
// We're currently tracking the active Session, but will be
// switching to tracking a different Session object.
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
activeSession.removeCallback(callback);
}
broadcastManager.unregisterReceiver(receiver);
} else {
// We're currently tracking a Session, but are now switching
// to a new Session, so we remove the callback from the old
// Session, and add it to the new one.
session.removeCallback(callback);
}
session = newSession;
session.addCallback(callback);
}
}
/**
* Start tracking the Session (either active or the one given).
*/
public void startTracking() {
if (isTracking) {
return;
}
if (this.session == null) {
addBroadcastReceiver();
}
// if the session is not null, then add the callback to it right away
if (getSession() != null) {
getSession().addCallback(callback);
}
isTracking = true;
}
/**
* Stop tracking the Session and remove any callbacks attached
* to those sessions.
*/
public void stopTracking() {
if (!isTracking) {
return;
}
Session session = getSession();
if (session != null) {
session.removeCallback(callback);
}
broadcastManager.unregisterReceiver(receiver);
isTracking = false;
}
/**
* Returns whether it's currently tracking the Session.
*
* @return true if currently tracking the Session
*/
public boolean isTracking() {
return isTracking;
}
/**
* Returns whether it's currently tracking the active Session.
*
* @return true if the currently tracked session is the active Session.
*/
public boolean isTrackingActiveSession() {
return session == null;
}
private void addBroadcastReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Session.ACTION_ACTIVE_SESSION_SET);
filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET);
// Add a broadcast receiver to listen to when the active Session
// is set or unset, and add/remove our callback as appropriate
broadcastManager.registerReceiver(receiver, filter);
}
/**
* The BroadcastReceiver implementation that either adds or removes the callback
* from the active Session object as it's SET or UNSET.
*/
private class ActiveSessionBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Session.ACTION_ACTIVE_SESSION_SET.equals(intent.getAction())) {
Session session = Session.getActiveSession();
if (session != null) {
session.addCallback(SessionTracker.this.callback);
}
}
}
}
private class CallbackWrapper implements Session.StatusCallback {
private final Session.StatusCallback wrapped;
public CallbackWrapper(Session.StatusCallback wrapped) {
this.wrapped = wrapped;
}
@Override
public void call(Session session, SessionState state, Exception exception) {
if (wrapped != null && isTracking()) {
wrapped.call(session, state, exception);
}
// if we're not tracking the Active Session, and the current session
// is closed, then start tracking the Active Session.
if (session == SessionTracker.this.session && state.isClosed()) {
setSession(null);
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
import android.annotation.SuppressLint;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
class JsonUtil {
static void jsonObjectClear(JSONObject jsonObject) {
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
keys.next();
keys.remove();
}
}
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
Object thisValue = jsonObject.opt(keys.next());
if (thisValue != null && thisValue.equals(value)) {
return true;
}
}
return false;
}
private final static class JSONObjectEntry implements Map.Entry<String, Object> {
private final String key;
private final Object value;
JSONObjectEntry(String key, Object value) {
this.key = key;
this.value = value;
}
@SuppressLint("FieldGetter")
@Override
public String getKey() {
return this.key;
}
@Override
public Object getValue() {
return this.value;
}
@Override
public Object setValue(Object object) {
throw new UnsupportedOperationException("JSONObjectEntry is immutable");
}
}
static Set<Map.Entry<String, Object>> jsonObjectEntrySet(JSONObject jsonObject) {
HashSet<Map.Entry<String, Object>> result = new HashSet<Map.Entry<String, Object>>();
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.opt(key);
result.add(new JSONObjectEntry(key, value));
}
return result;
}
static Set<String> jsonObjectKeySet(JSONObject jsonObject) {
HashSet<String> result = new HashSet<String>();
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
result.add(keys.next());
}
return result;
}
static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
try {
jsonObject.putOpt(entry.getKey(), entry.getValue());
} catch (JSONException e) {
throw new IllegalArgumentException(e);
}
}
}
static Collection<Object> jsonObjectValues(JSONObject jsonObject) {
ArrayList<Object> result = new ArrayList<Object>();
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
result.add(jsonObject.opt(keys.next()));
}
return result;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
/**
* Defines a GraphObject that represents the result of a query that returns multiple GraphObjects
* nested under a "data" property.
*
* Note that this interface is intended to be used with GraphObject.Factory
* and not implemented directly.
*/
public interface GraphMultiResult extends GraphObject {
/**
* Provides access to the GraphObjects that make up the result set.
* @return a list of GraphObjects
*/
public GraphObjectList<GraphObject> getData();
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
import org.json.JSONObject;
import java.util.Date;
import java.util.List;
/**
* Provides a strongly-typed representation of an Open Graph Action.
* For more documentation of OG Actions, see: https://developers.facebook.com/docs/opengraph/actions/
*
* Note that this interface is intended to be used with GraphObject.Factory
* and not implemented directly.
*/
public interface OpenGraphAction extends GraphObject {
/**
* Gets the ID of the action.
* @return the ID
*/
public String getId();
/**
* Sets the ID of the action.
* @param id the ID
*/
public void setId(String id);
/**
* Gets the start time of the action.
* @return the start time
*/
public Date getStartTime();
/**
* Sets the start time of the action.
* @param startTime the start time
*/
public void setStartTime(Date startTime);
/**
* Gets the end time of the action.
* @return the end time
*/
public Date getEndTime();
/**
* Sets the end time of the action.
* @param endTime the end time
*/
public void setEndTime(Date endTime);
/**
* Gets the time the action was published, if any.
* @return the publish time
*/
public Date getPublishTime();
/**
* Sets the time the action was published.
* @param publishTime the publish time
*/
public void setPublishTime(Date publishTime);
/**
* Gets the time the action was created.
* @return the creation time
*/
public Date getCreatedTime();
/**
* Sets the time the action was created.
* @param createdTime the creation time
*/
public void setCreatedTime(Date createdTime);
/**
* Gets the time the action expires at.
* @return the expiration time
*/
public Date getExpiresTime();
/**
* Sets the time the action expires at.
* @param expiresTime the expiration time
*/
public void setExpiresTime(Date expiresTime);
/**
* Gets the unique string which will be passed to the OG Action owner's website
* when a user clicks through this action on Facebook.
* @return the ref string
*/
public String getRef();
/**
* Sets the unique string which will be passed to the OG Action owner's website
* when a user clicks through this action on Facebook.
* @param ref the ref string
*/
public void setRef(String ref);
/**
* Gets the message assoicated with the action.
* @return the message
*/
public String getMessage();
/**
* Sets the message associated with the action.
* @param message the message
*/
public void setMessage(String message);
/**
* Gets the place where the action took place.
* @return the place
*/
public GraphPlace getPlace();
/**
* Sets the place where the action took place.
* @param place the place
*/
public void setPlace(GraphPlace place);
/**
* Gets the list of profiles that were tagged in the action.
* @return the profiles that were tagged in the action
*/
public List<GraphObject> getTags();
/**
* Sets the list of profiles that were tagged in the action.
* @param tags the profiles that were tagged in the action
*/
public void setTags(List<? extends GraphObject> tags);
/**
* Gets the images that were associated with the action.
* @return the images
*/
public List<JSONObject> getImage();
/**
* Sets the images that were associated with the action.
* @param image the images
*/
public void setImage(List<JSONObject> image);
/**
* Gets the from-user associated with the action.
* @return the user
*/
public GraphUser getFrom();
/**
* Sets the from-user associated with the action.
* @param from the from-user
*/
public void setFrom(GraphUser from);
/**
* Gets the 'likes' that have been performed on this action.
* @return the likes
*/
public JSONObject getLikes();
/**
* Sets the 'likes' that have been performed on this action.
* @param likes the likes
*/
public void setLikes(JSONObject likes);
/**
* Gets the application that created this action.
* @return the application
*/
public GraphObject getApplication();
/**
* Sets the application that created this action.
* @param application the application
*/
public void setApplication(GraphObject application);
/**
* Gets the comments that have been made on this action.
* @return the comments
*/
public JSONObject getComments();
/**
* Sets the comments that have been made on this action.
* @param comments the comments
*/
public void setComments(JSONObject comments);
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
/**
* Provides a strongly-typed representation of a Place as defined by the Graph API.
*
* Note that this interface is intended to be used with GraphObject.Factory
* and not implemented directly.
*/
public interface GraphPlace extends GraphObject {
/**
* Returns the ID of the place.
* @return the ID of the place
*/
public String getId();
/**
* Sets the ID of the place.
* @param id the ID of the place
*/
public void setId(String id);
/**
* Returns the name of the place.
* @return the name of the place
*/
public String getName();
/**
* Sets the name of the place.
* @param name the name of the place
*/
public void setName(String name);
/**
* Returns the category of the place.
* @return the category of the place
*/
public String getCategory();
/**
* Sets the category of the place.
* @param category the category of the place
*/
public void setCategory(String category);
/**
* Returns the location of the place.
* @return the location of the place
*/
public GraphLocation getLocation();
/**
* Sets the location of the place.
* @param location the location of the place
*/
public void setLocation(GraphLocation location);
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
/**
* Provides a strongly-typed representation of a User as defined by the Graph API.
*
* Note that this interface is intended to be used with GraphObject.Factory
* and not implemented directly.
*/
public interface GraphUser extends GraphObject {
/**
* Returns the ID of the user.
* @return the ID of the user
*/
public String getId();
/**
* Sets the ID of the user.
* @param id the ID of the user
*/
public void setId(String id);
/**
* Returns the name of the user.
* @return the name of the user
*/
public String getName();
/**
* Sets the name of the user.
* @param name the name of the user
*/
public void setName(String name);
/**
* Returns the first name of the user.
* @return the first name of the user
*/
public String getFirstName();
/**
* Sets the first name of the user.
* @param firstName the first name of the user
*/
public void setFirstName(String firstName);
/**
* Returns the middle name of the user.
* @return the middle name of the user
*/
public String getMiddleName();
/**
* Sets the middle name of the user.
* @param middleName the middle name of the user
*/
public void setMiddleName(String middleName);
/**
* Returns the last name of the user.
* @return the last name of the user
*/
public String getLastName();
/**
* Sets the last name of the user.
* @param lastName the last name of the user
*/
public void setLastName(String lastName);
/**
* Returns the Facebook URL of the user.
* @return the Facebook URL of the user
*/
public String getLink();
/**
* Sets the Facebook URL of the user.
* @param link the Facebook URL of the user
*/
public void setLink(String link);
/**
* Returns the Facebook username of the user.
* @return the Facebook username of the user
*/
public String getUsername();
/**
* Sets the Facebook username of the user.
* @param username the Facebook username of the user
*/
public void setUsername(String username);
/**
* Returns the birthday of the user.
* @return the birthday of the user
*/
public String getBirthday();
/**
* Sets the birthday of the user.
* @param birthday the birthday of the user
*/
public void setBirthday(String birthday);
/**
* Returns the current city of the user.
* @return the current city of the user
*/
public GraphLocation getLocation();
/**
* Sets the current city of the user.
* @param location the current city of the user
*/
public void setLocation(GraphLocation location);
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
import com.facebook.FacebookGraphObjectException;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* GraphObject is the primary interface used by the Facebook SDK for Android to represent objects in the Facebook
* Social Graph and the Facebook Open Graph (OG). It is the base interface for all typed access to graph objects
* in the SDK. No concrete classes implement GraphObject or its derived interfaces. Rather, they are implemented as
* proxies (see the {@link com.facebook.model.GraphObject.Factory Factory} class) that provide strongly-typed property
* getters and setters to access the underlying data. Since the primary use case for graph objects is sending and
* receiving them over the wire to/from Facebook services, they are represented as JSONObjects. No validation is done
* that a graph object is actually of a specific type -- any graph object can be treated as any GraphObject-derived
* interface, and the presence or absence of specific properties determines its suitability for use as that
* particular type of object.
* <br/>
*/
public interface GraphObject {
/**
* Returns a new proxy that treats this graph object as a different GraphObject-derived type.
* @param graphObjectClass the type of GraphObject to return
* @return a new instance of the GraphObject-derived-type that references the same underlying data
*/
public <T extends GraphObject> T cast(Class<T> graphObjectClass);
/**
* Returns a Java Collections map of names and properties. Modifying the returned map modifies the
* inner JSON representation.
* @return a Java Collections map representing the GraphObject state
*/
public Map<String, Object> asMap();
/**
* Gets the underlying JSONObject representation of this graph object.
* @return the underlying JSONObject representation of this graph object
*/
public JSONObject getInnerJSONObject();
/**
* Gets a property of the GraphObject
* @param propertyName the name of the property to get
* @return the value of the named property
*/
public Object getProperty(String propertyName);
/**
* Sets a property of the GraphObject
* @param propertyName the name of the property to set
* @param propertyValue the value of the named property to set
*/
public void setProperty(String propertyName, Object propertyValue);
/**
* Removes a property of the GraphObject
* @param propertyName the name of the property to remove
*/
public void removeProperty(String propertyName);
/**
* Creates proxies that implement GraphObject, GraphObjectList, and their derived types. These proxies allow access
* to underlying collections and name/value property bags via strongly-typed property getters and setters.
* <p/>
* This supports get/set properties that use primitive types, JSON types, Date, other GraphObject types, Iterable,
* Collection, List, and GraphObjectList.
*/
final class Factory {
private static final HashSet<Class<?>> verifiedGraphObjectClasses = new HashSet<Class<?>>();
private static final SimpleDateFormat[] dateFormats = new SimpleDateFormat[] {
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US), new SimpleDateFormat("yyyy-MM-dd", Locale.US), };
// No objects of this type should exist.
private Factory() {
}
/**
* Creates a GraphObject proxy that provides typed access to the data in an underlying JSONObject.
* @param json the JSONObject containing the data to be exposed
* @return a GraphObject that represents the underlying data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static GraphObject create(JSONObject json) {
return create(json, GraphObject.class);
}
/**
* Creates a GraphObject-derived proxy that provides typed access to the data in an underlying JSONObject.
* @param json the JSONObject containing the data to be exposed
* @param graphObjectClass the GraphObject-derived type to return
* @return a graphObjectClass that represents the underlying data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static <T extends GraphObject> T create(JSONObject json, Class<T> graphObjectClass) {
return createGraphObjectProxy(graphObjectClass, json);
}
/**
* Creates a GraphObject proxy that initially contains no data.
* @return a GraphObject with no data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static GraphObject create() {
return create(GraphObject.class);
}
/**
* Creates a GraphObject-derived proxy that initially contains no data.
* @param graphObjectClass the GraphObject-derived type to return
* @return a graphObjectClass with no data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static <T extends GraphObject> T create(Class<T> graphObjectClass) {
return createGraphObjectProxy(graphObjectClass, new JSONObject());
}
/**
* Determines if two GraphObjects represent the same underlying graph object, based on their IDs.
* @param a a graph object
* @param b another graph object
* @return true if both graph objects have an ID and it is the same ID, false otherwise
*/
public static boolean hasSameId(GraphObject a, GraphObject b) {
if (a == null || b == null || !a.asMap().containsKey("id") || !b.asMap().containsKey("id")) {
return false;
}
if (a.equals(b)) {
return true;
}
Object idA = a.getProperty("id");
Object idB = b.getProperty("id");
if (idA == null || idB == null || !(idA instanceof String) || !(idB instanceof String)) {
return false;
}
return idA.equals(idB);
}
/**
* Creates a GraphObjectList-derived proxy that provides typed access to the data in an underlying JSONArray.
* @param array the JSONArray containing the data to be exposed
* @param graphObjectClass the GraphObject-derived type to return
* @return a graphObjectClass that represents the underlying data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static <T> GraphObjectList<T> createList(JSONArray array, Class<T> graphObjectClass) {
return new GraphObjectListImpl<T>(array, graphObjectClass);
}
/**
* Creates a GraphObjectList-derived proxy that initially contains no data.
* @param graphObjectClass the GraphObject-derived type to return
* @return a GraphObjectList with no data
*
* @throws com.facebook.FacebookException
* If the passed in Class is not a valid GraphObject interface
*/
public static <T> GraphObjectList<T> createList(Class<T> graphObjectClass) {
return createList(new JSONArray(), graphObjectClass);
}
private static <T extends GraphObject> T createGraphObjectProxy(Class<T> graphObjectClass, JSONObject state) {
verifyCanProxyClass(graphObjectClass);
Class<?>[] interfaces = new Class[] { graphObjectClass };
GraphObjectProxy graphObjectProxy = new GraphObjectProxy(state, graphObjectClass);
@SuppressWarnings("unchecked")
T graphObject = (T) Proxy.newProxyInstance(GraphObject.class.getClassLoader(), interfaces, graphObjectProxy);
return graphObject;
}
private static Map<String, Object> createGraphObjectProxyForMap(JSONObject state) {
Class<?>[] interfaces = new Class[]{Map.class};
GraphObjectProxy graphObjectProxy = new GraphObjectProxy(state, Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> graphObject = (Map<String, Object>) Proxy
.newProxyInstance(GraphObject.class.getClassLoader(), interfaces, graphObjectProxy);
return graphObject;
}
private static synchronized <T extends GraphObject> boolean hasClassBeenVerified(Class<T> graphObjectClass) {
return verifiedGraphObjectClasses.contains(graphObjectClass);
}
private static synchronized <T extends GraphObject> void recordClassHasBeenVerified(Class<T> graphObjectClass) {
verifiedGraphObjectClasses.add(graphObjectClass);
}
private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) {
if (hasClassBeenVerified(graphObjectClass)) {
return;
}
if (!graphObjectClass.isInterface()) {
throw new FacebookGraphObjectException("Factory can only wrap interfaces, not class: "
+ graphObjectClass.getName());
}
Method[] methods = graphObjectClass.getMethods();
for (Method method : methods) {
String methodName = method.getName();
int parameterCount = method.getParameterTypes().length;
Class<?> returnType = method.getReturnType();
boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class);
if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) {
// Don't worry about any methods from GraphObject or one of its base classes.
continue;
} else if (parameterCount == 1 && returnType == Void.TYPE) {
if (hasPropertyNameOverride) {
// If a property override is present, it MUST be valid. We don't fallback
// to using the method name
if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
continue;
}
} else if (methodName.startsWith("set") && methodName.length() > 3) {
// Looks like a valid setter
continue;
}
} else if (parameterCount == 0 && returnType != Void.TYPE) {
if (hasPropertyNameOverride) {
// If a property override is present, it MUST be valid. We don't fallback
// to using the method name
if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
continue;
}
} else if (methodName.startsWith("get") && methodName.length() > 3) {
// Looks like a valid getter
continue;
}
}
throw new FacebookGraphObjectException("Factory can't proxy method: " + method.toString());
}
recordClassHasBeenVerified(graphObjectClass);
}
// If expectedType is a generic type, expectedTypeAsParameterizedType must be provided in order to determine
// generic parameter types.
static <U> U coerceValueToExpectedType(Object value, Class<U> expectedType,
ParameterizedType expectedTypeAsParameterizedType) {
if (value == null) {
return null;
}
Class<?> valueType = value.getClass();
if (expectedType.isAssignableFrom(valueType)) {
@SuppressWarnings("unchecked")
U result = (U) value;
return result;
}
if (expectedType.isPrimitive()) {
// If the result is a primitive, let the runtime succeed or fail at unboxing it.
@SuppressWarnings("unchecked")
U result = (U) value;
return result;
}
if (GraphObject.class.isAssignableFrom(expectedType)) {
@SuppressWarnings("unchecked")
Class<? extends GraphObject> graphObjectClass = (Class<? extends GraphObject>) expectedType;
// We need a GraphObject, but we don't have one.
if (JSONObject.class.isAssignableFrom(valueType)) {
// We can wrap a JSONObject as a GraphObject.
@SuppressWarnings("unchecked")
U result = (U) createGraphObjectProxy(graphObjectClass, (JSONObject) value);
return result;
} else if (GraphObject.class.isAssignableFrom(valueType)) {
// We can cast a GraphObject-derived class to another GraphObject-derived class.
@SuppressWarnings("unchecked")
U result = (U) ((GraphObject) value).cast(graphObjectClass);
return result;
} else {
throw new FacebookGraphObjectException("Can't create GraphObject from " + valueType.getName());
}
} else if (Iterable.class.equals(expectedType) || Collection.class.equals(expectedType)
|| List.class.equals(expectedType) || GraphObjectList.class.equals(expectedType)) {
if (expectedTypeAsParameterizedType == null) {
throw new FacebookGraphObjectException("can't infer generic type of: " + expectedType.toString());
}
Type[] actualTypeArguments = expectedTypeAsParameterizedType.getActualTypeArguments();
if (actualTypeArguments == null || actualTypeArguments.length != 1
|| !(actualTypeArguments[0] instanceof Class<?>)) {
throw new FacebookGraphObjectException(
"Expect collection properties to be of a type with exactly one generic parameter.");
}
Class<?> collectionGenericArgument = (Class<?>) actualTypeArguments[0];
if (JSONArray.class.isAssignableFrom(valueType)) {
JSONArray jsonArray = (JSONArray) value;
@SuppressWarnings("unchecked")
U result = (U) createList(jsonArray, collectionGenericArgument);
return result;
} else {
throw new FacebookGraphObjectException("Can't create Collection from " + valueType.getName());
}
} else if (String.class.equals(expectedType)) {
if (Double.class.isAssignableFrom(valueType) ||
Float.class.isAssignableFrom(valueType)) {
@SuppressWarnings("unchecked")
U result = (U) String.format("%f", value);
return result;
} else if (Number.class.isAssignableFrom(valueType)) {
@SuppressWarnings("unchecked")
U result = (U) String.format("%d", value);
return result;
}
} else if (Date.class.equals(expectedType)) {
if (String.class.isAssignableFrom(valueType)) {
for (SimpleDateFormat format : dateFormats) {
try {
Date date = format.parse((String) value);
if (date != null) {
@SuppressWarnings("unchecked")
U result = (U) date;
return result;
}
} catch (ParseException e) {
// Keep going.
}
}
}
}
throw new FacebookGraphObjectException("Can't convert type" + valueType.getName() + " to "
+ expectedType.getName());
}
static String convertCamelCaseToLowercaseWithUnderscores(String string) {
string = string.replaceAll("([a-z])([A-Z])", "$1_$2");
return string.toLowerCase(Locale.US);
}
private static Object getUnderlyingJSONObject(Object obj) {
Class<?> objClass = obj.getClass();
if (GraphObject.class.isAssignableFrom(objClass)) {
GraphObject graphObject = (GraphObject) obj;
return graphObject.getInnerJSONObject();
} else if (GraphObjectList.class.isAssignableFrom(objClass)) {
GraphObjectList<?> graphObjectList = (GraphObjectList<?>) obj;
return graphObjectList.getInnerJSONArray();
}
return obj;
}
private abstract static class ProxyBase<STATE> implements InvocationHandler {
// Pre-loaded Method objects for the methods in java.lang.Object
private static final String EQUALS_METHOD = "equals";
private static final String TOSTRING_METHOD = "toString";
protected final STATE state;
protected ProxyBase(STATE state) {
this.state = state;
}
// Declared to return Object just to simplify implementation of proxy helpers.
protected final Object throwUnexpectedMethodSignature(Method method) {
throw new FacebookGraphObjectException(getClass().getName() + " got an unexpected method signature: "
+ method.toString());
}
protected final Object proxyObjectMethods(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if (methodName.equals(EQUALS_METHOD)) {
Object other = args[0];
if (other == null) {
return false;
}
InvocationHandler handler = Proxy.getInvocationHandler(other);
if (!(handler instanceof GraphObjectProxy)) {
return false;
}
GraphObjectProxy otherProxy = (GraphObjectProxy) handler;
return this.state.equals(otherProxy.state);
} else if (methodName.equals(TOSTRING_METHOD)) {
return toString();
}
// For others, just defer to the implementation object.
return method.invoke(this.state, args);
}
}
private final static class GraphObjectProxy extends ProxyBase<JSONObject> {
private static final String CLEAR_METHOD = "clear";
private static final String CONTAINSKEY_METHOD = "containsKey";
private static final String CONTAINSVALUE_METHOD = "containsValue";
private static final String ENTRYSET_METHOD = "entrySet";
private static final String GET_METHOD = "get";
private static final String ISEMPTY_METHOD = "isEmpty";
private static final String KEYSET_METHOD = "keySet";
private static final String PUT_METHOD = "put";
private static final String PUTALL_METHOD = "putAll";
private static final String REMOVE_METHOD = "remove";
private static final String SIZE_METHOD = "size";
private static final String VALUES_METHOD = "values";
private static final String CAST_METHOD = "cast";
private static final String CASTTOMAP_METHOD = "asMap";
private static final String GETPROPERTY_METHOD = "getProperty";
private static final String SETPROPERTY_METHOD = "setProperty";
private static final String REMOVEPROPERTY_METHOD = "removeProperty";
private static final String GETINNERJSONOBJECT_METHOD = "getInnerJSONObject";
private final Class<?> graphObjectClass;
public GraphObjectProxy(JSONObject state, Class<?> graphObjectClass) {
super(state);
this.graphObjectClass = graphObjectClass;
}
@Override
public String toString() {
return String.format("GraphObject{graphObjectClass=%s, state=%s}", graphObjectClass.getSimpleName(), state);
}
@Override
public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?> declaringClass = method.getDeclaringClass();
if (declaringClass == Object.class) {
return proxyObjectMethods(proxy, method, args);
} else if (declaringClass == Map.class) {
return proxyMapMethods(method, args);
} else if (declaringClass == GraphObject.class) {
return proxyGraphObjectMethods(proxy, method, args);
} else if (GraphObject.class.isAssignableFrom(declaringClass)) {
return proxyGraphObjectGettersAndSetters(method, args);
}
return throwUnexpectedMethodSignature(method);
}
private final Object proxyMapMethods(Method method, Object[] args) {
String methodName = method.getName();
if (methodName.equals(CLEAR_METHOD)) {
JsonUtil.jsonObjectClear(this.state);
return null;
} else if (methodName.equals(CONTAINSKEY_METHOD)) {
return this.state.has((String) args[0]);
} else if (methodName.equals(CONTAINSVALUE_METHOD)) {
return JsonUtil.jsonObjectContainsValue(this.state, args[0]);
} else if (methodName.equals(ENTRYSET_METHOD)) {
return JsonUtil.jsonObjectEntrySet(this.state);
} else if (methodName.equals(GET_METHOD)) {
return this.state.opt((String) args[0]);
} else if (methodName.equals(ISEMPTY_METHOD)) {
return this.state.length() == 0;
} else if (methodName.equals(KEYSET_METHOD)) {
return JsonUtil.jsonObjectKeySet(this.state);
} else if (methodName.equals(PUT_METHOD)) {
return setJSONProperty(args);
} else if (methodName.equals(PUTALL_METHOD)) {
Map<String, Object> map = null;
if (args[0] instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, Object> castMap = (Map<String, Object>) args[0];
map = castMap;
} else if (args[0] instanceof GraphObject) {
map = ((GraphObject) args[0]).asMap();
}
JsonUtil.jsonObjectPutAll(this.state, map);
return null;
} else if (methodName.equals(REMOVE_METHOD)) {
this.state.remove((String) args[0]);
return null;
} else if (methodName.equals(SIZE_METHOD)) {
return this.state.length();
} else if (methodName.equals(VALUES_METHOD)) {
return JsonUtil.jsonObjectValues(this.state);
}
return throwUnexpectedMethodSignature(method);
}
private final Object proxyGraphObjectMethods(Object proxy, Method method, Object[] args) {
String methodName = method.getName();
if (methodName.equals(CAST_METHOD)) {
@SuppressWarnings("unchecked")
Class<? extends GraphObject> graphObjectClass = (Class<? extends GraphObject>) args[0];
if (graphObjectClass != null &&
graphObjectClass.isAssignableFrom(this.graphObjectClass)) {
return proxy;
}
return Factory.createGraphObjectProxy(graphObjectClass, this.state);
} else if (methodName.equals(GETINNERJSONOBJECT_METHOD)) {
InvocationHandler handler = Proxy.getInvocationHandler(proxy);
GraphObjectProxy otherProxy = (GraphObjectProxy) handler;
return otherProxy.state;
} else if (methodName.equals(CASTTOMAP_METHOD)) {
return Factory.createGraphObjectProxyForMap(this.state);
} else if (methodName.equals(GETPROPERTY_METHOD)) {
return state.opt((String) args[0]);
} else if (methodName.equals(SETPROPERTY_METHOD)) {
return setJSONProperty(args);
} else if (methodName.equals(REMOVEPROPERTY_METHOD)) {
this.state.remove((String) args[0]);
return null;
}
return throwUnexpectedMethodSignature(method);
}
private final Object proxyGraphObjectGettersAndSetters(Method method, Object[] args) throws JSONException {
String methodName = method.getName();
int parameterCount = method.getParameterTypes().length;
PropertyName propertyNameOverride = method.getAnnotation(PropertyName.class);
String key = propertyNameOverride != null ? propertyNameOverride.value() :
convertCamelCaseToLowercaseWithUnderscores(methodName.substring(3));
// If it's a get or a set on a GraphObject-derived class, we can handle it.
if (parameterCount == 0) {
// Has to be a getter. ASSUMPTION: The GraphObject-derived class has been verified
Object value = this.state.opt(key);
Class<?> expectedType = method.getReturnType();
Type genericReturnType = method.getGenericReturnType();
ParameterizedType parameterizedReturnType = null;
if (genericReturnType instanceof ParameterizedType) {
parameterizedReturnType = (ParameterizedType) genericReturnType;
}
value = coerceValueToExpectedType(value, expectedType, parameterizedReturnType);
return value;
} else if (parameterCount == 1) {
// Has to be a setter. ASSUMPTION: The GraphObject-derived class has been verified
Object value = args[0];
// If this is a wrapped object, store the underlying JSONObject instead, in order to serialize
// correctly.
if (GraphObject.class.isAssignableFrom(value.getClass())) {
value = ((GraphObject) value).getInnerJSONObject();
} else if (GraphObjectList.class.isAssignableFrom(value.getClass())) {
value = ((GraphObjectList<?>) value).getInnerJSONArray();
} else if (Iterable.class.isAssignableFrom(value.getClass())) {
JSONArray jsonArray = new JSONArray();
Iterable<?> iterable = (Iterable<?>) value;
for (Object o : iterable ) {
if (GraphObject.class.isAssignableFrom(o.getClass())) {
jsonArray.put(((GraphObject)o).getInnerJSONObject());
} else {
jsonArray.put(o);
}
}
value = jsonArray;
}
this.state.putOpt(key, value);
return null;
}
return throwUnexpectedMethodSignature(method);
}
private Object setJSONProperty(Object[] args) {
String name = (String) args[0];
Object property = args[1];
Object value = getUnderlyingJSONObject(property);
try {
state.putOpt(name, value);
} catch (JSONException e) {
throw new IllegalArgumentException(e);
}
return null;
}
}
private final static class GraphObjectListImpl<T> extends AbstractList<T> implements GraphObjectList<T> {
private final JSONArray state;
private final Class<?> itemType;
public GraphObjectListImpl(JSONArray state, Class<?> itemType) {
Validate.notNull(state, "state");
Validate.notNull(itemType, "itemType");
this.state = state;
this.itemType = itemType;
}
@Override
public String toString() {
return String.format("GraphObjectList{itemType=%s, state=%s}", itemType.getSimpleName(), state);
}
@Override
public void add(int location, T object) {
// We only support adding at the end of the list, due to JSONArray restrictions.
if (location < 0) {
throw new IndexOutOfBoundsException();
} else if (location < size()) {
throw new UnsupportedOperationException("Only adding items at the end of the list is supported.");
}
put(location, object);
}
@Override
public T set(int location, T object) {
checkIndex(location);
T result = get(location);
put(location, object);
return result;
}
@Override
public int hashCode() {
return state.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
GraphObjectListImpl<T> other = (GraphObjectListImpl<T>) obj;
return state.equals(other.state);
}
@SuppressWarnings("unchecked")
@Override
public T get(int location) {
checkIndex(location);
Object value = state.opt(location);
// Class<?> expectedType = method.getReturnType();
// Type genericType = method.getGenericReturnType();
T result = (T) coerceValueToExpectedType(value, itemType, null);
return result;
}
@Override
public int size() {
return state.length();
}
@Override
public final <U extends GraphObject> GraphObjectList<U> castToListOf(Class<U> graphObjectClass) {
if (GraphObject.class.isAssignableFrom(itemType)) {
if (graphObjectClass.isAssignableFrom(itemType)) {
@SuppressWarnings("unchecked")
GraphObjectList<U> result = (GraphObjectList<U>)this;
return result;
}
return createList(state, graphObjectClass);
} else {
throw new FacebookGraphObjectException("Can't cast GraphObjectCollection of non-GraphObject type "
+ itemType);
}
}
@Override
public final JSONArray getInnerJSONArray() {
return state;
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
private void checkIndex(int index) {
if (index < 0 || index >= state.length()) {
throw new IndexOutOfBoundsException();
}
}
private void put(int index, T obj) {
Object underlyingObject = getUnderlyingJSONObject(obj);
try {
state.put(index, underlyingObject);
} catch (JSONException e) {
throw new IllegalArgumentException(e);
}
}
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
/**
* Provides a strongly-typed representation of a Location as defined by the Graph API.
*
* Note that this interface is intended to be used with GraphObject.Factory
* and not implemented directly.
*/
public interface GraphLocation extends GraphObject {
/**
* Returns the street component of the location.
*
* @return the street component of the location, or null
*/
public String getStreet();
/**
* Sets the street component of the location.
*
* @param street
* the street component of the location, or null
*/
public void setStreet(String street);
/**
* Gets the city component of the location.
*
* @return the city component of the location
*/
public String getCity();
/**
* Sets the city component of the location.
*
* @param city
* the city component of the location
*/
public void setCity(String city);
/**
* Returns the state component of the location.
*
* @return the state component of the location
*/
public String getState();
/**
* Sets the state component of the location.
*
* @param state
* the state component of the location
*/
public void setState(String state);
/**
* Returns the country component of the location.
*
* @return the country component of the location
*/
public String getCountry();
/**
* Sets the country component of the location
*
* @param country
* the country component of the location
*/
public void setCountry(String country);
/**
* Returns the postal code component of the location.
*
* @return the postal code component of the location
*/
public String getZip();
/**
* Sets the postal code component of the location.
*
* @param zip
* the postal code component of the location
*/
public void setZip(String zip);
/**
* Returns the latitude component of the location.
*
* @return the latitude component of the location
*/
public double getLatitude();
/**
* Sets the latitude component of the location.
*
* @param latitude
* the latitude component of the location
*/
public void setLatitude(double latitude);
/**
* Returns the longitude component of the location.
*
* @return the longitude component of the location
*/
public double getLongitude();
/**
* Sets the longitude component of the location.
*
* @param longitude
* the longitude component of the location
*/
public void setLongitude(double longitude);
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Use this annotation on getters and setters in an interface that derives from
* GraphObject, if you wish to override the default property name that is inferred
* from the name of the method.
*
* If this annotation is specified on a method, it must contain a non-empty String
* value that represents the name of the property that the method is a getter or setter
* for.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyName {
String value();
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.model;
import org.json.JSONArray;
import java.util.List;
/**
* GraphObjectList is the primary representation of a collection of graph objects in the Facebook SDK for Android.
* It is not implemented by any concrete classes, but rather by a proxy (see the {@link com.facebook.model.GraphObject.Factory Factory}
* class). A GraphObjectList can actually contain elements of any type, not just graph objects, but its principal
* use in the SDK is to contain types derived from GraphObject.
* <br/>
*
* @param <T> the type of elements in the list
*/
public interface GraphObjectList<T> extends List<T> {
// cast method is only supported if T extends GraphObject
/**
* If T is derived from GraphObject, returns a new GraphObjectList exposing the same underlying data as a new
* GraphObject-derived type.
* @param graphObjectClass the GraphObject-derived type to return a list of
* @return a list representing the same underlying data, exposed as the new GraphObject-derived type
* @throws com.facebook.FacebookGraphObjectException if T does not derive from GraphObject
*/
public <U extends GraphObject> GraphObjectList<U> castToListOf(Class<U> graphObjectClass);
/**
* Gets the underlying JSONArray representation of the data.
* @return the underlying JSONArray representation of the data
*/
public JSONArray getInnerJSONArray();
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.util.Pair;
import com.facebook.internal.ServerProtocol;
import com.facebook.model.*;
import com.facebook.internal.Logger;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
/**
* A single request to be sent to the Facebook Platform through either the <a
* href="https://developers.facebook.com/docs/reference/api/">Graph API</a> or <a
* href="https://developers.facebook.com/docs/reference/rest/">REST API</a>. The Request class provides functionality
* relating to serializing and deserializing requests and responses, making calls in batches (with a single round-trip
* to the service) and making calls asynchronously.
*
* The particular service endpoint that a request targets is determined by either a graph path (see the
* {@link #setGraphPath(String) setGraphPath} method) or a REST method name (see the {@link #setRestMethod(String)
* setRestMethod} method); a single request may not target both.
*
* A Request can be executed either anonymously or representing an authenticated user. In the former case, no Session
* needs to be specified, while in the latter, a Session that is in an opened state must be provided. If requests are
* executed in a batch, a Facebook application ID must be associated with the batch, either by supplying a Session for
* at least one of the requests in the batch (the first one found in the batch will be used) or by calling the
* {@link #setDefaultBatchApplicationId(String) setDefaultBatchApplicationId} method.
*
* After completion of a request, its Session, if any, will be checked to determine if its Facebook access token needs
* to be extended; if so, a request to extend it will be issued in the background.
*/
public class Request {
/**
* The maximum number of requests that can be submitted in a single batch. This limit is enforced on the service
* side by the Facebook platform, not by the Request class.
*/
public static final int MAXIMUM_BATCH_SIZE = 50;
private static final String ME = "me";
private static final String MY_FRIENDS = "me/friends";
private static final String MY_PHOTOS = "me/photos";
private static final String MY_VIDEOS = "me/videos";
private static final String SEARCH = "search";
private static final String MY_FEED = "me/feed";
private static final String USER_AGENT_BASE = "FBAndroidSDK";
private static final String USER_AGENT_HEADER = "User-Agent";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
// Parameter names/values
private static final String PICTURE_PARAM = "picture";
private static final String FORMAT_PARAM = "format";
private static final String FORMAT_JSON = "json";
private static final String SDK_PARAM = "sdk";
private static final String SDK_ANDROID = "android";
private static final String ACCESS_TOKEN_PARAM = "access_token";
private static final String BATCH_ENTRY_NAME_PARAM = "name";
private static final String BATCH_ENTRY_OMIT_RESPONSE_ON_SUCCESS_PARAM = "omit_response_on_success";
private static final String BATCH_ENTRY_DEPENDS_ON_PARAM = "depends_on";
private static final String BATCH_APP_ID_PARAM = "batch_app_id";
private static final String BATCH_RELATIVE_URL_PARAM = "relative_url";
private static final String BATCH_BODY_PARAM = "body";
private static final String BATCH_METHOD_PARAM = "method";
private static final String BATCH_PARAM = "batch";
private static final String ATTACHMENT_FILENAME_PREFIX = "file";
private static final String ATTACHED_FILES_PARAM = "attached_files";
private static final String MIGRATION_BUNDLE_PARAM = "migration_bundle";
private static final String ISO_8601_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZ";
private static final String MIME_BOUNDARY = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
private static String defaultBatchApplicationId;
private Session session;
private HttpMethod httpMethod;
private String graphPath;
private GraphObject graphObject;
private String restMethod;
private String batchEntryName;
private String batchEntryDependsOn;
private boolean batchEntryOmitResultOnSuccess = true;
private Bundle parameters;
private Callback callback;
private String overriddenURL;
/**
* Constructs a request without a session, graph path, or any other parameters.
*/
public Request() {
this(null, null, null, null, null);
}
/**
* Constructs a request with a Session to retrieve a particular graph path. A Session need not be provided, in which
* case the request is sent without an access token and thus is not executed in the context of any particular user.
* Only certain graph requests can be expected to succeed in this case. If a Session is provided, it must be in an
* opened state or the request will fail.
*
* @param session
* the Session to use, or null
* @param graphPath
* the graph path to retrieve
*/
public Request(Session session, String graphPath) {
this(session, graphPath, null, null, null);
}
/**
* Constructs a request with a specific Session, graph path, parameters, and HTTP method. A Session need not be
* provided, in which case the request is sent without an access token and thus is not executed in the context of
* any particular user. Only certain graph requests can be expected to succeed in this case. If a Session is
* provided, it must be in an opened state or the request will fail.
*
* Depending on the httpMethod parameter, the object at the graph path may be retrieved, created, or deleted.
*
* @param session
* the Session to use, or null
* @param graphPath
* the graph path to retrieve, create, or delete
* @param parameters
* additional parameters to pass along with the Graph API request; parameters must be Strings, Numbers,
* Bitmaps, Dates, or Byte arrays.
* @param httpMethod
* the {@link HttpMethod} to use for the request, or null for default (HttpMethod.GET)
*/
public Request(Session session, String graphPath, Bundle parameters, HttpMethod httpMethod) {
this(session, graphPath, parameters, httpMethod, null);
}
/**
* Constructs a request with a specific Session, graph path, parameters, and HTTP method. A Session need not be
* provided, in which case the request is sent without an access token and thus is not executed in the context of
* any particular user. Only certain graph requests can be expected to succeed in this case. If a Session is
* provided, it must be in an opened state or the request will fail.
*
* Depending on the httpMethod parameter, the object at the graph path may be retrieved, created, or deleted.
*
* @param session
* the Session to use, or null
* @param graphPath
* the graph path to retrieve, create, or delete
* @param parameters
* additional parameters to pass along with the Graph API request; parameters must be Strings, Numbers,
* Bitmaps, Dates, or Byte arrays.
* @param httpMethod
* the {@link HttpMethod} to use for the request, or null for default (HttpMethod.GET)
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
*/
public Request(Session session, String graphPath, Bundle parameters, HttpMethod httpMethod, Callback callback) {
this.session = session;
this.graphPath = graphPath;
this.callback = callback;
setHttpMethod(httpMethod);
if (parameters != null) {
this.parameters = new Bundle(parameters);
} else {
this.parameters = new Bundle();
}
if (!this.parameters.containsKey(MIGRATION_BUNDLE_PARAM)) {
this.parameters.putString(MIGRATION_BUNDLE_PARAM, FacebookSdkVersion.MIGRATION_BUNDLE);
}
}
Request(Session session, URL overriddenURL) {
this.session = session;
this.overriddenURL = overriddenURL.toString();
setHttpMethod(HttpMethod.GET);
this.parameters = new Bundle();
}
/**
* Creates a new Request configured to post a GraphObject to a particular graph path, to either create or update the
* object at that path.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param graphPath
* the graph path to retrieve, create, or delete
* @param graphObject
* the GraphObject to create or update
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newPostRequest(Session session, String graphPath, GraphObject graphObject, Callback callback) {
Request request = new Request(session, graphPath, null, HttpMethod.POST , callback);
request.setGraphObject(graphObject);
return request;
}
/**
* Creates a new Request configured to make a call to the Facebook REST API.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param restMethod
* the method in the Facebook REST API to execute
* @param parameters
* additional parameters to pass along with the Graph API request; parameters must be Strings, Numbers,
* Bitmaps, Dates, or Byte arrays.
* @param httpMethod
* the HTTP method to use for the request; must be one of GET, POST, or DELETE
* @return a Request that is ready to execute
*/
public static Request newRestRequest(Session session, String restMethod, Bundle parameters, HttpMethod httpMethod) {
Request request = new Request(session, null, parameters, httpMethod);
request.setRestMethod(restMethod);
return request;
}
/**
* Creates a new Request configured to retrieve a user's own profile.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newMeRequest(Session session, final GraphUserCallback callback) {
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(response.getGraphObjectAs(GraphUser.class), response);
}
}
};
return new Request(session, ME, null, null, wrapper);
}
/**
* Creates a new Request configured to retrieve a user's friend list.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newMyFriendsRequest(Session session, final GraphUserListCallback callback) {
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(typedListFromResponse(response, GraphUser.class), response);
}
}
};
return new Request(session, MY_FRIENDS, null, null, wrapper);
}
/**
* Creates a new Request configured to upload a photo to the user's default photo album.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param image
* the image to upload
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newUploadPhotoRequest(Session session, Bitmap image, Callback callback) {
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, image);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
}
/**
* Creates a new Request configured to upload a photo to the user's default photo album. The photo
* will be read from the specified stream.
*
* @param session the Session to use, or null; if non-null, the session must be in an opened state
* @param file the file containing the photo to upload
* @param callback a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newUploadPhotoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, descriptor);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
}
/**
* Creates a new Request configured to upload a photo to the user's default photo album. The photo
* will be read from the specified file descriptor.
*
* @param session the Session to use, or null; if non-null, the session must be in an opened state
* @param file the file to upload
* @param callback a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newUploadVideoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
return new Request(session, MY_VIDEOS, parameters, HttpMethod.POST, callback);
}
/**
* Creates a new Request configured to retrieve a particular graph path.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param graphPath
* the graph path to retrieve
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newGraphPathRequest(Session session, String graphPath, Callback callback) {
return new Request(session, graphPath, null, null, callback);
}
/**
* Creates a new Request that is configured to perform a search for places near a specified location via the Graph
* API. At least one of location or searchText must be specified.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param location
* the location around which to search; only the latitude and longitude components of the location are
* meaningful
* @param radiusInMeters
* the radius around the location to search, specified in meters; this is ignored if
* no location is specified
* @param resultsLimit
* the maximum number of results to return
* @param searchText
* optional text to search for as part of the name or type of an object
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*
* @throws FacebookException If neither location nor searchText is specified
*/
public static Request newPlacesSearchRequest(Session session, Location location, int radiusInMeters,
int resultsLimit, String searchText, final GraphPlaceListCallback callback) {
if (location == null && Utility.isNullOrEmpty(searchText)) {
throw new FacebookException("Either location or searchText must be specified.");
}
Bundle parameters = new Bundle(5);
parameters.putString("type", "place");
parameters.putInt("limit", resultsLimit);
if (location != null) {
parameters.putString("center",
String.format(Locale.US, "%f,%f", location.getLatitude(), location.getLongitude()));
parameters.putInt("distance", radiusInMeters);
}
if (!Utility.isNullOrEmpty(searchText)) {
parameters.putString("q", searchText);
}
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(typedListFromResponse(response, GraphPlace.class), response);
}
}
};
return new Request(session, SEARCH, parameters, HttpMethod.GET, wrapper);
}
/**
* Creates a new Request configured to post a status update to a user's feed.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param message
* the text of the status update
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a Request that is ready to execute
*/
public static Request newStatusUpdateRequest(Session session, String message, Callback callback) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
return new Request(session, MY_FEED, parameters, HttpMethod.POST, callback);
}
/**
* Returns the GraphObject, if any, associated with this request.
*
* @return the GraphObject associated with this requeset, or null if there is none
*/
public final GraphObject getGraphObject() {
return this.graphObject;
}
/**
* Sets the GraphObject associated with this request. This is meaningful only for POST requests.
*
* @param graphObject
* the GraphObject to upload along with this request
*/
public final void setGraphObject(GraphObject graphObject) {
this.graphObject = graphObject;
}
/**
* Returns the graph path of this request, if any.
*
* @return the graph path of this request, or null if there is none
*/
public final String getGraphPath() {
return this.graphPath;
}
/**
* Sets the graph path of this request. A graph path may not be set if a REST method has been specified.
*
* @param graphPath
* the graph path for this request
*/
public final void setGraphPath(String graphPath) {
this.graphPath = graphPath;
}
/**
* Returns the {@link HttpMethod} to use for this request.
*
* @return the HttpMethod
*/
public final HttpMethod getHttpMethod() {
return this.httpMethod;
}
/**
* Sets the {@link HttpMethod} to use for this request.
*
* @param httpMethod
* the HttpMethod, or null for the default (HttpMethod.GET).
*/
public final void setHttpMethod(HttpMethod httpMethod) {
if (overriddenURL != null && httpMethod != HttpMethod.GET) {
throw new FacebookException("Can't change HTTP method on request with overridden URL.");
}
this.httpMethod = (httpMethod != null) ? httpMethod : HttpMethod.GET;
}
/**
* Returns the parameters for this request.
*
* @return the parameters
*/
public final Bundle getParameters() {
return this.parameters;
}
/**
* Sets the parameters for this request.
*
* @param parameters
* the parameters
*/
public final void setParameters(Bundle parameters) {
this.parameters = parameters;
}
/**
* Returns the REST method to call for this request.
*
* @return the REST method
*/
public final String getRestMethod() {
return this.restMethod;
}
/**
* Sets the REST method to call for this request. A REST method may not be set if a graph path has been specified.
*
* @param restMethod
* the REST method to call
*/
public final void setRestMethod(String restMethod) {
this.restMethod = restMethod;
}
/**
* Returns the Session associated with this request.
*
* @return the Session associated with this request, or null if none has been specified
*/
public final Session getSession() {
return this.session;
}
/**
* Sets the Session to use for this request. The Session does not need to be opened at the time it is specified, but
* it must be opened by the time the request is executed.
*
* @param session
* the Session to use for this request
*/
public final void setSession(Session session) {
this.session = session;
}
/**
* Returns the name of this request's entry in a batched request.
*
* @return the name of this request's batch entry, or null if none has been specified
*/
public final String getBatchEntryName() {
return this.batchEntryName;
}
/**
* Sets the name of this request's entry in a batched request. This value is only used if this request is submitted
* as part of a batched request. It can be used to specified dependencies between requests. See <a
* href="https://developers.facebook.com/docs/reference/api/batch/">Batch Requests</a> in the Graph API
* documentation for more details.
*
* @param batchEntryName
* the name of this request's entry in a batched request, which must be unique within a particular batch
* of requests
*/
public final void setBatchEntryName(String batchEntryName) {
this.batchEntryName = batchEntryName;
}
/**
* Returns the name of the request that this request entry explicitly depends on in a batched request.
*
* @return the name of this request's dependency, or null if none has been specified
*/
public final String getBatchEntryDependsOn() {
return this.batchEntryDependsOn;
}
/**
* Sets the name of the request entry that this request explicitly depends on in a batched request. This value is
* only used if this request is submitted as part of a batched request. It can be used to specified dependencies
* between requests. See <a href="https://developers.facebook.com/docs/reference/api/batch/">Batch Requests</a> in
* the Graph API documentation for more details.
*
* @param batchEntryDependsOn
* the name of the request entry that this entry depends on in a batched request
*/
public final void setBatchEntryDependsOn(String batchEntryDependsOn) {
this.batchEntryDependsOn = batchEntryDependsOn;
}
/**
* Returns whether or not this batch entry will return a response if it is successful. Only applies if another
* request entry in the batch specifies this entry as a dependency.
*
* @return the name of this request's dependency, or null if none has been specified
*/
public final boolean getBatchEntryOmitResultOnSuccess() {
return this.batchEntryOmitResultOnSuccess;
}
/**
* Sets whether or not this batch entry will return a response if it is successful. Only applies if another
* request entry in the batch specifies this entry as a dependency. See
* <a href="https://developers.facebook.com/docs/reference/api/batch/">Batch Requests</a> in the Graph API
* documentation for more details.
*
* @param batchEntryOmitResultOnSuccess
* the name of the request entry that this entry depends on in a batched request
*/
public final void setBatchEntryOmitResultOnSuccess(boolean batchEntryOmitResultOnSuccess) {
this.batchEntryOmitResultOnSuccess = batchEntryOmitResultOnSuccess;
}
/**
* Gets the default Facebook application ID that will be used to submit batched requests if none of those requests
* specifies a Session. Batched requests require an application ID, so either at least one request in a batch must
* specify a Session or the application ID must be specified explicitly.
*
* @return the Facebook application ID to use for batched requests if none can be determined
*/
public static final String getDefaultBatchApplicationId() {
return Request.defaultBatchApplicationId;
}
/**
* Sets the default application ID that will be used to submit batched requests if none of those requests specifies
* a Session. Batched requests require an application ID, so either at least one request in a batch must specify a
* Session or the application ID must be specified explicitly.
*
* @param applicationId
* the Facebook application ID to use for batched requests if none can be determined
*/
public static final void setDefaultBatchApplicationId(String applicationId) {
Request.defaultBatchApplicationId = applicationId;
}
/**
* Returns the callback which will be called when the request finishes.
*
* @return the callback
*/
public final Callback getCallback() {
return callback;
}
/**
* Sets the callback which will be called when the request finishes.
*
* @param callback
* the callback
*/
public final void setCallback(Callback callback) {
this.callback = callback;
}
/**
* Starts a new Request configured to post a GraphObject to a particular graph path, to either create or update the
* object at that path.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param graphPath
* the graph path to retrieve, create, or delete
* @param graphObject
* the GraphObject to create or update
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executePostRequestAsync(Session session, String graphPath, GraphObject graphObject,
Callback callback) {
return newPostRequest(session, graphPath, graphObject, callback).executeAsync();
}
/**
* Creates a new Request configured to make a call to the Facebook REST API.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param restMethod
* the method in the Facebook REST API to execute
* @param parameters
* additional parameters to pass along with the Graph API request; parameters must be Strings, Numbers,
* Bitmaps, Dates, or Byte arrays.
* @param httpMethod
* the HTTP method to use for the request; must be one of GET, POST, or DELETE
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeRestRequestAsync(Session session, String restMethod, Bundle parameters,
HttpMethod httpMethod) {
return newRestRequest(session, restMethod, parameters, httpMethod).executeAsync();
}
/**
* Creates a new Request configured to retrieve a user's own profile.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeMeRequestAsync(Session session, GraphUserCallback callback) {
return newMeRequest(session, callback).executeAsync();
}
/**
* Creates a new Request configured to retrieve a user's friend list.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeMyFriendsRequestAsync(Session session, GraphUserListCallback callback) {
return newMyFriendsRequest(session, callback).executeAsync();
}
/**
* Creates a new Request configured to upload a photo to the user's default photo album.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param image
* the image to upload
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeUploadPhotoRequestAsync(Session session, Bitmap image, Callback callback) {
return newUploadPhotoRequest(session, image, callback).executeAsync();
}
/**
* Creates a new Request configured to upload a photo to the user's default photo album. The photo
* will be read from the specified stream.
* <p/>
* This should only be called from the UI thread.
*
* @param session the Session to use, or null; if non-null, the session must be in an opened state
* @param file the file containing the photo to upload
* @param callback a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeUploadPhotoRequestAsync(Session session, File file,
Callback callback) throws FileNotFoundException {
return newUploadPhotoRequest(session, file, callback).executeAsync();
}
/**
* Creates a new Request configured to retrieve a particular graph path.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param graphPath
* the graph path to retrieve
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeGraphPathRequestAsync(Session session, String graphPath, Callback callback) {
return newGraphPathRequest(session, graphPath, callback).executeAsync();
}
/**
* Creates a new Request that is configured to perform a search for places near a specified location via the Graph
* API.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param location
* the location around which to search; only the latitude and longitude components of the location are
* meaningful
* @param radiusInMeters
* the radius around the location to search, specified in meters
* @param resultsLimit
* the maximum number of results to return
* @param searchText
* optional text to search for as part of the name or type of an object
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*
* @throws FacebookException If neither location nor searchText is specified
*/
public static RequestAsyncTask executePlacesSearchRequestAsync(Session session, Location location, int radiusInMeters,
int resultsLimit, String searchText, GraphPlaceListCallback callback) {
return newPlacesSearchRequest(session, location, radiusInMeters, resultsLimit, searchText, callback).executeAsync();
}
/**
* Creates a new Request configured to post a status update to a user's feed.
* <p/>
* This should only be called from the UI thread.
*
* @param session
* the Session to use, or null; if non-null, the session must be in an opened state
* @param message
* the text of the status update
* @param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeStatusUpdateRequestAsync(Session session, String message, Callback callback) {
return newStatusUpdateRequest(session, message, callback).executeAsync();
}
/**
* Executes this request and returns the response.
* <p/>
* This should only be called if you have transitioned off the UI thread.
*
* @return the Response object representing the results of the request
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
* @throws IllegalArgumentException
*/
public final Response executeAndWait() {
return Request.executeAndWait(this);
}
/**
* Executes this request and returns the response.
* <p/>
* This should only be called from the UI thread.
*
* @return a RequestAsyncTask that is executing the request
*
* @throws IllegalArgumentException
*/
public final RequestAsyncTask executeAsync() {
return Request.executeBatchAsync(this);
}
/**
* Serializes one or more requests but does not execute them. The resulting HttpURLConnection can be executed
* explicitly by the caller.
*
* @param requests
* one or more Requests to serialize
* @return an HttpURLConnection which is ready to execute
*
* @throws FacebookException
* If any of the requests in the batch are badly constructed or if there are problems
* contacting the service
* @throws IllegalArgumentException if the passed in array is zero-length
* @throws NullPointerException if the passed in array or any of its contents are null
*/
public static HttpURLConnection toHttpConnection(Request... requests) {
return toHttpConnection(Arrays.asList(requests));
}
/**
* Serializes one or more requests but does not execute them. The resulting HttpURLConnection can be executed
* explicitly by the caller.
*
* @param requests
* one or more Requests to serialize
* @return an HttpURLConnection which is ready to execute
*
* @throws FacebookException
* If any of the requests in the batch are badly constructed or if there are problems
* contacting the service
* @throws IllegalArgumentException if the passed in collection is empty
* @throws NullPointerException if the passed in collection or any of its contents are null
*/
public static HttpURLConnection toHttpConnection(Collection<Request> requests) {
Validate.notEmptyAndContainsNoNulls(requests, "requests");
return toHttpConnection(new RequestBatch(requests));
}
/**
* Serializes one or more requests but does not execute them. The resulting HttpURLConnection can be executed
* explicitly by the caller.
*
* @param requests
* a RequestBatch to serialize
* @return an HttpURLConnection which is ready to execute
*
* @throws FacebookException
* If any of the requests in the batch are badly constructed or if there are problems
* contacting the service
* @throws IllegalArgumentException
*/
public static HttpURLConnection toHttpConnection(RequestBatch requests) {
for (Request request : requests) {
request.validate();
}
URL url = null;
try {
if (requests.size() == 1) {
// Single request case.
Request request = requests.get(0);
// In the non-batch case, the URL we use really is the same one returned by getUrlForSingleRequest.
url = new URL(request.getUrlForSingleRequest());
} else {
// Batch case -- URL is just the graph API base, individual request URLs are serialized
// as relative_url parameters within each batch entry.
url = new URL(ServerProtocol.GRAPH_URL);
}
} catch (MalformedURLException e) {
throw new FacebookException("could not construct URL for request", e);
}
HttpURLConnection connection;
try {
connection = createConnection(url);
serializeToUrlConnection(requests, connection);
} catch (IOException e) {
throw new FacebookException("could not construct request body", e);
} catch (JSONException e) {
throw new FacebookException("could not construct request body", e);
}
return connection;
}
/**
* Executes a single request on the current thread and returns the response.
* <p/>
* This should only be used if you have transitioned off the UI thread.
*
* @param request
* the Request to execute
*
* @return the Response object representing the results of the request
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
*/
public static Response executeAndWait(Request request) {
List<Response> responses = executeBatchAndWait(request);
if (responses == null || responses.size() != 1) {
throw new FacebookException("invalid state: expected a single response");
}
return responses.get(0);
}
/**
* Executes requests on the current thread as a single batch and returns the responses.
* <p/>
* This should only be used if you have transitioned off the UI thread.
*
* @param requests
* the Requests to execute
*
* @return a list of Response objects representing the results of the requests; responses are returned in the same
* order as the requests were specified.
*
* @throws NullPointerException
* In case of a null request
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
*/
public static List<Response> executeBatchAndWait(Request... requests) {
Validate.notNull(requests, "requests");
return executeBatchAndWait(Arrays.asList(requests));
}
/**
* Executes requests as a single batch on the current thread and returns the responses.
* <p/>
* This should only be used if you have transitioned off the UI thread.
*
* @param requests
* the Requests to execute
*
* @return a list of Response objects representing the results of the requests; responses are returned in the same
* order as the requests were specified.
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
*/
public static List<Response> executeBatchAndWait(Collection<Request> requests) {
return executeBatchAndWait(new RequestBatch(requests));
}
/**
* Executes requests on the current thread as a single batch and returns the responses.
* <p/>
* This should only be used if you have transitioned off the UI thread.
*
* @param requests
* the batch of Requests to execute
*
* @return a list of Response objects representing the results of the requests; responses are returned in the same
* order as the requests were specified.
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
* @throws IllegalArgumentException if the passed in RequestBatch is empty
* @throws NullPointerException if the passed in RequestBatch or any of its contents are null
*/
public static List<Response> executeBatchAndWait(RequestBatch requests) {
Validate.notEmptyAndContainsNoNulls(requests, "requests");
HttpURLConnection connection = null;
try {
connection = toHttpConnection(requests);
} catch (Exception ex) {
List<Response> responses = Response.constructErrorResponses(requests.getRequests(), null, new FacebookException(ex));
runCallbacks(requests, responses);
return responses;
}
List<Response> responses = executeConnectionAndWait(connection, requests);
return responses;
}
/**
* Executes requests as a single batch asynchronously. This function will return immediately, and the requests will
* be processed on a separate thread. In order to process results of a request, or determine whether a request
* succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method).
* <p/>
* This should only be called from the UI thread.
*
* @param requests
* the Requests to execute
* @return a RequestAsyncTask that is executing the request
*
* @throws NullPointerException
* If a null request is passed in
*/
public static RequestAsyncTask executeBatchAsync(Request... requests) {
Validate.notNull(requests, "requests");
return executeBatchAsync(Arrays.asList(requests));
}
/**
* Executes requests as a single batch asynchronously. This function will return immediately, and the requests will
* be processed on a separate thread. In order to process results of a request, or determine whether a request
* succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method).
* <p/>
* This should only be called from the UI thread.
*
* @param requests
* the Requests to execute
* @return a RequestAsyncTask that is executing the request
*
* @throws IllegalArgumentException if the passed in collection is empty
* @throws NullPointerException if the passed in collection or any of its contents are null
*/
public static RequestAsyncTask executeBatchAsync(Collection<Request> requests) {
return executeBatchAsync(new RequestBatch(requests));
}
/**
* Executes requests as a single batch asynchronously. This function will return immediately, and the requests will
* be processed on a separate thread. In order to process results of a request, or determine whether a request
* succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method).
* <p/>
* This should only be called from the UI thread.
*
* @param requests
* the RequestBatch to execute
* @return a RequestAsyncTask that is executing the request
*
* @throws IllegalArgumentException if the passed in RequestBatch is empty
* @throws NullPointerException if the passed in RequestBatch or any of its contents are null
*/
public static RequestAsyncTask executeBatchAsync(RequestBatch requests) {
Validate.notEmptyAndContainsNoNulls(requests, "requests");
RequestAsyncTask asyncTask = new RequestAsyncTask(requests);
asyncTask.executeOnSettingsExecutor();
return asyncTask;
}
/**
* Executes requests that have already been serialized into an HttpURLConnection. No validation is done that the
* contents of the connection actually reflect the serialized requests, so it is the caller's responsibility to
* ensure that it will correctly generate the desired responses.
* <p/>
* This should only be called if you have transitioned off the UI thread.
*
* @param connection
* the HttpURLConnection that the requests were serialized into
* @param requests
* the requests represented by the HttpURLConnection
* @return a list of Responses corresponding to the requests
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
*/
public static List<Response> executeConnectionAndWait(HttpURLConnection connection, Collection<Request> requests) {
return executeConnectionAndWait(connection, new RequestBatch(requests));
}
/**
* Executes requests that have already been serialized into an HttpURLConnection. No validation is done that the
* contents of the connection actually reflect the serialized requests, so it is the caller's responsibility to
* ensure that it will correctly generate the desired responses.
* <p/>
* This should only be called if you have transitioned off the UI thread.
*
* @param connection
* the HttpURLConnection that the requests were serialized into
* @param requests
* the RequestBatch represented by the HttpURLConnection
* @return a list of Responses corresponding to the requests
*
* @throws FacebookException
* If there was an error in the protocol used to communicate with the service
*/
public static List<Response> executeConnectionAndWait(HttpURLConnection connection, RequestBatch requests) {
List<Response> responses = Response.fromHttpConnection(connection, requests);
Utility.disconnectQuietly(connection);
int numRequests = requests.size();
if (numRequests != responses.size()) {
throw new FacebookException(String.format("Received %d responses while expecting %d", responses.size(),
numRequests));
}
runCallbacks(requests, responses);
// See if any of these sessions needs its token to be extended. We do this after issuing the request so as to
// reduce network contention.
HashSet<Session> sessions = new HashSet<Session>();
for (Request request : requests) {
if (request.session != null) {
sessions.add(request.session);
}
}
for (Session session : sessions) {
session.extendAccessTokenIfNeeded();
}
return responses;
}
/**
* Asynchronously executes requests that have already been serialized into an HttpURLConnection. No validation is
* done that the contents of the connection actually reflect the serialized requests, so it is the caller's
* responsibility to ensure that it will correctly generate the desired responses. This function will return
* immediately, and the requests will be processed on a separate thread. In order to process results of a request,
* or determine whether a request succeeded or failed, a callback must be specified (see the
* {@link #setCallback(Callback) setCallback} method).
* <p/>
* This should only be called from the UI thread.
*
* @param connection
* the HttpURLConnection that the requests were serialized into
* @param requests
* the requests represented by the HttpURLConnection
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeConnectionAsync(HttpURLConnection connection, RequestBatch requests) {
return executeConnectionAsync(null, connection, requests);
}
/**
* Asynchronously executes requests that have already been serialized into an HttpURLConnection. No validation is
* done that the contents of the connection actually reflect the serialized requests, so it is the caller's
* responsibility to ensure that it will correctly generate the desired responses. This function will return
* immediately, and the requests will be processed on a separate thread. In order to process results of a request,
* or determine whether a request succeeded or failed, a callback must be specified (see the
* {@link #setCallback(Callback) setCallback} method)
* <p/>
* This should only be called from the UI thread.
*
* @param callbackHandler
* a Handler that will be used to post calls to the callback for each request; if null, a Handler will be
* instantiated on the calling thread
* @param connection
* the HttpURLConnection that the requests were serialized into
* @param requests
* the requests represented by the HttpURLConnection
* @return a RequestAsyncTask that is executing the request
*/
public static RequestAsyncTask executeConnectionAsync(Handler callbackHandler, HttpURLConnection connection,
RequestBatch requests) {
Validate.notNull(connection, "connection");
RequestAsyncTask asyncTask = new RequestAsyncTask(connection, requests);
requests.setCallbackHandler(callbackHandler);
asyncTask.executeOnSettingsExecutor();
return asyncTask;
}
/**
* Returns a string representation of this Request, useful for debugging.
*
* @return the debugging information
*/
@Override
public String toString() {
return new StringBuilder().append("{Request: ").append(" session: ").append(session).append(", graphPath: ")
.append(graphPath).append(", graphObject: ").append(graphObject).append(", restMethod: ")
.append(restMethod).append(", httpMethod: ").append(httpMethod).append(", parameters: ")
.append(parameters).append("}").toString();
}
static void runCallbacks(final RequestBatch requests, List<Response> responses) {
int numRequests = requests.size();
// Compile the list of callbacks to call and then run them either on this thread or via the Handler we received
final ArrayList<Pair<Callback, Response>> callbacks = new ArrayList<Pair<Callback, Response>>();
for (int i = 0; i < numRequests; ++i) {
Request request = requests.get(i);
if (request.callback != null) {
callbacks.add(new Pair<Callback, Response>(request.callback, responses.get(i)));
}
}
if (callbacks.size() > 0) {
Runnable runnable = new Runnable() {
public void run() {
for (Pair<Callback, Response> pair : callbacks) {
pair.first.onCompleted(pair.second);
}
List<RequestBatch.Callback> batchCallbacks = requests.getCallbacks();
for (RequestBatch.Callback batchCallback : batchCallbacks) {
batchCallback.onBatchCompleted(requests);
}
}
};
Handler callbackHandler = requests.getCallbackHandler();
if (callbackHandler == null) {
// Run on this thread.
runnable.run();
} else {
// Post to the handler.
callbackHandler.post(runnable);
}
}
}
static HttpURLConnection createConnection(URL url) throws IOException {
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(USER_AGENT_HEADER, getUserAgent());
connection.setRequestProperty(CONTENT_TYPE_HEADER, getMimeContentType());
connection.setChunkedStreamingMode(0);
return connection;
}
private void addCommonParameters() {
if (this.session != null) {
if (!this.session.isOpened()) {
throw new FacebookException("Session provided to a Request in un-opened state.");
} else if (!this.parameters.containsKey(ACCESS_TOKEN_PARAM)) {
String accessToken = this.session.getAccessToken();
Logger.registerAccessToken(accessToken);
this.parameters.putString(ACCESS_TOKEN_PARAM, accessToken);
}
}
this.parameters.putString(SDK_PARAM, SDK_ANDROID);
this.parameters.putString(FORMAT_PARAM, FORMAT_JSON);
}
private String appendParametersToBaseUrl(String baseUrl) {
Uri.Builder uriBuilder = new Uri.Builder().encodedPath(baseUrl);
Set<String> keys = this.parameters.keySet();
for (String key : keys) {
Object value = this.parameters.get(key);
if (value == null) {
value = "";
}
if (isSupportedParameterType(value)) {
value = parameterToString(value);
} else {
if (httpMethod == HttpMethod.GET) {
throw new IllegalArgumentException(String.format("Unsupported parameter type for GET request: %s",
value.getClass().getSimpleName()));
}
continue;
}
uriBuilder.appendQueryParameter(key, value.toString());
}
return uriBuilder.toString();
}
final String getUrlForBatchedRequest() {
if (overriddenURL != null) {
throw new FacebookException("Can't override URL for a batch request");
}
String baseUrl;
if (this.restMethod != null) {
baseUrl = ServerProtocol.BATCHED_REST_METHOD_URL_BASE + this.restMethod;
} else {
baseUrl = this.graphPath;
}
addCommonParameters();
return appendParametersToBaseUrl(baseUrl);
}
final String getUrlForSingleRequest() {
if (overriddenURL != null) {
return overriddenURL.toString();
}
String baseUrl;
if (this.restMethod != null) {
baseUrl = ServerProtocol.REST_URL_BASE + this.restMethod;
} else {
baseUrl = ServerProtocol.GRAPH_URL_BASE + this.graphPath;
}
addCommonParameters();
return appendParametersToBaseUrl(baseUrl);
}
private void serializeToBatch(JSONArray batch, Bundle attachments) throws JSONException, IOException {
JSONObject batchEntry = new JSONObject();
if (this.batchEntryName != null) {
batchEntry.put(BATCH_ENTRY_NAME_PARAM, this.batchEntryName);
batchEntry.put(BATCH_ENTRY_OMIT_RESPONSE_ON_SUCCESS_PARAM, this.batchEntryOmitResultOnSuccess);
}
if (this.batchEntryDependsOn != null) {
batchEntry.put(BATCH_ENTRY_DEPENDS_ON_PARAM, this.batchEntryDependsOn);
}
String relativeURL = getUrlForBatchedRequest();
batchEntry.put(BATCH_RELATIVE_URL_PARAM, relativeURL);
batchEntry.put(BATCH_METHOD_PARAM, httpMethod);
if (this.session != null) {
String accessToken = this.session.getAccessToken();
Logger.registerAccessToken(accessToken);
}
// Find all of our attachments. Remember their names and put them in the attachment map.
ArrayList<String> attachmentNames = new ArrayList<String>();
Set<String> keys = this.parameters.keySet();
for (String key : keys) {
Object value = this.parameters.get(key);
if (isSupportedAttachmentType(value)) {
// Make the name unique across this entire batch.
String name = String.format("%s%d", ATTACHMENT_FILENAME_PREFIX, attachments.size());
attachmentNames.add(name);
Utility.putObjectInBundle(attachments, name, value);
}
}
if (!attachmentNames.isEmpty()) {
String attachmentNamesString = TextUtils.join(",", attachmentNames);
batchEntry.put(ATTACHED_FILES_PARAM, attachmentNamesString);
}
if (this.graphObject != null) {
// Serialize the graph object into the "body" parameter.
final ArrayList<String> keysAndValues = new ArrayList<String>();
processGraphObject(this.graphObject, relativeURL, new KeyValueSerializer() {
@Override
public void writeString(String key, String value) throws IOException {
keysAndValues.add(String.format("%s=%s", key, URLEncoder.encode(value, "UTF-8")));
}
});
String bodyValue = TextUtils.join("&", keysAndValues);
batchEntry.put(BATCH_BODY_PARAM, bodyValue);
}
batch.put(batchEntry);
}
private void validate() {
if (graphPath != null && restMethod != null) {
throw new IllegalArgumentException("Only one of a graph path or REST method may be specified per request.");
}
}
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");
int numRequests = requests.size();
HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
connection.setRequestMethod(connectionHttpMethod.name());
URL url = connection.getURL();
logger.append("Request:\n");
logger.appendKeyValue("Id", requests.getId());
logger.appendKeyValue("URL", url);
logger.appendKeyValue("Method", connection.getRequestMethod());
logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));
connection.setConnectTimeout(requests.getTimeout());
connection.setReadTimeout(requests.getTimeout());
// If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
// turn it into a POST.
boolean isPost = (connectionHttpMethod == HttpMethod.POST);
if (!isPost) {
logger.log();
return;
}
connection.setDoOutput(true);
BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
try {
Serializer serializer = new Serializer(outputStream, logger);
if (numRequests == 1) {
Request request = requests.get(0);
logger.append(" Parameters:\n");
serializeParameters(request.parameters, serializer);
logger.append(" Attachments:\n");
serializeAttachments(request.parameters, serializer);
if (request.graphObject != null) {
processGraphObject(request.graphObject, url.getPath(), serializer);
}
} else {
String batchAppID = getBatchAppId(requests);
if (Utility.isNullOrEmpty(batchAppID)) {
throw new FacebookException("At least one request in a batch must have an open Session, or a "
+ "default app ID must be specified.");
}
serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);
// We write out all the requests as JSON, remembering which file attachments they have, then
// write out the attachments.
Bundle attachments = new Bundle();
serializeRequestsAsJSON(serializer, requests, attachments);
logger.append(" Attachments:\n");
serializeAttachments(attachments, serializer);
}
} finally {
outputStream.close();
}
logger.log();
}
private static void processGraphObject(GraphObject graphObject, String path, KeyValueSerializer serializer)
throws IOException {
// In general, graph objects are passed by reference (ID/URL). But if this is an OG Action,
// we need to pass the entire values of the contents of the 'image' property, as they
// contain important metadata beyond just a URL. We don't have a 100% foolproof way of knowing
// if we are posting an OG Action, given that batched requests can have parameter substitution,
// but passing the OG Action type as a substituted parameter is unlikely.
// It looks like an OG Action if it's posted to me/namespace:action[?other=stuff].
boolean isOGAction = false;
if (path.startsWith("me/") || path.startsWith("/me/")) {
int colonLocation = path.indexOf(":");
int questionMarkLocation = path.indexOf("?");
isOGAction = colonLocation > 3 && (questionMarkLocation == -1 || colonLocation < questionMarkLocation);
}
Set<Entry<String, Object>> entries = graphObject.asMap().entrySet();
for (Entry<String, Object> entry : entries) {
boolean passByValue = isOGAction && entry.getKey().equalsIgnoreCase("image");
processGraphObjectProperty(entry.getKey(), entry.getValue(), serializer, passByValue);
}
}
private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
boolean passByValue) throws IOException {
Class<?> valueClass = value.getClass();
if (GraphObject.class.isAssignableFrom(valueClass)) {
value = ((GraphObject) value).getInnerJSONObject();
valueClass = value.getClass();
} else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
value = ((GraphObjectList<?>) value).getInnerJSONArray();
valueClass = value.getClass();
}
if (JSONObject.class.isAssignableFrom(valueClass)) {
JSONObject jsonObject = (JSONObject) value;
if (passByValue) {
// We need to pass all properties of this object in key[propertyName] format.
@SuppressWarnings("unchecked")
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String propertyName = keys.next();
String subKey = String.format("%s[%s]", key, propertyName);
processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
}
} else {
// Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
// for "key"
if (jsonObject.has("id")) {
processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
} else if (jsonObject.has("url")) {
processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
}
}
} else if (JSONArray.class.isAssignableFrom(valueClass)) {
JSONArray jsonArray = (JSONArray) value;
int length = jsonArray.length();
for (int i = 0; i < length; ++i) {
String subKey = String.format("%s[%d]", key, i);
processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
}
} else if (String.class.isAssignableFrom(valueClass) ||
Number.class.isAssignableFrom(valueClass) ||
Boolean.class.isAssignableFrom(valueClass)) {
serializer.writeString(key, value.toString());
} else if (Date.class.isAssignableFrom(valueClass)) {
Date date = (Date) value;
// The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
// Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
// dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
// that is what we support here. Apps that need pre-migration behavior can explicitly send these as
// integer timestamps rather than Dates.
final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
serializer.writeString(key, iso8601DateFormat.format(date));
}
}
private static void serializeParameters(Bundle bundle, Serializer serializer) throws IOException {
Set<String> keys = bundle.keySet();
for (String key : keys) {
Object value = bundle.get(key);
if (isSupportedParameterType(value)) {
serializer.writeObject(key, value);
}
}
}
private static void serializeAttachments(Bundle bundle, Serializer serializer) throws IOException {
Set<String> keys = bundle.keySet();
for (String key : keys) {
Object value = bundle.get(key);
if (isSupportedAttachmentType(value)) {
serializer.writeObject(key, value);
}
}
}
private static void serializeRequestsAsJSON(Serializer serializer, Collection<Request> requests, Bundle attachments)
throws JSONException, IOException {
JSONArray batch = new JSONArray();
for (Request request : requests) {
request.serializeToBatch(batch, attachments);
}
String batchAsString = batch.toString();
serializer.writeString(BATCH_PARAM, batchAsString);
}
private static String getMimeContentType() {
return String.format("multipart/form-data; boundary=%s", MIME_BOUNDARY);
}
private static volatile String userAgent;
private static String getUserAgent() {
if (userAgent == null) {
userAgent = String.format("%s.%s", USER_AGENT_BASE, FacebookSdkVersion.BUILD);
}
return userAgent;
}
private static String getBatchAppId(RequestBatch batch) {
if (!Utility.isNullOrEmpty(batch.getBatchApplicationId())) {
return batch.getBatchApplicationId();
}
for (Request request : batch) {
Session session = request.session;
if (session != null) {
return session.getApplicationId();
}
}
return Request.defaultBatchApplicationId;
}
private static <T extends GraphObject> List<T> typedListFromResponse(Response response, Class<T> clazz) {
GraphMultiResult multiResult = response.getGraphObjectAs(GraphMultiResult.class);
if (multiResult == null) {
return null;
}
GraphObjectList<GraphObject> data = multiResult.getData();
if (data == null) {
return null;
}
return data.castToListOf(clazz);
}
private static boolean isSupportedAttachmentType(Object value) {
return value instanceof Bitmap || value instanceof byte[] || value instanceof ParcelFileDescriptor;
}
private static boolean isSupportedParameterType(Object value) {
return value instanceof String || value instanceof Boolean || value instanceof Number ||
value instanceof Date;
}
private static String parameterToString(Object value) {
if (value instanceof String) {
return (String) value;
} else if (value instanceof Boolean || value instanceof Number) {
return value.toString();
} else if (value instanceof Date) {
final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
return iso8601DateFormat.format(value);
}
throw new IllegalArgumentException("Unsupported parameter type.");
}
private interface KeyValueSerializer {
void writeString(String key, String value) throws IOException;
}
private static class Serializer implements KeyValueSerializer {
private final BufferedOutputStream outputStream;
private final Logger logger;
private boolean firstWrite = true;
public Serializer(BufferedOutputStream outputStream, Logger logger) {
this.outputStream = outputStream;
this.logger = logger;
}
public void writeObject(String key, Object value) throws IOException {
if (isSupportedParameterType(value)) {
writeString(key, parameterToString(value));
} else if (value instanceof Bitmap) {
writeBitmap(key, (Bitmap) value);
} else if (value instanceof byte[]) {
writeBytes(key, (byte[]) value);
} else if (value instanceof ParcelFileDescriptor) {
writeFile(key, (ParcelFileDescriptor) value);
} else {
throw new IllegalArgumentException("value is not a supported type: String, Bitmap, byte[]");
}
}
public void writeString(String key, String value) throws IOException {
writeContentDisposition(key, null, null);
writeLine("%s", value);
writeRecordBoundary();
if (logger != null) {
logger.appendKeyValue(" " + key, value);
}
}
public void writeBitmap(String key, Bitmap bitmap) throws IOException {
writeContentDisposition(key, key, "image/png");
// Note: quality parameter is ignored for PNG
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
writeLine("");
writeRecordBoundary();
logger.appendKeyValue(" " + key, "<Image>");
}
public void writeBytes(String key, byte[] bytes) throws IOException {
writeContentDisposition(key, key, "content/unknown");
this.outputStream.write(bytes);
writeLine("");
writeRecordBoundary();
logger.appendKeyValue(" " + key, String.format("<Data: %d>", bytes.length));
}
public void writeFile(String key, ParcelFileDescriptor descriptor) throws IOException {
writeContentDisposition(key, key, "content/unknown");
ParcelFileDescriptor.AutoCloseInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
int totalBytes = 0;
try {
inputStream = new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
this.outputStream.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
} finally {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
writeLine("");
writeRecordBoundary();
logger.appendKeyValue(" " + key, String.format("<Data: %d>", totalBytes));
}
public void writeRecordBoundary() throws IOException {
writeLine("--%s", MIME_BOUNDARY);
}
public void writeContentDisposition(String name, String filename, String contentType) throws IOException {
write("Content-Disposition: form-data; name=\"%s\"", name);
if (filename != null) {
write("; filename=\"%s\"", filename);
}
writeLine(""); // newline after Content-Disposition
if (contentType != null) {
writeLine("%s: %s", CONTENT_TYPE_HEADER, contentType);
}
writeLine(""); // blank line before content
}
public void write(String format, Object... args) throws IOException {
if (firstWrite) {
// Prepend all of our output with a boundary string.
this.outputStream.write("--".getBytes());
this.outputStream.write(MIME_BOUNDARY.getBytes());
this.outputStream.write("\r\n".getBytes());
firstWrite = false;
}
this.outputStream.write(String.format(format, args).getBytes());
}
public void writeLine(String format, Object... args) throws IOException {
write(format, args);
write("\r\n");
}
}
/**
* Specifies the interface that consumers of the Request class can implement in order to be notified when a
* particular request completes, either successfully or with an error.
*/
public interface Callback {
/**
* The method that will be called when a request completes.
*
* @param response
* the Response of this request, which may include error information if the request was unsuccessful
*/
void onCompleted(Response response);
}
/**
* Specifies the interface that consumers of
* {@link Request#executeMeRequestAsync(Session, com.facebook.Request.GraphUserCallback)}
* can use to be notified when the request completes, either successfully or with an error.
*/
public interface GraphUserCallback {
/**
* The method that will be called when the request completes.
*
* @param user the GraphObject representing the returned user, or null
* @param response the Response of this request, which may include error information if the request was unsuccessful
*/
void onCompleted(GraphUser user, Response response);
}
/**
* Specifies the interface that consumers of
* {@link Request#executeMyFriendsRequestAsync(Session, com.facebook.Request.GraphUserListCallback)}
* can use to be notified when the request completes, either successfully or with an error.
*/
public interface GraphUserListCallback {
/**
* The method that will be called when the request completes.
*
* @param users the list of GraphObjects representing the returned friends, or null
* @param response the Response of this request, which may include error information if the request was unsuccessful
*/
void onCompleted(List<GraphUser> users, Response response);
}
/**
* Specifies the interface that consumers of
* {@link Request#executePlacesSearchRequestAsync(Session, android.location.Location, int, int, String, com.facebook.Request.GraphPlaceListCallback)}
* can use to be notified when the request completes, either successfully or with an error.
*/
public interface GraphPlaceListCallback {
/**
* The method that will be called when the request completes.
*
* @param places the list of GraphObjects representing the returned places, or null
* @param response the Response of this request, which may include error information if the request was unsuccessful
*/
void onCompleted(List<GraphPlace> places, Response response);
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
/**
* Defines an AsyncTask suitable for executing a Request in the background. May be subclassed
* by applications having unique threading model needs.
*/
@TargetApi(3)
public class RequestAsyncTask extends AsyncTask<Void, Void, List<Response>> {
private static final String TAG = RequestAsyncTask.class.getCanonicalName();
private static Method executeOnExecutorMethod;
private final HttpURLConnection connection;
private final RequestBatch requests;
private Exception exception;
static {
for (Method method : AsyncTask.class.getMethods()) {
if ("executeOnExecutor".equals(method.getName())) {
Class<?>[] parameters = method.getParameterTypes();
if ((parameters.length == 2) && (parameters[0] == Executor.class) && parameters[1].isArray()) {
executeOnExecutorMethod = method;
break;
}
}
}
}
/**
* Constructor. Serialization of the requests will be done in the background, so any serialization-
* related errors will be returned via the Response.getException() method.
*
* @param requests the requests to execute
*/
public RequestAsyncTask(Request... requests) {
this(null, new RequestBatch(requests));
}
/**
* Constructor. Serialization of the requests will be done in the background, so any serialization-
* related errors will be returned via the Response.getException() method.
*
* @param requests the requests to execute
*/
public RequestAsyncTask(Collection<Request> requests) {
this(null, new RequestBatch(requests));
}
/**
* Constructor. Serialization of the requests will be done in the background, so any serialization-
* related errors will be returned via the Response.getException() method.
*
* @param requests the requests to execute
*/
public RequestAsyncTask(RequestBatch requests) {
this(null, requests);
}
/**
* Constructor that allows specification of an HTTP connection to use for executing
* the requests. No validation is done that the contents of the connection actually
* reflect the serialized requests, so it is the caller's responsibility to ensure
* that it will correctly generate the desired responses.
*
* @param connection the HTTP connection to use to execute the requests
* @param requests the requests to execute
*/
public RequestAsyncTask(HttpURLConnection connection, Request... requests) {
this(connection, new RequestBatch(requests));
}
/**
* Constructor that allows specification of an HTTP connection to use for executing
* the requests. No validation is done that the contents of the connection actually
* reflect the serialized requests, so it is the caller's responsibility to ensure
* that it will correctly generate the desired responses.
*
* @param connection the HTTP connection to use to execute the requests
* @param requests the requests to execute
*/
public RequestAsyncTask(HttpURLConnection connection, Collection<Request> requests) {
this(connection, new RequestBatch(requests));
}
/**
* Constructor that allows specification of an HTTP connection to use for executing
* the requests. No validation is done that the contents of the connection actually
* reflect the serialized requests, so it is the caller's responsibility to ensure
* that it will correctly generate the desired responses.
*
* @param connection the HTTP connection to use to execute the requests
* @param requests the requests to execute
*/
public RequestAsyncTask(HttpURLConnection connection, RequestBatch requests) {
this.requests = requests;
this.connection = connection;
}
protected final Exception getException() {
return exception;
}
protected final RequestBatch getRequests() {
return requests;
}
@Override
public String toString() {
return new StringBuilder().append("{RequestAsyncTask: ").append(" connection: ").append(connection)
.append(", requests: ").append(requests).append("}").toString();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (requests.getCallbackHandler() == null) {
// We want any callbacks to go to a handler on this thread unless a handler has already been specified.
requests.setCallbackHandler(new Handler());
}
}
@Override
protected void onPostExecute(List<Response> result) {
super.onPostExecute(result);
if (exception != null) {
Log.d(TAG, String.format("onPostExecute: exception encountered during request: %s", exception.getMessage()));
}
}
@Override
protected List<Response> doInBackground(Void... params) {
try {
if (connection == null) {
return requests.executeAndWait();
} else {
return Request.executeConnectionAndWait(connection, requests);
}
} catch (Exception e) {
exception = e;
return null;
}
}
RequestAsyncTask executeOnSettingsExecutor() {
try {
if (executeOnExecutorMethod != null) {
executeOnExecutorMethod.invoke(this, Settings.getExecutor(), null);
return this;
}
} catch (InvocationTargetException e) {
// fall-through
} catch (IllegalAccessException e) {
// fall-through
}
this.execute();
return this;
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import com.facebook.internal.Utility;
import com.facebook.internal.Validate;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* This class represents an access token returned by the Facebook Login service, along with associated
* metadata such as its expiration date and permissions. In general, the {@link Session} class will
* abstract away the need to worry about the details of an access token, but there are situations
* (such as handling native links, importing previously-obtained access tokens, etc.) where it is
* useful to deal with access tokens directly. Factory methods are provided to construct access tokens.
* <p/>
* For more information on access tokens, see
* https://developers.facebook.com/docs/concepts/login/access-tokens-and-types/.
*/
public final class AccessToken implements Serializable {
private static final long serialVersionUID = 1L;
static final String ACCESS_TOKEN_KEY = "access_token";
static final String EXPIRES_IN_KEY = "expires_in";
private static final Date MIN_DATE = new Date(Long.MIN_VALUE);
private static final Date MAX_DATE = new Date(Long.MAX_VALUE);
private static final Date DEFAULT_EXPIRATION_TIME = MAX_DATE;
private static final Date DEFAULT_LAST_REFRESH_TIME = new Date();
private static final AccessTokenSource DEFAULT_ACCESS_TOKEN_SOURCE = AccessTokenSource.FACEBOOK_APPLICATION_WEB;
private static final Date ALREADY_EXPIRED_EXPIRATION_TIME = MIN_DATE;
private final Date expires;
private final List<String> permissions;
private final String token;
private final AccessTokenSource source;
private final Date lastRefresh;
AccessToken(String token, Date expires, List<String> permissions, AccessTokenSource source, Date lastRefresh) {
if (permissions == null) {
permissions = Collections.emptyList();
}
this.expires = expires;
this.permissions = Collections.unmodifiableList(permissions);
this.token = token;
this.source = source;
this.lastRefresh = lastRefresh;
}
/**
* Gets the string representing the access token.
*
* @return the string representing the access token
*/
public String getToken() {
return this.token;
}
/**
* Gets the date at which the access token expires.
*
* @return the expiration date of the token
*/
public Date getExpires() {
return this.expires;
}
/**
* Gets the list of permissions associated with this access token. Note that the most up-to-date
* list of permissions is maintained by the Facebook service, so this list may be outdated if
* permissions have been added or removed since the time the AccessToken object was created. For
* more information on permissions, see https://developers.facebook.com/docs/reference/login/#permissions.
*
* @return a read-only list of strings representing the permissions granted via this access token
*/
public List<String> getPermissions() {
return this.permissions;
}
/**
* Gets the {@link AccessTokenSource} indicating how this access token was obtained.
*
* @return the enum indicating how the access token was obtained
*/
public AccessTokenSource getSource() {
return source;
}
/**
* Gets the date at which the token was last refreshed. Since tokens expire, the Facebook SDK
* will attempt to renew them periodically.
*
* @return the date at which this token was last refreshed
*/
public Date getLastRefresh() {
return this.lastRefresh;
}
/**
* Creates a new AccessToken using the supplied information from a previously-obtained access
* token (for instance, from an already-cached access token obtained prior to integration with the
* Facebook SDK).
*
* @param accessToken the access token string obtained from Facebook
* @param expirationTime the expiration date associated with the token; if null, an infinite expiration time is
* assumed (but will become correct when the token is refreshed)
* @param lastRefreshTime the last time the token was refreshed (or when it was first obtained); if null,
* the current time is used.
* @param accessTokenSource an enum indicating how the token was originally obtained (in most cases,
* this will be either AccessTokenSource.FACEBOOK_APPLICATION or
* AccessTokenSource.WEB_VIEW); if null, FACEBOOK_APPLICATION is assumed.
* @param permissions the permissions that were requested when the token was obtained (or when
* it was last reauthorized); may be null if permission set is unknown
* @return a new AccessToken
*/
public static AccessToken createFromExistingAccessToken(String accessToken, Date expirationTime,
Date lastRefreshTime, AccessTokenSource accessTokenSource, List<String> permissions) {
if (expirationTime == null) {
expirationTime = DEFAULT_EXPIRATION_TIME;
}
if (lastRefreshTime == null) {
lastRefreshTime = DEFAULT_LAST_REFRESH_TIME;
}
if (accessTokenSource == null) {
accessTokenSource = DEFAULT_ACCESS_TOKEN_SOURCE;
}
return new AccessToken(accessToken, expirationTime, permissions, accessTokenSource, lastRefreshTime);
}
/**
* Creates a new AccessToken using the information contained in an Intent populated by the Facebook
* application in order to launch a native link. For more information on native linking, please see
* https://developers.facebook.com/docs/mobile/android/deep_linking/.
*
* @param intent the Intent that was used to start an Activity; must not be null
* @return a new AccessToken, or null if the Intent did not contain enough data to create one
*/
public static AccessToken createFromNativeLinkingIntent(Intent intent) {
Validate.notNull(intent, "intent");
if (intent.getExtras() == null) {
return null;
}
return createFromBundle(null, intent.getExtras(), AccessTokenSource.FACEBOOK_APPLICATION_WEB, new Date());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{AccessToken");
builder.append(" token:").append(tokenToString());
appendPermissions(builder);
builder.append("}");
return builder.toString();
}
static AccessToken createEmptyToken(List<String> permissions) {
return new AccessToken("", ALREADY_EXPIRED_EXPIRATION_TIME, permissions, AccessTokenSource.NONE,
DEFAULT_LAST_REFRESH_TIME);
}
static AccessToken createFromString(String token, List<String> permissions, AccessTokenSource source) {
return new AccessToken(token, DEFAULT_EXPIRATION_TIME, permissions, source, DEFAULT_LAST_REFRESH_TIME);
}
static AccessToken createFromNativeLogin(Bundle bundle, AccessTokenSource source) {
Date expires = getBundleLongAsDate(
bundle, NativeProtocol.EXTRA_EXPIRES_SECONDS_SINCE_EPOCH, new Date(0));
ArrayList<String> permissions = bundle.getStringArrayList(NativeProtocol.EXTRA_PERMISSIONS);
String token = bundle.getString(NativeProtocol.EXTRA_ACCESS_TOKEN);
return createNew(permissions, token, expires, source);
}
static AccessToken createFromWebBundle(List<String> requestedPermissions, Bundle bundle, AccessTokenSource source) {
Date expires = getBundleLongAsDate(bundle, EXPIRES_IN_KEY, new Date());
String token = bundle.getString(ACCESS_TOKEN_KEY);
return createNew(requestedPermissions, token, expires, source);
}
@SuppressLint("FieldGetter")
static AccessToken createFromRefresh(AccessToken current, Bundle bundle) {
// Only tokens obtained via SSO support refresh. Token refresh returns the expiration date in
// seconds from the epoch rather than seconds from now.
assert (current.source == AccessTokenSource.FACEBOOK_APPLICATION_WEB ||
current.source == AccessTokenSource.FACEBOOK_APPLICATION_NATIVE ||
current.source == AccessTokenSource.FACEBOOK_APPLICATION_SERVICE);
Date expires = getBundleLongAsDate(bundle, EXPIRES_IN_KEY, new Date(0));
String token = bundle.getString(ACCESS_TOKEN_KEY);
return createNew(current.getPermissions(), token, expires, current.source);
}
static AccessToken createFromTokenWithRefreshedPermissions(AccessToken token, List<String> permissions) {
return new AccessToken(token.token, token.expires, permissions, token.source, token.lastRefresh);
}
private static AccessToken createNew(
List<String> requestedPermissions, String accessToken, Date expires, AccessTokenSource source) {
if (Utility.isNullOrEmpty(accessToken) || (expires == null)) {
return createEmptyToken(requestedPermissions);
} else {
return new AccessToken(accessToken, expires, requestedPermissions, source, new Date());
}
}
static AccessToken createFromCache(Bundle bundle) {
// Copy the list so we can guarantee immutable
List<String> originalPermissions = bundle.getStringArrayList(TokenCachingStrategy.PERMISSIONS_KEY);
List<String> permissions;
if (originalPermissions == null) {
permissions = Collections.emptyList();
} else {
permissions = Collections.unmodifiableList(new ArrayList<String>(originalPermissions));
}
return new AccessToken(bundle.getString(TokenCachingStrategy.TOKEN_KEY), TokenCachingStrategy.getDate(bundle,
TokenCachingStrategy.EXPIRATION_DATE_KEY), permissions, TokenCachingStrategy.getSource(bundle),
TokenCachingStrategy.getDate(bundle, TokenCachingStrategy.LAST_REFRESH_DATE_KEY));
}
Bundle toCacheBundle() {
Bundle bundle = new Bundle();
bundle.putString(TokenCachingStrategy.TOKEN_KEY, this.token);
TokenCachingStrategy.putDate(bundle, TokenCachingStrategy.EXPIRATION_DATE_KEY, expires);
bundle.putStringArrayList(TokenCachingStrategy.PERMISSIONS_KEY, new ArrayList<String>(permissions));
bundle.putSerializable(TokenCachingStrategy.TOKEN_SOURCE_KEY, source);
TokenCachingStrategy.putDate(bundle, TokenCachingStrategy.LAST_REFRESH_DATE_KEY, lastRefresh);
return bundle;
}
boolean isInvalid() {
return Utility.isNullOrEmpty(this.token) || new Date().after(this.expires);
}
private static AccessToken createFromBundle(List<String> requestedPermissions, Bundle bundle,
AccessTokenSource source,
Date expirationBase) {
String token = bundle.getString(ACCESS_TOKEN_KEY);
Date expires = getBundleLongAsDate(bundle, EXPIRES_IN_KEY, expirationBase);
if (Utility.isNullOrEmpty(token) || (expires == null)) {
return null;
}
return new AccessToken(token, expires, requestedPermissions, source, new Date());
}
private String tokenToString() {
if (this.token == null) {
return "null";
} else if (Settings.isLoggingBehaviorEnabled(LoggingBehavior.INCLUDE_ACCESS_TOKENS)) {
return this.token;
} else {
return "ACCESS_TOKEN_REMOVED";
}
}
private void appendPermissions(StringBuilder builder) {
builder.append(" permissions:");
if (this.permissions == null) {
builder.append("null");
} else {
builder.append("[");
builder.append(TextUtils.join(", ", permissions));
builder.append("]");
}
}
private static class SerializationProxyV1 implements Serializable {
private static final long serialVersionUID = -2488473066578201069L;
private final Date expires;
private final List<String> permissions;
private final String token;
private final AccessTokenSource source;
private final Date lastRefresh;
private SerializationProxyV1(String token, Date expires,
List<String> permissions, AccessTokenSource source, Date lastRefresh) {
this.expires = expires;
this.permissions = permissions;
this.token = token;
this.source = source;
this.lastRefresh = lastRefresh;
}
private Object readResolve() {
return new AccessToken(token, expires, permissions, source, lastRefresh);
}
}
private Object writeReplace() {
return new SerializationProxyV1(token, expires, permissions, source, lastRefresh);
}
// have a readObject that throws to prevent spoofing
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Cannot readObject, serialization proxy required");
}
private static Date getBundleLongAsDate(Bundle bundle, String key, Date dateBase) {
if (bundle == null) {
return null;
}
long secondsFromBase = Long.MIN_VALUE;
Object secondsObject = bundle.get(key);
if (secondsObject instanceof Long) {
secondsFromBase = (Long) secondsObject;
} else if (secondsObject instanceof String) {
try {
secondsFromBase = Long.parseLong((String) secondsObject);
} catch (NumberFormatException e) {
return null;
}
} else {
return null;
}
if (secondsFromBase == 0) {
return new Date(Long.MAX_VALUE);
} else {
return new Date(dateBase.getTime() + (secondsFromBase * 1000L));
}
}
}
| Java |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
/**
* Specifies the behaviors to try during
* {@link Session#openForRead(com.facebook.Session.OpenRequest) openForRead},
* {@link Session#openForPublish(com.facebook.Session.OpenRequest) openForPublish},
* {@link Session#requestNewReadPermissions(com.facebook.Session.NewPermissionsRequest) requestNewReadPermissions}, or
* {@link Session#requestNewPublishPermissions(com.facebook.Session.NewPermissionsRequest) requestNewPublishPermissions}.
*/
public enum SessionLoginBehavior {
/**
* Specifies that Session should attempt Single Sign On (SSO), and if that
* does not work fall back to dialog auth. This is the default behavior.
*/
SSO_WITH_FALLBACK(true, true),
/**
* Specifies that Session should only attempt SSO. If SSO fails, then the
* open or new permissions call fails.
*/
SSO_ONLY(true, false),
/**
* Specifies that SSO should not be attempted, and to only use dialog auth.
*/
SUPPRESS_SSO(false, true);
private final boolean allowsKatanaAuth;
private final boolean allowsWebViewAuth;
private SessionLoginBehavior(boolean allowsKatanaAuth, boolean allowsWebViewAuth) {
this.allowsKatanaAuth = allowsKatanaAuth;
this.allowsWebViewAuth = allowsWebViewAuth;
}
boolean allowsKatanaAuth() {
return allowsKatanaAuth;
}
boolean allowsWebViewAuth() {
return allowsWebViewAuth;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.facebook.android;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;
import android.view.View;
import com.nineoldandroids.util.Property;
import com.nineoldandroids.view.animation.AnimatorProxy;
/**
* This subclass of {@link ValueAnimator} provides support for animating properties on target objects.
* The constructors of this class take parameters to define the target object that will be animated
* as well as the name of the property that will be animated. Appropriate set/get functions
* are then determined internally and the animation will call these functions as necessary to
* animate the property.
*
* @see #setPropertyName(String)
*
*/
public final class ObjectAnimator extends ValueAnimator {
private static final boolean DBG = false;
private static final Map<String, Property> PROXY_PROPERTIES = new HashMap<String, Property>();
static {
PROXY_PROPERTIES.put("alpha", PreHoneycombCompat.ALPHA);
PROXY_PROPERTIES.put("pivotX", PreHoneycombCompat.PIVOT_X);
PROXY_PROPERTIES.put("pivotY", PreHoneycombCompat.PIVOT_Y);
PROXY_PROPERTIES.put("translationX", PreHoneycombCompat.TRANSLATION_X);
PROXY_PROPERTIES.put("translationY", PreHoneycombCompat.TRANSLATION_Y);
PROXY_PROPERTIES.put("rotation", PreHoneycombCompat.ROTATION);
PROXY_PROPERTIES.put("rotationX", PreHoneycombCompat.ROTATION_X);
PROXY_PROPERTIES.put("rotationY", PreHoneycombCompat.ROTATION_Y);
PROXY_PROPERTIES.put("scaleX", PreHoneycombCompat.SCALE_X);
PROXY_PROPERTIES.put("scaleY", PreHoneycombCompat.SCALE_Y);
PROXY_PROPERTIES.put("scrollX", PreHoneycombCompat.SCROLL_X);
PROXY_PROPERTIES.put("scrollY", PreHoneycombCompat.SCROLL_Y);
PROXY_PROPERTIES.put("x", PreHoneycombCompat.X);
PROXY_PROPERTIES.put("y", PreHoneycombCompat.Y);
}
// The target object on which the property exists, set in the constructor
private Object mTarget;
private String mPropertyName;
private Property mProperty;
/**
* Sets the name of the property that will be animated. This name is used to derive
* a setter function that will be called to set animated values.
* For example, a property name of <code>foo</code> will result
* in a call to the function <code>setFoo()</code> on the target object. If either
* <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will
* also be derived and called.
*
* <p>For best performance of the mechanism that calls the setter function determined by the
* name of the property being animated, use <code>float</code> or <code>int</code> typed values,
* and make the setter function for those properties have a <code>void</code> return value. This
* will cause the code to take an optimized path for these constrained circumstances. Other
* property types and return types will work, but will have more overhead in processing
* the requests due to normal reflection mechanisms.</p>
*
* <p>Note that the setter function derived from this property name
* must take the same parameter type as the
* <code>valueFrom</code> and <code>valueTo</code> properties, otherwise the call to
* the setter function will fail.</p>
*
* <p>If this ObjectAnimator has been set up to animate several properties together,
* using more than one PropertyValuesHolder objects, then setting the propertyName simply
* sets the propertyName in the first of those PropertyValuesHolder objects.</p>
*
* @param propertyName The name of the property being animated. Should not be null.
*/
public void setPropertyName(String propertyName) {
// mValues could be null if this is being constructed piecemeal. Just record the
// propertyName to be used later when setValues() is called if so.
if (mValues != null) {
PropertyValuesHolder valuesHolder = mValues[0];
String oldName = valuesHolder.getPropertyName();
valuesHolder.setPropertyName(propertyName);
mValuesMap.remove(oldName);
mValuesMap.put(propertyName, valuesHolder);
}
mPropertyName = propertyName;
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Sets the property that will be animated. Property objects will take precedence over
* properties specified by the {@link #setPropertyName(String)} method. Animations should
* be set up to use one or the other, not both.
*
* @param property The property being animated. Should not be null.
*/
public void setProperty(Property property) {
// mValues could be null if this is being constructed piecemeal. Just record the
// propertyName to be used later when setValues() is called if so.
if (mValues != null) {
PropertyValuesHolder valuesHolder = mValues[0];
String oldName = valuesHolder.getPropertyName();
valuesHolder.setProperty(property);
mValuesMap.remove(oldName);
mValuesMap.put(mPropertyName, valuesHolder);
}
if (mProperty != null) {
mPropertyName = property.getName();
}
mProperty = property;
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Gets the name of the property that will be animated. This name will be used to derive
* a setter function that will be called to set animated values.
* For example, a property name of <code>foo</code> will result
* in a call to the function <code>setFoo()</code> on the target object. If either
* <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will
* also be derived and called.
*/
public String getPropertyName() {
return mPropertyName;
}
/**
* Creates a new ObjectAnimator object. This default constructor is primarily for
* use internally; the other constructors which take parameters are more generally
* useful.
*/
public ObjectAnimator() {
}
/**
* Private utility constructor that initializes the target object and name of the
* property being animated.
*
* @param target The object whose property is to be animated. This object should
* have a public method on it called <code>setName()</code>, where <code>name</code> is
* the value of the <code>propertyName</code> parameter.
* @param propertyName The name of the property being animated.
*/
private ObjectAnimator(Object target, String propertyName) {
mTarget = target;
setPropertyName(propertyName);
}
/**
* Private utility constructor that initializes the target object and property being animated.
*
* @param target The object whose property is to be animated.
* @param property The property being animated.
*/
private <T> ObjectAnimator(T target, Property<T, ?> property) {
mTarget = target;
setProperty(property);
}
/**
* Constructs and returns an ObjectAnimator that animates between int values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated. This object should
* have a public method on it called <code>setName()</code>, where <code>name</code> is
* the value of the <code>propertyName</code> parameter.
* @param propertyName The name of the property being animated.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static ObjectAnimator ofInt(Object target, String propertyName, int... values) {
ObjectAnimator anim = new ObjectAnimator(target, propertyName);
anim.setIntValues(values);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between int values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated.
* @param property The property being animated.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static <T> ObjectAnimator ofInt(T target, Property<T, Integer> property, int... values) {
ObjectAnimator anim = new ObjectAnimator(target, property);
anim.setIntValues(values);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between float values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated. This object should
* have a public method on it called <code>setName()</code>, where <code>name</code> is
* the value of the <code>propertyName</code> parameter.
* @param propertyName The name of the property being animated.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static ObjectAnimator ofFloat(Object target, String propertyName, float... values) {
ObjectAnimator anim = new ObjectAnimator(target, propertyName);
anim.setFloatValues(values);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between float values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated.
* @param property The property being animated.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static <T> ObjectAnimator ofFloat(T target, Property<T, Float> property,
float... values) {
ObjectAnimator anim = new ObjectAnimator(target, property);
anim.setFloatValues(values);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between Object values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated. This object should
* have a public method on it called <code>setName()</code>, where <code>name</code> is
* the value of the <code>propertyName</code> parameter.
* @param propertyName The name of the property being animated.
* @param evaluator A TypeEvaluator that will be called on each animation frame to
* provide the necessary interpolation between the Object values to derive the animated
* value.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static ObjectAnimator ofObject(Object target, String propertyName,
TypeEvaluator evaluator, Object... values) {
ObjectAnimator anim = new ObjectAnimator(target, propertyName);
anim.setObjectValues(values);
anim.setEvaluator(evaluator);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between Object values. A single
* value implies that that value is the one being animated to. Two values imply a starting
* and ending values. More than two values imply a starting value, values to animate through
* along the way, and an ending value (these values will be distributed evenly across
* the duration of the animation).
*
* @param target The object whose property is to be animated.
* @param property The property being animated.
* @param evaluator A TypeEvaluator that will be called on each animation frame to
* provide the necessary interpolation between the Object values to derive the animated
* value.
* @param values A set of values that the animation will animate between over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static <T, V> ObjectAnimator ofObject(T target, Property<T, V> property,
TypeEvaluator<V> evaluator, V... values) {
ObjectAnimator anim = new ObjectAnimator(target, property);
anim.setObjectValues(values);
anim.setEvaluator(evaluator);
return anim;
}
/**
* Constructs and returns an ObjectAnimator that animates between the sets of values specified
* in <code>PropertyValueHolder</code> objects. This variant should be used when animating
* several properties at once with the same ObjectAnimator, since PropertyValuesHolder allows
* you to associate a set of animation values with a property name.
*
* @param target The object whose property is to be animated. Depending on how the
* PropertyValuesObjects were constructed, the target object should either have the {@link
* android.util.Property} objects used to construct the PropertyValuesHolder objects or (if the
* PropertyValuesHOlder objects were created with property names) the target object should have
* public methods on it called <code>setName()</code>, where <code>name</code> is the name of
* the property passed in as the <code>propertyName</code> parameter for each of the
* PropertyValuesHolder objects.
* @param values A set of PropertyValuesHolder objects whose values will be animated between
* over time.
* @return An ObjectAnimator object that is set up to animate between the given values.
*/
public static ObjectAnimator ofPropertyValuesHolder(Object target,
PropertyValuesHolder... values) {
ObjectAnimator anim = new ObjectAnimator();
anim.mTarget = target;
anim.setValues(values);
return anim;
}
@Override
public void setIntValues(int... values) {
if (mValues == null || mValues.length == 0) {
// No values yet - this animator is being constructed piecemeal. Init the values with
// whatever the current propertyName is
if (mProperty != null) {
setValues(PropertyValuesHolder.ofInt(mProperty, values));
} else {
setValues(PropertyValuesHolder.ofInt(mPropertyName, values));
}
} else {
super.setIntValues(values);
}
}
@Override
public void setFloatValues(float... values) {
if (mValues == null || mValues.length == 0) {
// No values yet - this animator is being constructed piecemeal. Init the values with
// whatever the current propertyName is
if (mProperty != null) {
setValues(PropertyValuesHolder.ofFloat(mProperty, values));
} else {
setValues(PropertyValuesHolder.ofFloat(mPropertyName, values));
}
} else {
super.setFloatValues(values);
}
}
@Override
public void setObjectValues(Object... values) {
if (mValues == null || mValues.length == 0) {
// No values yet - this animator is being constructed piecemeal. Init the values with
// whatever the current propertyName is
if (mProperty != null) {
setValues(PropertyValuesHolder.ofObject(mProperty, (TypeEvaluator)null, values));
} else {
setValues(PropertyValuesHolder.ofObject(mPropertyName, (TypeEvaluator)null, values));
}
} else {
super.setObjectValues(values);
}
}
@Override
public void start() {
if (DBG) {
Log.d("ObjectAnimator", "Anim target, duration: " + mTarget + ", " + getDuration());
for (int i = 0; i < mValues.length; ++i) {
PropertyValuesHolder pvh = mValues[i];
ArrayList<Keyframe> keyframes = pvh.mKeyframeSet.mKeyframes;
Log.d("ObjectAnimator", " Values[" + i + "]: " +
pvh.getPropertyName() + ", " + keyframes.get(0).getValue() + ", " +
keyframes.get(pvh.mKeyframeSet.mNumKeyframes - 1).getValue());
}
}
super.start();
}
/**
* This function is called immediately before processing the first animation
* frame of an animation. If there is a nonzero <code>startDelay</code>, the
* function is called after that delay ends.
* It takes care of the final initialization steps for the
* animation. This includes setting mEvaluator, if the user has not yet
* set it up, and the setter/getter methods, if the user did not supply
* them.
*
* <p>Overriders of this method should call the superclass method to cause
* internal mechanisms to be set up correctly.</p>
*/
@Override
void initAnimation() {
if (!mInitialized) {
// mValueType may change due to setter/getter setup; do this before calling super.init(),
// which uses mValueType to set up the default type evaluator.
if ((mProperty == null) && AnimatorProxy.NEEDS_PROXY && (mTarget instanceof View) && PROXY_PROPERTIES.containsKey(mPropertyName)) {
setProperty(PROXY_PROPERTIES.get(mPropertyName));
}
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].setupSetterAndGetter(mTarget);
}
super.initAnimation();
}
}
/**
* Sets the length of the animation. The default duration is 300 milliseconds.
*
* @param duration The length of the animation, in milliseconds.
* @return ObjectAnimator The object called with setDuration(). This return
* value makes it easier to compose statements together that construct and then set the
* duration, as in
* <code>ObjectAnimator.ofInt(target, propertyName, 0, 10).setDuration(500).start()</code>.
*/
@Override
public ObjectAnimator setDuration(long duration) {
super.setDuration(duration);
return this;
}
/**
* The target object whose property will be animated by this animation
*
* @return The object being animated
*/
public Object getTarget() {
return mTarget;
}
/**
* Sets the target object whose property will be animated by this animation
*
* @param target The object being animated
*/
@Override
public void setTarget(Object target) {
if (mTarget != target) {
final Object oldTarget = mTarget;
mTarget = target;
if (oldTarget != null && target != null && oldTarget.getClass() == target.getClass()) {
return;
}
// New target type should cause re-initialization prior to starting
mInitialized = false;
}
}
@Override
public void setupStartValues() {
initAnimation();
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].setupStartValue(mTarget);
}
}
@Override
public void setupEndValues() {
initAnimation();
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].setupEndValue(mTarget);
}
}
/**
* This method is called with the elapsed fraction of the animation during every
* animation frame. This function turns the elapsed fraction into an interpolated fraction
* and then into an animated value (from the evaluator. The function is called mostly during
* animation updates, but it is also called when the <code>end()</code>
* function is called, to set the final value on the property.
*
* <p>Overrides of this method must call the superclass to perform the calculation
* of the animated value.</p>
*
* @param fraction The elapsed fraction of the animation.
*/
@Override
void animateValue(float fraction) {
super.animateValue(fraction);
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].setAnimatedValue(mTarget);
}
}
@Override
public ObjectAnimator clone() {
final ObjectAnimator anim = (ObjectAnimator) super.clone();
return anim;
}
@Override
public String toString() {
String returnVal = "ObjectAnimator@" + Integer.toHexString(hashCode()) + ", target " +
mTarget;
if (mValues != null) {
for (int i = 0; i < mValues.length; ++i) {
returnVal += "\n " + mValues[i].toString();
}
}
return returnVal;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import android.view.animation.Interpolator;
/**
* This class plays a set of {@link Animator} objects in the specified order. Animations
* can be set up to play together, in sequence, or after a specified delay.
*
* <p>There are two different approaches to adding animations to a <code>AnimatorSet</code>:
* either the {@link AnimatorSet#playTogether(Animator[]) playTogether()} or
* {@link AnimatorSet#playSequentially(Animator[]) playSequentially()} methods can be called to add
* a set of animations all at once, or the {@link AnimatorSet#play(Animator)} can be
* used in conjunction with methods in the {@link AnimatorSet.Builder Builder}
* class to add animations
* one by one.</p>
*
* <p>It is possible to set up a <code>AnimatorSet</code> with circular dependencies between
* its animations. For example, an animation a1 could be set up to start before animation a2, a2
* before a3, and a3 before a1. The results of this configuration are undefined, but will typically
* result in none of the affected animations being played. Because of this (and because
* circular dependencies do not make logical sense anyway), circular dependencies
* should be avoided, and the dependency flow of animations should only be in one direction.
*/
public final class AnimatorSet extends Animator {
/**
* Internal variables
* NOTE: This object implements the clone() method, making a deep copy of any referenced
* objects. As other non-trivial fields are added to this class, make sure to add logic
* to clone() to make deep copies of them.
*/
/**
* Tracks animations currently being played, so that we know what to
* cancel or end when cancel() or end() is called on this AnimatorSet
*/
private ArrayList<Animator> mPlayingSet = new ArrayList<Animator>();
/**
* Contains all nodes, mapped to their respective Animators. When new
* dependency information is added for an Animator, we want to add it
* to a single node representing that Animator, not create a new Node
* if one already exists.
*/
private HashMap<Animator, Node> mNodeMap = new HashMap<Animator, Node>();
/**
* Set of all nodes created for this AnimatorSet. This list is used upon
* starting the set, and the nodes are placed in sorted order into the
* sortedNodes collection.
*/
private ArrayList<Node> mNodes = new ArrayList<Node>();
/**
* The sorted list of nodes. This is the order in which the animations will
* be played. The details about when exactly they will be played depend
* on the dependency relationships of the nodes.
*/
private ArrayList<Node> mSortedNodes = new ArrayList<Node>();
/**
* Flag indicating whether the nodes should be sorted prior to playing. This
* flag allows us to cache the previous sorted nodes so that if the sequence
* is replayed with no changes, it does not have to re-sort the nodes again.
*/
private boolean mNeedsSort = true;
private AnimatorSetListener mSetListener = null;
/**
* Flag indicating that the AnimatorSet has been manually
* terminated (by calling cancel() or end()).
* This flag is used to avoid starting other animations when currently-playing
* child animations of this AnimatorSet end. It also determines whether cancel/end
* notifications are sent out via the normal AnimatorSetListener mechanism.
*/
boolean mTerminated = false;
/**
* Indicates whether an AnimatorSet has been start()'d, whether or
* not there is a nonzero startDelay.
*/
private boolean mStarted = false;
// The amount of time in ms to delay starting the animation after start() is called
private long mStartDelay = 0;
// Animator used for a nonzero startDelay
private ValueAnimator mDelayAnim = null;
// How long the child animations should last in ms. The default value is negative, which
// simply means that there is no duration set on the AnimatorSet. When a real duration is
// set, it is passed along to the child animations.
private long mDuration = -1;
/**
* Sets up this AnimatorSet to play all of the supplied animations at the same time.
*
* @param items The animations that will be started simultaneously.
*/
public void playTogether(Animator... items) {
if (items != null) {
mNeedsSort = true;
Builder builder = play(items[0]);
for (int i = 1; i < items.length; ++i) {
builder.with(items[i]);
}
}
}
/**
* Sets up this AnimatorSet to play all of the supplied animations at the same time.
*
* @param items The animations that will be started simultaneously.
*/
public void playTogether(Collection<Animator> items) {
if (items != null && items.size() > 0) {
mNeedsSort = true;
Builder builder = null;
for (Animator anim : items) {
if (builder == null) {
builder = play(anim);
} else {
builder.with(anim);
}
}
}
}
/**
* Sets up this AnimatorSet to play each of the supplied animations when the
* previous animation ends.
*
* @param items The animations that will be started one after another.
*/
public void playSequentially(Animator... items) {
if (items != null) {
mNeedsSort = true;
if (items.length == 1) {
play(items[0]);
} else {
for (int i = 0; i < items.length - 1; ++i) {
play(items[i]).before(items[i+1]);
}
}
}
}
/**
* Sets up this AnimatorSet to play each of the supplied animations when the
* previous animation ends.
*
* @param items The animations that will be started one after another.
*/
public void playSequentially(List<Animator> items) {
if (items != null && items.size() > 0) {
mNeedsSort = true;
if (items.size() == 1) {
play(items.get(0));
} else {
for (int i = 0; i < items.size() - 1; ++i) {
play(items.get(i)).before(items.get(i+1));
}
}
}
}
/**
* Returns the current list of child Animator objects controlled by this
* AnimatorSet. This is a copy of the internal list; modifications to the returned list
* will not affect the AnimatorSet, although changes to the underlying Animator objects
* will affect those objects being managed by the AnimatorSet.
*
* @return ArrayList<Animator> The list of child animations of this AnimatorSet.
*/
public ArrayList<Animator> getChildAnimations() {
ArrayList<Animator> childList = new ArrayList<Animator>();
for (Node node : mNodes) {
childList.add(node.animation);
}
return childList;
}
/**
* Sets the target object for all current {@link #getChildAnimations() child animations}
* of this AnimatorSet that take targets ({@link ObjectAnimator} and
* AnimatorSet).
*
* @param target The object being animated
*/
@Override
public void setTarget(Object target) {
for (Node node : mNodes) {
Animator animation = node.animation;
if (animation instanceof AnimatorSet) {
((AnimatorSet)animation).setTarget(target);
} else if (animation instanceof ObjectAnimator) {
((ObjectAnimator)animation).setTarget(target);
}
}
}
/**
* Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations}
* of this AnimatorSet.
*
* @param interpolator the interpolator to be used by each child animation of this AnimatorSet
*/
@Override
public void setInterpolator(/*Time*/Interpolator interpolator) {
for (Node node : mNodes) {
node.animation.setInterpolator(interpolator);
}
}
/**
* This method creates a <code>Builder</code> object, which is used to
* set up playing constraints. This initial <code>play()</code> method
* tells the <code>Builder</code> the animation that is the dependency for
* the succeeding commands to the <code>Builder</code>. For example,
* calling <code>play(a1).with(a2)</code> sets up the AnimatorSet to play
* <code>a1</code> and <code>a2</code> at the same time,
* <code>play(a1).before(a2)</code> sets up the AnimatorSet to play
* <code>a1</code> first, followed by <code>a2</code>, and
* <code>play(a1).after(a2)</code> sets up the AnimatorSet to play
* <code>a2</code> first, followed by <code>a1</code>.
*
* <p>Note that <code>play()</code> is the only way to tell the
* <code>Builder</code> the animation upon which the dependency is created,
* so successive calls to the various functions in <code>Builder</code>
* will all refer to the initial parameter supplied in <code>play()</code>
* as the dependency of the other animations. For example, calling
* <code>play(a1).before(a2).before(a3)</code> will play both <code>a2</code>
* and <code>a3</code> when a1 ends; it does not set up a dependency between
* <code>a2</code> and <code>a3</code>.</p>
*
* @param anim The animation that is the dependency used in later calls to the
* methods in the returned <code>Builder</code> object. A null parameter will result
* in a null <code>Builder</code> return value.
* @return Builder The object that constructs the AnimatorSet based on the dependencies
* outlined in the calls to <code>play</code> and the other methods in the
* <code>Builder</code object.
*/
public Builder play(Animator anim) {
if (anim != null) {
mNeedsSort = true;
return new Builder(anim);
}
return null;
}
/**
* {@inheritDoc}
*
* <p>Note that canceling a <code>AnimatorSet</code> also cancels all of the animations that it
* is responsible for.</p>
*/
@SuppressWarnings("unchecked")
@Override
public void cancel() {
mTerminated = true;
if (isStarted()) {
ArrayList<AnimatorListener> tmpListeners = null;
if (mListeners != null) {
tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone();
for (AnimatorListener listener : tmpListeners) {
listener.onAnimationCancel(this);
}
}
if (mDelayAnim != null && mDelayAnim.isRunning()) {
// If we're currently in the startDelay period, just cancel that animator and
// send out the end event to all listeners
mDelayAnim.cancel();
} else if (mSortedNodes.size() > 0) {
for (Node node : mSortedNodes) {
node.animation.cancel();
}
}
if (tmpListeners != null) {
for (AnimatorListener listener : tmpListeners) {
listener.onAnimationEnd(this);
}
}
mStarted = false;
}
}
/**
* {@inheritDoc}
*
* <p>Note that ending a <code>AnimatorSet</code> also ends all of the animations that it is
* responsible for.</p>
*/
@Override
public void end() {
mTerminated = true;
if (isStarted()) {
if (mSortedNodes.size() != mNodes.size()) {
// hasn't been started yet - sort the nodes now, then end them
sortNodes();
for (Node node : mSortedNodes) {
if (mSetListener == null) {
mSetListener = new AnimatorSetListener(this);
}
node.animation.addListener(mSetListener);
}
}
if (mDelayAnim != null) {
mDelayAnim.cancel();
}
if (mSortedNodes.size() > 0) {
for (Node node : mSortedNodes) {
node.animation.end();
}
}
if (mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
for (AnimatorListener listener : tmpListeners) {
listener.onAnimationEnd(this);
}
}
mStarted = false;
}
}
/**
* Returns true if any of the child animations of this AnimatorSet have been started and have
* not yet ended.
* @return Whether this AnimatorSet has been started and has not yet ended.
*/
@Override
public boolean isRunning() {
for (Node node : mNodes) {
if (node.animation.isRunning()) {
return true;
}
}
return false;
}
@Override
public boolean isStarted() {
return mStarted;
}
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
*
* @return the number of milliseconds to delay running the animation
*/
@Override
public long getStartDelay() {
return mStartDelay;
}
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
* @param startDelay The amount of the delay, in milliseconds
*/
@Override
public void setStartDelay(long startDelay) {
mStartDelay = startDelay;
}
/**
* Gets the length of each of the child animations of this AnimatorSet. This value may
* be less than 0, which indicates that no duration has been set on this AnimatorSet
* and each of the child animations will use their own duration.
*
* @return The length of the animation, in milliseconds, of each of the child
* animations of this AnimatorSet.
*/
@Override
public long getDuration() {
return mDuration;
}
/**
* Sets the length of each of the current child animations of this AnimatorSet. By default,
* each child animation will use its own duration. If the duration is set on the AnimatorSet,
* then each child animation inherits this duration.
*
* @param duration The length of the animation, in milliseconds, of each of the child
* animations of this AnimatorSet.
*/
@Override
public AnimatorSet setDuration(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("duration must be a value of zero or greater");
}
for (Node node : mNodes) {
// TODO: don't set the duration of the timing-only nodes created by AnimatorSet to
// insert "play-after" delays
node.animation.setDuration(duration);
}
mDuration = duration;
return this;
}
@Override
public void setupStartValues() {
for (Node node : mNodes) {
node.animation.setupStartValues();
}
}
@Override
public void setupEndValues() {
for (Node node : mNodes) {
node.animation.setupEndValues();
}
}
/**
* {@inheritDoc}
*
* <p>Starting this <code>AnimatorSet</code> will, in turn, start the animations for which
* it is responsible. The details of when exactly those animations are started depends on
* the dependency relationships that have been set up between the animations.
*/
@SuppressWarnings("unchecked")
@Override
public void start() {
mTerminated = false;
mStarted = true;
// First, sort the nodes (if necessary). This will ensure that sortedNodes
// contains the animation nodes in the correct order.
sortNodes();
int numSortedNodes = mSortedNodes.size();
for (int i = 0; i < numSortedNodes; ++i) {
Node node = mSortedNodes.get(i);
// First, clear out the old listeners
ArrayList<AnimatorListener> oldListeners = node.animation.getListeners();
if (oldListeners != null && oldListeners.size() > 0) {
final ArrayList<AnimatorListener> clonedListeners = new
ArrayList<AnimatorListener>(oldListeners);
for (AnimatorListener listener : clonedListeners) {
if (listener instanceof DependencyListener ||
listener instanceof AnimatorSetListener) {
node.animation.removeListener(listener);
}
}
}
}
// nodesToStart holds the list of nodes to be started immediately. We don't want to
// start the animations in the loop directly because we first need to set up
// dependencies on all of the nodes. For example, we don't want to start an animation
// when some other animation also wants to start when the first animation begins.
final ArrayList<Node> nodesToStart = new ArrayList<Node>();
for (int i = 0; i < numSortedNodes; ++i) {
Node node = mSortedNodes.get(i);
if (mSetListener == null) {
mSetListener = new AnimatorSetListener(this);
}
if (node.dependencies == null || node.dependencies.size() == 0) {
nodesToStart.add(node);
} else {
int numDependencies = node.dependencies.size();
for (int j = 0; j < numDependencies; ++j) {
Dependency dependency = node.dependencies.get(j);
dependency.node.animation.addListener(
new DependencyListener(this, node, dependency.rule));
}
node.tmpDependencies = (ArrayList<Dependency>) node.dependencies.clone();
}
node.animation.addListener(mSetListener);
}
// Now that all dependencies are set up, start the animations that should be started.
if (mStartDelay <= 0) {
for (Node node : nodesToStart) {
node.animation.start();
mPlayingSet.add(node.animation);
}
} else {
mDelayAnim = ValueAnimator.ofFloat(0f, 1f);
mDelayAnim.setDuration(mStartDelay);
mDelayAnim.addListener(new AnimatorListenerAdapter() {
boolean canceled = false;
public void onAnimationCancel(Animator anim) {
canceled = true;
}
public void onAnimationEnd(Animator anim) {
if (!canceled) {
int numNodes = nodesToStart.size();
for (int i = 0; i < numNodes; ++i) {
Node node = nodesToStart.get(i);
node.animation.start();
mPlayingSet.add(node.animation);
}
}
}
});
mDelayAnim.start();
}
if (mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationStart(this);
}
}
if (mNodes.size() == 0 && mStartDelay == 0) {
// Handle unusual case where empty AnimatorSet is started - should send out
// end event immediately since the event will not be sent out at all otherwise
mStarted = false;
if (mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationEnd(this);
}
}
}
}
@Override
public AnimatorSet clone() {
final AnimatorSet anim = (AnimatorSet) super.clone();
/*
* The basic clone() operation copies all items. This doesn't work very well for
* AnimatorSet, because it will copy references that need to be recreated and state
* that may not apply. What we need to do now is put the clone in an uninitialized
* state, with fresh, empty data structures. Then we will build up the nodes list
* manually, as we clone each Node (and its animation). The clone will then be sorted,
* and will populate any appropriate lists, when it is started.
*/
anim.mNeedsSort = true;
anim.mTerminated = false;
anim.mStarted = false;
anim.mPlayingSet = new ArrayList<Animator>();
anim.mNodeMap = new HashMap<Animator, Node>();
anim.mNodes = new ArrayList<Node>();
anim.mSortedNodes = new ArrayList<Node>();
// Walk through the old nodes list, cloning each node and adding it to the new nodemap.
// One problem is that the old node dependencies point to nodes in the old AnimatorSet.
// We need to track the old/new nodes in order to reconstruct the dependencies in the clone.
HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>(); // <old, new>
for (Node node : mNodes) {
Node nodeClone = node.clone();
nodeCloneMap.put(node, nodeClone);
anim.mNodes.add(nodeClone);
anim.mNodeMap.put(nodeClone.animation, nodeClone);
// Clear out the dependencies in the clone; we'll set these up manually later
nodeClone.dependencies = null;
nodeClone.tmpDependencies = null;
nodeClone.nodeDependents = null;
nodeClone.nodeDependencies = null;
// clear out any listeners that were set up by the AnimatorSet; these will
// be set up when the clone's nodes are sorted
ArrayList<AnimatorListener> cloneListeners = nodeClone.animation.getListeners();
if (cloneListeners != null) {
ArrayList<AnimatorListener> listenersToRemove = null;
for (AnimatorListener listener : cloneListeners) {
if (listener instanceof AnimatorSetListener) {
if (listenersToRemove == null) {
listenersToRemove = new ArrayList<AnimatorListener>();
}
listenersToRemove.add(listener);
}
}
if (listenersToRemove != null) {
for (AnimatorListener listener : listenersToRemove) {
cloneListeners.remove(listener);
}
}
}
}
// Now that we've cloned all of the nodes, we're ready to walk through their
// dependencies, mapping the old dependencies to the new nodes
for (Node node : mNodes) {
Node nodeClone = nodeCloneMap.get(node);
if (node.dependencies != null) {
for (Dependency dependency : node.dependencies) {
Node clonedDependencyNode = nodeCloneMap.get(dependency.node);
Dependency cloneDependency = new Dependency(clonedDependencyNode,
dependency.rule);
nodeClone.addDependency(cloneDependency);
}
}
}
return anim;
}
/**
* This class is the mechanism by which animations are started based on events in other
* animations. If an animation has multiple dependencies on other animations, then
* all dependencies must be satisfied before the animation is started.
*/
private static class DependencyListener implements AnimatorListener {
private AnimatorSet mAnimatorSet;
// The node upon which the dependency is based.
private Node mNode;
// The Dependency rule (WITH or AFTER) that the listener should wait for on
// the node
private int mRule;
public DependencyListener(AnimatorSet animatorSet, Node node, int rule) {
this.mAnimatorSet = animatorSet;
this.mNode = node;
this.mRule = rule;
}
/**
* Ignore cancel events for now. We may want to handle this eventually,
* to prevent follow-on animations from running when some dependency
* animation is canceled.
*/
public void onAnimationCancel(Animator animation) {
}
/**
* An end event is received - see if this is an event we are listening for
*/
public void onAnimationEnd(Animator animation) {
if (mRule == Dependency.AFTER) {
startIfReady(animation);
}
}
/**
* Ignore repeat events for now
*/
public void onAnimationRepeat(Animator animation) {
}
/**
* A start event is received - see if this is an event we are listening for
*/
public void onAnimationStart(Animator animation) {
if (mRule == Dependency.WITH) {
startIfReady(animation);
}
}
/**
* Check whether the event received is one that the node was waiting for.
* If so, mark it as complete and see whether it's time to start
* the animation.
* @param dependencyAnimation the animation that sent the event.
*/
private void startIfReady(Animator dependencyAnimation) {
if (mAnimatorSet.mTerminated) {
// if the parent AnimatorSet was canceled, then don't start any dependent anims
return;
}
Dependency dependencyToRemove = null;
int numDependencies = mNode.tmpDependencies.size();
for (int i = 0; i < numDependencies; ++i) {
Dependency dependency = mNode.tmpDependencies.get(i);
if (dependency.rule == mRule &&
dependency.node.animation == dependencyAnimation) {
// rule fired - remove the dependency and listener and check to
// see whether it's time to start the animation
dependencyToRemove = dependency;
dependencyAnimation.removeListener(this);
break;
}
}
mNode.tmpDependencies.remove(dependencyToRemove);
if (mNode.tmpDependencies.size() == 0) {
// all dependencies satisfied: start the animation
mNode.animation.start();
mAnimatorSet.mPlayingSet.add(mNode.animation);
}
}
}
private class AnimatorSetListener implements AnimatorListener {
private AnimatorSet mAnimatorSet;
AnimatorSetListener(AnimatorSet animatorSet) {
mAnimatorSet = animatorSet;
}
public void onAnimationCancel(Animator animation) {
if (!mTerminated) {
// Listeners are already notified of the AnimatorSet canceling in cancel().
// The logic below only kicks in when animations end normally
if (mPlayingSet.size() == 0) {
if (mListeners != null) {
int numListeners = mListeners.size();
for (int i = 0; i < numListeners; ++i) {
mListeners.get(i).onAnimationCancel(mAnimatorSet);
}
}
}
}
}
@SuppressWarnings("unchecked")
public void onAnimationEnd(Animator animation) {
animation.removeListener(this);
mPlayingSet.remove(animation);
Node animNode = mAnimatorSet.mNodeMap.get(animation);
animNode.done = true;
if (!mTerminated) {
// Listeners are already notified of the AnimatorSet ending in cancel() or
// end(); the logic below only kicks in when animations end normally
ArrayList<Node> sortedNodes = mAnimatorSet.mSortedNodes;
boolean allDone = true;
int numSortedNodes = sortedNodes.size();
for (int i = 0; i < numSortedNodes; ++i) {
if (!sortedNodes.get(i).done) {
allDone = false;
break;
}
}
if (allDone) {
// If this was the last child animation to end, then notify listeners that this
// AnimatorSet has ended
if (mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationEnd(mAnimatorSet);
}
}
mAnimatorSet.mStarted = false;
}
}
}
// Nothing to do
public void onAnimationRepeat(Animator animation) {
}
// Nothing to do
public void onAnimationStart(Animator animation) {
}
}
/**
* This method sorts the current set of nodes, if needed. The sort is a simple
* DependencyGraph sort, which goes like this:
* - All nodes without dependencies become 'roots'
* - while roots list is not null
* - for each root r
* - add r to sorted list
* - remove r as a dependency from any other node
* - any nodes with no dependencies are added to the roots list
*/
private void sortNodes() {
if (mNeedsSort) {
mSortedNodes.clear();
ArrayList<Node> roots = new ArrayList<Node>();
int numNodes = mNodes.size();
for (int i = 0; i < numNodes; ++i) {
Node node = mNodes.get(i);
if (node.dependencies == null || node.dependencies.size() == 0) {
roots.add(node);
}
}
ArrayList<Node> tmpRoots = new ArrayList<Node>();
while (roots.size() > 0) {
int numRoots = roots.size();
for (int i = 0; i < numRoots; ++i) {
Node root = roots.get(i);
mSortedNodes.add(root);
if (root.nodeDependents != null) {
int numDependents = root.nodeDependents.size();
for (int j = 0; j < numDependents; ++j) {
Node node = root.nodeDependents.get(j);
node.nodeDependencies.remove(root);
if (node.nodeDependencies.size() == 0) {
tmpRoots.add(node);
}
}
}
}
roots.clear();
roots.addAll(tmpRoots);
tmpRoots.clear();
}
mNeedsSort = false;
if (mSortedNodes.size() != mNodes.size()) {
throw new IllegalStateException("Circular dependencies cannot exist"
+ " in AnimatorSet");
}
} else {
// Doesn't need sorting, but still need to add in the nodeDependencies list
// because these get removed as the event listeners fire and the dependencies
// are satisfied
int numNodes = mNodes.size();
for (int i = 0; i < numNodes; ++i) {
Node node = mNodes.get(i);
if (node.dependencies != null && node.dependencies.size() > 0) {
int numDependencies = node.dependencies.size();
for (int j = 0; j < numDependencies; ++j) {
Dependency dependency = node.dependencies.get(j);
if (node.nodeDependencies == null) {
node.nodeDependencies = new ArrayList<Node>();
}
if (!node.nodeDependencies.contains(dependency.node)) {
node.nodeDependencies.add(dependency.node);
}
}
}
// nodes are 'done' by default; they become un-done when started, and done
// again when ended
node.done = false;
}
}
}
/**
* Dependency holds information about the node that some other node is
* dependent upon and the nature of that dependency.
*
*/
private static class Dependency {
static final int WITH = 0; // dependent node must start with this dependency node
static final int AFTER = 1; // dependent node must start when this dependency node finishes
// The node that the other node with this Dependency is dependent upon
public Node node;
// The nature of the dependency (WITH or AFTER)
public int rule;
public Dependency(Node node, int rule) {
this.node = node;
this.rule = rule;
}
}
/**
* A Node is an embodiment of both the Animator that it wraps as well as
* any dependencies that are associated with that Animation. This includes
* both dependencies upon other nodes (in the dependencies list) as
* well as dependencies of other nodes upon this (in the nodeDependents list).
*/
private static class Node implements Cloneable {
public Animator animation;
/**
* These are the dependencies that this node's animation has on other
* nodes. For example, if this node's animation should begin with some
* other animation ends, then there will be an item in this node's
* dependencies list for that other animation's node.
*/
public ArrayList<Dependency> dependencies = null;
/**
* tmpDependencies is a runtime detail. We use the dependencies list for sorting.
* But we also use the list to keep track of when multiple dependencies are satisfied,
* but removing each dependency as it is satisfied. We do not want to remove
* the dependency itself from the list, because we need to retain that information
* if the AnimatorSet is launched in the future. So we create a copy of the dependency
* list when the AnimatorSet starts and use this tmpDependencies list to track the
* list of satisfied dependencies.
*/
public ArrayList<Dependency> tmpDependencies = null;
/**
* nodeDependencies is just a list of the nodes that this Node is dependent upon.
* This information is used in sortNodes(), to determine when a node is a root.
*/
public ArrayList<Node> nodeDependencies = null;
/**
* nodeDepdendents is the list of nodes that have this node as a dependency. This
* is a utility field used in sortNodes to facilitate removing this node as a
* dependency when it is a root node.
*/
public ArrayList<Node> nodeDependents = null;
/**
* Flag indicating whether the animation in this node is finished. This flag
* is used by AnimatorSet to check, as each animation ends, whether all child animations
* are done and it's time to send out an end event for the entire AnimatorSet.
*/
public boolean done = false;
/**
* Constructs the Node with the animation that it encapsulates. A Node has no
* dependencies by default; dependencies are added via the addDependency()
* method.
*
* @param animation The animation that the Node encapsulates.
*/
public Node(Animator animation) {
this.animation = animation;
}
/**
* Add a dependency to this Node. The dependency includes information about the
* node that this node is dependency upon and the nature of the dependency.
* @param dependency
*/
public void addDependency(Dependency dependency) {
if (dependencies == null) {
dependencies = new ArrayList<Dependency>();
nodeDependencies = new ArrayList<Node>();
}
dependencies.add(dependency);
if (!nodeDependencies.contains(dependency.node)) {
nodeDependencies.add(dependency.node);
}
Node dependencyNode = dependency.node;
if (dependencyNode.nodeDependents == null) {
dependencyNode.nodeDependents = new ArrayList<Node>();
}
dependencyNode.nodeDependents.add(this);
}
@Override
public Node clone() {
try {
Node node = (Node) super.clone();
node.animation = (Animator) animation.clone();
return node;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
/**
* The <code>Builder</code> object is a utility class to facilitate adding animations to a
* <code>AnimatorSet</code> along with the relationships between the various animations. The
* intention of the <code>Builder</code> methods, along with the {@link
* AnimatorSet#play(Animator) play()} method of <code>AnimatorSet</code> is to make it possible
* to express the dependency relationships of animations in a natural way. Developers can also
* use the {@link AnimatorSet#playTogether(Animator[]) playTogether()} and {@link
* AnimatorSet#playSequentially(Animator[]) playSequentially()} methods if these suit the need,
* but it might be easier in some situations to express the AnimatorSet of animations in pairs.
* <p/>
* <p>The <code>Builder</code> object cannot be constructed directly, but is rather constructed
* internally via a call to {@link AnimatorSet#play(Animator)}.</p>
* <p/>
* <p>For example, this sets up a AnimatorSet to play anim1 and anim2 at the same time, anim3 to
* play when anim2 finishes, and anim4 to play when anim3 finishes:</p>
* <pre>
* AnimatorSet s = new AnimatorSet();
* s.play(anim1).with(anim2);
* s.play(anim2).before(anim3);
* s.play(anim4).after(anim3);
* </pre>
* <p/>
* <p>Note in the example that both {@link Builder#before(Animator)} and {@link
* Builder#after(Animator)} are used. These are just different ways of expressing the same
* relationship and are provided to make it easier to say things in a way that is more natural,
* depending on the situation.</p>
* <p/>
* <p>It is possible to make several calls into the same <code>Builder</code> object to express
* multiple relationships. However, note that it is only the animation passed into the initial
* {@link AnimatorSet#play(Animator)} method that is the dependency in any of the successive
* calls to the <code>Builder</code> object. For example, the following code starts both anim2
* and anim3 when anim1 ends; there is no direct dependency relationship between anim2 and
* anim3:
* <pre>
* AnimatorSet s = new AnimatorSet();
* s.play(anim1).before(anim2).before(anim3);
* </pre>
* If the desired result is to play anim1 then anim2 then anim3, this code expresses the
* relationship correctly:</p>
* <pre>
* AnimatorSet s = new AnimatorSet();
* s.play(anim1).before(anim2);
* s.play(anim2).before(anim3);
* </pre>
* <p/>
* <p>Note that it is possible to express relationships that cannot be resolved and will not
* result in sensible results. For example, <code>play(anim1).after(anim1)</code> makes no
* sense. In general, circular dependencies like this one (or more indirect ones where a depends
* on b, which depends on c, which depends on a) should be avoided. Only create AnimatorSets
* that can boil down to a simple, one-way relationship of animations starting with, before, and
* after other, different, animations.</p>
*/
public class Builder {
/**
* This tracks the current node being processed. It is supplied to the play() method
* of AnimatorSet and passed into the constructor of Builder.
*/
private Node mCurrentNode;
/**
* package-private constructor. Builders are only constructed by AnimatorSet, when the
* play() method is called.
*
* @param anim The animation that is the dependency for the other animations passed into
* the other methods of this Builder object.
*/
Builder(Animator anim) {
mCurrentNode = mNodeMap.get(anim);
if (mCurrentNode == null) {
mCurrentNode = new Node(anim);
mNodeMap.put(anim, mCurrentNode);
mNodes.add(mCurrentNode);
}
}
/**
* Sets up the given animation to play at the same time as the animation supplied in the
* {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object.
*
* @param anim The animation that will play when the animation supplied to the
* {@link AnimatorSet#play(Animator)} method starts.
*/
public Builder with(Animator anim) {
Node node = mNodeMap.get(anim);
if (node == null) {
node = new Node(anim);
mNodeMap.put(anim, node);
mNodes.add(node);
}
Dependency dependency = new Dependency(mCurrentNode, Dependency.WITH);
node.addDependency(dependency);
return this;
}
/**
* Sets up the given animation to play when the animation supplied in the
* {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
* ends.
*
* @param anim The animation that will play when the animation supplied to the
* {@link AnimatorSet#play(Animator)} method ends.
*/
public Builder before(Animator anim) {
Node node = mNodeMap.get(anim);
if (node == null) {
node = new Node(anim);
mNodeMap.put(anim, node);
mNodes.add(node);
}
Dependency dependency = new Dependency(mCurrentNode, Dependency.AFTER);
node.addDependency(dependency);
return this;
}
/**
* Sets up the given animation to play when the animation supplied in the
* {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
* to start when the animation supplied in this method call ends.
*
* @param anim The animation whose end will cause the animation supplied to the
* {@link AnimatorSet#play(Animator)} method to play.
*/
public Builder after(Animator anim) {
Node node = mNodeMap.get(anim);
if (node == null) {
node = new Node(anim);
mNodeMap.put(anim, node);
mNodes.add(node);
}
Dependency dependency = new Dependency(node, Dependency.AFTER);
mCurrentNode.addDependency(dependency);
return this;
}
/**
* Sets up the animation supplied in the
* {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
* to play when the given amount of time elapses.
*
* @param delay The number of milliseconds that should elapse before the
* animation starts.
*/
public Builder after(long delay) {
// setup dummy ValueAnimator just to run the clock
ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(delay);
after(anim);
return this;
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
/**
* This adapter class provides empty implementations of the methods from {@link android.animation.Animator.AnimatorListener}.
* Any custom listener that cares only about a subset of the methods of this listener can
* simply subclass this adapter class instead of implementing the interface directly.
*/
public abstract class AnimatorListenerAdapter implements Animator.AnimatorListener {
/**
* {@inheritDoc}
*/
@Override
public void onAnimationCancel(Animator animation) {
}
/**
* {@inheritDoc}
*/
@Override
public void onAnimationEnd(Animator animation) {
}
/**
* {@inheritDoc}
*/
@Override
public void onAnimationRepeat(Animator animation) {
}
/**
* {@inheritDoc}
*/
@Override
public void onAnimationStart(Animator animation) {
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AndroidRuntimeException;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class provides a simple timing engine for running animations
* which calculate animated values and set them on target objects.
*
* <p>There is a single timing pulse that all animations use. It runs in a
* custom handler to ensure that property changes happen on the UI thread.</p>
*
* <p>By default, ValueAnimator uses non-linear time interpolation, via the
* {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
* out of an animation. This behavior can be changed by calling
* {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
*/
public class ValueAnimator extends Animator {
/**
* Internal constants
*/
/*
* The default amount of time in ms between animation frames
*/
private static final long DEFAULT_FRAME_DELAY = 10;
/**
* Messages sent to timing handler: START is sent when an animation first begins, FRAME is sent
* by the handler to itself to process the next animation frame
*/
static final int ANIMATION_START = 0;
static final int ANIMATION_FRAME = 1;
/**
* Values used with internal variable mPlayingState to indicate the current state of an
* animation.
*/
static final int STOPPED = 0; // Not yet playing
static final int RUNNING = 1; // Playing normally
static final int SEEKED = 2; // Seeked to some time value
/**
* Internal variables
* NOTE: This object implements the clone() method, making a deep copy of any referenced
* objects. As other non-trivial fields are added to this class, make sure to add logic
* to clone() to make deep copies of them.
*/
// The first time that the animation's animateFrame() method is called. This time is used to
// determine elapsed time (and therefore the elapsed fraction) in subsequent calls
// to animateFrame()
long mStartTime;
/**
* Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
* to a value.
*/
long mSeekTime = -1;
// TODO: We access the following ThreadLocal variables often, some of them on every update.
// If ThreadLocal access is significantly expensive, we may want to put all of these
// fields into a structure sot hat we just access ThreadLocal once to get the reference
// to that structure, then access the structure directly for each field.
// The static sAnimationHandler processes the internal timing loop on which all animations
// are based
private static ThreadLocal<AnimationHandler> sAnimationHandler =
new ThreadLocal<AnimationHandler>();
// The per-thread list of all active animations
private static final ThreadLocal<ArrayList<ValueAnimator>> sAnimations =
new ThreadLocal<ArrayList<ValueAnimator>>() {
@Override
protected ArrayList<ValueAnimator> initialValue() {
return new ArrayList<ValueAnimator>();
}
};
// The per-thread set of animations to be started on the next animation frame
private static final ThreadLocal<ArrayList<ValueAnimator>> sPendingAnimations =
new ThreadLocal<ArrayList<ValueAnimator>>() {
@Override
protected ArrayList<ValueAnimator> initialValue() {
return new ArrayList<ValueAnimator>();
}
};
/**
* Internal per-thread collections used to avoid set collisions as animations start and end
* while being processed.
*/
private static final ThreadLocal<ArrayList<ValueAnimator>> sDelayedAnims =
new ThreadLocal<ArrayList<ValueAnimator>>() {
@Override
protected ArrayList<ValueAnimator> initialValue() {
return new ArrayList<ValueAnimator>();
}
};
private static final ThreadLocal<ArrayList<ValueAnimator>> sEndingAnims =
new ThreadLocal<ArrayList<ValueAnimator>>() {
@Override
protected ArrayList<ValueAnimator> initialValue() {
return new ArrayList<ValueAnimator>();
}
};
private static final ThreadLocal<ArrayList<ValueAnimator>> sReadyAnims =
new ThreadLocal<ArrayList<ValueAnimator>>() {
@Override
protected ArrayList<ValueAnimator> initialValue() {
return new ArrayList<ValueAnimator>();
}
};
// The time interpolator to be used if none is set on the animation
private static final /*Time*/Interpolator sDefaultInterpolator =
new AccelerateDecelerateInterpolator();
// type evaluators for the primitive types handled by this implementation
private static final TypeEvaluator sIntEvaluator = new IntEvaluator();
private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator();
/**
* Used to indicate whether the animation is currently playing in reverse. This causes the
* elapsed fraction to be inverted to calculate the appropriate values.
*/
private boolean mPlayingBackwards = false;
/**
* This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the
* repeatCount (if repeatCount!=INFINITE), the animation ends
*/
private int mCurrentIteration = 0;
/**
* Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
*/
private float mCurrentFraction = 0f;
/**
* Tracks whether a startDelay'd animation has begun playing through the startDelay.
*/
private boolean mStartedDelay = false;
/**
* Tracks the time at which the animation began playing through its startDelay. This is
* different from the mStartTime variable, which is used to track when the animation became
* active (which is when the startDelay expired and the animation was added to the active
* animations list).
*/
private long mDelayStartTime;
/**
* Flag that represents the current state of the animation. Used to figure out when to start
* an animation (if state == STOPPED). Also used to end an animation that
* has been cancel()'d or end()'d since the last animation frame. Possible values are
* STOPPED, RUNNING, SEEKED.
*/
int mPlayingState = STOPPED;
/**
* Additional playing state to indicate whether an animator has been start()'d. There is
* some lag between a call to start() and the first animation frame. We should still note
* that the animation has been started, even if it's first animation frame has not yet
* happened, and reflect that state in isRunning().
* Note that delayed animations are different: they are not started until their first
* animation frame, which occurs after their delay elapses.
*/
private boolean mRunning = false;
/**
* Additional playing state to indicate whether an animator has been start()'d, whether or
* not there is a nonzero startDelay.
*/
private boolean mStarted = false;
/**
* Flag that denotes whether the animation is set up and ready to go. Used to
* set up animation that has not yet been started.
*/
boolean mInitialized = false;
//
// Backing variables
//
// How long the animation should last in ms
private long mDuration = 300;
// The amount of time in ms to delay starting the animation after start() is called
private long mStartDelay = 0;
// The number of milliseconds between animation frames
private static long sFrameDelay = DEFAULT_FRAME_DELAY;
// The number of times the animation will repeat. The default is 0, which means the animation
// will play only once
private int mRepeatCount = 0;
/**
* The type of repetition that will occur when repeatMode is nonzero. RESTART means the
* animation will start from the beginning on every new cycle. REVERSE means the animation
* will reverse directions on each iteration.
*/
private int mRepeatMode = RESTART;
/**
* The time interpolator to be used. The elapsed fraction of the animation will be passed
* through this interpolator to calculate the interpolated fraction, which is then used to
* calculate the animated values.
*/
private /*Time*/Interpolator mInterpolator = sDefaultInterpolator;
/**
* The set of listeners to be sent events through the life of an animation.
*/
private ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
/**
* The property/value sets being animated.
*/
PropertyValuesHolder[] mValues;
/**
* A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
* by property name during calls to getAnimatedValue(String).
*/
HashMap<String, PropertyValuesHolder> mValuesMap;
/**
* Public constants
*/
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation restarts from the beginning.
*/
public static final int RESTART = 1;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation reverses direction on every iteration.
*/
public static final int REVERSE = 2;
/**
* This value used used with the {@link #setRepeatCount(int)} property to repeat
* the animation indefinitely.
*/
public static final int INFINITE = -1;
/**
* Creates a new ValueAnimator object. This default constructor is primarily for
* use internally; the factory methods which take parameters are more generally
* useful.
*/
public ValueAnimator() {
}
/**
* Constructs and returns a ValueAnimator that animates between int values. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* @param values A set of values that the animation will animate between over time.
* @return A ValueAnimator object that is set up to animate between the given values.
*/
public static ValueAnimator ofInt(int... values) {
ValueAnimator anim = new ValueAnimator();
anim.setIntValues(values);
return anim;
}
/**
* Constructs and returns a ValueAnimator that animates between float values. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* @param values A set of values that the animation will animate between over time.
* @return A ValueAnimator object that is set up to animate between the given values.
*/
public static ValueAnimator ofFloat(float... values) {
ValueAnimator anim = new ValueAnimator();
anim.setFloatValues(values);
return anim;
}
/**
* Constructs and returns a ValueAnimator that animates between the values
* specified in the PropertyValuesHolder objects.
*
* @param values A set of PropertyValuesHolder objects whose values will be animated
* between over time.
* @return A ValueAnimator object that is set up to animate between the given values.
*/
public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
ValueAnimator anim = new ValueAnimator();
anim.setValues(values);
return anim;
}
/**
* Constructs and returns a ValueAnimator that animates between Object values. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
* factory method also takes a TypeEvaluator object that the ValueAnimator will use
* to perform that interpolation.
*
* @param evaluator A TypeEvaluator that will be called on each animation frame to
* provide the ncessry interpolation between the Object values to derive the animated
* value.
* @param values A set of values that the animation will animate between over time.
* @return A ValueAnimator object that is set up to animate between the given values.
*/
public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
ValueAnimator anim = new ValueAnimator();
anim.setObjectValues(values);
anim.setEvaluator(evaluator);
return anim;
}
/**
* Sets int values that will be animated between. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* <p>If there are already multiple sets of values defined for this ValueAnimator via more
* than one PropertyValuesHolder object, this method will set the values for the first
* of those objects.</p>
*
* @param values A set of values that the animation will animate between over time.
*/
public void setIntValues(int... values) {
if (values == null || values.length == 0) {
return;
}
if (mValues == null || mValues.length == 0) {
setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)});
} else {
PropertyValuesHolder valuesHolder = mValues[0];
valuesHolder.setIntValues(values);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Sets float values that will be animated between. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* <p>If there are already multiple sets of values defined for this ValueAnimator via more
* than one PropertyValuesHolder object, this method will set the values for the first
* of those objects.</p>
*
* @param values A set of values that the animation will animate between over time.
*/
public void setFloatValues(float... values) {
if (values == null || values.length == 0) {
return;
}
if (mValues == null || mValues.length == 0) {
setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)});
} else {
PropertyValuesHolder valuesHolder = mValues[0];
valuesHolder.setFloatValues(values);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Sets the values to animate between for this animation. A single
* value implies that that value is the one being animated to. However, this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation (unlike ObjectAnimator, which can derive that value
* from the target object and property being animated). Therefore, there should typically
* be two or more values.
*
* <p>If there are already multiple sets of values defined for this ValueAnimator via more
* than one PropertyValuesHolder object, this method will set the values for the first
* of those objects.</p>
*
* <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
* between these value objects. ValueAnimator only knows how to interpolate between the
* primitive types specified in the other setValues() methods.</p>
*
* @param values The set of values to animate between.
*/
public void setObjectValues(Object... values) {
if (values == null || values.length == 0) {
return;
}
if (mValues == null || mValues.length == 0) {
setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("",
(TypeEvaluator)null, values)});
} else {
PropertyValuesHolder valuesHolder = mValues[0];
valuesHolder.setObjectValues(values);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Sets the values, per property, being animated between. This function is called internally
* by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can
* be constructed without values and this method can be called to set the values manually
* instead.
*
* @param values The set of values, per property, being animated between.
*/
public void setValues(PropertyValuesHolder... values) {
int numValues = values.length;
mValues = values;
mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
for (int i = 0; i < numValues; ++i) {
PropertyValuesHolder valuesHolder = (PropertyValuesHolder) values[i];
mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
/**
* Returns the values that this ValueAnimator animates between. These values are stored in
* PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
* of value objects instead.
*
* @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
* values, per property, that define the animation.
*/
public PropertyValuesHolder[] getValues() {
return mValues;
}
/**
* This function is called immediately before processing the first animation
* frame of an animation. If there is a nonzero <code>startDelay</code>, the
* function is called after that delay ends.
* It takes care of the final initialization steps for the
* animation.
*
* <p>Overrides of this method should call the superclass method to ensure
* that internal mechanisms for the animation are set up correctly.</p>
*/
void initAnimation() {
if (!mInitialized) {
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].init();
}
mInitialized = true;
}
}
/**
* Sets the length of the animation. The default duration is 300 milliseconds.
*
* @param duration The length of the animation, in milliseconds. This value cannot
* be negative.
* @return ValueAnimator The object called with setDuration(). This return
* value makes it easier to compose statements together that construct and then set the
* duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
*/
public ValueAnimator setDuration(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
duration);
}
mDuration = duration;
return this;
}
/**
* Gets the length of the animation. The default duration is 300 milliseconds.
*
* @return The length of the animation, in milliseconds.
*/
public long getDuration() {
return mDuration;
}
/**
* Sets the position of the animation to the specified point in time. This time should
* be between 0 and the total duration of the animation, including any repetition. If
* the animation has not yet been started, then it will not advance forward after it is
* set to this time; it will simply set the time to this value and perform any appropriate
* actions based on that time. If the animation is already running, then setCurrentPlayTime()
* will set the current playing time to this value and continue playing from that point.
*
* @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
*/
public void setCurrentPlayTime(long playTime) {
initAnimation();
long currentTime = AnimationUtils.currentAnimationTimeMillis();
if (mPlayingState != RUNNING) {
mSeekTime = playTime;
mPlayingState = SEEKED;
}
mStartTime = currentTime - playTime;
animationFrame(currentTime);
}
/**
* Gets the current position of the animation in time, which is equal to the current
* time minus the time that the animation started. An animation that is not yet started will
* return a value of zero.
*
* @return The current position in time of the animation.
*/
public long getCurrentPlayTime() {
if (!mInitialized || mPlayingState == STOPPED) {
return 0;
}
return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
}
/**
* This custom, static handler handles the timing pulse that is shared by
* all active animations. This approach ensures that the setting of animation
* values will happen on the UI thread and that all animations will share
* the same times for calculating their values, which makes synchronizing
* animations possible.
*
*/
private static class AnimationHandler extends Handler {
/**
* There are only two messages that we care about: ANIMATION_START and
* ANIMATION_FRAME. The START message is sent when an animation's start()
* method is called. It cannot start synchronously when start() is called
* because the call may be on the wrong thread, and it would also not be
* synchronized with other animations because it would not start on a common
* timing pulse. So each animation sends a START message to the handler, which
* causes the handler to place the animation on the active animations queue and
* start processing frames for that animation.
* The FRAME message is the one that is sent over and over while there are any
* active animations to process.
*/
@Override
public void handleMessage(Message msg) {
boolean callAgain = true;
ArrayList<ValueAnimator> animations = sAnimations.get();
ArrayList<ValueAnimator> delayedAnims = sDelayedAnims.get();
switch (msg.what) {
// TODO: should we avoid sending frame message when starting if we
// were already running?
case ANIMATION_START:
ArrayList<ValueAnimator> pendingAnimations = sPendingAnimations.get();
if (animations.size() > 0 || delayedAnims.size() > 0) {
callAgain = false;
}
// pendingAnims holds any animations that have requested to be started
// We're going to clear sPendingAnimations, but starting animation may
// cause more to be added to the pending list (for example, if one animation
// starting triggers another starting). So we loop until sPendingAnimations
// is empty.
while (pendingAnimations.size() > 0) {
ArrayList<ValueAnimator> pendingCopy =
(ArrayList<ValueAnimator>) pendingAnimations.clone();
pendingAnimations.clear();
int count = pendingCopy.size();
for (int i = 0; i < count; ++i) {
ValueAnimator anim = pendingCopy.get(i);
// If the animation has a startDelay, place it on the delayed list
if (anim.mStartDelay == 0) {
anim.startAnimation();
} else {
delayedAnims.add(anim);
}
}
}
// fall through to process first frame of new animations
case ANIMATION_FRAME:
// currentTime holds the common time for all animations processed
// during this frame
long currentTime = AnimationUtils.currentAnimationTimeMillis();
ArrayList<ValueAnimator> readyAnims = sReadyAnims.get();
ArrayList<ValueAnimator> endingAnims = sEndingAnims.get();
// First, process animations currently sitting on the delayed queue, adding
// them to the active animations if they are ready
int numDelayedAnims = delayedAnims.size();
for (int i = 0; i < numDelayedAnims; ++i) {
ValueAnimator anim = delayedAnims.get(i);
if (anim.delayedAnimationFrame(currentTime)) {
readyAnims.add(anim);
}
}
int numReadyAnims = readyAnims.size();
if (numReadyAnims > 0) {
for (int i = 0; i < numReadyAnims; ++i) {
ValueAnimator anim = readyAnims.get(i);
anim.startAnimation();
anim.mRunning = true;
delayedAnims.remove(anim);
}
readyAnims.clear();
}
// Now process all active animations. The return value from animationFrame()
// tells the handler whether it should now be ended
int numAnims = animations.size();
int i = 0;
while (i < numAnims) {
ValueAnimator anim = animations.get(i);
if (anim.animationFrame(currentTime)) {
endingAnims.add(anim);
}
if (animations.size() == numAnims) {
++i;
} else {
// An animation might be canceled or ended by client code
// during the animation frame. Check to see if this happened by
// seeing whether the current index is the same as it was before
// calling animationFrame(). Another approach would be to copy
// animations to a temporary list and process that list instead,
// but that entails garbage and processing overhead that would
// be nice to avoid.
--numAnims;
endingAnims.remove(anim);
}
}
if (endingAnims.size() > 0) {
for (i = 0; i < endingAnims.size(); ++i) {
endingAnims.get(i).endAnimation();
}
endingAnims.clear();
}
// If there are still active or delayed animations, call the handler again
// after the frameDelay
if (callAgain && (!animations.isEmpty() || !delayedAnims.isEmpty())) {
sendEmptyMessageDelayed(ANIMATION_FRAME, Math.max(0, sFrameDelay -
(AnimationUtils.currentAnimationTimeMillis() - currentTime)));
}
break;
}
}
}
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
*
* @return the number of milliseconds to delay running the animation
*/
public long getStartDelay() {
return mStartDelay;
}
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
* @param startDelay The amount of the delay, in milliseconds
*/
public void setStartDelay(long startDelay) {
this.mStartDelay = startDelay;
}
/**
* The amount of time, in milliseconds, between each frame of the animation. This is a
* requested time that the animation will attempt to honor, but the actual delay between
* frames may be different, depending on system load and capabilities. This is a static
* function because the same delay will be applied to all animations, since they are all
* run off of a single timing loop.
*
* @return the requested time between frames, in milliseconds
*/
public static long getFrameDelay() {
return sFrameDelay;
}
/**
* The amount of time, in milliseconds, between each frame of the animation. This is a
* requested time that the animation will attempt to honor, but the actual delay between
* frames may be different, depending on system load and capabilities. This is a static
* function because the same delay will be applied to all animations, since they are all
* run off of a single timing loop.
*
* @param frameDelay the requested time between frames, in milliseconds
*/
public static void setFrameDelay(long frameDelay) {
sFrameDelay = frameDelay;
}
/**
* The most recent value calculated by this <code>ValueAnimator</code> when there is just one
* property being animated. This value is only sensible while the animation is running. The main
* purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
* during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
* is called during each animation frame, immediately after the value is calculated.
*
* @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
* the single property being animated. If there are several properties being animated
* (specified by several PropertyValuesHolder objects in the constructor), this function
* returns the animated value for the first of those objects.
*/
public Object getAnimatedValue() {
if (mValues != null && mValues.length > 0) {
return mValues[0].getAnimatedValue();
}
// Shouldn't get here; should always have values unless ValueAnimator was set up wrong
return null;
}
/**
* The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
* The main purpose for this read-only property is to retrieve the value from the
* <code>ValueAnimator</code> during a call to
* {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
* is called during each animation frame, immediately after the value is calculated.
*
* @return animatedValue The value most recently calculated for the named property
* by this <code>ValueAnimator</code>.
*/
public Object getAnimatedValue(String propertyName) {
PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
if (valuesHolder != null) {
return valuesHolder.getAnimatedValue();
} else {
// At least avoid crashing if called with bogus propertyName
return null;
}
}
/**
* Sets how many times the animation should be repeated. If the repeat
* count is 0, the animation is never repeated. If the repeat count is
* greater than 0 or {@link #INFINITE}, the repeat mode will be taken
* into account. The repeat count is 0 by default.
*
* @param value the number of times the animation should be repeated
*/
public void setRepeatCount(int value) {
mRepeatCount = value;
}
/**
* Defines how many times the animation should repeat. The default value
* is 0.
*
* @return the number of times the animation should repeat, or {@link #INFINITE}
*/
public int getRepeatCount() {
return mRepeatCount;
}
/**
* Defines what this animation should do when it reaches the end. This
* setting is applied only when the repeat count is either greater than
* 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
*
* @param value {@link #RESTART} or {@link #REVERSE}
*/
public void setRepeatMode(int value) {
mRepeatMode = value;
}
/**
* Defines what this animation should do when it reaches the end.
*
* @return either one of {@link #REVERSE} or {@link #RESTART}
*/
public int getRepeatMode() {
return mRepeatMode;
}
/**
* Adds a listener to the set of listeners that are sent update events through the life of
* an animation. This method is called on all listeners for every frame of the animation,
* after the values for the animation have been calculated.
*
* @param listener the listener to be added to the current set of listeners for this animation.
*/
public void addUpdateListener(AnimatorUpdateListener listener) {
if (mUpdateListeners == null) {
mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
}
mUpdateListeners.add(listener);
}
/**
* Removes all listeners from the set listening to frame updates for this animation.
*/
public void removeAllUpdateListeners() {
if (mUpdateListeners == null) {
return;
}
mUpdateListeners.clear();
mUpdateListeners = null;
}
/**
* Removes a listener from the set listening to frame updates for this animation.
*
* @param listener the listener to be removed from the current set of update listeners
* for this animation.
*/
public void removeUpdateListener(AnimatorUpdateListener listener) {
if (mUpdateListeners == null) {
return;
}
mUpdateListeners.remove(listener);
if (mUpdateListeners.size() == 0) {
mUpdateListeners = null;
}
}
/**
* The time interpolator used in calculating the elapsed fraction of this animation. The
* interpolator determines whether the animation runs with linear or non-linear motion,
* such as acceleration and deceleration. The default value is
* {@link android.view.animation.AccelerateDecelerateInterpolator}
*
* @param value the interpolator to be used by this animation. A value of <code>null</code>
* will result in linear interpolation.
*/
@Override
public void setInterpolator(/*Time*/Interpolator value) {
if (value != null) {
mInterpolator = value;
} else {
mInterpolator = new LinearInterpolator();
}
}
/**
* Returns the timing interpolator that this ValueAnimator uses.
*
* @return The timing interpolator for this ValueAnimator.
*/
public /*Time*/Interpolator getInterpolator() {
return mInterpolator;
}
/**
* The type evaluator to be used when calculating the animated values of this animation.
* The system will automatically assign a float or int evaluator based on the type
* of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
* are not one of these primitive types, or if different evaluation is desired (such as is
* necessary with int values that represent colors), a custom evaluator needs to be assigned.
* For example, when running an animation on color values, the {@link ArgbEvaluator}
* should be used to get correct RGB color interpolation.
*
* <p>If this ValueAnimator has only one set of values being animated between, this evaluator
* will be used for that set. If there are several sets of values being animated, which is
* the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
* is assigned just to the first PropertyValuesHolder object.</p>
*
* @param value the evaluator to be used this animation
*/
public void setEvaluator(TypeEvaluator value) {
if (value != null && mValues != null && mValues.length > 0) {
mValues[0].setEvaluator(value);
}
}
/**
* Start the animation playing. This version of start() takes a boolean flag that indicates
* whether the animation should play in reverse. The flag is usually false, but may be set
* to true if called from the reverse() method.
*
* <p>The animation started by calling this method will be run on the thread that called
* this method. This thread should have a Looper on it (a runtime exception will be thrown if
* this is not the case). Also, if the animation will animate
* properties of objects in the view hierarchy, then the calling thread should be the UI
* thread for that view hierarchy.</p>
*
* @param playBackwards Whether the ValueAnimator should start playing in reverse.
*/
private void start(boolean playBackwards) {
if (Looper.myLooper() == null) {
throw new AndroidRuntimeException("Animators may only be run on Looper threads");
}
mPlayingBackwards = playBackwards;
mCurrentIteration = 0;
mPlayingState = STOPPED;
mStarted = true;
mStartedDelay = false;
sPendingAnimations.get().add(this);
if (mStartDelay == 0) {
// This sets the initial value of the animation, prior to actually starting it running
setCurrentPlayTime(getCurrentPlayTime());
mPlayingState = STOPPED;
mRunning = true;
if (mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationStart(this);
}
}
}
AnimationHandler animationHandler = sAnimationHandler.get();
if (animationHandler == null) {
animationHandler = new AnimationHandler();
sAnimationHandler.set(animationHandler);
}
animationHandler.sendEmptyMessage(ANIMATION_START);
}
@Override
public void start() {
start(false);
}
@Override
public void cancel() {
// Only cancel if the animation is actually running or has been started and is about
// to run
if (mPlayingState != STOPPED || sPendingAnimations.get().contains(this) ||
sDelayedAnims.get().contains(this)) {
// Only notify listeners if the animator has actually started
if (mRunning && mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
for (AnimatorListener listener : tmpListeners) {
listener.onAnimationCancel(this);
}
}
endAnimation();
}
}
@Override
public void end() {
if (!sAnimations.get().contains(this) && !sPendingAnimations.get().contains(this)) {
// Special case if the animation has not yet started; get it ready for ending
mStartedDelay = false;
startAnimation();
} else if (!mInitialized) {
initAnimation();
}
// The final value set on the target varies, depending on whether the animation
// was supposed to repeat an odd number of times
if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) {
animateValue(0f);
} else {
animateValue(1f);
}
endAnimation();
}
@Override
public boolean isRunning() {
return (mPlayingState == RUNNING || mRunning);
}
@Override
public boolean isStarted() {
return mStarted;
}
/**
* Plays the ValueAnimator in reverse. If the animation is already running,
* it will stop itself and play backwards from the point reached when reverse was called.
* If the animation is not currently running, then it will start from the end and
* play backwards. This behavior is only set for the current animation; future playing
* of the animation will use the default behavior of playing forward.
*/
public void reverse() {
mPlayingBackwards = !mPlayingBackwards;
if (mPlayingState == RUNNING) {
long currentTime = AnimationUtils.currentAnimationTimeMillis();
long currentPlayTime = currentTime - mStartTime;
long timeLeft = mDuration - currentPlayTime;
mStartTime = currentTime - timeLeft;
} else {
start(true);
}
}
/**
* Called internally to end an animation by removing it from the animations list. Must be
* called on the UI thread.
*/
private void endAnimation() {
sAnimations.get().remove(this);
sPendingAnimations.get().remove(this);
sDelayedAnims.get().remove(this);
mPlayingState = STOPPED;
if (mRunning && mListeners != null) {
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationEnd(this);
}
}
mRunning = false;
mStarted = false;
}
/**
* Called internally to start an animation by adding it to the active animations list. Must be
* called on the UI thread.
*/
private void startAnimation() {
initAnimation();
sAnimations.get().add(this);
if (mStartDelay > 0 && mListeners != null) {
// Listeners were already notified in start() if startDelay is 0; this is
// just for delayed animations
ArrayList<AnimatorListener> tmpListeners =
(ArrayList<AnimatorListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onAnimationStart(this);
}
}
}
/**
* Internal function called to process an animation frame on an animation that is currently
* sleeping through its <code>startDelay</code> phase. The return value indicates whether it
* should be woken up and put on the active animations queue.
*
* @param currentTime The current animation time, used to calculate whether the animation
* has exceeded its <code>startDelay</code> and should be started.
* @return True if the animation's <code>startDelay</code> has been exceeded and the animation
* should be added to the set of active animations.
*/
private boolean delayedAnimationFrame(long currentTime) {
if (!mStartedDelay) {
mStartedDelay = true;
mDelayStartTime = currentTime;
} else {
long deltaTime = currentTime - mDelayStartTime;
if (deltaTime > mStartDelay) {
// startDelay ended - start the anim and record the
// mStartTime appropriately
mStartTime = currentTime - (deltaTime - mStartDelay);
mPlayingState = RUNNING;
return true;
}
}
return false;
}
/**
* This internal function processes a single animation frame for a given animation. The
* currentTime parameter is the timing pulse sent by the handler, used to calculate the
* elapsed duration, and therefore
* the elapsed fraction, of the animation. The return value indicates whether the animation
* should be ended (which happens when the elapsed time of the animation exceeds the
* animation's duration, including the repeatCount).
*
* @param currentTime The current time, as tracked by the static timing handler
* @return true if the animation's duration, including any repetitions due to
* <code>repeatCount</code> has been exceeded and the animation should be ended.
*/
boolean animationFrame(long currentTime) {
boolean done = false;
if (mPlayingState == STOPPED) {
mPlayingState = RUNNING;
if (mSeekTime < 0) {
mStartTime = currentTime;
} else {
mStartTime = currentTime - mSeekTime;
// Now that we're playing, reset the seek time
mSeekTime = -1;
}
}
switch (mPlayingState) {
case RUNNING:
case SEEKED:
float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
if (fraction >= 1f) {
if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
// Time to repeat
if (mListeners != null) {
int numListeners = mListeners.size();
for (int i = 0; i < numListeners; ++i) {
mListeners.get(i).onAnimationRepeat(this);
}
}
if (mRepeatMode == REVERSE) {
mPlayingBackwards = mPlayingBackwards ? false : true;
}
mCurrentIteration += (int)fraction;
fraction = fraction % 1f;
mStartTime += mDuration;
} else {
done = true;
fraction = Math.min(fraction, 1.0f);
}
}
if (mPlayingBackwards) {
fraction = 1f - fraction;
}
animateValue(fraction);
break;
}
return done;
}
/**
* Returns the current animation fraction, which is the elapsed/interpolated fraction used in
* the most recent frame update on the animation.
*
* @return Elapsed/interpolated fraction of the animation.
*/
public float getAnimatedFraction() {
return mCurrentFraction;
}
/**
* This method is called with the elapsed fraction of the animation during every
* animation frame. This function turns the elapsed fraction into an interpolated fraction
* and then into an animated value (from the evaluator. The function is called mostly during
* animation updates, but it is also called when the <code>end()</code>
* function is called, to set the final value on the property.
*
* <p>Overrides of this method must call the superclass to perform the calculation
* of the animated value.</p>
*
* @param fraction The elapsed fraction of the animation.
*/
void animateValue(float fraction) {
fraction = mInterpolator.getInterpolation(fraction);
mCurrentFraction = fraction;
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].calculateValue(fraction);
}
if (mUpdateListeners != null) {
int numListeners = mUpdateListeners.size();
for (int i = 0; i < numListeners; ++i) {
mUpdateListeners.get(i).onAnimationUpdate(this);
}
}
}
@Override
public ValueAnimator clone() {
final ValueAnimator anim = (ValueAnimator) super.clone();
if (mUpdateListeners != null) {
ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners;
anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
int numListeners = oldListeners.size();
for (int i = 0; i < numListeners; ++i) {
anim.mUpdateListeners.add(oldListeners.get(i));
}
}
anim.mSeekTime = -1;
anim.mPlayingBackwards = false;
anim.mCurrentIteration = 0;
anim.mInitialized = false;
anim.mPlayingState = STOPPED;
anim.mStartedDelay = false;
PropertyValuesHolder[] oldValues = mValues;
if (oldValues != null) {
int numValues = oldValues.length;
anim.mValues = new PropertyValuesHolder[numValues];
anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
for (int i = 0; i < numValues; ++i) {
PropertyValuesHolder newValuesHolder = oldValues[i].clone();
anim.mValues[i] = newValuesHolder;
anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder);
}
}
return anim;
}
/**
* Implementors of this interface can add themselves as update listeners
* to an <code>ValueAnimator</code> instance to receive callbacks on every animation
* frame, after the current frame's values have been calculated for that
* <code>ValueAnimator</code>.
*/
public static interface AnimatorUpdateListener {
/**
* <p>Notifies the occurrence of another frame of the animation.</p>
*
* @param animation The animation which was repeated.
*/
void onAnimationUpdate(ValueAnimator animation);
}
/**
* Return the number of animations currently running.
*
* Used by StrictMode internally to annotate violations. Only
* called on the main thread.
*
* @hide
*/
public static int getCurrentAnimationsCount() {
return sAnimations.get().size();
}
/**
* Clear all animations on this thread, without canceling or ending them.
* This should be used with caution.
*
* @hide
*/
public static void clearAllAnimations() {
sAnimations.get().clear();
sPendingAnimations.get().clear();
sDelayedAnims.get().clear();
}
@Override
public String toString() {
String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode());
if (mValues != null) {
for (int i = 0; i < mValues.length; ++i) {
returnVal += "\n " + mValues[i].toString();
}
}
return returnVal;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Keyframe.IntKeyframe;
import java.util.ArrayList;
/**
* This class holds a collection of IntKeyframe objects and is called by ValueAnimator to calculate
* values between those keyframes for a given animation. The class internal to the animation
* package because it is an implementation detail of how Keyframes are stored and used.
*
* <p>This type-specific subclass of KeyframeSet, along with the other type-specific subclass for
* float, exists to speed up the getValue() method when there is no custom
* TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the
* Object equivalents of these primitive types.</p>
*/
class IntKeyframeSet extends KeyframeSet {
private int firstValue;
private int lastValue;
private int deltaValue;
private boolean firstTime = true;
public IntKeyframeSet(IntKeyframe... keyframes) {
super(keyframes);
}
@Override
public Object getValue(float fraction) {
return getIntValue(fraction);
}
@Override
public IntKeyframeSet clone() {
ArrayList<Keyframe> keyframes = mKeyframes;
int numKeyframes = mKeyframes.size();
IntKeyframe[] newKeyframes = new IntKeyframe[numKeyframes];
for (int i = 0; i < numKeyframes; ++i) {
newKeyframes[i] = (IntKeyframe) keyframes.get(i).clone();
}
IntKeyframeSet newSet = new IntKeyframeSet(newKeyframes);
return newSet;
}
public int getIntValue(float fraction) {
if (mNumKeyframes == 2) {
if (firstTime) {
firstTime = false;
firstValue = ((IntKeyframe) mKeyframes.get(0)).getIntValue();
lastValue = ((IntKeyframe) mKeyframes.get(1)).getIntValue();
deltaValue = lastValue - firstValue;
}
if (mInterpolator != null) {
fraction = mInterpolator.getInterpolation(fraction);
}
if (mEvaluator == null) {
return firstValue + (int)(fraction * deltaValue);
} else {
return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).intValue();
}
}
if (fraction <= 0f) {
final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0);
final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(1);
int prevValue = prevKeyframe.getIntValue();
int nextValue = nextKeyframe.getIntValue();
float prevFraction = prevKeyframe.getFraction();
float nextFraction = nextKeyframe.getFraction();
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction);
return mEvaluator == null ?
prevValue + (int)(intervalFraction * (nextValue - prevValue)) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).
intValue();
} else if (fraction >= 1f) {
final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 2);
final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 1);
int prevValue = prevKeyframe.getIntValue();
int nextValue = nextKeyframe.getIntValue();
float prevFraction = prevKeyframe.getFraction();
float nextFraction = nextKeyframe.getFraction();
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction);
return mEvaluator == null ?
prevValue + (int)(intervalFraction * (nextValue - prevValue)) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).intValue();
}
IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0);
for (int i = 1; i < mNumKeyframes; ++i) {
IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(i);
if (fraction < nextKeyframe.getFraction()) {
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevKeyframe.getFraction()) /
(nextKeyframe.getFraction() - prevKeyframe.getFraction());
int prevValue = prevKeyframe.getIntValue();
int nextValue = nextKeyframe.getIntValue();
return mEvaluator == null ?
prevValue + (int)(intervalFraction * (nextValue - prevValue)) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).
intValue();
}
prevKeyframe = nextKeyframe;
}
// shouldn't get here
return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).intValue();
}
}
| Java |
package com.nineoldandroids.animation;
/**
* This class provides a simple callback mechanism to listeners that is synchronized with other
* animators in the system. There is no duration, interpolation, or object value-setting
* with this Animator. Instead, it is simply started and proceeds to send out events on every
* animation frame to its TimeListener (if set), with information about this animator,
* the total elapsed time, and the time since the last animation frame.
*
* @hide
*/
public class TimeAnimator extends ValueAnimator {
private TimeListener mListener;
private long mPreviousTime = -1;
@Override
boolean animationFrame(long currentTime) {
if (mPlayingState == STOPPED) {
mPlayingState = RUNNING;
if (mSeekTime < 0) {
mStartTime = currentTime;
} else {
mStartTime = currentTime - mSeekTime;
// Now that we're playing, reset the seek time
mSeekTime = -1;
}
}
if (mListener != null) {
long totalTime = currentTime - mStartTime;
long deltaTime = (mPreviousTime < 0) ? 0 : (currentTime - mPreviousTime);
mPreviousTime = currentTime;
mListener.onTimeUpdate(this, totalTime, deltaTime);
}
return false;
}
/**
* Sets a listener that is sent update events throughout the life of
* an animation.
*
* @param listener the listener to be set.
*/
public void setTimeListener(TimeListener listener) {
mListener = listener;
}
@Override
void animateValue(float fraction) {
// Noop
}
@Override
void initAnimation() {
// noop
}
/**
* Implementors of this interface can set themselves as update listeners
* to a <code>TimeAnimator</code> instance to receive callbacks on every animation
* frame to receive the total time since the animator started and the delta time
* since the last frame. The first time the listener is called, totalTime and
* deltaTime should both be zero.
*
* @hide
*/
public static interface TimeListener {
/**
* <p>Notifies listeners of the occurrence of another frame of the animation,
* along with information about the elapsed time.</p>
*
* @param animation The animator sending out the notification.
* @param totalTime The
*/
void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime);
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
/**
* This evaluator can be used to perform type interpolation between integer
* values that represent ARGB colors.
*/
public class ArgbEvaluator implements TypeEvaluator {
/**
* This function returns the calculated in-between value for a color
* given integers that represent the start and end values in the four
* bytes of the 32-bit int. Each channel is separately linearly interpolated
* and the resulting calculated values are recombined into the return value.
*
* @param fraction The fraction from the starting to the ending values
* @param startValue A 32-bit int value representing colors in the
* separate bytes of the parameter
* @param endValue A 32-bit int value representing colors in the
* separate bytes of the parameter
* @return A value that is calculated to be the linearly interpolated
* result, derived by separating the start and end values into separate
* color channels and interpolating each one separately, recombining the
* resulting values in the same way.
*/
public Object evaluate(float fraction, Object startValue, Object endValue) {
int startInt = (Integer) startValue;
int startA = (startInt >> 24);
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24);
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int)((startA + (int)(fraction * (endA - startA))) << 24) |
(int)((startR + (int)(fraction * (endR - startR))) << 16) |
(int)((startG + (int)(fraction * (endG - startG))) << 8) |
(int)((startB + (int)(fraction * (endB - startB))));
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import java.util.ArrayList;
import java.util.Arrays;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Keyframe.FloatKeyframe;
import com.nineoldandroids.animation.Keyframe.IntKeyframe;
import com.nineoldandroids.animation.Keyframe.ObjectKeyframe;
/**
* This class holds a collection of Keyframe objects and is called by ValueAnimator to calculate
* values between those keyframes for a given animation. The class internal to the animation
* package because it is an implementation detail of how Keyframes are stored and used.
*/
class KeyframeSet {
int mNumKeyframes;
Keyframe mFirstKeyframe;
Keyframe mLastKeyframe;
/*Time*/Interpolator mInterpolator; // only used in the 2-keyframe case
ArrayList<Keyframe> mKeyframes; // only used when there are not 2 keyframes
TypeEvaluator mEvaluator;
public KeyframeSet(Keyframe... keyframes) {
mNumKeyframes = keyframes.length;
mKeyframes = new ArrayList<Keyframe>();
mKeyframes.addAll(Arrays.asList(keyframes));
mFirstKeyframe = mKeyframes.get(0);
mLastKeyframe = mKeyframes.get(mNumKeyframes - 1);
mInterpolator = mLastKeyframe.getInterpolator();
}
public static KeyframeSet ofInt(int... values) {
int numKeyframes = values.length;
IntKeyframe keyframes[] = new IntKeyframe[Math.max(numKeyframes,2)];
if (numKeyframes == 1) {
keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f);
keyframes[1] = (IntKeyframe) Keyframe.ofInt(1f, values[0]);
} else {
keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f, values[0]);
for (int i = 1; i < numKeyframes; ++i) {
keyframes[i] = (IntKeyframe) Keyframe.ofInt((float) i / (numKeyframes - 1), values[i]);
}
}
return new IntKeyframeSet(keyframes);
}
public static KeyframeSet ofFloat(float... values) {
int numKeyframes = values.length;
FloatKeyframe keyframes[] = new FloatKeyframe[Math.max(numKeyframes,2)];
if (numKeyframes == 1) {
keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f);
keyframes[1] = (FloatKeyframe) Keyframe.ofFloat(1f, values[0]);
} else {
keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f, values[0]);
for (int i = 1; i < numKeyframes; ++i) {
keyframes[i] = (FloatKeyframe) Keyframe.ofFloat((float) i / (numKeyframes - 1), values[i]);
}
}
return new FloatKeyframeSet(keyframes);
}
public static KeyframeSet ofKeyframe(Keyframe... keyframes) {
// if all keyframes of same primitive type, create the appropriate KeyframeSet
int numKeyframes = keyframes.length;
boolean hasFloat = false;
boolean hasInt = false;
boolean hasOther = false;
for (int i = 0; i < numKeyframes; ++i) {
if (keyframes[i] instanceof FloatKeyframe) {
hasFloat = true;
} else if (keyframes[i] instanceof IntKeyframe) {
hasInt = true;
} else {
hasOther = true;
}
}
if (hasFloat && !hasInt && !hasOther) {
FloatKeyframe floatKeyframes[] = new FloatKeyframe[numKeyframes];
for (int i = 0; i < numKeyframes; ++i) {
floatKeyframes[i] = (FloatKeyframe) keyframes[i];
}
return new FloatKeyframeSet(floatKeyframes);
} else if (hasInt && !hasFloat && !hasOther) {
IntKeyframe intKeyframes[] = new IntKeyframe[numKeyframes];
for (int i = 0; i < numKeyframes; ++i) {
intKeyframes[i] = (IntKeyframe) keyframes[i];
}
return new IntKeyframeSet(intKeyframes);
} else {
return new KeyframeSet(keyframes);
}
}
public static KeyframeSet ofObject(Object... values) {
int numKeyframes = values.length;
ObjectKeyframe keyframes[] = new ObjectKeyframe[Math.max(numKeyframes,2)];
if (numKeyframes == 1) {
keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f);
keyframes[1] = (ObjectKeyframe) Keyframe.ofObject(1f, values[0]);
} else {
keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f, values[0]);
for (int i = 1; i < numKeyframes; ++i) {
keyframes[i] = (ObjectKeyframe) Keyframe.ofObject((float) i / (numKeyframes - 1), values[i]);
}
}
return new KeyframeSet(keyframes);
}
/**
* Sets the TypeEvaluator to be used when calculating animated values. This object
* is required only for KeyframeSets that are not either IntKeyframeSet or FloatKeyframeSet,
* both of which assume their own evaluator to speed up calculations with those primitive
* types.
*
* @param evaluator The TypeEvaluator to be used to calculate animated values.
*/
public void setEvaluator(TypeEvaluator evaluator) {
mEvaluator = evaluator;
}
@Override
public KeyframeSet clone() {
ArrayList<Keyframe> keyframes = mKeyframes;
int numKeyframes = mKeyframes.size();
Keyframe[] newKeyframes = new Keyframe[numKeyframes];
for (int i = 0; i < numKeyframes; ++i) {
newKeyframes[i] = keyframes.get(i).clone();
}
KeyframeSet newSet = new KeyframeSet(newKeyframes);
return newSet;
}
/**
* Gets the animated value, given the elapsed fraction of the animation (interpolated by the
* animation's interpolator) and the evaluator used to calculate in-between values. This
* function maps the input fraction to the appropriate keyframe interval and a fraction
* between them and returns the interpolated value. Note that the input fraction may fall
* outside the [0-1] bounds, if the animation's interpolator made that happen (e.g., a
* spring interpolation that might send the fraction past 1.0). We handle this situation by
* just using the two keyframes at the appropriate end when the value is outside those bounds.
*
* @param fraction The elapsed fraction of the animation
* @return The animated value.
*/
public Object getValue(float fraction) {
// Special-case optimization for the common case of only two keyframes
if (mNumKeyframes == 2) {
if (mInterpolator != null) {
fraction = mInterpolator.getInterpolation(fraction);
}
return mEvaluator.evaluate(fraction, mFirstKeyframe.getValue(),
mLastKeyframe.getValue());
}
if (fraction <= 0f) {
final Keyframe nextKeyframe = mKeyframes.get(1);
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
final float prevFraction = mFirstKeyframe.getFraction();
float intervalFraction = (fraction - prevFraction) /
(nextKeyframe.getFraction() - prevFraction);
return mEvaluator.evaluate(intervalFraction, mFirstKeyframe.getValue(),
nextKeyframe.getValue());
} else if (fraction >= 1f) {
final Keyframe prevKeyframe = mKeyframes.get(mNumKeyframes - 2);
final /*Time*/Interpolator interpolator = mLastKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
final float prevFraction = prevKeyframe.getFraction();
float intervalFraction = (fraction - prevFraction) /
(mLastKeyframe.getFraction() - prevFraction);
return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(),
mLastKeyframe.getValue());
}
Keyframe prevKeyframe = mFirstKeyframe;
for (int i = 1; i < mNumKeyframes; ++i) {
Keyframe nextKeyframe = mKeyframes.get(i);
if (fraction < nextKeyframe.getFraction()) {
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
final float prevFraction = prevKeyframe.getFraction();
float intervalFraction = (fraction - prevFraction) /
(nextKeyframe.getFraction() - prevFraction);
return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(),
nextKeyframe.getValue());
}
prevKeyframe = nextKeyframe;
}
// shouldn't reach here
return mLastKeyframe.getValue();
}
@Override
public String toString() {
String returnVal = " ";
for (int i = 0; i < mNumKeyframes; ++i) {
returnVal += mKeyframes.get(i).getValue() + " ";
}
return returnVal;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.content.res.Resources.NotFoundException;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.util.Xml;
import android.view.animation.AnimationUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
/**
* This class is used to instantiate animator XML files into Animator objects.
* <p>
* For performance reasons, inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use this inflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource (R.
* <em>something</em> file.)
*/
public class AnimatorInflater {
private static final int[] AnimatorSet = new int[] {
/* 0 */ android.R.attr.ordering,
};
private static final int AnimatorSet_ordering = 0;
private static final int[] PropertyAnimator = new int[] {
/* 0 */ android.R.attr.propertyName,
};
private static final int PropertyAnimator_propertyName = 0;
private static final int[] Animator = new int[] {
/* 0 */ android.R.attr.interpolator,
/* 1 */ android.R.attr.duration,
/* 2 */ android.R.attr.startOffset,
/* 3 */ android.R.attr.repeatCount,
/* 4 */ android.R.attr.repeatMode,
/* 5 */ android.R.attr.valueFrom,
/* 6 */ android.R.attr.valueTo,
/* 7 */ android.R.attr.valueType,
};
private static final int Animator_interpolator = 0;
private static final int Animator_duration = 1;
private static final int Animator_startOffset = 2;
private static final int Animator_repeatCount = 3;
private static final int Animator_repeatMode = 4;
private static final int Animator_valueFrom = 5;
private static final int Animator_valueTo = 6;
private static final int Animator_valueType = 7;
/**
* These flags are used when parsing AnimatorSet objects
*/
private static final int TOGETHER = 0;
//private static final int SEQUENTIALLY = 1;
/**
* Enum values used in XML attributes to indicate the value for mValueType
*/
private static final int VALUE_TYPE_FLOAT = 0;
//private static final int VALUE_TYPE_INT = 1;
//private static final int VALUE_TYPE_COLOR = 4;
//private static final int VALUE_TYPE_CUSTOM = 5;
/**
* Loads an {@link Animator} object from a resource
*
* @param context Application context used to access resources
* @param id The resource id of the animation to load
* @return The animator object reference by the specified id
* @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
*/
public static Animator loadAnimator(Context context, int id)
throws NotFoundException {
XmlResourceParser parser = null;
try {
parser = context.getResources().getAnimation(id);
return createAnimatorFromXml(context, parser);
} catch (XmlPullParserException ex) {
Resources.NotFoundException rnf =
new Resources.NotFoundException("Can't load animation resource ID #0x" +
Integer.toHexString(id));
rnf.initCause(ex);
throw rnf;
} catch (IOException ex) {
Resources.NotFoundException rnf =
new Resources.NotFoundException("Can't load animation resource ID #0x" +
Integer.toHexString(id));
rnf.initCause(ex);
throw rnf;
} finally {
if (parser != null) parser.close();
}
}
private static Animator createAnimatorFromXml(Context c, XmlPullParser parser)
throws XmlPullParserException, IOException {
return createAnimatorFromXml(c, parser, Xml.asAttributeSet(parser), null, 0);
}
private static Animator createAnimatorFromXml(Context c, XmlPullParser parser,
AttributeSet attrs, AnimatorSet parent, int sequenceOrdering)
throws XmlPullParserException, IOException {
Animator anim = null;
ArrayList<Animator> childAnims = null;
// Make sure we are on a start tag.
int type;
int depth = parser.getDepth();
while (((type=parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("objectAnimator")) {
anim = loadObjectAnimator(c, attrs);
} else if (name.equals("animator")) {
anim = loadAnimator(c, attrs, null);
} else if (name.equals("set")) {
anim = new AnimatorSet();
TypedArray a = c.obtainStyledAttributes(attrs,
/*com.android.internal.R.styleable.*/AnimatorSet);
TypedValue orderingValue = new TypedValue();
a.getValue(/*com.android.internal.R.styleable.*/AnimatorSet_ordering, orderingValue);
int ordering = orderingValue.type == TypedValue.TYPE_INT_DEC ? orderingValue.data : TOGETHER;
createAnimatorFromXml(c, parser, attrs, (AnimatorSet) anim, ordering);
a.recycle();
} else {
throw new RuntimeException("Unknown animator name: " + parser.getName());
}
if (parent != null) {
if (childAnims == null) {
childAnims = new ArrayList<Animator>();
}
childAnims.add(anim);
}
}
if (parent != null && childAnims != null) {
Animator[] animsArray = new Animator[childAnims.size()];
int index = 0;
for (Animator a : childAnims) {
animsArray[index++] = a;
}
if (sequenceOrdering == TOGETHER) {
parent.playTogether(animsArray);
} else {
parent.playSequentially(animsArray);
}
}
return anim;
}
private static ObjectAnimator loadObjectAnimator(Context context, AttributeSet attrs)
throws NotFoundException {
ObjectAnimator anim = new ObjectAnimator();
loadAnimator(context, attrs, anim);
TypedArray a =
context.obtainStyledAttributes(attrs, /*com.android.internal.R.styleable.*/PropertyAnimator);
String propertyName = a.getString(/*com.android.internal.R.styleable.*/PropertyAnimator_propertyName);
anim.setPropertyName(propertyName);
a.recycle();
return anim;
}
/**
* Creates a new animation whose parameters come from the specified context and
* attributes set.
*
* @param context the application environment
* @param attrs the set of attributes holding the animation parameters
*/
private static ValueAnimator loadAnimator(Context context, AttributeSet attrs, ValueAnimator anim)
throws NotFoundException {
TypedArray a =
context.obtainStyledAttributes(attrs, /*com.android.internal.R.styleable.*/Animator);
long duration = a.getInt(/*com.android.internal.R.styleable.*/Animator_duration, 0);
long startDelay = a.getInt(/*com.android.internal.R.styleable.*/Animator_startOffset, 0);
int valueType = a.getInt(/*com.android.internal.R.styleable.*/Animator_valueType,
VALUE_TYPE_FLOAT);
if (anim == null) {
anim = new ValueAnimator();
}
//TypeEvaluator evaluator = null;
int valueFromIndex = /*com.android.internal.R.styleable.*/Animator_valueFrom;
int valueToIndex = /*com.android.internal.R.styleable.*/Animator_valueTo;
boolean getFloats = (valueType == VALUE_TYPE_FLOAT);
TypedValue tvFrom = a.peekValue(valueFromIndex);
boolean hasFrom = (tvFrom != null);
int fromType = hasFrom ? tvFrom.type : 0;
TypedValue tvTo = a.peekValue(valueToIndex);
boolean hasTo = (tvTo != null);
int toType = hasTo ? tvTo.type : 0;
if ((hasFrom && (fromType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
(fromType <= TypedValue.TYPE_LAST_COLOR_INT)) ||
(hasTo && (toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
(toType <= TypedValue.TYPE_LAST_COLOR_INT))) {
// special case for colors: ignore valueType and get ints
getFloats = false;
anim.setEvaluator(new ArgbEvaluator());
}
if (getFloats) {
float valueFrom;
float valueTo;
if (hasFrom) {
if (fromType == TypedValue.TYPE_DIMENSION) {
valueFrom = a.getDimension(valueFromIndex, 0f);
} else {
valueFrom = a.getFloat(valueFromIndex, 0f);
}
if (hasTo) {
if (toType == TypedValue.TYPE_DIMENSION) {
valueTo = a.getDimension(valueToIndex, 0f);
} else {
valueTo = a.getFloat(valueToIndex, 0f);
}
anim.setFloatValues(valueFrom, valueTo);
} else {
anim.setFloatValues(valueFrom);
}
} else {
if (toType == TypedValue.TYPE_DIMENSION) {
valueTo = a.getDimension(valueToIndex, 0f);
} else {
valueTo = a.getFloat(valueToIndex, 0f);
}
anim.setFloatValues(valueTo);
}
} else {
int valueFrom;
int valueTo;
if (hasFrom) {
if (fromType == TypedValue.TYPE_DIMENSION) {
valueFrom = (int) a.getDimension(valueFromIndex, 0f);
} else if ((fromType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
(fromType <= TypedValue.TYPE_LAST_COLOR_INT)) {
valueFrom = a.getColor(valueFromIndex, 0);
} else {
valueFrom = a.getInt(valueFromIndex, 0);
}
if (hasTo) {
if (toType == TypedValue.TYPE_DIMENSION) {
valueTo = (int) a.getDimension(valueToIndex, 0f);
} else if ((toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
(toType <= TypedValue.TYPE_LAST_COLOR_INT)) {
valueTo = a.getColor(valueToIndex, 0);
} else {
valueTo = a.getInt(valueToIndex, 0);
}
anim.setIntValues(valueFrom, valueTo);
} else {
anim.setIntValues(valueFrom);
}
} else {
if (hasTo) {
if (toType == TypedValue.TYPE_DIMENSION) {
valueTo = (int) a.getDimension(valueToIndex, 0f);
} else if ((toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
(toType <= TypedValue.TYPE_LAST_COLOR_INT)) {
valueTo = a.getColor(valueToIndex, 0);
} else {
valueTo = a.getInt(valueToIndex, 0);
}
anim.setIntValues(valueTo);
}
}
}
anim.setDuration(duration);
anim.setStartDelay(startDelay);
if (a.hasValue(/*com.android.internal.R.styleable.*/Animator_repeatCount)) {
anim.setRepeatCount(
a.getInt(/*com.android.internal.R.styleable.*/Animator_repeatCount, 0));
}
if (a.hasValue(/*com.android.internal.R.styleable.*/Animator_repeatMode)) {
anim.setRepeatMode(
a.getInt(/*com.android.internal.R.styleable.*/Animator_repeatMode,
ValueAnimator.RESTART));
}
//if (evaluator != null) {
// anim.setEvaluator(evaluator);
//}
final int resID =
a.getResourceId(/*com.android.internal.R.styleable.*/Animator_interpolator, 0);
if (resID > 0) {
anim.setInterpolator(AnimationUtils.loadInterpolator(context, resID));
}
a.recycle();
return anim;
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
/**
* This evaluator can be used to perform type interpolation between <code>int</code> values.
*/
public class IntEvaluator implements TypeEvaluator<Integer> {
/**
* This function returns the result of linearly interpolating the start and end values, with
* <code>fraction</code> representing the proportion between the start and end values. The
* calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>,
* where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,
* and <code>t</code> is <code>fraction</code>.
*
* @param fraction The fraction from the starting to the ending values
* @param startValue The start value; should be of type <code>int</code> or
* <code>Integer</code>
* @param endValue The end value; should be of type <code>int</code> or <code>Integer</code>
* @return A linear interpolation between the start and end values, given the
* <code>fraction</code> parameter.
*/
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int startInt = startValue;
return (int)(startInt + fraction * (endValue - startInt));
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import java.util.ArrayList;
import android.view.animation.Interpolator;
/**
* This is the superclass for classes which provide basic support for animations which can be
* started, ended, and have <code>AnimatorListeners</code> added to them.
*/
public abstract class Animator implements Cloneable {
/**
* The set of listeners to be sent events through the life of an animation.
*/
ArrayList<AnimatorListener> mListeners = null;
/**
* Starts this animation. If the animation has a nonzero startDelay, the animation will start
* running after that delay elapses. A non-delayed animation will have its initial
* value(s) set immediately, followed by calls to
* {@link AnimatorListener#onAnimationStart(Animator)} for any listeners of this animator.
*
* <p>The animation started by calling this method will be run on the thread that called
* this method. This thread should have a Looper on it (a runtime exception will be thrown if
* this is not the case). Also, if the animation will animate
* properties of objects in the view hierarchy, then the calling thread should be the UI
* thread for that view hierarchy.</p>
*
*/
public void start() {
}
/**
* Cancels the animation. Unlike {@link #end()}, <code>cancel()</code> causes the animation to
* stop in its tracks, sending an
* {@link android.animation.Animator.AnimatorListener#onAnimationCancel(Animator)} to
* its listeners, followed by an
* {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} message.
*
* <p>This method must be called on the thread that is running the animation.</p>
*/
public void cancel() {
}
/**
* Ends the animation. This causes the animation to assign the end value of the property being
* animated, then calling the
* {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} method on
* its listeners.
*
* <p>This method must be called on the thread that is running the animation.</p>
*/
public void end() {
}
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
*
* @return the number of milliseconds to delay running the animation
*/
public abstract long getStartDelay();
/**
* The amount of time, in milliseconds, to delay starting the animation after
* {@link #start()} is called.
* @param startDelay The amount of the delay, in milliseconds
*/
public abstract void setStartDelay(long startDelay);
/**
* Sets the length of the animation.
*
* @param duration The length of the animation, in milliseconds.
*/
public abstract Animator setDuration(long duration);
/**
* Gets the length of the animation.
*
* @return The length of the animation, in milliseconds.
*/
public abstract long getDuration();
/**
* The time interpolator used in calculating the elapsed fraction of this animation. The
* interpolator determines whether the animation runs with linear or non-linear motion,
* such as acceleration and deceleration. The default value is
* {@link android.view.animation.AccelerateDecelerateInterpolator}
*
* @param value the interpolator to be used by this animation
*/
public abstract void setInterpolator(/*Time*/Interpolator value);
/**
* Returns whether this Animator is currently running (having been started and gone past any
* initial startDelay period and not yet ended).
*
* @return Whether the Animator is running.
*/
public abstract boolean isRunning();
/**
* Returns whether this Animator has been started and not yet ended. This state is a superset
* of the state of {@link #isRunning()}, because an Animator with a nonzero
* {@link #getStartDelay() startDelay} will return true for {@link #isStarted()} during the
* delay phase, whereas {@link #isRunning()} will return true only after the delay phase
* is complete.
*
* @return Whether the Animator has been started and not yet ended.
*/
public boolean isStarted() {
// Default method returns value for isRunning(). Subclasses should override to return a
// real value.
return isRunning();
}
/**
* Adds a listener to the set of listeners that are sent events through the life of an
* animation, such as start, repeat, and end.
*
* @param listener the listener to be added to the current set of listeners for this animation.
*/
public void addListener(AnimatorListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<AnimatorListener>();
}
mListeners.add(listener);
}
/**
* Removes a listener from the set listening to this animation.
*
* @param listener the listener to be removed from the current set of listeners for this
* animation.
*/
public void removeListener(AnimatorListener listener) {
if (mListeners == null) {
return;
}
mListeners.remove(listener);
if (mListeners.size() == 0) {
mListeners = null;
}
}
/**
* Gets the set of {@link android.animation.Animator.AnimatorListener} objects that are currently
* listening for events on this <code>Animator</code> object.
*
* @return ArrayList<AnimatorListener> The set of listeners.
*/
public ArrayList<AnimatorListener> getListeners() {
return mListeners;
}
/**
* Removes all listeners from this object. This is equivalent to calling
* <code>getListeners()</code> followed by calling <code>clear()</code> on the
* returned list of listeners.
*/
public void removeAllListeners() {
if (mListeners != null) {
mListeners.clear();
mListeners = null;
}
}
@Override
public Animator clone() {
try {
final Animator anim = (Animator) super.clone();
if (mListeners != null) {
ArrayList<AnimatorListener> oldListeners = mListeners;
anim.mListeners = new ArrayList<AnimatorListener>();
int numListeners = oldListeners.size();
for (int i = 0; i < numListeners; ++i) {
anim.mListeners.add(oldListeners.get(i));
}
}
return anim;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
/**
* This method tells the object to use appropriate information to extract
* starting values for the animation. For example, a AnimatorSet object will pass
* this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target object
* and PropertyValuesHolder objects to get the start values for its properties.
* An ValueAnimator object will ignore the request since it does not have enough
* information (such as a target object) to gather these values.
*/
public void setupStartValues() {
}
/**
* This method tells the object to use appropriate information to extract
* ending values for the animation. For example, a AnimatorSet object will pass
* this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target object
* and PropertyValuesHolder objects to get the start values for its properties.
* An ValueAnimator object will ignore the request since it does not have enough
* information (such as a target object) to gather these values.
*/
public void setupEndValues() {
}
/**
* Sets the target object whose property will be animated by this animation. Not all subclasses
* operate on target objects (for example, {@link ValueAnimator}, but this method
* is on the superclass for the convenience of dealing generically with those subclasses
* that do handle targets.
*
* @param target The object being animated
*/
public void setTarget(Object target) {
}
/**
* <p>An animation listener receives notifications from an animation.
* Notifications indicate animation related events, such as the end or the
* repetition of the animation.</p>
*/
public static interface AnimatorListener {
/**
* <p>Notifies the start of the animation.</p>
*
* @param animation The started animation.
*/
void onAnimationStart(Animator animation);
/**
* <p>Notifies the end of the animation. This callback is not invoked
* for animations with repeat count set to INFINITE.</p>
*
* @param animation The animation which reached its end.
*/
void onAnimationEnd(Animator animation);
/**
* <p>Notifies the cancellation of the animation. This callback is not invoked
* for animations with repeat count set to INFINITE.</p>
*
* @param animation The animation which was canceled.
*/
void onAnimationCancel(Animator animation);
/**
* <p>Notifies the repetition of the animation.</p>
*
* @param animation The animation which was repeated.
*/
void onAnimationRepeat(Animator animation);
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.view.animation.Interpolator;
/**
* This class holds a time/value pair for an animation. The Keyframe class is used
* by {@link ValueAnimator} to define the values that the animation target will have over the course
* of the animation. As the time proceeds from one keyframe to the other, the value of the
* target object will animate between the value at the previous keyframe and the value at the
* next keyframe. Each keyframe also holds an optional {@link TimeInterpolator}
* object, which defines the time interpolation over the intervalue preceding the keyframe.
*
* <p>The Keyframe class itself is abstract. The type-specific factory methods will return
* a subclass of Keyframe specific to the type of value being stored. This is done to improve
* performance when dealing with the most common cases (e.g., <code>float</code> and
* <code>int</code> values). Other types will fall into a more general Keyframe class that
* treats its values as Objects. Unless your animation requires dealing with a custom type
* or a data structure that needs to be animated directly (and evaluated using an implementation
* of {@link TypeEvaluator}), you should stick to using float and int as animations using those
* types have lower runtime overhead than other types.</p>
*/
public abstract class Keyframe implements Cloneable {
/**
* The time at which mValue will hold true.
*/
float mFraction;
/**
* The type of the value in this Keyframe. This type is determined at construction time,
* based on the type of the <code>value</code> object passed into the constructor.
*/
Class mValueType;
/**
* The optional time interpolator for the interval preceding this keyframe. A null interpolator
* (the default) results in linear interpolation over the interval.
*/
private /*Time*/Interpolator mInterpolator = null;
/**
* Flag to indicate whether this keyframe has a valid value. This flag is used when an
* animation first starts, to populate placeholder keyframes with real values derived
* from the target object.
*/
boolean mHasValue = false;
/**
* Constructs a Keyframe object with the given time and value. The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
* @param value The value that the object will animate to as the animation time approaches
* the time in this keyframe, and the the value animated from as the time passes the time in
* this keyframe.
*/
public static Keyframe ofInt(float fraction, int value) {
return new IntKeyframe(fraction, value);
}
/**
* Constructs a Keyframe object with the given time. The value at this time will be derived
* from the target object when the animation first starts (note that this implies that keyframes
* with no initial value must be used as part of an {@link ObjectAnimator}).
* The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
*/
public static Keyframe ofInt(float fraction) {
return new IntKeyframe(fraction);
}
/**
* Constructs a Keyframe object with the given time and value. The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
* @param value The value that the object will animate to as the animation time approaches
* the time in this keyframe, and the the value animated from as the time passes the time in
* this keyframe.
*/
public static Keyframe ofFloat(float fraction, float value) {
return new FloatKeyframe(fraction, value);
}
/**
* Constructs a Keyframe object with the given time. The value at this time will be derived
* from the target object when the animation first starts (note that this implies that keyframes
* with no initial value must be used as part of an {@link ObjectAnimator}).
* The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
*/
public static Keyframe ofFloat(float fraction) {
return new FloatKeyframe(fraction);
}
/**
* Constructs a Keyframe object with the given time and value. The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
* @param value The value that the object will animate to as the animation time approaches
* the time in this keyframe, and the the value animated from as the time passes the time in
* this keyframe.
*/
public static Keyframe ofObject(float fraction, Object value) {
return new ObjectKeyframe(fraction, value);
}
/**
* Constructs a Keyframe object with the given time. The value at this time will be derived
* from the target object when the animation first starts (note that this implies that keyframes
* with no initial value must be used as part of an {@link ObjectAnimator}).
* The time defines the
* time, as a proportion of an overall animation's duration, at which the value will hold true
* for the animation. The value for the animation between keyframes will be calculated as
* an interpolation between the values at those keyframes.
*
* @param fraction The time, expressed as a value between 0 and 1, representing the fraction
* of time elapsed of the overall animation duration.
*/
public static Keyframe ofObject(float fraction) {
return new ObjectKeyframe(fraction, null);
}
/**
* Indicates whether this keyframe has a valid value. This method is called internally when
* an {@link ObjectAnimator} first starts; keyframes without values are assigned values at
* that time by deriving the value for the property from the target object.
*
* @return boolean Whether this object has a value assigned.
*/
public boolean hasValue() {
return mHasValue;
}
/**
* Gets the value for this Keyframe.
*
* @return The value for this Keyframe.
*/
public abstract Object getValue();
/**
* Sets the value for this Keyframe.
*
* @param value value for this Keyframe.
*/
public abstract void setValue(Object value);
/**
* Gets the time for this keyframe, as a fraction of the overall animation duration.
*
* @return The time associated with this keyframe, as a fraction of the overall animation
* duration. This should be a value between 0 and 1.
*/
public float getFraction() {
return mFraction;
}
/**
* Sets the time for this keyframe, as a fraction of the overall animation duration.
*
* @param fraction time associated with this keyframe, as a fraction of the overall animation
* duration. This should be a value between 0 and 1.
*/
public void setFraction(float fraction) {
mFraction = fraction;
}
/**
* Gets the optional interpolator for this Keyframe. A value of <code>null</code> indicates
* that there is no interpolation, which is the same as linear interpolation.
*
* @return The optional interpolator for this Keyframe.
*/
public /*Time*/Interpolator getInterpolator() {
return mInterpolator;
}
/**
* Sets the optional interpolator for this Keyframe. A value of <code>null</code> indicates
* that there is no interpolation, which is the same as linear interpolation.
*
* @return The optional interpolator for this Keyframe.
*/
public void setInterpolator(/*Time*/Interpolator interpolator) {
mInterpolator = interpolator;
}
/**
* Gets the type of keyframe. This information is used by ValueAnimator to determine the type of
* {@link TypeEvaluator} to use when calculating values between keyframes. The type is based
* on the type of Keyframe created.
*
* @return The type of the value stored in the Keyframe.
*/
public Class getType() {
return mValueType;
}
@Override
public abstract Keyframe clone();
/**
* This internal subclass is used for all types which are not int or float.
*/
static class ObjectKeyframe extends Keyframe {
/**
* The value of the animation at the time mFraction.
*/
Object mValue;
ObjectKeyframe(float fraction, Object value) {
mFraction = fraction;
mValue = value;
mHasValue = (value != null);
mValueType = mHasValue ? value.getClass() : Object.class;
}
public Object getValue() {
return mValue;
}
public void setValue(Object value) {
mValue = value;
mHasValue = (value != null);
}
@Override
public ObjectKeyframe clone() {
ObjectKeyframe kfClone = new ObjectKeyframe(getFraction(), mValue);
kfClone.setInterpolator(getInterpolator());
return kfClone;
}
}
/**
* Internal subclass used when the keyframe value is of type int.
*/
static class IntKeyframe extends Keyframe {
/**
* The value of the animation at the time mFraction.
*/
int mValue;
IntKeyframe(float fraction, int value) {
mFraction = fraction;
mValue = value;
mValueType = int.class;
mHasValue = true;
}
IntKeyframe(float fraction) {
mFraction = fraction;
mValueType = int.class;
}
public int getIntValue() {
return mValue;
}
public Object getValue() {
return mValue;
}
public void setValue(Object value) {
if (value != null && value.getClass() == Integer.class) {
mValue = ((Integer)value).intValue();
mHasValue = true;
}
}
@Override
public IntKeyframe clone() {
IntKeyframe kfClone = new IntKeyframe(getFraction(), mValue);
kfClone.setInterpolator(getInterpolator());
return kfClone;
}
}
/**
* Internal subclass used when the keyframe value is of type float.
*/
static class FloatKeyframe extends Keyframe {
/**
* The value of the animation at the time mFraction.
*/
float mValue;
FloatKeyframe(float fraction, float value) {
mFraction = fraction;
mValue = value;
mValueType = float.class;
mHasValue = true;
}
FloatKeyframe(float fraction) {
mFraction = fraction;
mValueType = float.class;
}
public float getFloatValue() {
return mValue;
}
public Object getValue() {
return mValue;
}
public void setValue(Object value) {
if (value != null && value.getClass() == Float.class) {
mValue = ((Float)value).floatValue();
mHasValue = true;
}
}
@Override
public FloatKeyframe clone() {
FloatKeyframe kfClone = new FloatKeyframe(getFraction(), mValue);
kfClone.setInterpolator(getInterpolator());
return kfClone;
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.nineoldandroids.util.FloatProperty;
import com.nineoldandroids.util.IntProperty;
import com.nineoldandroids.util.Property;
/**
* This class holds information about a property and the values that that property
* should take on during an animation. PropertyValuesHolder objects can be used to create
* animations with ValueAnimator or ObjectAnimator that operate on several different properties
* in parallel.
*/
public class PropertyValuesHolder implements Cloneable {
/**
* The name of the property associated with the values. This need not be a real property,
* unless this object is being used with ObjectAnimator. But this is the name by which
* aniamted values are looked up with getAnimatedValue(String) in ValueAnimator.
*/
String mPropertyName;
/**
* @hide
*/
protected Property mProperty;
/**
* The setter function, if needed. ObjectAnimator hands off this functionality to
* PropertyValuesHolder, since it holds all of the per-property information. This
* property is automatically
* derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator.
*/
Method mSetter = null;
/**
* The getter function, if needed. ObjectAnimator hands off this functionality to
* PropertyValuesHolder, since it holds all of the per-property information. This
* property is automatically
* derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator.
* The getter is only derived and used if one of the values is null.
*/
private Method mGetter = null;
/**
* The type of values supplied. This information is used both in deriving the setter/getter
* functions and in deriving the type of TypeEvaluator.
*/
Class mValueType;
/**
* The set of keyframes (time/value pairs) that define this animation.
*/
KeyframeSet mKeyframeSet = null;
// type evaluators for the primitive types handled by this implementation
private static final TypeEvaluator sIntEvaluator = new IntEvaluator();
private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator();
// We try several different types when searching for appropriate setter/getter functions.
// The caller may have supplied values in a type that does not match the setter/getter
// functions (such as the integers 0 and 1 to represent floating point values for alpha).
// Also, the use of generics in constructors means that we end up with the Object versions
// of primitive types (Float vs. float). But most likely, the setter/getter functions
// will take primitive types instead.
// So we supply an ordered array of other types to try before giving up.
private static Class[] FLOAT_VARIANTS = {float.class, Float.class, double.class, int.class,
Double.class, Integer.class};
private static Class[] INTEGER_VARIANTS = {int.class, Integer.class, float.class, double.class,
Float.class, Double.class};
private static Class[] DOUBLE_VARIANTS = {double.class, Double.class, float.class, int.class,
Float.class, Integer.class};
// These maps hold all property entries for a particular class. This map
// is used to speed up property/setter/getter lookups for a given class/property
// combination. No need to use reflection on the combination more than once.
private static final HashMap<Class, HashMap<String, Method>> sSetterPropertyMap =
new HashMap<Class, HashMap<String, Method>>();
private static final HashMap<Class, HashMap<String, Method>> sGetterPropertyMap =
new HashMap<Class, HashMap<String, Method>>();
// This lock is used to ensure that only one thread is accessing the property maps
// at a time.
final ReentrantReadWriteLock mPropertyMapLock = new ReentrantReadWriteLock();
// Used to pass single value to varargs parameter in setter invocation
final Object[] mTmpValueArray = new Object[1];
/**
* The type evaluator used to calculate the animated values. This evaluator is determined
* automatically based on the type of the start/end objects passed into the constructor,
* but the system only knows about the primitive types int and float. Any other
* type will need to set the evaluator to a custom evaluator for that type.
*/
private TypeEvaluator mEvaluator;
/**
* The value most recently calculated by calculateValue(). This is set during
* that function and might be retrieved later either by ValueAnimator.animatedValue() or
* by the property-setting logic in ObjectAnimator.animatedValue().
*/
private Object mAnimatedValue;
/**
* Internal utility constructor, used by the factory methods to set the property name.
* @param propertyName The name of the property for this holder.
*/
private PropertyValuesHolder(String propertyName) {
mPropertyName = propertyName;
}
/**
* Internal utility constructor, used by the factory methods to set the property.
* @param property The property for this holder.
*/
private PropertyValuesHolder(Property property) {
mProperty = property;
if (property != null) {
mPropertyName = property.getName();
}
}
/**
* Constructs and returns a PropertyValuesHolder with a given property name and
* set of int values.
* @param propertyName The name of the property being animated.
* @param values The values that the named property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static PropertyValuesHolder ofInt(String propertyName, int... values) {
return new IntPropertyValuesHolder(propertyName, values);
}
/**
* Constructs and returns a PropertyValuesHolder with a given property and
* set of int values.
* @param property The property being animated. Should not be null.
* @param values The values that the property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static PropertyValuesHolder ofInt(Property<?, Integer> property, int... values) {
return new IntPropertyValuesHolder(property, values);
}
/**
* Constructs and returns a PropertyValuesHolder with a given property name and
* set of float values.
* @param propertyName The name of the property being animated.
* @param values The values that the named property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static PropertyValuesHolder ofFloat(String propertyName, float... values) {
return new FloatPropertyValuesHolder(propertyName, values);
}
/**
* Constructs and returns a PropertyValuesHolder with a given property and
* set of float values.
* @param property The property being animated. Should not be null.
* @param values The values that the property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static PropertyValuesHolder ofFloat(Property<?, Float> property, float... values) {
return new FloatPropertyValuesHolder(property, values);
}
/**
* Constructs and returns a PropertyValuesHolder with a given property name and
* set of Object values. This variant also takes a TypeEvaluator because the system
* cannot automatically interpolate between objects of unknown type.
*
* @param propertyName The name of the property being animated.
* @param evaluator A TypeEvaluator that will be called on each animation frame to
* provide the necessary interpolation between the Object values to derive the animated
* value.
* @param values The values that the named property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static PropertyValuesHolder ofObject(String propertyName, TypeEvaluator evaluator,
Object... values) {
PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName);
pvh.setObjectValues(values);
pvh.setEvaluator(evaluator);
return pvh;
}
/**
* Constructs and returns a PropertyValuesHolder with a given property and
* set of Object values. This variant also takes a TypeEvaluator because the system
* cannot automatically interpolate between objects of unknown type.
*
* @param property The property being animated. Should not be null.
* @param evaluator A TypeEvaluator that will be called on each animation frame to
* provide the necessary interpolation between the Object values to derive the animated
* value.
* @param values The values that the property will animate between.
* @return PropertyValuesHolder The constructed PropertyValuesHolder object.
*/
public static <V> PropertyValuesHolder ofObject(Property property,
TypeEvaluator<V> evaluator, V... values) {
PropertyValuesHolder pvh = new PropertyValuesHolder(property);
pvh.setObjectValues(values);
pvh.setEvaluator(evaluator);
return pvh;
}
/**
* Constructs and returns a PropertyValuesHolder object with the specified property name and set
* of values. These values can be of any type, but the type should be consistent so that
* an appropriate {@link android.animation.TypeEvaluator} can be found that matches
* the common type.
* <p>If there is only one value, it is assumed to be the end value of an animation,
* and an initial value will be derived, if possible, by calling a getter function
* on the object. Also, if any value is null, the value will be filled in when the animation
* starts in the same way. This mechanism of automatically getting null values only works
* if the PropertyValuesHolder object is used in conjunction
* {@link ObjectAnimator}, and with a getter function
* derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has
* no way of determining what the value should be.
* @param propertyName The name of the property associated with this set of values. This
* can be the actual property name to be used when using a ObjectAnimator object, or
* just a name used to get animated values, such as if this object is used with an
* ValueAnimator object.
* @param values The set of values to animate between.
*/
public static PropertyValuesHolder ofKeyframe(String propertyName, Keyframe... values) {
KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values);
if (keyframeSet instanceof IntKeyframeSet) {
return new IntPropertyValuesHolder(propertyName, (IntKeyframeSet) keyframeSet);
} else if (keyframeSet instanceof FloatKeyframeSet) {
return new FloatPropertyValuesHolder(propertyName, (FloatKeyframeSet) keyframeSet);
}
else {
PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName);
pvh.mKeyframeSet = keyframeSet;
pvh.mValueType = ((Keyframe)values[0]).getType();
return pvh;
}
}
/**
* Constructs and returns a PropertyValuesHolder object with the specified property and set
* of values. These values can be of any type, but the type should be consistent so that
* an appropriate {@link android.animation.TypeEvaluator} can be found that matches
* the common type.
* <p>If there is only one value, it is assumed to be the end value of an animation,
* and an initial value will be derived, if possible, by calling the property's
* {@link android.util.Property#get(Object)} function.
* Also, if any value is null, the value will be filled in when the animation
* starts in the same way. This mechanism of automatically getting null values only works
* if the PropertyValuesHolder object is used in conjunction with
* {@link ObjectAnimator}, since otherwise PropertyValuesHolder has
* no way of determining what the value should be.
* @param property The property associated with this set of values. Should not be null.
* @param values The set of values to animate between.
*/
public static PropertyValuesHolder ofKeyframe(Property property, Keyframe... values) {
KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values);
if (keyframeSet instanceof IntKeyframeSet) {
return new IntPropertyValuesHolder(property, (IntKeyframeSet) keyframeSet);
} else if (keyframeSet instanceof FloatKeyframeSet) {
return new FloatPropertyValuesHolder(property, (FloatKeyframeSet) keyframeSet);
}
else {
PropertyValuesHolder pvh = new PropertyValuesHolder(property);
pvh.mKeyframeSet = keyframeSet;
pvh.mValueType = ((Keyframe)values[0]).getType();
return pvh;
}
}
/**
* Set the animated values for this object to this set of ints.
* If there is only one value, it is assumed to be the end value of an animation,
* and an initial value will be derived, if possible, by calling a getter function
* on the object. Also, if any value is null, the value will be filled in when the animation
* starts in the same way. This mechanism of automatically getting null values only works
* if the PropertyValuesHolder object is used in conjunction
* {@link ObjectAnimator}, and with a getter function
* derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has
* no way of determining what the value should be.
*
* @param values One or more values that the animation will animate between.
*/
public void setIntValues(int... values) {
mValueType = int.class;
mKeyframeSet = KeyframeSet.ofInt(values);
}
/**
* Set the animated values for this object to this set of floats.
* If there is only one value, it is assumed to be the end value of an animation,
* and an initial value will be derived, if possible, by calling a getter function
* on the object. Also, if any value is null, the value will be filled in when the animation
* starts in the same way. This mechanism of automatically getting null values only works
* if the PropertyValuesHolder object is used in conjunction
* {@link ObjectAnimator}, and with a getter function
* derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has
* no way of determining what the value should be.
*
* @param values One or more values that the animation will animate between.
*/
public void setFloatValues(float... values) {
mValueType = float.class;
mKeyframeSet = KeyframeSet.ofFloat(values);
}
/**
* Set the animated values for this object to this set of Keyframes.
*
* @param values One or more values that the animation will animate between.
*/
public void setKeyframes(Keyframe... values) {
int numKeyframes = values.length;
Keyframe keyframes[] = new Keyframe[Math.max(numKeyframes,2)];
mValueType = ((Keyframe)values[0]).getType();
for (int i = 0; i < numKeyframes; ++i) {
keyframes[i] = (Keyframe)values[i];
}
mKeyframeSet = new KeyframeSet(keyframes);
}
/**
* Set the animated values for this object to this set of Objects.
* If there is only one value, it is assumed to be the end value of an animation,
* and an initial value will be derived, if possible, by calling a getter function
* on the object. Also, if any value is null, the value will be filled in when the animation
* starts in the same way. This mechanism of automatically getting null values only works
* if the PropertyValuesHolder object is used in conjunction
* {@link ObjectAnimator}, and with a getter function
* derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has
* no way of determining what the value should be.
*
* @param values One or more values that the animation will animate between.
*/
public void setObjectValues(Object... values) {
mValueType = values[0].getClass();
mKeyframeSet = KeyframeSet.ofObject(values);
}
/**
* Determine the setter or getter function using the JavaBeans convention of setFoo or
* getFoo for a property named 'foo'. This function figures out what the name of the
* function should be and uses reflection to find the Method with that name on the
* target object.
*
* @param targetClass The class to search for the method
* @param prefix "set" or "get", depending on whether we need a setter or getter.
* @param valueType The type of the parameter (in the case of a setter). This type
* is derived from the values set on this PropertyValuesHolder. This type is used as
* a first guess at the parameter type, but we check for methods with several different
* types to avoid problems with slight mis-matches between supplied values and actual
* value types used on the setter.
* @return Method the method associated with mPropertyName.
*/
private Method getPropertyFunction(Class targetClass, String prefix, Class valueType) {
// TODO: faster implementation...
Method returnVal = null;
String methodName = getMethodName(prefix, mPropertyName);
Class args[] = null;
if (valueType == null) {
try {
returnVal = targetClass.getMethod(methodName, args);
} catch (NoSuchMethodException e) {
/* The native implementation uses JNI to do reflection, which allows access to private methods.
* getDeclaredMethod(..) does not find superclass methods, so it's implemented as a fallback.
*/
try {
returnVal = targetClass.getDeclaredMethod(methodName, args);
returnVal.setAccessible(true);
} catch (NoSuchMethodException e2) {
Log.e("PropertyValuesHolder",
"Couldn't find no-arg method for property " + mPropertyName + ": " + e);
}
}
} else {
args = new Class[1];
Class typeVariants[];
if (mValueType.equals(Float.class)) {
typeVariants = FLOAT_VARIANTS;
} else if (mValueType.equals(Integer.class)) {
typeVariants = INTEGER_VARIANTS;
} else if (mValueType.equals(Double.class)) {
typeVariants = DOUBLE_VARIANTS;
} else {
typeVariants = new Class[1];
typeVariants[0] = mValueType;
}
for (Class typeVariant : typeVariants) {
args[0] = typeVariant;
try {
returnVal = targetClass.getMethod(methodName, args);
// change the value type to suit
mValueType = typeVariant;
return returnVal;
} catch (NoSuchMethodException e) {
/* The native implementation uses JNI to do reflection, which allows access to private methods.
* getDeclaredMethod(..) does not find superclass methods, so it's implemented as a fallback.
*/
try {
returnVal = targetClass.getDeclaredMethod(methodName, args);
returnVal.setAccessible(true);
// change the value type to suit
mValueType = typeVariant;
return returnVal;
} catch (NoSuchMethodException e2) {
// Swallow the error and keep trying other variants
}
}
}
// If we got here, then no appropriate function was found
Log.e("PropertyValuesHolder",
"Couldn't find setter/getter for property " + mPropertyName +
" with value type "+ mValueType);
}
return returnVal;
}
/**
* Returns the setter or getter requested. This utility function checks whether the
* requested method exists in the propertyMapMap cache. If not, it calls another
* utility function to request the Method from the targetClass directly.
* @param targetClass The Class on which the requested method should exist.
* @param propertyMapMap The cache of setters/getters derived so far.
* @param prefix "set" or "get", for the setter or getter.
* @param valueType The type of parameter passed into the method (null for getter).
* @return Method the method associated with mPropertyName.
*/
private Method setupSetterOrGetter(Class targetClass,
HashMap<Class, HashMap<String, Method>> propertyMapMap,
String prefix, Class valueType) {
Method setterOrGetter = null;
try {
// Have to lock property map prior to reading it, to guard against
// another thread putting something in there after we've checked it
// but before we've added an entry to it
mPropertyMapLock.writeLock().lock();
HashMap<String, Method> propertyMap = propertyMapMap.get(targetClass);
if (propertyMap != null) {
setterOrGetter = propertyMap.get(mPropertyName);
}
if (setterOrGetter == null) {
setterOrGetter = getPropertyFunction(targetClass, prefix, valueType);
if (propertyMap == null) {
propertyMap = new HashMap<String, Method>();
propertyMapMap.put(targetClass, propertyMap);
}
propertyMap.put(mPropertyName, setterOrGetter);
}
} finally {
mPropertyMapLock.writeLock().unlock();
}
return setterOrGetter;
}
/**
* Utility function to get the setter from targetClass
* @param targetClass The Class on which the requested method should exist.
*/
void setupSetter(Class targetClass) {
mSetter = setupSetterOrGetter(targetClass, sSetterPropertyMap, "set", mValueType);
}
/**
* Utility function to get the getter from targetClass
*/
private void setupGetter(Class targetClass) {
mGetter = setupSetterOrGetter(targetClass, sGetterPropertyMap, "get", null);
}
/**
* Internal function (called from ObjectAnimator) to set up the setter and getter
* prior to running the animation. If the setter has not been manually set for this
* object, it will be derived automatically given the property name, target object, and
* types of values supplied. If no getter has been set, it will be supplied iff any of the
* supplied values was null. If there is a null value, then the getter (supplied or derived)
* will be called to set those null values to the current value of the property
* on the target object.
* @param target The object on which the setter (and possibly getter) exist.
*/
void setupSetterAndGetter(Object target) {
if (mProperty != null) {
// check to make sure that mProperty is on the class of target
try {
Object testValue = mProperty.get(target);
for (Keyframe kf : mKeyframeSet.mKeyframes) {
if (!kf.hasValue()) {
kf.setValue(mProperty.get(target));
}
}
return;
} catch (ClassCastException e) {
Log.e("PropertyValuesHolder","No such property (" + mProperty.getName() +
") on target object " + target + ". Trying reflection instead");
mProperty = null;
}
}
Class targetClass = target.getClass();
if (mSetter == null) {
setupSetter(targetClass);
}
for (Keyframe kf : mKeyframeSet.mKeyframes) {
if (!kf.hasValue()) {
if (mGetter == null) {
setupGetter(targetClass);
}
try {
kf.setValue(mGetter.invoke(target));
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
}
}
/**
* Utility function to set the value stored in a particular Keyframe. The value used is
* whatever the value is for the property name specified in the keyframe on the target object.
*
* @param target The target object from which the current value should be extracted.
* @param kf The keyframe which holds the property name and value.
*/
private void setupValue(Object target, Keyframe kf) {
if (mProperty != null) {
kf.setValue(mProperty.get(target));
}
try {
if (mGetter == null) {
Class targetClass = target.getClass();
setupGetter(targetClass);
}
kf.setValue(mGetter.invoke(target));
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
/**
* This function is called by ObjectAnimator when setting the start values for an animation.
* The start values are set according to the current values in the target object. The
* property whose value is extracted is whatever is specified by the propertyName of this
* PropertyValuesHolder object.
*
* @param target The object which holds the start values that should be set.
*/
void setupStartValue(Object target) {
setupValue(target, mKeyframeSet.mKeyframes.get(0));
}
/**
* This function is called by ObjectAnimator when setting the end values for an animation.
* The end values are set according to the current values in the target object. The
* property whose value is extracted is whatever is specified by the propertyName of this
* PropertyValuesHolder object.
*
* @param target The object which holds the start values that should be set.
*/
void setupEndValue(Object target) {
setupValue(target, mKeyframeSet.mKeyframes.get(mKeyframeSet.mKeyframes.size() - 1));
}
@Override
public PropertyValuesHolder clone() {
try {
PropertyValuesHolder newPVH = (PropertyValuesHolder) super.clone();
newPVH.mPropertyName = mPropertyName;
newPVH.mProperty = mProperty;
newPVH.mKeyframeSet = mKeyframeSet.clone();
newPVH.mEvaluator = mEvaluator;
return newPVH;
} catch (CloneNotSupportedException e) {
// won't reach here
return null;
}
}
/**
* Internal function to set the value on the target object, using the setter set up
* earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator
* to handle turning the value calculated by ValueAnimator into a value set on the object
* according to the name of the property.
* @param target The target object on which the value is set
*/
void setAnimatedValue(Object target) {
if (mProperty != null) {
mProperty.set(target, getAnimatedValue());
}
if (mSetter != null) {
try {
mTmpValueArray[0] = getAnimatedValue();
mSetter.invoke(target, mTmpValueArray);
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
}
/**
* Internal function, called by ValueAnimator, to set up the TypeEvaluator that will be used
* to calculate animated values.
*/
void init() {
if (mEvaluator == null) {
// We already handle int and float automatically, but not their Object
// equivalents
mEvaluator = (mValueType == Integer.class) ? sIntEvaluator :
(mValueType == Float.class) ? sFloatEvaluator :
null;
}
if (mEvaluator != null) {
// KeyframeSet knows how to evaluate the common types - only give it a custom
// evaluator if one has been set on this class
mKeyframeSet.setEvaluator(mEvaluator);
}
}
/**
* The TypeEvaluator will the automatically determined based on the type of values
* supplied to PropertyValuesHolder. The evaluator can be manually set, however, if so
* desired. This may be important in cases where either the type of the values supplied
* do not match the way that they should be interpolated between, or if the values
* are of a custom type or one not currently understood by the animation system. Currently,
* only values of type float and int (and their Object equivalents: Float
* and Integer) are correctly interpolated; all other types require setting a TypeEvaluator.
* @param evaluator
*/
public void setEvaluator(TypeEvaluator evaluator) {
mEvaluator = evaluator;
mKeyframeSet.setEvaluator(evaluator);
}
/**
* Function used to calculate the value according to the evaluator set up for
* this PropertyValuesHolder object. This function is called by ValueAnimator.animateValue().
*
* @param fraction The elapsed, interpolated fraction of the animation.
*/
void calculateValue(float fraction) {
mAnimatedValue = mKeyframeSet.getValue(fraction);
}
/**
* Sets the name of the property that will be animated. This name is used to derive
* a setter function that will be called to set animated values.
* For example, a property name of <code>foo</code> will result
* in a call to the function <code>setFoo()</code> on the target object. If either
* <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will
* also be derived and called.
*
* <p>Note that the setter function derived from this property name
* must take the same parameter type as the
* <code>valueFrom</code> and <code>valueTo</code> properties, otherwise the call to
* the setter function will fail.</p>
*
* @param propertyName The name of the property being animated.
*/
public void setPropertyName(String propertyName) {
mPropertyName = propertyName;
}
/**
* Sets the property that will be animated.
*
* <p>Note that if this PropertyValuesHolder object is used with ObjectAnimator, the property
* must exist on the target object specified in that ObjectAnimator.</p>
*
* @param property The property being animated.
*/
public void setProperty(Property property) {
mProperty = property;
}
/**
* Gets the name of the property that will be animated. This name will be used to derive
* a setter function that will be called to set animated values.
* For example, a property name of <code>foo</code> will result
* in a call to the function <code>setFoo()</code> on the target object. If either
* <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will
* also be derived and called.
*/
public String getPropertyName() {
return mPropertyName;
}
/**
* Internal function, called by ValueAnimator and ObjectAnimator, to retrieve the value
* most recently calculated in calculateValue().
* @return
*/
Object getAnimatedValue() {
return mAnimatedValue;
}
@Override
public String toString() {
return mPropertyName + ": " + mKeyframeSet.toString();
}
/**
* Utility method to derive a setter/getter method name from a property name, where the
* prefix is typically "set" or "get" and the first letter of the property name is
* capitalized.
*
* @param prefix The precursor to the method name, before the property name begins, typically
* "set" or "get".
* @param propertyName The name of the property that represents the bulk of the method name
* after the prefix. The first letter of this word will be capitalized in the resulting
* method name.
* @return String the property name converted to a method name according to the conventions
* specified above.
*/
static String getMethodName(String prefix, String propertyName) {
if (propertyName == null || propertyName.length() == 0) {
// shouldn't get here
return prefix;
}
char firstLetter = Character.toUpperCase(propertyName.charAt(0));
String theRest = propertyName.substring(1);
return prefix + firstLetter + theRest;
}
static class IntPropertyValuesHolder extends PropertyValuesHolder {
// Cache JNI functions to avoid looking them up twice
//private static final HashMap<Class, HashMap<String, Integer>> sJNISetterPropertyMap =
// new HashMap<Class, HashMap<String, Integer>>();
//int mJniSetter;
private IntProperty mIntProperty;
IntKeyframeSet mIntKeyframeSet;
int mIntAnimatedValue;
public IntPropertyValuesHolder(String propertyName, IntKeyframeSet keyframeSet) {
super(propertyName);
mValueType = int.class;
mKeyframeSet = keyframeSet;
mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet;
}
public IntPropertyValuesHolder(Property property, IntKeyframeSet keyframeSet) {
super(property);
mValueType = int.class;
mKeyframeSet = keyframeSet;
mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet;
if (property instanceof IntProperty) {
mIntProperty = (IntProperty) mProperty;
}
}
public IntPropertyValuesHolder(String propertyName, int... values) {
super(propertyName);
setIntValues(values);
}
public IntPropertyValuesHolder(Property property, int... values) {
super(property);
setIntValues(values);
if (property instanceof IntProperty) {
mIntProperty = (IntProperty) mProperty;
}
}
@Override
public void setIntValues(int... values) {
super.setIntValues(values);
mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet;
}
@Override
void calculateValue(float fraction) {
mIntAnimatedValue = mIntKeyframeSet.getIntValue(fraction);
}
@Override
Object getAnimatedValue() {
return mIntAnimatedValue;
}
@Override
public IntPropertyValuesHolder clone() {
IntPropertyValuesHolder newPVH = (IntPropertyValuesHolder) super.clone();
newPVH.mIntKeyframeSet = (IntKeyframeSet) newPVH.mKeyframeSet;
return newPVH;
}
/**
* Internal function to set the value on the target object, using the setter set up
* earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator
* to handle turning the value calculated by ValueAnimator into a value set on the object
* according to the name of the property.
* @param target The target object on which the value is set
*/
@Override
void setAnimatedValue(Object target) {
if (mIntProperty != null) {
mIntProperty.setValue(target, mIntAnimatedValue);
return;
}
if (mProperty != null) {
mProperty.set(target, mIntAnimatedValue);
return;
}
//if (mJniSetter != 0) {
// nCallIntMethod(target, mJniSetter, mIntAnimatedValue);
// return;
//}
if (mSetter != null) {
try {
mTmpValueArray[0] = mIntAnimatedValue;
mSetter.invoke(target, mTmpValueArray);
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
}
@Override
void setupSetter(Class targetClass) {
if (mProperty != null) {
return;
}
// Check new static hashmap<propName, int> for setter method
//try {
// mPropertyMapLock.writeLock().lock();
// HashMap<String, Integer> propertyMap = sJNISetterPropertyMap.get(targetClass);
// if (propertyMap != null) {
// Integer mJniSetterInteger = propertyMap.get(mPropertyName);
// if (mJniSetterInteger != null) {
// mJniSetter = mJniSetterInteger;
// }
// }
// if (mJniSetter == 0) {
// String methodName = getMethodName("set", mPropertyName);
// mJniSetter = nGetIntMethod(targetClass, methodName);
// if (mJniSetter != 0) {
// if (propertyMap == null) {
// propertyMap = new HashMap<String, Integer>();
// sJNISetterPropertyMap.put(targetClass, propertyMap);
// }
// propertyMap.put(mPropertyName, mJniSetter);
// }
// }
//} catch (NoSuchMethodError e) {
// Log.d("PropertyValuesHolder",
// "Can't find native method using JNI, use reflection" + e);
//} finally {
// mPropertyMapLock.writeLock().unlock();
//}
//if (mJniSetter == 0) {
// Couldn't find method through fast JNI approach - just use reflection
super.setupSetter(targetClass);
//}
}
}
static class FloatPropertyValuesHolder extends PropertyValuesHolder {
// Cache JNI functions to avoid looking them up twice
//private static final HashMap<Class, HashMap<String, Integer>> sJNISetterPropertyMap =
// new HashMap<Class, HashMap<String, Integer>>();
//int mJniSetter;
private FloatProperty mFloatProperty;
FloatKeyframeSet mFloatKeyframeSet;
float mFloatAnimatedValue;
public FloatPropertyValuesHolder(String propertyName, FloatKeyframeSet keyframeSet) {
super(propertyName);
mValueType = float.class;
mKeyframeSet = keyframeSet;
mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet;
}
public FloatPropertyValuesHolder(Property property, FloatKeyframeSet keyframeSet) {
super(property);
mValueType = float.class;
mKeyframeSet = keyframeSet;
mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet;
if (property instanceof FloatProperty) {
mFloatProperty = (FloatProperty) mProperty;
}
}
public FloatPropertyValuesHolder(String propertyName, float... values) {
super(propertyName);
setFloatValues(values);
}
public FloatPropertyValuesHolder(Property property, float... values) {
super(property);
setFloatValues(values);
if (property instanceof FloatProperty) {
mFloatProperty = (FloatProperty) mProperty;
}
}
@Override
public void setFloatValues(float... values) {
super.setFloatValues(values);
mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet;
}
@Override
void calculateValue(float fraction) {
mFloatAnimatedValue = mFloatKeyframeSet.getFloatValue(fraction);
}
@Override
Object getAnimatedValue() {
return mFloatAnimatedValue;
}
@Override
public FloatPropertyValuesHolder clone() {
FloatPropertyValuesHolder newPVH = (FloatPropertyValuesHolder) super.clone();
newPVH.mFloatKeyframeSet = (FloatKeyframeSet) newPVH.mKeyframeSet;
return newPVH;
}
/**
* Internal function to set the value on the target object, using the setter set up
* earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator
* to handle turning the value calculated by ValueAnimator into a value set on the object
* according to the name of the property.
* @param target The target object on which the value is set
*/
@Override
void setAnimatedValue(Object target) {
if (mFloatProperty != null) {
mFloatProperty.setValue(target, mFloatAnimatedValue);
return;
}
if (mProperty != null) {
mProperty.set(target, mFloatAnimatedValue);
return;
}
//if (mJniSetter != 0) {
// nCallFloatMethod(target, mJniSetter, mFloatAnimatedValue);
// return;
//}
if (mSetter != null) {
try {
mTmpValueArray[0] = mFloatAnimatedValue;
mSetter.invoke(target, mTmpValueArray);
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
}
@Override
void setupSetter(Class targetClass) {
if (mProperty != null) {
return;
}
// Check new static hashmap<propName, int> for setter method
//try {
// mPropertyMapLock.writeLock().lock();
// HashMap<String, Integer> propertyMap = sJNISetterPropertyMap.get(targetClass);
// if (propertyMap != null) {
// Integer mJniSetterInteger = propertyMap.get(mPropertyName);
// if (mJniSetterInteger != null) {
// mJniSetter = mJniSetterInteger;
// }
// }
// if (mJniSetter == 0) {
// String methodName = getMethodName("set", mPropertyName);
// mJniSetter = nGetFloatMethod(targetClass, methodName);
// if (mJniSetter != 0) {
// if (propertyMap == null) {
// propertyMap = new HashMap<String, Integer>();
// sJNISetterPropertyMap.put(targetClass, propertyMap);
// }
// propertyMap.put(mPropertyName, mJniSetter);
// }
// }
//} catch (NoSuchMethodError e) {
// Log.d("PropertyValuesHolder",
// "Can't find native method using JNI, use reflection" + e);
//} finally {
// mPropertyMapLock.writeLock().unlock();
//}
//if (mJniSetter == 0) {
// Couldn't find method through fast JNI approach - just use reflection
super.setupSetter(targetClass);
//}
}
}
//native static private int nGetIntMethod(Class targetClass, String methodName);
//native static private int nGetFloatMethod(Class targetClass, String methodName);
//native static private void nCallIntMethod(Object target, int methodID, int arg);
//native static private void nCallFloatMethod(Object target, int methodID, float arg);
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
/**
* This evaluator can be used to perform type interpolation between <code>float</code> values.
*/
public class FloatEvaluator implements TypeEvaluator<Number> {
/**
* This function returns the result of linearly interpolating the start and end values, with
* <code>fraction</code> representing the proportion between the start and end values. The
* calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>,
* where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,
* and <code>t</code> is <code>fraction</code>.
*
* @param fraction The fraction from the starting to the ending values
* @param startValue The start value; should be of type <code>float</code> or
* <code>Float</code>
* @param endValue The end value; should be of type <code>float</code> or <code>Float</code>
* @return A linear interpolation between the start and end values, given the
* <code>fraction</code> parameter.
*/
public Float evaluate(float fraction, Number startValue, Number endValue) {
float startFloat = startValue.floatValue();
return startFloat + fraction * (endValue.floatValue() - startFloat);
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Keyframe.FloatKeyframe;
import java.util.ArrayList;
/**
* This class holds a collection of FloatKeyframe objects and is called by ValueAnimator to calculate
* values between those keyframes for a given animation. The class internal to the animation
* package because it is an implementation detail of how Keyframes are stored and used.
*
* <p>This type-specific subclass of KeyframeSet, along with the other type-specific subclass for
* int, exists to speed up the getValue() method when there is no custom
* TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the
* Object equivalents of these primitive types.</p>
*/
class FloatKeyframeSet extends KeyframeSet {
private float firstValue;
private float lastValue;
private float deltaValue;
private boolean firstTime = true;
public FloatKeyframeSet(FloatKeyframe... keyframes) {
super(keyframes);
}
@Override
public Object getValue(float fraction) {
return getFloatValue(fraction);
}
@Override
public FloatKeyframeSet clone() {
ArrayList<Keyframe> keyframes = mKeyframes;
int numKeyframes = mKeyframes.size();
FloatKeyframe[] newKeyframes = new FloatKeyframe[numKeyframes];
for (int i = 0; i < numKeyframes; ++i) {
newKeyframes[i] = (FloatKeyframe) keyframes.get(i).clone();
}
FloatKeyframeSet newSet = new FloatKeyframeSet(newKeyframes);
return newSet;
}
public float getFloatValue(float fraction) {
if (mNumKeyframes == 2) {
if (firstTime) {
firstTime = false;
firstValue = ((FloatKeyframe) mKeyframes.get(0)).getFloatValue();
lastValue = ((FloatKeyframe) mKeyframes.get(1)).getFloatValue();
deltaValue = lastValue - firstValue;
}
if (mInterpolator != null) {
fraction = mInterpolator.getInterpolation(fraction);
}
if (mEvaluator == null) {
return firstValue + fraction * deltaValue;
} else {
return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).floatValue();
}
}
if (fraction <= 0f) {
final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0);
final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(1);
float prevValue = prevKeyframe.getFloatValue();
float nextValue = nextKeyframe.getFloatValue();
float prevFraction = prevKeyframe.getFraction();
float nextFraction = nextKeyframe.getFraction();
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction);
return mEvaluator == null ?
prevValue + intervalFraction * (nextValue - prevValue) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).
floatValue();
} else if (fraction >= 1f) {
final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 2);
final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 1);
float prevValue = prevKeyframe.getFloatValue();
float nextValue = nextKeyframe.getFloatValue();
float prevFraction = prevKeyframe.getFraction();
float nextFraction = nextKeyframe.getFraction();
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction);
return mEvaluator == null ?
prevValue + intervalFraction * (nextValue - prevValue) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).
floatValue();
}
FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0);
for (int i = 1; i < mNumKeyframes; ++i) {
FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(i);
if (fraction < nextKeyframe.getFraction()) {
final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
float intervalFraction = (fraction - prevKeyframe.getFraction()) /
(nextKeyframe.getFraction() - prevKeyframe.getFraction());
float prevValue = prevKeyframe.getFloatValue();
float nextValue = nextKeyframe.getFloatValue();
return mEvaluator == null ?
prevValue + intervalFraction * (nextValue - prevValue) :
((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).
floatValue();
}
prevKeyframe = nextKeyframe;
}
// shouldn't get here
return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).floatValue();
}
}
| Java |
package com.nineoldandroids.animation;
import android.view.View;
import com.nineoldandroids.util.FloatProperty;
import com.nineoldandroids.util.IntProperty;
import com.nineoldandroids.util.Property;
import com.nineoldandroids.view.animation.AnimatorProxy;
final class PreHoneycombCompat {
static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setAlpha(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getAlpha();
}
};
static Property<View, Float> PIVOT_X = new FloatProperty<View>("pivotX") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setPivotX(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getPivotX();
}
};
static Property<View, Float> PIVOT_Y = new FloatProperty<View>("pivotY") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setPivotY(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getPivotY();
}
};
static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setTranslationX(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getTranslationX();
}
};
static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setTranslationY(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getTranslationY();
}
};
static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setRotation(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getRotation();
}
};
static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setRotationX(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getRotationX();
}
};
static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setRotationY(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getRotationY();
}
};
static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setScaleX(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getScaleX();
}
};
static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setScaleY(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getScaleY();
}
};
static Property<View, Integer> SCROLL_X = new IntProperty<View>("scrollX") {
@Override
public void setValue(View object, int value) {
AnimatorProxy.wrap(object).setScrollX(value);
}
@Override
public Integer get(View object) {
return AnimatorProxy.wrap(object).getScrollX();
}
};
static Property<View, Integer> SCROLL_Y = new IntProperty<View>("scrollY") {
@Override
public void setValue(View object, int value) {
AnimatorProxy.wrap(object).setScrollY(value);
}
@Override
public Integer get(View object) {
return AnimatorProxy.wrap(object).getScrollY();
}
};
static Property<View, Float> X = new FloatProperty<View>("x") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setX(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getX();
}
};
static Property<View, Float> Y = new FloatProperty<View>("y") {
@Override
public void setValue(View object, float value) {
AnimatorProxy.wrap(object).setY(value);
}
@Override
public Float get(View object) {
return AnimatorProxy.wrap(object).getY();
}
};
//No instances
private PreHoneycombCompat() {}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.animation;
/**
* Interface for use with the {@link ValueAnimator#setEvaluator(TypeEvaluator)} function. Evaluators
* allow developers to create animations on arbitrary property types, by allowing them to supply
* custom evaulators for types that are not automatically understood and used by the animation
* system.
*
* @see ValueAnimator#setEvaluator(TypeEvaluator)
*/
public interface TypeEvaluator<T> {
/**
* This function returns the result of linearly interpolating the start and end values, with
* <code>fraction</code> representing the proportion between the start and end values. The
* calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>,
* where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,
* and <code>t</code> is <code>fraction</code>.
*
* @param fraction The fraction from the starting to the ending values
* @param startValue The start value.
* @param endValue The end value.
* @return A linear interpolation between the start and end values, given the
* <code>fraction</code> parameter.
*/
public T evaluate(float fraction, T startValue, T endValue);
} | Java |
package com.nineoldandroids.view.animation;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Build;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
/**
* A proxy class to allow for modifying post-3.0 view properties on all pre-3.0
* platforms. <strong>DO NOT</strong> wrap your views with this class if you
* are using {@code ObjectAnimator} as it will handle that itself.
*/
public final class AnimatorProxy extends Animation {
/** Whether or not the current running platform needs to be proxied. */
public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK).intValue() < Build.VERSION_CODES.HONEYCOMB;
private static final WeakHashMap<View, AnimatorProxy> PROXIES =
new WeakHashMap<View, AnimatorProxy>();
/**
* Create a proxy to allow for modifying post-3.0 view properties on all
* pre-3.0 platforms. <strong>DO NOT</strong> wrap your views if you are
* using {@code ObjectAnimator} as it will handle that itself.
*
* @param view View to wrap.
* @return Proxy to post-3.0 properties.
*/
public static AnimatorProxy wrap(View view) {
AnimatorProxy proxy = PROXIES.get(view);
// This checks if the proxy already exists and whether it still is the animation of the given view
if (proxy == null || proxy != view.getAnimation()) {
proxy = new AnimatorProxy(view);
PROXIES.put(view, proxy);
}
return proxy;
}
private final WeakReference<View> mView;
private final Camera mCamera = new Camera();
private boolean mHasPivot;
private float mAlpha = 1;
private float mPivotX;
private float mPivotY;
private float mRotationX;
private float mRotationY;
private float mRotationZ;
private float mScaleX = 1;
private float mScaleY = 1;
private float mTranslationX;
private float mTranslationY;
private final RectF mBefore = new RectF();
private final RectF mAfter = new RectF();
private final Matrix mTempMatrix = new Matrix();
private AnimatorProxy(View view) {
setDuration(0); //perform transformation immediately
setFillAfter(true); //persist transformation beyond duration
view.setAnimation(this);
mView = new WeakReference<View>(view);
}
public float getAlpha() {
return mAlpha;
}
public void setAlpha(float alpha) {
if (mAlpha != alpha) {
mAlpha = alpha;
View view = mView.get();
if (view != null) {
view.invalidate();
}
}
}
public float getPivotX() {
return mPivotX;
}
public void setPivotX(float pivotX) {
if (!mHasPivot || mPivotX != pivotX) {
prepareForUpdate();
mHasPivot = true;
mPivotX = pivotX;
invalidateAfterUpdate();
}
}
public float getPivotY() {
return mPivotY;
}
public void setPivotY(float pivotY) {
if (!mHasPivot || mPivotY != pivotY) {
prepareForUpdate();
mHasPivot = true;
mPivotY = pivotY;
invalidateAfterUpdate();
}
}
public float getRotation() {
return mRotationZ;
}
public void setRotation(float rotation) {
if (mRotationZ != rotation) {
prepareForUpdate();
mRotationZ = rotation;
invalidateAfterUpdate();
}
}
public float getRotationX() {
return mRotationX;
}
public void setRotationX(float rotationX) {
if (mRotationX != rotationX) {
prepareForUpdate();
mRotationX = rotationX;
invalidateAfterUpdate();
}
}
public float getRotationY() {
return mRotationY;
}
public void setRotationY(float rotationY) {
if (mRotationY != rotationY) {
prepareForUpdate();
mRotationY = rotationY;
invalidateAfterUpdate();
}
}
public float getScaleX() {
return mScaleX;
}
public void setScaleX(float scaleX) {
if (mScaleX != scaleX) {
prepareForUpdate();
mScaleX = scaleX;
invalidateAfterUpdate();
}
}
public float getScaleY() {
return mScaleY;
}
public void setScaleY(float scaleY) {
if (mScaleY != scaleY) {
prepareForUpdate();
mScaleY = scaleY;
invalidateAfterUpdate();
}
}
public int getScrollX() {
View view = mView.get();
if (view == null) {
return 0;
}
return view.getScrollX();
}
public void setScrollX(int value) {
View view = mView.get();
if (view != null) {
view.scrollTo(value, view.getScrollY());
}
}
public int getScrollY() {
View view = mView.get();
if (view == null) {
return 0;
}
return view.getScrollY();
}
public void setScrollY(int value) {
View view = mView.get();
if (view != null) {
view.scrollTo(view.getScrollX(), value);
}
}
public float getTranslationX() {
return mTranslationX;
}
public void setTranslationX(float translationX) {
if (mTranslationX != translationX) {
prepareForUpdate();
mTranslationX = translationX;
invalidateAfterUpdate();
}
}
public float getTranslationY() {
return mTranslationY;
}
public void setTranslationY(float translationY) {
if (mTranslationY != translationY) {
prepareForUpdate();
mTranslationY = translationY;
invalidateAfterUpdate();
}
}
public float getX() {
View view = mView.get();
if (view == null) {
return 0;
}
return view.getLeft() + mTranslationX;
}
public void setX(float x) {
View view = mView.get();
if (view != null) {
setTranslationX(x - view.getLeft());
}
}
public float getY() {
View view = mView.get();
if (view == null) {
return 0;
}
return view.getTop() + mTranslationY;
}
public void setY(float y) {
View view = mView.get();
if (view != null) {
setTranslationY(y - view.getTop());
}
}
private void prepareForUpdate() {
View view = mView.get();
if (view != null) {
computeRect(mBefore, view);
}
}
private void invalidateAfterUpdate() {
View view = mView.get();
if (view == null || view.getParent() == null) {
return;
}
final RectF after = mAfter;
computeRect(after, view);
after.union(mBefore);
((View)view.getParent()).invalidate(
(int) Math.floor(after.left),
(int) Math.floor(after.top),
(int) Math.ceil(after.right),
(int) Math.ceil(after.bottom));
}
private void computeRect(final RectF r, View view) {
// compute current rectangle according to matrix transformation
final float w = view.getWidth();
final float h = view.getHeight();
// use a rectangle at 0,0 to make sure we don't run into issues with scaling
r.set(0, 0, w, h);
final Matrix m = mTempMatrix;
m.reset();
transformMatrix(m, view);
mTempMatrix.mapRect(r);
r.offset(view.getLeft(), view.getTop());
// Straighten coords if rotations flipped them
if (r.right < r.left) {
final float f = r.right;
r.right = r.left;
r.left = f;
}
if (r.bottom < r.top) {
final float f = r.top;
r.top = r.bottom;
r.bottom = f;
}
}
private void transformMatrix(Matrix m, View view) {
final float w = view.getWidth();
final float h = view.getHeight();
final boolean hasPivot = mHasPivot;
final float pX = hasPivot ? mPivotX : w / 2f;
final float pY = hasPivot ? mPivotY : h / 2f;
final float rX = mRotationX;
final float rY = mRotationY;
final float rZ = mRotationZ;
if ((rX != 0) || (rY != 0) || (rZ != 0)) {
final Camera camera = mCamera;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = mScaleX;
final float sY = mScaleY;
if ((sX != 1.0f) || (sY != 1.0f)) {
m.postScale(sX, sY);
final float sPX = -(pX / w) * ((sX * w) - w);
final float sPY = -(pY / h) * ((sY * h) - h);
m.postTranslate(sPX, sPY);
}
m.postTranslate(mTranslationX, mTranslationY);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
View view = mView.get();
if (view != null) {
t.setAlpha(mAlpha);
transformMatrix(t.getMatrix(), view);
}
}
}
| Java |
package com.nineoldandroids.view;
import java.lang.ref.WeakReference;
import android.view.View;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
class ViewPropertyAnimatorICS extends ViewPropertyAnimator {
/**
* A value to be returned when the WeakReference holding the native implementation
* returns <code>null</code>
*/
private final static long RETURN_WHEN_NULL = -1L;
/**
* A WeakReference holding the native implementation of ViewPropertyAnimator
*/
private final WeakReference<android.view.ViewPropertyAnimator> mNative;
ViewPropertyAnimatorICS(View view) {
mNative = new WeakReference<android.view.ViewPropertyAnimator>(view.animate());
}
@Override
public ViewPropertyAnimator setDuration(long duration) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.setDuration(duration);
}
return this;
}
@Override
public long getDuration() {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
return n.getDuration();
}
return RETURN_WHEN_NULL;
}
@Override
public ViewPropertyAnimator setStartDelay(long startDelay) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.setStartDelay(startDelay);
}
return this;
}
@Override
public long getStartDelay() {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
return n.getStartDelay();
}
return RETURN_WHEN_NULL;
}
@Override
public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.setInterpolator(interpolator);
}
return this;
}
@Override
public ViewPropertyAnimator setListener(final AnimatorListener listener) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
if (listener == null) {
n.setListener(null);
} else {
n.setListener(new android.animation.Animator.AnimatorListener() {
@Override
public void onAnimationStart(android.animation.Animator animation) {
listener.onAnimationStart(null);
}
@Override
public void onAnimationRepeat(android.animation.Animator animation) {
listener.onAnimationRepeat(null);
}
@Override
public void onAnimationEnd(android.animation.Animator animation) {
listener.onAnimationEnd(null);
}
@Override
public void onAnimationCancel(android.animation.Animator animation) {
listener.onAnimationCancel(null);
}
});
}
}
return this;
}
@Override
public void start() {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.start();
}
}
@Override
public void cancel() {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.cancel();
}
}
@Override
public ViewPropertyAnimator x(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.x(value);
}
return this;
}
@Override
public ViewPropertyAnimator xBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.xBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator y(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.y(value);
}
return this;
}
@Override
public ViewPropertyAnimator yBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.yBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotation(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotation(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotationBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotationBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotationX(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotationX(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotationXBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotationXBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotationY(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotationY(value);
}
return this;
}
@Override
public ViewPropertyAnimator rotationYBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.rotationYBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator translationX(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.translationX(value);
}
return this;
}
@Override
public ViewPropertyAnimator translationXBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.translationXBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator translationY(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.translationY(value);
}
return this;
}
@Override
public ViewPropertyAnimator translationYBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.translationYBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator scaleX(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.scaleX(value);
}
return this;
}
@Override
public ViewPropertyAnimator scaleXBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.scaleXBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator scaleY(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.scaleY(value);
}
return this;
}
@Override
public ViewPropertyAnimator scaleYBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.scaleYBy(value);
}
return this;
}
@Override
public ViewPropertyAnimator alpha(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.alpha(value);
}
return this;
}
@Override
public ViewPropertyAnimator alphaBy(float value) {
android.view.ViewPropertyAnimator n = mNative.get();
if (n != null) {
n.alphaBy(value);
}
return this;
}
}
| Java |
package com.nineoldandroids.view;
import android.view.View;
import static com.nineoldandroids.view.animation.AnimatorProxy.NEEDS_PROXY;
import static com.nineoldandroids.view.animation.AnimatorProxy.wrap;
public final class ViewHelper {
private ViewHelper() {}
public static float getAlpha(View view) {
return NEEDS_PROXY ? wrap(view).getAlpha() : Honeycomb.getAlpha(view);
}
public static void setAlpha(View view, float alpha) {
if (NEEDS_PROXY) {
wrap(view).setAlpha(alpha);
} else {
Honeycomb.setAlpha(view, alpha);
}
}
public static float getPivotX(View view) {
return NEEDS_PROXY ? wrap(view).getPivotX() : Honeycomb.getPivotX(view);
}
public static void setPivotX(View view, float pivotX) {
if (NEEDS_PROXY) {
wrap(view).setPivotX(pivotX);
} else {
Honeycomb.setPivotX(view, pivotX);
}
}
public static float getPivotY(View view) {
return NEEDS_PROXY ? wrap(view).getPivotY() : Honeycomb.getPivotY(view);
}
public static void setPivotY(View view, float pivotY) {
if (NEEDS_PROXY) {
wrap(view).setPivotY(pivotY);
} else {
Honeycomb.setPivotY(view, pivotY);
}
}
public static float getRotation(View view) {
return NEEDS_PROXY ? wrap(view).getRotation() : Honeycomb.getRotation(view);
}
public static void setRotation(View view, float rotation) {
if (NEEDS_PROXY) {
wrap(view).setRotation(rotation);
} else {
Honeycomb.setRotation(view, rotation);
}
}
public static float getRotationX(View view) {
return NEEDS_PROXY ? wrap(view).getRotationX() : Honeycomb.getRotationX(view);
}
public static void setRotationX(View view, float rotationX) {
if (NEEDS_PROXY) {
wrap(view).setRotationX(rotationX);
} else {
Honeycomb.setRotationX(view, rotationX);
}
}
public static float getRotationY(View view) {
return NEEDS_PROXY ? wrap(view).getRotationY() : Honeycomb.getRotationY(view);
}
public static void setRotationY(View view, float rotationY) {
if (NEEDS_PROXY) {
wrap(view).setRotationY(rotationY);
} else {
Honeycomb.setRotationY(view, rotationY);
}
}
public static float getScaleX(View view) {
return NEEDS_PROXY ? wrap(view).getScaleX() : Honeycomb.getScaleX(view);
}
public static void setScaleX(View view, float scaleX) {
if (NEEDS_PROXY) {
wrap(view).setScaleX(scaleX);
} else {
Honeycomb.setScaleX(view, scaleX);
}
}
public static float getScaleY(View view) {
return NEEDS_PROXY ? wrap(view).getScaleY() : Honeycomb.getScaleY(view);
}
public static void setScaleY(View view, float scaleY) {
if (NEEDS_PROXY) {
wrap(view).setScaleY(scaleY);
} else {
Honeycomb.setScaleY(view, scaleY);
}
}
public static float getScrollX(View view) {
return NEEDS_PROXY ? wrap(view).getScrollX() : Honeycomb.getScrollX(view);
}
public static void setScrollX(View view, int scrollX) {
if (NEEDS_PROXY) {
wrap(view).setScrollX(scrollX);
} else {
Honeycomb.setScrollX(view, scrollX);
}
}
public static float getScrollY(View view) {
return NEEDS_PROXY ? wrap(view).getScrollY() : Honeycomb.getScrollY(view);
}
public static void setScrollY(View view, int scrollY) {
if (NEEDS_PROXY) {
wrap(view).setScrollY(scrollY);
} else {
Honeycomb.setScrollY(view, scrollY);
}
}
public static float getTranslationX(View view) {
return NEEDS_PROXY ? wrap(view).getTranslationX() : Honeycomb.getTranslationX(view);
}
public static void setTranslationX(View view, float translationX) {
if (NEEDS_PROXY) {
wrap(view).setTranslationX(translationX);
} else {
Honeycomb.setTranslationX(view, translationX);
}
}
public static float getTranslationY(View view) {
return NEEDS_PROXY ? wrap(view).getTranslationY() : Honeycomb.getTranslationY(view);
}
public static void setTranslationY(View view, float translationY) {
if (NEEDS_PROXY) {
wrap(view).setTranslationY(translationY);
} else {
Honeycomb.setTranslationY(view, translationY);
}
}
public static float getX(View view) {
return NEEDS_PROXY ? wrap(view).getX() : Honeycomb.getX(view);
}
public static void setX(View view, float x) {
if (NEEDS_PROXY) {
wrap(view).setX(x);
} else {
Honeycomb.setX(view, x);
}
}
public static float getY(View view) {
return NEEDS_PROXY ? wrap(view).getY() : Honeycomb.getY(view);
}
public static void setY(View view, float y) {
if (NEEDS_PROXY) {
wrap(view).setY(y);
} else {
Honeycomb.setY(view, y);
}
}
private static final class Honeycomb {
static float getAlpha(View view) {
return view.getAlpha();
}
static void setAlpha(View view, float alpha) {
view.setAlpha(alpha);
}
static float getPivotX(View view) {
return view.getPivotX();
}
static void setPivotX(View view, float pivotX) {
view.setPivotX(pivotX);
}
static float getPivotY(View view) {
return view.getPivotY();
}
static void setPivotY(View view, float pivotY) {
view.setPivotY(pivotY);
}
static float getRotation(View view) {
return view.getRotation();
}
static void setRotation(View view, float rotation) {
view.setRotation(rotation);
}
static float getRotationX(View view) {
return view.getRotationX();
}
static void setRotationX(View view, float rotationX) {
view.setRotationX(rotationX);
}
static float getRotationY(View view) {
return view.getRotationY();
}
static void setRotationY(View view, float rotationY) {
view.setRotationY(rotationY);
}
static float getScaleX(View view) {
return view.getScaleX();
}
static void setScaleX(View view, float scaleX) {
view.setScaleX(scaleX);
}
static float getScaleY(View view) {
return view.getScaleY();
}
static void setScaleY(View view, float scaleY) {
view.setScaleY(scaleY);
}
static float getScrollX(View view) {
return view.getScrollX();
}
static void setScrollX(View view, int scrollX) {
view.setScrollX(scrollX);
}
static float getScrollY(View view) {
return view.getScrollY();
}
static void setScrollY(View view, int scrollY) {
view.setScrollY(scrollY);
}
static float getTranslationX(View view) {
return view.getTranslationX();
}
static void setTranslationX(View view, float translationX) {
view.setTranslationX(translationX);
}
static float getTranslationY(View view) {
return view.getTranslationY();
}
static void setTranslationY(View view, float translationY) {
view.setTranslationY(translationY);
}
static float getX(View view) {
return view.getX();
}
static void setX(View view, float x) {
view.setX(x);
}
static float getY(View view) {
return view.getY();
}
static void setY(View view, float y) {
view.setY(y);
}
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.view;
import java.util.WeakHashMap;
import android.os.Build;
import android.view.View;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Animator;
/**
* This class enables automatic and optimized animation of select properties on View objects.
* If only one or two properties on a View object are being animated, then using an
* {@link android.animation.ObjectAnimator} is fine; the property setters called by ObjectAnimator
* are well equipped to do the right thing to set the property and invalidate the view
* appropriately. But if several properties are animated simultaneously, or if you just want a
* more convenient syntax to animate a specific property, then ViewPropertyAnimator might be
* more well-suited to the task.
*
* <p>This class may provide better performance for several simultaneous animations, because
* it will optimize invalidate calls to take place only once for several properties instead of each
* animated property independently causing its own invalidation. Also, the syntax of using this
* class could be easier to use because the caller need only tell the View object which
* property to animate, and the value to animate either to or by, and this class handles the
* details of configuring the underlying Animator class and starting it.</p>
*
* <p>This class is not constructed by the caller, but rather by the View whose properties
* it will animate. Calls to {@link android.view.View#animate()} will return a reference
* to the appropriate ViewPropertyAnimator object for that View.</p>
*
*/
public abstract class ViewPropertyAnimator {
private static final WeakHashMap<View, ViewPropertyAnimator> ANIMATORS =
new WeakHashMap<View, ViewPropertyAnimator>(0);
/**
* This method returns a ViewPropertyAnimator object, which can be used to animate specific
* properties on this View.
*
* @param view View to animate.
* @return The ViewPropertyAnimator associated with this View.
*/
public static ViewPropertyAnimator animate(View view) {
ViewPropertyAnimator animator = ANIMATORS.get(view);
if (animator == null) {
final int version = Integer.valueOf(Build.VERSION.SDK);
if (version >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
animator = new ViewPropertyAnimatorICS(view);
} else if (version >= Build.VERSION_CODES.HONEYCOMB) {
animator = new ViewPropertyAnimatorHC(view);
} else {
animator = new ViewPropertyAnimatorPreHC(view);
}
ANIMATORS.put(view, animator);
}
return animator;
}
/**
* Sets the duration for the underlying animator that animates the requested properties.
* By default, the animator uses the default value for ValueAnimator. Calling this method
* will cause the declared value to be used instead.
* @param duration The length of ensuing property animations, in milliseconds. The value
* cannot be negative.
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator setDuration(long duration);
/**
* Returns the current duration of property animations. If the duration was set on this
* object, that value is returned. Otherwise, the default value of the underlying Animator
* is returned.
*
* @see #setDuration(long)
* @return The duration of animations, in milliseconds.
*/
public abstract long getDuration();
/**
* Returns the current startDelay of property animations. If the startDelay was set on this
* object, that value is returned. Otherwise, the default value of the underlying Animator
* is returned.
*
* @see #setStartDelay(long)
* @return The startDelay of animations, in milliseconds.
*/
public abstract long getStartDelay();
/**
* Sets the startDelay for the underlying animator that animates the requested properties.
* By default, the animator uses the default value for ValueAnimator. Calling this method
* will cause the declared value to be used instead.
* @param startDelay The delay of ensuing property animations, in milliseconds. The value
* cannot be negative.
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator setStartDelay(long startDelay);
/**
* Sets the interpolator for the underlying animator that animates the requested properties.
* By default, the animator uses the default interpolator for ValueAnimator. Calling this method
* will cause the declared object to be used instead.
*
* @param interpolator The TimeInterpolator to be used for ensuing property animations.
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator setInterpolator(/*Time*/Interpolator interpolator);
/**
* Sets a listener for events in the underlying Animators that run the property
* animations.
*
* @param listener The listener to be called with AnimatorListener events.
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator setListener(Animator.AnimatorListener listener);
/**
* Starts the currently pending property animations immediately. Calling <code>start()</code>
* is optional because all animations start automatically at the next opportunity. However,
* if the animations are needed to start immediately and synchronously (not at the time when
* the next event is processed by the hierarchy, which is when the animations would begin
* otherwise), then this method can be used.
*/
public abstract void start();
/**
* Cancels all property animations that are currently running or pending.
*/
public abstract void cancel();
/**
* This method will cause the View's <code>x</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator x(float value);
/**
* This method will cause the View's <code>x</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator xBy(float value);
/**
* This method will cause the View's <code>y</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator y(float value);
/**
* This method will cause the View's <code>y</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator yBy(float value);
/**
* This method will cause the View's <code>rotation</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotation(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotation(float value);
/**
* This method will cause the View's <code>rotation</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotation(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotationBy(float value);
/**
* This method will cause the View's <code>rotationX</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotationX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotationX(float value);
/**
* This method will cause the View's <code>rotationX</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotationX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotationXBy(float value);
/**
* This method will cause the View's <code>rotationY</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotationY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotationY(float value);
/**
* This method will cause the View's <code>rotationY</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotationY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator rotationYBy(float value);
/**
* This method will cause the View's <code>translationX</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setTranslationX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator translationX(float value);
/**
* This method will cause the View's <code>translationX</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setTranslationX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator translationXBy(float value);
/**
* This method will cause the View's <code>translationY</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setTranslationY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator translationY(float value);
/**
* This method will cause the View's <code>translationY</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setTranslationY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator translationYBy(float value);
/**
* This method will cause the View's <code>scaleX</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setScaleX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator scaleX(float value);
/**
* This method will cause the View's <code>scaleX</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setScaleX(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator scaleXBy(float value);
/**
* This method will cause the View's <code>scaleY</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setScaleY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator scaleY(float value);
/**
* This method will cause the View's <code>scaleY</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setScaleY(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator scaleYBy(float value);
/**
* This method will cause the View's <code>alpha</code> property to be animated to the
* specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setAlpha(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator alpha(float value);
/**
* This method will cause the View's <code>alpha</code> property to be animated by the
* specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setAlpha(float)
* @return This object, allowing calls to methods in this class to be chained.
*/
public abstract ViewPropertyAnimator alphaBy(float value);
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.view;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import android.view.View;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.animation.AnimatorProxy;
class ViewPropertyAnimatorPreHC extends ViewPropertyAnimator {
/**
* Proxy animation class which will allow us access to post-Honeycomb properties that were not
* otherwise available.
*/
private final AnimatorProxy mProxy;
/**
* A WeakReference holding the View whose properties are being animated by this class. This is
* set at construction time.
*/
private final WeakReference<View> mView;
/**
* The duration of the underlying Animator object. By default, we don't set the duration
* on the Animator and just use its default duration. If the duration is ever set on this
* Animator, then we use the duration that it was set to.
*/
private long mDuration;
/**
* A flag indicating whether the duration has been set on this object. If not, we don't set
* the duration on the underlying Animator, but instead just use its default duration.
*/
private boolean mDurationSet = false;
/**
* The startDelay of the underlying Animator object. By default, we don't set the startDelay
* on the Animator and just use its default startDelay. If the startDelay is ever set on this
* Animator, then we use the startDelay that it was set to.
*/
private long mStartDelay = 0;
/**
* A flag indicating whether the startDelay has been set on this object. If not, we don't set
* the startDelay on the underlying Animator, but instead just use its default startDelay.
*/
private boolean mStartDelaySet = false;
/**
* The interpolator of the underlying Animator object. By default, we don't set the interpolator
* on the Animator and just use its default interpolator. If the interpolator is ever set on
* this Animator, then we use the interpolator that it was set to.
*/
private /*Time*/Interpolator mInterpolator;
/**
* A flag indicating whether the interpolator has been set on this object. If not, we don't set
* the interpolator on the underlying Animator, but instead just use its default interpolator.
*/
private boolean mInterpolatorSet = false;
/**
* Listener for the lifecycle events of the underlying
*/
private Animator.AnimatorListener mListener = null;
/**
* This listener is the mechanism by which the underlying Animator causes changes to the
* properties currently being animated, as well as the cleanup after an animation is
* complete.
*/
private AnimatorEventListener mAnimatorEventListener = new AnimatorEventListener();
/**
* This list holds the properties that have been asked to animate. We allow the caller to
* request several animations prior to actually starting the underlying animator. This
* enables us to run one single animator to handle several properties in parallel. Each
* property is tossed onto the pending list until the animation actually starts (which is
* done by posting it onto mView), at which time the pending list is cleared and the properties
* on that list are added to the list of properties associated with that animator.
*/
ArrayList<NameValuesHolder> mPendingAnimations = new ArrayList<NameValuesHolder>();
/**
* Constants used to associate a property being requested and the mechanism used to set
* the property (this class calls directly into View to set the properties in question).
*/
private static final int NONE = 0x0000;
private static final int TRANSLATION_X = 0x0001;
private static final int TRANSLATION_Y = 0x0002;
private static final int SCALE_X = 0x0004;
private static final int SCALE_Y = 0x0008;
private static final int ROTATION = 0x0010;
private static final int ROTATION_X = 0x0020;
private static final int ROTATION_Y = 0x0040;
private static final int X = 0x0080;
private static final int Y = 0x0100;
private static final int ALPHA = 0x0200;
private static final int TRANSFORM_MASK = TRANSLATION_X | TRANSLATION_Y | SCALE_X | SCALE_Y |
ROTATION | ROTATION_X | ROTATION_Y | X | Y;
/**
* The mechanism by which the user can request several properties that are then animated
* together works by posting this Runnable to start the underlying Animator. Every time
* a property animation is requested, we cancel any previous postings of the Runnable
* and re-post it. This means that we will only ever run the Runnable (and thus start the
* underlying animator) after the caller is done setting the properties that should be
* animated together.
*/
private Runnable mAnimationStarter = new Runnable() {
@Override
public void run() {
startAnimation();
}
};
/**
* This class holds information about the overall animation being run on the set of
* properties. The mask describes which properties are being animated and the
* values holder is the list of all property/value objects.
*/
private static class PropertyBundle {
int mPropertyMask;
ArrayList<NameValuesHolder> mNameValuesHolder;
PropertyBundle(int propertyMask, ArrayList<NameValuesHolder> nameValuesHolder) {
mPropertyMask = propertyMask;
mNameValuesHolder = nameValuesHolder;
}
/**
* Removes the given property from being animated as a part of this
* PropertyBundle. If the property was a part of this bundle, it returns
* true to indicate that it was, in fact, canceled. This is an indication
* to the caller that a cancellation actually occurred.
*
* @param propertyConstant The property whose cancellation is requested.
* @return true if the given property is a part of this bundle and if it
* has therefore been canceled.
*/
boolean cancel(int propertyConstant) {
if ((mPropertyMask & propertyConstant) != 0 && mNameValuesHolder != null) {
int count = mNameValuesHolder.size();
for (int i = 0; i < count; ++i) {
NameValuesHolder nameValuesHolder = mNameValuesHolder.get(i);
if (nameValuesHolder.mNameConstant == propertyConstant) {
mNameValuesHolder.remove(i);
mPropertyMask &= ~propertyConstant;
return true;
}
}
}
return false;
}
}
/**
* This list tracks the list of properties being animated by any particular animator.
* In most situations, there would only ever be one animator running at a time. But it is
* possible to request some properties to animate together, then while those properties
* are animating, to request some other properties to animate together. The way that
* works is by having this map associate the group of properties being animated with the
* animator handling the animation. On every update event for an Animator, we ask the
* map for the associated properties and set them accordingly.
*/
private HashMap<Animator, PropertyBundle> mAnimatorMap =
new HashMap<Animator, PropertyBundle>();
/**
* This is the information we need to set each property during the animation.
* mNameConstant is used to set the appropriate field in View, and the from/delta
* values are used to calculate the animated value for a given animation fraction
* during the animation.
*/
private static class NameValuesHolder {
int mNameConstant;
float mFromValue;
float mDeltaValue;
NameValuesHolder(int nameConstant, float fromValue, float deltaValue) {
mNameConstant = nameConstant;
mFromValue = fromValue;
mDeltaValue = deltaValue;
}
}
/**
* Constructor, called by View. This is private by design, as the user should only
* get a ViewPropertyAnimator by calling View.animate().
*
* @param view The View associated with this ViewPropertyAnimator
*/
ViewPropertyAnimatorPreHC(View view) {
mView = new WeakReference<View>(view);
mProxy = AnimatorProxy.wrap(view);
}
/**
* Sets the duration for the underlying animator that animates the requested properties.
* By default, the animator uses the default value for ValueAnimator. Calling this method
* will cause the declared value to be used instead.
* @param duration The length of ensuing property animations, in milliseconds. The value
* cannot be negative.
* @return This object, allowing calls to methods in this class to be chained.
*/
public ViewPropertyAnimator setDuration(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
duration);
}
mDurationSet = true;
mDuration = duration;
return this;
}
/**
* Returns the current duration of property animations. If the duration was set on this
* object, that value is returned. Otherwise, the default value of the underlying Animator
* is returned.
*
* @see #setDuration(long)
* @return The duration of animations, in milliseconds.
*/
public long getDuration() {
if (mDurationSet) {
return mDuration;
} else {
// Just return the default from ValueAnimator, since that's what we'd get if
// the value has not been set otherwise
return new ValueAnimator().getDuration();
}
}
@Override
public long getStartDelay() {
if (mStartDelaySet) {
return mStartDelay;
} else {
// Just return the default from ValueAnimator (0), since that's what we'd get if
// the value has not been set otherwise
return 0;
}
}
@Override
public ViewPropertyAnimator setStartDelay(long startDelay) {
if (startDelay < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
startDelay);
}
mStartDelaySet = true;
mStartDelay = startDelay;
return this;
}
@Override
public ViewPropertyAnimator setInterpolator(/*Time*/Interpolator interpolator) {
mInterpolatorSet = true;
mInterpolator = interpolator;
return this;
}
@Override
public ViewPropertyAnimator setListener(Animator.AnimatorListener listener) {
mListener = listener;
return this;
}
@Override
public void start() {
startAnimation();
}
@Override
public void cancel() {
if (mAnimatorMap.size() > 0) {
HashMap<Animator, PropertyBundle> mAnimatorMapCopy =
(HashMap<Animator, PropertyBundle>)mAnimatorMap.clone();
Set<Animator> animatorSet = mAnimatorMapCopy.keySet();
for (Animator runningAnim : animatorSet) {
runningAnim.cancel();
}
}
mPendingAnimations.clear();
View v = mView.get();
if (v != null) {
v.removeCallbacks(mAnimationStarter);
}
}
@Override
public ViewPropertyAnimator x(float value) {
animateProperty(X, value);
return this;
}
@Override
public ViewPropertyAnimator xBy(float value) {
animatePropertyBy(X, value);
return this;
}
@Override
public ViewPropertyAnimator y(float value) {
animateProperty(Y, value);
return this;
}
@Override
public ViewPropertyAnimator yBy(float value) {
animatePropertyBy(Y, value);
return this;
}
@Override
public ViewPropertyAnimator rotation(float value) {
animateProperty(ROTATION, value);
return this;
}
@Override
public ViewPropertyAnimator rotationBy(float value) {
animatePropertyBy(ROTATION, value);
return this;
}
@Override
public ViewPropertyAnimator rotationX(float value) {
animateProperty(ROTATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator rotationXBy(float value) {
animatePropertyBy(ROTATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator rotationY(float value) {
animateProperty(ROTATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator rotationYBy(float value) {
animatePropertyBy(ROTATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator translationX(float value) {
animateProperty(TRANSLATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator translationXBy(float value) {
animatePropertyBy(TRANSLATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator translationY(float value) {
animateProperty(TRANSLATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator translationYBy(float value) {
animatePropertyBy(TRANSLATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator scaleX(float value) {
animateProperty(SCALE_X, value);
return this;
}
@Override
public ViewPropertyAnimator scaleXBy(float value) {
animatePropertyBy(SCALE_X, value);
return this;
}
@Override
public ViewPropertyAnimator scaleY(float value) {
animateProperty(SCALE_Y, value);
return this;
}
@Override
public ViewPropertyAnimator scaleYBy(float value) {
animatePropertyBy(SCALE_Y, value);
return this;
}
@Override
public ViewPropertyAnimator alpha(float value) {
animateProperty(ALPHA, value);
return this;
}
@Override
public ViewPropertyAnimator alphaBy(float value) {
animatePropertyBy(ALPHA, value);
return this;
}
/**
* Starts the underlying Animator for a set of properties. We use a single animator that
* simply runs from 0 to 1, and then use that fractional value to set each property
* value accordingly.
*/
private void startAnimation() {
ValueAnimator animator = ValueAnimator.ofFloat(1.0f);
ArrayList<NameValuesHolder> nameValueList =
(ArrayList<NameValuesHolder>) mPendingAnimations.clone();
mPendingAnimations.clear();
int propertyMask = 0;
int propertyCount = nameValueList.size();
for (int i = 0; i < propertyCount; ++i) {
NameValuesHolder nameValuesHolder = nameValueList.get(i);
propertyMask |= nameValuesHolder.mNameConstant;
}
mAnimatorMap.put(animator, new PropertyBundle(propertyMask, nameValueList));
animator.addUpdateListener(mAnimatorEventListener);
animator.addListener(mAnimatorEventListener);
if (mStartDelaySet) {
animator.setStartDelay(mStartDelay);
}
if (mDurationSet) {
animator.setDuration(mDuration);
}
if (mInterpolatorSet) {
animator.setInterpolator(mInterpolator);
}
animator.start();
}
/**
* Utility function, called by the various x(), y(), etc. methods. This stores the
* constant name for the property along with the from/delta values that will be used to
* calculate and set the property during the animation. This structure is added to the
* pending animations, awaiting the eventual start() of the underlying animator. A
* Runnable is posted to start the animation, and any pending such Runnable is canceled
* (which enables us to end up starting just one animator for all of the properties
* specified at one time).
*
* @param constantName The specifier for the property being animated
* @param toValue The value to which the property will animate
*/
private void animateProperty(int constantName, float toValue) {
float fromValue = getValue(constantName);
float deltaValue = toValue - fromValue;
animatePropertyBy(constantName, fromValue, deltaValue);
}
/**
* Utility function, called by the various xBy(), yBy(), etc. methods. This method is
* just like animateProperty(), except the value is an offset from the property's
* current value, instead of an absolute "to" value.
*
* @param constantName The specifier for the property being animated
* @param byValue The amount by which the property will change
*/
private void animatePropertyBy(int constantName, float byValue) {
float fromValue = getValue(constantName);
animatePropertyBy(constantName, fromValue, byValue);
}
/**
* Utility function, called by animateProperty() and animatePropertyBy(), which handles the
* details of adding a pending animation and posting the request to start the animation.
*
* @param constantName The specifier for the property being animated
* @param startValue The starting value of the property
* @param byValue The amount by which the property will change
*/
private void animatePropertyBy(int constantName, float startValue, float byValue) {
// First, cancel any existing animations on this property
if (mAnimatorMap.size() > 0) {
Animator animatorToCancel = null;
Set<Animator> animatorSet = mAnimatorMap.keySet();
for (Animator runningAnim : animatorSet) {
PropertyBundle bundle = mAnimatorMap.get(runningAnim);
if (bundle.cancel(constantName)) {
// property was canceled - cancel the animation if it's now empty
// Note that it's safe to break out here because every new animation
// on a property will cancel a previous animation on that property, so
// there can only ever be one such animation running.
if (bundle.mPropertyMask == NONE) {
// the animation is no longer changing anything - cancel it
animatorToCancel = runningAnim;
break;
}
}
}
if (animatorToCancel != null) {
animatorToCancel.cancel();
}
}
NameValuesHolder nameValuePair = new NameValuesHolder(constantName, startValue, byValue);
mPendingAnimations.add(nameValuePair);
View v = mView.get();
if (v != null) {
v.removeCallbacks(mAnimationStarter);
v.post(mAnimationStarter);
}
}
/**
* This method handles setting the property values directly in the View object's fields.
* propertyConstant tells it which property should be set, value is the value to set
* the property to.
*
* @param propertyConstant The property to be set
* @param value The value to set the property to
*/
private void setValue(int propertyConstant, float value) {
//final View.TransformationInfo info = mView.mTransformationInfo;
switch (propertyConstant) {
case TRANSLATION_X:
//info.mTranslationX = value;
mProxy.setTranslationX(value);
break;
case TRANSLATION_Y:
//info.mTranslationY = value;
mProxy.setTranslationY(value);
break;
case ROTATION:
//info.mRotation = value;
mProxy.setRotation(value);
break;
case ROTATION_X:
//info.mRotationX = value;
mProxy.setRotationX(value);
break;
case ROTATION_Y:
//info.mRotationY = value;
mProxy.setRotationY(value);
break;
case SCALE_X:
//info.mScaleX = value;
mProxy.setScaleX(value);
break;
case SCALE_Y:
//info.mScaleY = value;
mProxy.setScaleY(value);
break;
case X:
//info.mTranslationX = value - mView.mLeft;
mProxy.setX(value);
break;
case Y:
//info.mTranslationY = value - mView.mTop;
mProxy.setY(value);
break;
case ALPHA:
//info.mAlpha = value;
mProxy.setAlpha(value);
break;
}
}
/**
* This method gets the value of the named property from the View object.
*
* @param propertyConstant The property whose value should be returned
* @return float The value of the named property
*/
private float getValue(int propertyConstant) {
//final View.TransformationInfo info = mView.mTransformationInfo;
switch (propertyConstant) {
case TRANSLATION_X:
//return info.mTranslationX;
return mProxy.getTranslationX();
case TRANSLATION_Y:
//return info.mTranslationY;
return mProxy.getTranslationY();
case ROTATION:
//return info.mRotation;
return mProxy.getRotation();
case ROTATION_X:
//return info.mRotationX;
return mProxy.getRotationX();
case ROTATION_Y:
//return info.mRotationY;
return mProxy.getRotationY();
case SCALE_X:
//return info.mScaleX;
return mProxy.getScaleX();
case SCALE_Y:
//return info.mScaleY;
return mProxy.getScaleY();
case X:
//return mView.mLeft + info.mTranslationX;
return mProxy.getX();
case Y:
//return mView.mTop + info.mTranslationY;
return mProxy.getY();
case ALPHA:
//return info.mAlpha;
return mProxy.getAlpha();
}
return 0;
}
/**
* Utility class that handles the various Animator events. The only ones we care
* about are the end event (which we use to clean up the animator map when an animator
* finishes) and the update event (which we use to calculate the current value of each
* property and then set it on the view object).
*/
private class AnimatorEventListener
implements Animator.AnimatorListener, ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationStart(Animator animation) {
if (mListener != null) {
mListener.onAnimationStart(animation);
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (mListener != null) {
mListener.onAnimationCancel(animation);
}
}
@Override
public void onAnimationRepeat(Animator animation) {
if (mListener != null) {
mListener.onAnimationRepeat(animation);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (mListener != null) {
mListener.onAnimationEnd(animation);
}
mAnimatorMap.remove(animation);
// If the map is empty, it means all animation are done or canceled, so the listener
// isn't needed anymore. Not nulling it would cause it to leak any objects used in
// its implementation
if (mAnimatorMap.isEmpty()) {
mListener = null;
}
}
/**
* Calculate the current value for each property and set it on the view. Invalidate
* the view object appropriately, depending on which properties are being animated.
*
* @param animation The animator associated with the properties that need to be
* set. This animator holds the animation fraction which we will use to calculate
* the current value of each property.
*/
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// alpha requires slightly different treatment than the other (transform) properties.
// The logic in setAlpha() is not simply setting mAlpha, plus the invalidation
// logic is dependent on how the view handles an internal call to onSetAlpha().
// We track what kinds of properties are set, and how alpha is handled when it is
// set, and perform the invalidation steps appropriately.
//boolean alphaHandled = false;
//mView.invalidateParentCaches();
float fraction = animation.getAnimatedFraction();
PropertyBundle propertyBundle = mAnimatorMap.get(animation);
int propertyMask = propertyBundle.mPropertyMask;
if ((propertyMask & TRANSFORM_MASK) != 0) {
View v = mView.get();
if (v != null) {
v.invalidate(/*false*/);
}
}
ArrayList<NameValuesHolder> valueList = propertyBundle.mNameValuesHolder;
if (valueList != null) {
int count = valueList.size();
for (int i = 0; i < count; ++i) {
NameValuesHolder values = valueList.get(i);
float value = values.mFromValue + fraction * values.mDeltaValue;
//if (values.mNameConstant == ALPHA) {
// alphaHandled = mView.setAlphaNoInvalidation(value);
//} else {
setValue(values.mNameConstant, value);
//}
}
}
/*if ((propertyMask & TRANSFORM_MASK) != 0) {
mView.mTransformationInfo.mMatrixDirty = true;
mView.mPrivateFlags |= View.DRAWN; // force another invalidation
}*/
// invalidate(false) in all cases except if alphaHandled gets set to true
// via the call to setAlphaNoInvalidation(), above
View v = mView.get();
if (v != null) {
v.invalidate(/*alphaHandled*/);
}
}
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.view;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import android.view.View;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
class ViewPropertyAnimatorHC extends ViewPropertyAnimator {
/**
* A WeakReference holding the View whose properties are being animated by this class.
* This is set at construction time.
*/
private final WeakReference<View> mView;
/**
* The duration of the underlying Animator object. By default, we don't set the duration
* on the Animator and just use its default duration. If the duration is ever set on this
* Animator, then we use the duration that it was set to.
*/
private long mDuration;
/**
* A flag indicating whether the duration has been set on this object. If not, we don't set
* the duration on the underlying Animator, but instead just use its default duration.
*/
private boolean mDurationSet = false;
/**
* The startDelay of the underlying Animator object. By default, we don't set the startDelay
* on the Animator and just use its default startDelay. If the startDelay is ever set on this
* Animator, then we use the startDelay that it was set to.
*/
private long mStartDelay = 0;
/**
* A flag indicating whether the startDelay has been set on this object. If not, we don't set
* the startDelay on the underlying Animator, but instead just use its default startDelay.
*/
private boolean mStartDelaySet = false;
/**
* The interpolator of the underlying Animator object. By default, we don't set the interpolator
* on the Animator and just use its default interpolator. If the interpolator is ever set on
* this Animator, then we use the interpolator that it was set to.
*/
private /*Time*/Interpolator mInterpolator;
/**
* A flag indicating whether the interpolator has been set on this object. If not, we don't set
* the interpolator on the underlying Animator, but instead just use its default interpolator.
*/
private boolean mInterpolatorSet = false;
/**
* Listener for the lifecycle events of the underlying
*/
private Animator.AnimatorListener mListener = null;
/**
* This listener is the mechanism by which the underlying Animator causes changes to the
* properties currently being animated, as well as the cleanup after an animation is
* complete.
*/
private AnimatorEventListener mAnimatorEventListener = new AnimatorEventListener();
/**
* This list holds the properties that have been asked to animate. We allow the caller to
* request several animations prior to actually starting the underlying animator. This
* enables us to run one single animator to handle several properties in parallel. Each
* property is tossed onto the pending list until the animation actually starts (which is
* done by posting it onto mView), at which time the pending list is cleared and the properties
* on that list are added to the list of properties associated with that animator.
*/
ArrayList<NameValuesHolder> mPendingAnimations = new ArrayList<NameValuesHolder>();
/**
* Constants used to associate a property being requested and the mechanism used to set
* the property (this class calls directly into View to set the properties in question).
*/
private static final int NONE = 0x0000;
private static final int TRANSLATION_X = 0x0001;
private static final int TRANSLATION_Y = 0x0002;
private static final int SCALE_X = 0x0004;
private static final int SCALE_Y = 0x0008;
private static final int ROTATION = 0x0010;
private static final int ROTATION_X = 0x0020;
private static final int ROTATION_Y = 0x0040;
private static final int X = 0x0080;
private static final int Y = 0x0100;
private static final int ALPHA = 0x0200;
private static final int TRANSFORM_MASK = TRANSLATION_X | TRANSLATION_Y | SCALE_X | SCALE_Y |
ROTATION | ROTATION_X | ROTATION_Y | X | Y;
/**
* The mechanism by which the user can request several properties that are then animated
* together works by posting this Runnable to start the underlying Animator. Every time
* a property animation is requested, we cancel any previous postings of the Runnable
* and re-post it. This means that we will only ever run the Runnable (and thus start the
* underlying animator) after the caller is done setting the properties that should be
* animated together.
*/
private Runnable mAnimationStarter = new Runnable() {
@Override
public void run() {
startAnimation();
}
};
/**
* This class holds information about the overall animation being run on the set of
* properties. The mask describes which properties are being animated and the
* values holder is the list of all property/value objects.
*/
private static class PropertyBundle {
int mPropertyMask;
ArrayList<NameValuesHolder> mNameValuesHolder;
PropertyBundle(int propertyMask, ArrayList<NameValuesHolder> nameValuesHolder) {
mPropertyMask = propertyMask;
mNameValuesHolder = nameValuesHolder;
}
/**
* Removes the given property from being animated as a part of this
* PropertyBundle. If the property was a part of this bundle, it returns
* true to indicate that it was, in fact, canceled. This is an indication
* to the caller that a cancellation actually occurred.
*
* @param propertyConstant The property whose cancellation is requested.
* @return true if the given property is a part of this bundle and if it
* has therefore been canceled.
*/
boolean cancel(int propertyConstant) {
if ((mPropertyMask & propertyConstant) != 0 && mNameValuesHolder != null) {
int count = mNameValuesHolder.size();
for (int i = 0; i < count; ++i) {
NameValuesHolder nameValuesHolder = mNameValuesHolder.get(i);
if (nameValuesHolder.mNameConstant == propertyConstant) {
mNameValuesHolder.remove(i);
mPropertyMask &= ~propertyConstant;
return true;
}
}
}
return false;
}
}
/**
* This list tracks the list of properties being animated by any particular animator.
* In most situations, there would only ever be one animator running at a time. But it is
* possible to request some properties to animate together, then while those properties
* are animating, to request some other properties to animate together. The way that
* works is by having this map associate the group of properties being animated with the
* animator handling the animation. On every update event for an Animator, we ask the
* map for the associated properties and set them accordingly.
*/
private HashMap<Animator, PropertyBundle> mAnimatorMap =
new HashMap<Animator, PropertyBundle>();
/**
* This is the information we need to set each property during the animation.
* mNameConstant is used to set the appropriate field in View, and the from/delta
* values are used to calculate the animated value for a given animation fraction
* during the animation.
*/
private static class NameValuesHolder {
int mNameConstant;
float mFromValue;
float mDeltaValue;
NameValuesHolder(int nameConstant, float fromValue, float deltaValue) {
mNameConstant = nameConstant;
mFromValue = fromValue;
mDeltaValue = deltaValue;
}
}
/**
* Constructor, called by View. This is private by design, as the user should only
* get a ViewPropertyAnimator by calling View.animate().
*
* @param view The View associated with this ViewPropertyAnimator
*/
ViewPropertyAnimatorHC(View view) {
mView = new WeakReference<View>(view);
}
/**
* Sets the duration for the underlying animator that animates the requested properties.
* By default, the animator uses the default value for ValueAnimator. Calling this method
* will cause the declared value to be used instead.
* @param duration The length of ensuing property animations, in milliseconds. The value
* cannot be negative.
* @return This object, allowing calls to methods in this class to be chained.
*/
public ViewPropertyAnimator setDuration(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
duration);
}
mDurationSet = true;
mDuration = duration;
return this;
}
/**
* Returns the current duration of property animations. If the duration was set on this
* object, that value is returned. Otherwise, the default value of the underlying Animator
* is returned.
*
* @see #setDuration(long)
* @return The duration of animations, in milliseconds.
*/
public long getDuration() {
if (mDurationSet) {
return mDuration;
} else {
// Just return the default from ValueAnimator, since that's what we'd get if
// the value has not been set otherwise
return new ValueAnimator().getDuration();
}
}
@Override
public long getStartDelay() {
if (mStartDelaySet) {
return mStartDelay;
} else {
// Just return the default from ValueAnimator (0), since that's what we'd get if
// the value has not been set otherwise
return 0;
}
}
@Override
public ViewPropertyAnimator setStartDelay(long startDelay) {
if (startDelay < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
startDelay);
}
mStartDelaySet = true;
mStartDelay = startDelay;
return this;
}
@Override
public ViewPropertyAnimator setInterpolator(/*Time*/Interpolator interpolator) {
mInterpolatorSet = true;
mInterpolator = interpolator;
return this;
}
@Override
public ViewPropertyAnimator setListener(Animator.AnimatorListener listener) {
mListener = listener;
return this;
}
@Override
public void start() {
startAnimation();
}
@Override
public void cancel() {
if (mAnimatorMap.size() > 0) {
HashMap<Animator, PropertyBundle> mAnimatorMapCopy =
(HashMap<Animator, PropertyBundle>)mAnimatorMap.clone();
Set<Animator> animatorSet = mAnimatorMapCopy.keySet();
for (Animator runningAnim : animatorSet) {
runningAnim.cancel();
}
}
mPendingAnimations.clear();
View v = mView.get();
if (v != null) {
v.removeCallbacks(mAnimationStarter);
}
}
@Override
public ViewPropertyAnimator x(float value) {
animateProperty(X, value);
return this;
}
@Override
public ViewPropertyAnimator xBy(float value) {
animatePropertyBy(X, value);
return this;
}
@Override
public ViewPropertyAnimator y(float value) {
animateProperty(Y, value);
return this;
}
@Override
public ViewPropertyAnimator yBy(float value) {
animatePropertyBy(Y, value);
return this;
}
@Override
public ViewPropertyAnimator rotation(float value) {
animateProperty(ROTATION, value);
return this;
}
@Override
public ViewPropertyAnimator rotationBy(float value) {
animatePropertyBy(ROTATION, value);
return this;
}
@Override
public ViewPropertyAnimator rotationX(float value) {
animateProperty(ROTATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator rotationXBy(float value) {
animatePropertyBy(ROTATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator rotationY(float value) {
animateProperty(ROTATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator rotationYBy(float value) {
animatePropertyBy(ROTATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator translationX(float value) {
animateProperty(TRANSLATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator translationXBy(float value) {
animatePropertyBy(TRANSLATION_X, value);
return this;
}
@Override
public ViewPropertyAnimator translationY(float value) {
animateProperty(TRANSLATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator translationYBy(float value) {
animatePropertyBy(TRANSLATION_Y, value);
return this;
}
@Override
public ViewPropertyAnimator scaleX(float value) {
animateProperty(SCALE_X, value);
return this;
}
@Override
public ViewPropertyAnimator scaleXBy(float value) {
animatePropertyBy(SCALE_X, value);
return this;
}
@Override
public ViewPropertyAnimator scaleY(float value) {
animateProperty(SCALE_Y, value);
return this;
}
@Override
public ViewPropertyAnimator scaleYBy(float value) {
animatePropertyBy(SCALE_Y, value);
return this;
}
@Override
public ViewPropertyAnimator alpha(float value) {
animateProperty(ALPHA, value);
return this;
}
@Override
public ViewPropertyAnimator alphaBy(float value) {
animatePropertyBy(ALPHA, value);
return this;
}
/**
* Starts the underlying Animator for a set of properties. We use a single animator that
* simply runs from 0 to 1, and then use that fractional value to set each property
* value accordingly.
*/
private void startAnimation() {
ValueAnimator animator = ValueAnimator.ofFloat(1.0f);
ArrayList<NameValuesHolder> nameValueList =
(ArrayList<NameValuesHolder>) mPendingAnimations.clone();
mPendingAnimations.clear();
int propertyMask = 0;
int propertyCount = nameValueList.size();
for (int i = 0; i < propertyCount; ++i) {
NameValuesHolder nameValuesHolder = nameValueList.get(i);
propertyMask |= nameValuesHolder.mNameConstant;
}
mAnimatorMap.put(animator, new PropertyBundle(propertyMask, nameValueList));
animator.addUpdateListener(mAnimatorEventListener);
animator.addListener(mAnimatorEventListener);
if (mStartDelaySet) {
animator.setStartDelay(mStartDelay);
}
if (mDurationSet) {
animator.setDuration(mDuration);
}
if (mInterpolatorSet) {
animator.setInterpolator(mInterpolator);
}
animator.start();
}
/**
* Utility function, called by the various x(), y(), etc. methods. This stores the
* constant name for the property along with the from/delta values that will be used to
* calculate and set the property during the animation. This structure is added to the
* pending animations, awaiting the eventual start() of the underlying animator. A
* Runnable is posted to start the animation, and any pending such Runnable is canceled
* (which enables us to end up starting just one animator for all of the properties
* specified at one time).
*
* @param constantName The specifier for the property being animated
* @param toValue The value to which the property will animate
*/
private void animateProperty(int constantName, float toValue) {
float fromValue = getValue(constantName);
float deltaValue = toValue - fromValue;
animatePropertyBy(constantName, fromValue, deltaValue);
}
/**
* Utility function, called by the various xBy(), yBy(), etc. methods. This method is
* just like animateProperty(), except the value is an offset from the property's
* current value, instead of an absolute "to" value.
*
* @param constantName The specifier for the property being animated
* @param byValue The amount by which the property will change
*/
private void animatePropertyBy(int constantName, float byValue) {
float fromValue = getValue(constantName);
animatePropertyBy(constantName, fromValue, byValue);
}
/**
* Utility function, called by animateProperty() and animatePropertyBy(), which handles the
* details of adding a pending animation and posting the request to start the animation.
*
* @param constantName The specifier for the property being animated
* @param startValue The starting value of the property
* @param byValue The amount by which the property will change
*/
private void animatePropertyBy(int constantName, float startValue, float byValue) {
// First, cancel any existing animations on this property
if (mAnimatorMap.size() > 0) {
Animator animatorToCancel = null;
Set<Animator> animatorSet = mAnimatorMap.keySet();
for (Animator runningAnim : animatorSet) {
PropertyBundle bundle = mAnimatorMap.get(runningAnim);
if (bundle.cancel(constantName)) {
// property was canceled - cancel the animation if it's now empty
// Note that it's safe to break out here because every new animation
// on a property will cancel a previous animation on that property, so
// there can only ever be one such animation running.
if (bundle.mPropertyMask == NONE) {
// the animation is no longer changing anything - cancel it
animatorToCancel = runningAnim;
break;
}
}
}
if (animatorToCancel != null) {
animatorToCancel.cancel();
}
}
NameValuesHolder nameValuePair = new NameValuesHolder(constantName, startValue, byValue);
mPendingAnimations.add(nameValuePair);
View v = mView.get();
if (v != null) {
v.removeCallbacks(mAnimationStarter);
v.post(mAnimationStarter);
}
}
/**
* This method handles setting the property values directly in the View object's fields.
* propertyConstant tells it which property should be set, value is the value to set
* the property to.
*
* @param propertyConstant The property to be set
* @param value The value to set the property to
*/
private void setValue(int propertyConstant, float value) {
//final View.TransformationInfo info = mView.mTransformationInfo;
View v = mView.get();
if (v != null) {
switch (propertyConstant) {
case TRANSLATION_X:
//info.mTranslationX = value;
v.setTranslationX(value);
break;
case TRANSLATION_Y:
//info.mTranslationY = value;
v.setTranslationY(value);
break;
case ROTATION:
//info.mRotation = value;
v.setRotation(value);
break;
case ROTATION_X:
//info.mRotationX = value;
v.setRotationX(value);
break;
case ROTATION_Y:
//info.mRotationY = value;
v.setRotationY(value);
break;
case SCALE_X:
//info.mScaleX = value;
v.setScaleX(value);
break;
case SCALE_Y:
//info.mScaleY = value;
v.setScaleY(value);
break;
case X:
//info.mTranslationX = value - v.mLeft;
v.setX(value);
break;
case Y:
//info.mTranslationY = value - v.mTop;
v.setY(value);
break;
case ALPHA:
//info.mAlpha = value;
v.setAlpha(value);
break;
}
}
}
/**
* This method gets the value of the named property from the View object.
*
* @param propertyConstant The property whose value should be returned
* @return float The value of the named property
*/
private float getValue(int propertyConstant) {
//final View.TransformationInfo info = mView.mTransformationInfo;
View v = mView.get();
if (v != null) {
switch (propertyConstant) {
case TRANSLATION_X:
//return info.mTranslationX;
return v.getTranslationX();
case TRANSLATION_Y:
//return info.mTranslationY;
return v.getTranslationY();
case ROTATION:
//return info.mRotation;
return v.getRotation();
case ROTATION_X:
//return info.mRotationX;
return v.getRotationX();
case ROTATION_Y:
//return info.mRotationY;
return v.getRotationY();
case SCALE_X:
//return info.mScaleX;
return v.getScaleX();
case SCALE_Y:
//return info.mScaleY;
return v.getScaleY();
case X:
//return v.mLeft + info.mTranslationX;
return v.getX();
case Y:
//return v.mTop + info.mTranslationY;
return v.getY();
case ALPHA:
//return info.mAlpha;
return v.getAlpha();
}
}
return 0;
}
/**
* Utility class that handles the various Animator events. The only ones we care
* about are the end event (which we use to clean up the animator map when an animator
* finishes) and the update event (which we use to calculate the current value of each
* property and then set it on the view object).
*/
private class AnimatorEventListener
implements Animator.AnimatorListener, ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationStart(Animator animation) {
if (mListener != null) {
mListener.onAnimationStart(animation);
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (mListener != null) {
mListener.onAnimationCancel(animation);
}
}
@Override
public void onAnimationRepeat(Animator animation) {
if (mListener != null) {
mListener.onAnimationRepeat(animation);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (mListener != null) {
mListener.onAnimationEnd(animation);
}
mAnimatorMap.remove(animation);
// If the map is empty, it means all animation are done or canceled, so the listener
// isn't needed anymore. Not nulling it would cause it to leak any objects used in
// its implementation
if (mAnimatorMap.isEmpty()) {
mListener = null;
}
}
/**
* Calculate the current value for each property and set it on the view. Invalidate
* the view object appropriately, depending on which properties are being animated.
*
* @param animation The animator associated with the properties that need to be
* set. This animator holds the animation fraction which we will use to calculate
* the current value of each property.
*/
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// alpha requires slightly different treatment than the other (transform) properties.
// The logic in setAlpha() is not simply setting mAlpha, plus the invalidation
// logic is dependent on how the view handles an internal call to onSetAlpha().
// We track what kinds of properties are set, and how alpha is handled when it is
// set, and perform the invalidation steps appropriately.
//boolean alphaHandled = false;
//mView.invalidateParentCaches();
float fraction = animation.getAnimatedFraction();
PropertyBundle propertyBundle = mAnimatorMap.get(animation);
int propertyMask = propertyBundle.mPropertyMask;
if ((propertyMask & TRANSFORM_MASK) != 0) {
View v = mView.get();
if (v != null) {
v.invalidate(/*false*/);
}
}
ArrayList<NameValuesHolder> valueList = propertyBundle.mNameValuesHolder;
if (valueList != null) {
int count = valueList.size();
for (int i = 0; i < count; ++i) {
NameValuesHolder values = valueList.get(i);
float value = values.mFromValue + fraction * values.mDeltaValue;
//if (values.mNameConstant == ALPHA) {
// alphaHandled = mView.setAlphaNoInvalidation(value);
//} else {
setValue(values.mNameConstant, value);
//}
}
}
/*if ((propertyMask & TRANSFORM_MASK) != 0) {
mView.mTransformationInfo.mMatrixDirty = true;
mView.mPrivateFlags |= View.DRAWN; // force another invalidation
}*/
// invalidate(false) in all cases except if alphaHandled gets set to true
// via the call to setAlphaNoInvalidation(), above
View v = mView.get();
if (v != null) {
v.invalidate(/*alphaHandled*/);
}
}
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Internal class to automatically generate a Property for a given class/name pair, given the
* specification of {@link Property#of(java.lang.Class, java.lang.Class, java.lang.String)}
*/
class ReflectiveProperty<T, V> extends Property<T, V> {
private static final String PREFIX_GET = "get";
private static final String PREFIX_IS = "is";
private static final String PREFIX_SET = "set";
private Method mSetter;
private Method mGetter;
private Field mField;
/**
* For given property name 'name', look for getName/isName method or 'name' field.
* Also look for setName method (optional - could be readonly). Failing method getters and
* field results in throwing NoSuchPropertyException.
*
* @param propertyHolder The class on which the methods or field are found
* @param name The name of the property, where this name is capitalized and appended to
* "get" and "is to search for the appropriate methods. If the get/is methods are not found,
* the constructor will search for a field with that exact name.
*/
public ReflectiveProperty(Class<T> propertyHolder, Class<V> valueType, String name) {
// TODO: cache reflection info for each new class/name pair
super(valueType, name);
char firstLetter = Character.toUpperCase(name.charAt(0));
String theRest = name.substring(1);
String capitalizedName = firstLetter + theRest;
String getterName = PREFIX_GET + capitalizedName;
try {
mGetter = propertyHolder.getMethod(getterName, (Class<?>[]) null);
} catch (NoSuchMethodException e) {
try {
/* The native implementation uses JNI to do reflection, which allows access to private methods.
* getDeclaredMethod(..) does not find superclass methods, so it's implemented as a fallback.
*/
mGetter = propertyHolder.getDeclaredMethod(getterName, (Class<?>[]) null);
mGetter.setAccessible(true);
} catch (NoSuchMethodException e2) {
// getName() not available - try isName() instead
getterName = PREFIX_IS + capitalizedName;
try {
mGetter = propertyHolder.getMethod(getterName, (Class<?>[]) null);
} catch (NoSuchMethodException e3) {
try {
/* The native implementation uses JNI to do reflection, which allows access to private methods.
* getDeclaredMethod(..) does not find superclass methods, so it's implemented as a fallback.
*/
mGetter = propertyHolder.getDeclaredMethod(getterName, (Class<?>[]) null);
mGetter.setAccessible(true);
} catch (NoSuchMethodException e4) {
// Try public field instead
try {
mField = propertyHolder.getField(name);
Class fieldType = mField.getType();
if (!typesMatch(valueType, fieldType)) {
throw new NoSuchPropertyException("Underlying type (" + fieldType + ") " +
"does not match Property type (" + valueType + ")");
}
return;
} catch (NoSuchFieldException e5) {
// no way to access property - throw appropriate exception
throw new NoSuchPropertyException("No accessor method or field found for"
+ " property with name " + name);
}
}
}
}
}
Class getterType = mGetter.getReturnType();
// Check to make sure our getter type matches our valueType
if (!typesMatch(valueType, getterType)) {
throw new NoSuchPropertyException("Underlying type (" + getterType + ") " +
"does not match Property type (" + valueType + ")");
}
String setterName = PREFIX_SET + capitalizedName;
try {
// mSetter = propertyHolder.getMethod(setterName, getterType);
// The native implementation uses JNI to do reflection, which allows access to private methods.
mSetter = propertyHolder.getDeclaredMethod(setterName, getterType);
mSetter.setAccessible(true);
} catch (NoSuchMethodException ignored) {
// Okay to not have a setter - just a readonly property
}
}
/**
* Utility method to check whether the type of the underlying field/method on the target
* object matches the type of the Property. The extra checks for primitive types are because
* generics will force the Property type to be a class, whereas the type of the underlying
* method/field will probably be a primitive type instead. Accept float as matching Float,
* etc.
*/
private boolean typesMatch(Class<V> valueType, Class getterType) {
if (getterType != valueType) {
if (getterType.isPrimitive()) {
return (getterType == float.class && valueType == Float.class) ||
(getterType == int.class && valueType == Integer.class) ||
(getterType == boolean.class && valueType == Boolean.class) ||
(getterType == long.class && valueType == Long.class) ||
(getterType == double.class && valueType == Double.class) ||
(getterType == short.class && valueType == Short.class) ||
(getterType == byte.class && valueType == Byte.class) ||
(getterType == char.class && valueType == Character.class);
}
return false;
}
return true;
}
@Override
public void set(T object, V value) {
if (mSetter != null) {
try {
mSetter.invoke(object, value);
} catch (IllegalAccessException e) {
throw new AssertionError();
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
} else if (mField != null) {
try {
mField.set(object, value);
} catch (IllegalAccessException e) {
throw new AssertionError();
}
} else {
throw new UnsupportedOperationException("Property " + getName() +" is read-only");
}
}
@Override
public V get(T object) {
if (mGetter != null) {
try {
return (V) mGetter.invoke(object, (Object[])null);
} catch (IllegalAccessException e) {
throw new AssertionError();
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
} else if (mField != null) {
try {
return (V) mField.get(object);
} catch (IllegalAccessException e) {
throw new AssertionError();
}
}
// Should not get here: there should always be a non-null getter or field
throw new AssertionError();
}
/**
* Returns false if there is no setter or public field underlying this Property.
*/
@Override
public boolean isReadOnly() {
return (mSetter == null && mField == null);
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.util;
/**
* An implementation of {@link android.util.Property} to be used specifically with fields of type
* <code>float</code>. This type-specific subclass enables performance benefit by allowing
* calls to a {@link #set(Object, Float) set()} function that takes the primitive
* <code>float</code> type and avoids autoboxing and other overhead associated with the
* <code>Float</code> class.
*
* @param <T> The class on which the Property is declared.
*
* @hide
*/
public abstract class FloatProperty<T> extends Property<T, Float> {
public FloatProperty(String name) {
super(Float.class, name);
}
/**
* A type-specific override of the {@link #set(Object, Float)} that is faster when dealing
* with fields of type <code>float</code>.
*/
public abstract void setValue(T object, float value);
@Override
final public void set(T object, Float value) {
setValue(object, value);
}
} | Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.util;
/**
* A property is an abstraction that can be used to represent a <emb>mutable</em> value that is held
* in a <em>host</em> object. The Property's {@link #set(Object, Object)} or {@link #get(Object)}
* methods can be implemented in terms of the private fields of the host object, or via "setter" and
* "getter" methods or by some other mechanism, as appropriate.
*
* @param <T> The class on which the property is declared.
* @param <V> The type that this property represents.
*/
public abstract class Property<T, V> {
private final String mName;
private final Class<V> mType;
/**
* This factory method creates and returns a Property given the <code>class</code> and
* <code>name</code> parameters, where the <code>"name"</code> parameter represents either:
* <ul>
* <li>a public <code>getName()</code> method on the class which takes no arguments, plus an
* optional public <code>setName()</code> method which takes a value of the same type
* returned by <code>getName()</code>
* <li>a public <code>isName()</code> method on the class which takes no arguments, plus an
* optional public <code>setName()</code> method which takes a value of the same type
* returned by <code>isName()</code>
* <li>a public <code>name</code> field on the class
* </ul>
*
* <p>If either of the get/is method alternatives is found on the class, but an appropriate
* <code>setName()</code> method is not found, the <code>Property</code> will be
* {@link #isReadOnly() readOnly}. Calling the {@link #set(Object, Object)} method on such
* a property is allowed, but will have no effect.</p>
*
* <p>If neither the methods nor the field are found on the class a
* {@link NoSuchPropertyException} exception will be thrown.</p>
*/
public static <T, V> Property<T, V> of(Class<T> hostType, Class<V> valueType, String name) {
return new ReflectiveProperty<T, V>(hostType, valueType, name);
}
/**
* A constructor that takes an identifying name and {@link #getType() type} for the property.
*/
public Property(Class<V> type, String name) {
mName = name;
mType = type;
}
/**
* Returns true if the {@link #set(Object, Object)} method does not set the value on the target
* object (in which case the {@link #set(Object, Object) set()} method should throw a {@link
* NoSuchPropertyException} exception). This may happen if the Property wraps functionality that
* allows querying the underlying value but not setting it. For example, the {@link #of(Class,
* Class, String)} factory method may return a Property with name "foo" for an object that has
* only a <code>getFoo()</code> or <code>isFoo()</code> method, but no matching
* <code>setFoo()</code> method.
*/
public boolean isReadOnly() {
return false;
}
/**
* Sets the value on <code>object</code> which this property represents. If the method is unable
* to set the value on the target object it will throw an {@link UnsupportedOperationException}
* exception.
*/
public void set(T object, V value) {
throw new UnsupportedOperationException("Property " + getName() +" is read-only");
}
/**
* Returns the current value that this property represents on the given <code>object</code>.
*/
public abstract V get(T object);
/**
* Returns the name for this property.
*/
public String getName() {
return mName;
}
/**
* Returns the type for this property.
*/
public Class<V> getType() {
return mType;
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.util;
/**
* An implementation of {@link android.util.Property} to be used specifically with fields of type
* <code>int</code>. This type-specific subclass enables performance benefit by allowing
* calls to a {@link #set(Object, Integer) set()} function that takes the primitive
* <code>int</code> type and avoids autoboxing and other overhead associated with the
* <code>Integer</code> class.
*
* @param <T> The class on which the Property is declared.
*
* @hide
*/
public abstract class IntProperty<T> extends Property<T, Integer> {
public IntProperty(String name) {
super(Integer.class, name);
}
/**
* A type-specific override of the {@link #set(Object, Integer)} that is faster when dealing
* with fields of type <code>int</code>.
*/
public abstract void setValue(T object, int value);
@Override
final public void set(T object, Integer value) {
set(object, value.intValue());
}
} | Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nineoldandroids.util;
/**
* Thrown when code requests a {@link Property} on a class that does
* not expose the appropriate method or field.
*
* @see Property#of(java.lang.Class, java.lang.Class, java.lang.String)
*/
public class NoSuchPropertyException extends RuntimeException {
public NoSuchPropertyException(String s) {
super(s);
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.nineoldandroids;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
package jp.jma.oraclecard;
import java.io.File;
import net.cardgame.orcalecard.utils.ConstantValue;
import uk.co.senab.bitmapcache.BitmapLruCache;
import android.app.Application;
import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.LoaderSettings;
import com.novoda.imageloader.core.LoaderSettings.SettingsBuilder;
import com.novoda.imageloader.core.cache.LruBitmapCache;
public class MyApplication extends Application {
private BitmapLruCache mCache;
private ImageManager imageManager;
private static MyApplication mApplication;
@Override
public void onCreate() {
super.onCreate();
mApplication = this;
File cacheLocation;
cacheLocation = new File(ConstantValue.getBasePatchApp(this)
+ "/Android-BitmapCache");
if (!cacheLocation.exists())
cacheLocation.mkdirs();
BitmapLruCache.Builder builder = new BitmapLruCache.Builder(this);
builder.setMemoryCacheEnabled(true)
.setMemoryCacheMaxSizeUsingHeapSize();
builder.setDiskCacheEnabled(true).setDiskCacheLocation(cacheLocation)
.setDiskCacheMaxSize(200000000);
mCache = builder.build();
mySettingCache();
}
public static MyApplication getInstance() {
return mApplication;
}
public BitmapLruCache getBitmapCache() {
return mCache;
}
private void mySettingCache() {
SettingsBuilder settingsBuilder = new SettingsBuilder();
// You can force the urlConnection to disconnect after every call.
// settingsBuilder.withDisconnectOnEveryCall(true);
// We have different types of cache, check cache package for more info
settingsBuilder.withCacheManager(new LruBitmapCache(this));
settingsBuilder.withExpirationPeriod(40 * 7l * 24l * 3600l * 1000l);
// You can set a specific read timeout
settingsBuilder.withReadTimeout(30000);
// You can set a specific connection timeout
settingsBuilder.withConnectionTimeout(30000);
// You can disable the multi-threading ability to download image
settingsBuilder.withAsyncTasks(true);
// You can set a specific directory for caching files on the sdcard
settingsBuilder.withCacheDir(new File("/something"));
// Setting this to false means that file cache will use the url without
// the query part
// for the generation of the hashname
settingsBuilder.withEnableQueryInHashGeneration(false);
LoaderSettings loaderSettings = settingsBuilder.build(this);
imageManager = new ImageManager(this, loaderSettings);
}
/**
* Convenient method of access the imageLoader
*/
public ImageManager getImageLoader() {
return imageManager;
}
}
| Java |
package net.cardgame.orcalecard;
import java.io.File;
import net.cardgame.orcalecard.utils.ConstantValue;
import android.content.Context;
public class GalleryFileCache {
private File cacheDir;
public GalleryFileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
// cacheDir = new File(ConstantValue.BASE_PATCH_SDCARD + "myCache");
cacheDir = new File(ConstantValue.getBasePatchApp(context) + "/myCache");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(url.hashCode());
// Another possible solution (thanks to grantland)
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
} | Java |
package net.cardgame.orcalecard;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;
public class GalleryFlow extends Gallery {
private Camera mCamera = new Camera();
private int mMaxRotationAngle = 70;
private int mMaxZoom = -10; // Buc anh trung tam se tien gan ve phia truoc
private int mCoveflowCenter;
private float mSpeed = 0.9f;
public GalleryFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
}
public GalleryFlow(Context context, AttributeSet attrs) {
super(context, attrs);
this.setStaticTransformationsEnabled(true);
}
public GalleryFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);
}
public int getMaxRotationAngle() {
return mMaxRotationAngle;
}
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}
public int getMaxZoom() {
return mMaxZoom;
}
public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
+ getPaddingLeft();
}
private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}
protected boolean getChildStaticTransformation(View child, Transformation t) {
final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth();
int rotationAngle = 0;
t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);
if (childCenter == mCoveflowCenter) {
transformImageBitmap((ImageView) child, t, 0);
} else {
rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
if (Math.abs(rotationAngle) > mMaxRotationAngle) {
rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
: mMaxRotationAngle;
}
transformImageBitmap((ImageView) child, t, rotationAngle);
}
if (android.os.Build.VERSION.SDK_INT >= 11)
child.invalidate();
return true;
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}
private void transformImageBitmap(ImageView child, Transformation t,
int rotationAngle) {
mCamera.save();
final Matrix imageMatrix = t.getMatrix();
final int imageHeight = child.getLayoutParams().height;
final int imageWidth = child.getLayoutParams().width;
final int rotation = Math.abs(rotationAngle);
mCamera.translate(0.0f, 0.0f, 100.0f);
// As the angle of the view gets less, zoom in
if (rotation < mMaxRotationAngle) {
float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
mCamera.translate(0.0f, 0.0f, zoomAmount);
}
mCamera.rotateY(rotationAngle);
mCamera.getMatrix(imageMatrix);
imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
mCamera.restore();
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return super.onFling(e1, e2, velocityX / mSpeed, velocityY);
}
}
| Java |
package net.cardgame.orcalecard;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.utils.ConstantValue;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SplashDeckBeanActivity extends Activity implements
AnimationListener, OnClickListener {
ImageView img_ring;
int deckId;
int state_machine = 0;
boolean clickable = true;
MediaPlayer mediaPlayer;
SettingApp setting;
ImageView img_bg, image_scale, img_deckbean_info;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_deckbean_activity);
setting = ConstantValue.getSettingApp(this);
// get deck bean Id & number to get card
Bundle bundle = getIntent().getExtras();
deckId = bundle.getInt("deckId");
img_bg = (ImageView) findViewById(R.id.image_bg_splash_deck);
image_scale = (ImageView) findViewById(R.id.img_scale);
img_deckbean_info = (ImageView) findViewById(R.id.image_deckbean_info);
img_ring = (ImageView) findViewById(R.id.img_ef_ring);
findViewById(R.id.btnhelp_splash_deckbean).setOnClickListener(this);
findViewById(R.id.btnBack_splash_deckbean).setOnClickListener(this);
loadImage();
}
void loadImage() {
if (deckId == 999) {
img_bg.setImageResource(R.drawable.bg999);
img_deckbean_info.setImageResource(R.drawable.c999m);
image_scale.setImageResource(R.drawable.c999p);
Animation hyperspaceJump = AnimationUtils.loadAnimation(
SplashDeckBeanActivity.this, R.anim.scale_animation);
hyperspaceJump.setAnimationListener(this);
image_scale.startAnimation(hyperspaceJump);
return;
}
String id = deckId < 10 ? "0" + deckId : "" + deckId;
String patchBg = ConstantValue.getPatchCardData(this) + "Card_" + id
+ "/en_bg" + id + ".jpg";
String patchImageScale = ConstantValue.getPatchCardData(this) + "Card_"
+ id + "/en_c" + id + "p.png";
String patchImageInfo = ConstantValue.getPatchCardData(this) + "Card_"
+ id + "/en_c" + id + "m.png";
new ThreadLoadImage(this, handler, patchBg, img_bg, 1).start();
new ThreadLoadImage(this, handler, patchImageInfo, img_deckbean_info, 2)
.start();
new ThreadLoadImage(this, handler, patchImageScale, image_scale, 3)
.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 1:
img_bg.setImageDrawable((Drawable) msg.obj);
Animation hyperspaceJump = AnimationUtils.loadAnimation(
SplashDeckBeanActivity.this, R.anim.scale_animation);
hyperspaceJump
.setAnimationListener(SplashDeckBeanActivity.this);
image_scale.startAnimation(hyperspaceJump);
break;
case 2:
img_deckbean_info.setImageDrawable((Drawable) msg.obj);
break;
case 3:
image_scale.setImageDrawable((Drawable) msg.obj);
break;
default:
break;
}
}
};
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
switch (state_machine) {
case 0:
state_machine = 1;
img_ring.setImageResource(R.drawable.ef_ring);
Animation ef_ring = AnimationUtils.loadAnimation(this,
R.anim.ring_animation);
ef_ring.setAnimationListener(this);
img_ring.startAnimation(ef_ring);
break;
case 1:
state_machine = 2;
img_ring.setVisibility(View.INVISIBLE);
image_scale.setOnClickListener(this);
break;
case 2:
img_ring.setVisibility(View.INVISIBLE);
gotoGetCard();
break;
default:
break;
}
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!clickable)
return;
switch (v.getId()) {
case R.id.btnhelp_splash_deckbean:// go to help Activity
clickable = false;
Intent i = new Intent(this, HelpActivity.class);
i.putExtra("indexTypeHelp", 8);
startActivityForResult(i, 5);
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
break;
case R.id.btnBack_splash_deckbean:
clickable = false;
backtoCardDeckActivity();
break;
case R.id.img_scale: // go to get card Activity
clickable = false;
if (setting.sound) {
new ThreadPlayMusic(this).start();
}
img_ring.setVisibility(View.VISIBLE);
Animation ef_ring = AnimationUtils.loadAnimation(this,
R.anim.ring_animation);
ef_ring.setAnimationListener(this);
img_ring.startAnimation(ef_ring);
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
clickable = true;
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
backtoCardDeckActivity();
}
private void gotoGetCard() {
Intent intent = new Intent(this, GetCardActivity.class);
intent.putExtras(getIntent().getExtras());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
this.finish();
}
private void backtoCardDeckActivity() {
Intent intent = new Intent(this, CardDeckActivity.class);
intent.putExtras(getIntent().getExtras());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
this.finish();
}
class ThreadPlayMusic extends Thread {
Context mContext;
ThreadPlayMusic(Context context) {
mContext = context;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
MediaPlayer mediaPlayer = MediaPlayer.create(mContext,
R.raw.se_deck_clearing);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.