code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.text.TextUtils;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background {@link android.app.Service} that adds or removes session Calendar events through
* the {@link CalendarContract} API available in Android 4.0 or above.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class SessionCalendarService extends IntentService {
private static final String TAG = makeLogTag(SessionCalendarService.class);
public static final String ACTION_ADD_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.ADD_SESSION_CALENDAR";
public static final String ACTION_REMOVE_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.REMOVE_SESSION_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.UPDATE_ALL_SESSIONS_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED =
"com.google.android.apps.iosched.action.UPDATE_CALENDAR_COMPLETED";
public static final String ACTION_CLEAR_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.CLEAR_ALL_SESSIONS_CALENDAR";
public static final String EXTRA_ACCOUNT_NAME =
"com.google.android.apps.iosched.extra.ACCOUNT_NAME";
public static final String EXTRA_SESSION_BLOCK_START =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_START";
public static final String EXTRA_SESSION_BLOCK_END =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_END";
public static final String EXTRA_SESSION_TITLE =
"com.google.android.apps.iosched.extra.SESSION_TITLE";
public static final String EXTRA_SESSION_ROOM =
"com.google.android.apps.iosched.extra.SESSION_ROOM";
private static final long INVALID_CALENDAR_ID = -1;
// TODO: localize
private static final String CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION =
"%added by Google I/O 2012%";
public SessionCalendarService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
final ContentResolver resolver = getContentResolver();
boolean isAddEvent = false;
if (ACTION_ADD_SESSION_CALENDAR.equals(action)) {
isAddEvent = true;
} else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) {
isAddEvent = false;
} else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processAllSessionsCalendar(resolver, getCalendarId(intent)));
sendBroadcast(new Intent(
SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED));
} catch (RemoteException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
}
} else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processClearAllSessions(resolver, getCalendarId(intent)));
} catch (RemoteException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
}
} else {
return;
}
final Uri uri = intent.getData();
final Bundle extras = intent.getExtras();
if (uri == null || extras == null) {
return;
}
try {
resolver.applyBatch(CalendarContract.AUTHORITY,
processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri,
extras.getLong(EXTRA_SESSION_BLOCK_START),
extras.getLong(EXTRA_SESSION_BLOCK_END),
extras.getString(EXTRA_SESSION_TITLE),
extras.getString(EXTRA_SESSION_ROOM)));
} catch (RemoteException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
}
}
/**
* Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user
* specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}.
*/
private long getCalendarId(Intent intent) {
final String accountName;
if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) {
accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
} else {
accountName = AccountUtils.getChosenAccountName(this);
}
if (TextUtils.isEmpty(accountName)) {
return INVALID_CALENDAR_ID;
}
// TODO: The calendar ID should be stored in shared preferences upon choosing an account.
Cursor calendarsCursor = getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
new String[]{"_id"},
// TODO: Handle case where the calendar is not displayed or not sync'd
"account_name = ownerAccount and account_name = ?",
new String[]{accountName},
null);
long calendarId = INVALID_CALENDAR_ID;
if (calendarsCursor != null && calendarsCursor.moveToFirst()) {
calendarId = calendarsCursor.getLong(0);
calendarsCursor.close();
}
return calendarId;
}
private String makeCalendarEventTitle(String sessionTitle) {
return sessionTitle + getResources().getString(R.string.session_calendar_suffix);
}
/**
* Processes all sessions in the
* {@link com.google.android.apps.iosched.provider.ScheduleProvider}, adding or removing
* calendar events to/from the specified Google Calendar depending on whether a session is
* in the user's schedule or not.
*/
private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver,
final long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Retrieves all sessions. For each session, add to Calendar if starred and attempt to
// remove from Calendar if unstarred.
Cursor cursor = resolver.query(
ScheduleContract.Sessions.CONTENT_URI,
SessionsQuery.PROJECTION,
null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Uri uri = ScheduleContract.Sessions.buildSessionUri(
Long.valueOf(cursor.getLong(0)).toString());
boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_STARRED) == 1);
if (isAddEvent) {
batch.addAll(processSessionCalendar(resolver,
calendarId, isAddEvent, uri,
cursor.getLong(SessionsQuery.BLOCK_START),
cursor.getLong(SessionsQuery.BLOCK_END),
cursor.getString(SessionsQuery.SESSION_TITLE),
cursor.getString(SessionsQuery.ROOM_NAME)));
}
}
cursor.close();
}
return batch;
}
/**
* Adds or removes a single session to/from the specified Google Calendar.
*/
private ArrayList<ContentProviderOperation> processSessionCalendar(
final ContentResolver resolver,
final long calendarId, final boolean isAddEvent,
final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd,
final String sessionTitle, final String sessionRoom) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);
Cursor cursor;
ContentValues values = new ContentValues();
// Add Calendar event.
if (isAddEvent) {
if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
return batch;
}
// Check if the calendar event exists first. If it does, we don't want to add a
// duplicate one.
cursor = resolver.query(
CalendarContract.Events.CONTENT_URI, // URI
new String[] {CalendarContract.Events._ID}, // Projection
CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
+ CalendarContract.Events.TITLE + "=? and "
+ CalendarContract.Events.DTSTART + ">=? and "
+ CalendarContract.Events.DTEND + "<=?",
new String[]{ // Selection args
Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
},
null);
long newEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
// Calendar event already exists for this session.
newEventId = cursor.getLong(0);
cursor.close();
} else {
// Calendar event doesn't exist, create it.
// NOTE: we can't use batch processing here because we need the result of
// the insert.
values.clear();
values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
values.put(CalendarContract.Events.TITLE, calendarEventTitle);
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
values.put(CalendarContract.Events.EVENT_TIMEZONE,
UIUtils.CONFERENCE_TIME_ZONE.getID());
Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
String eventId = eventUri.getLastPathSegment();
if (eventId == null) {
return batch; // Should be empty at this point
}
newEventId = Long.valueOf(eventId);
// Since we're adding session reminder to system notification, we're not creating
// Calendar event reminders. If we were to create Calendar event reminders, this
// is how we would do it.
//values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
//values.put(CalendarContract.Reminders.MINUTES, 10);
//values.put(CalendarContract.Reminders.METHOD,
// CalendarContract.Reminders.METHOD_ALERT); // Or default?
//cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//values.clear();
}
// Update the session in our own provider with the newly created calendar event ID.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
resolver.update(sessionUri, values, null, null);
} else {
// Remove Calendar event, if exists.
// Get the event calendar id.
cursor = resolver.query(sessionUri,
new String[] {ScheduleContract.Sessions.SESSION_CAL_EVENT_ID},
null, null, null);
long calendarEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
calendarEventId = cursor.getLong(0);
cursor.close();
}
// Try to remove the Calendar Event based on key. If successful, move on;
// otherwise, remove the event based on Event title.
int affectedRows = 0;
if (calendarEventId != -1) {
affectedRows = resolver.delete(
CalendarContract.Events.CONTENT_URI,
CalendarContract.Events._ID + "=?",
new String[]{Long.valueOf(calendarEventId).toString()});
}
if (affectedRows == 0) {
resolver.delete(CalendarContract.Events.CONTENT_URI,
String.format("%s=? and %s=? and %s=? and %s=?",
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND),
new String[]{Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.valueOf(sessionBlockStart).toString(),
Long.valueOf(sessionBlockEnd).toString()});
}
// Remove the session and calendar event association.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
resolver.update(sessionUri, values, null, null);
}
return batch;
}
/**
* Removes all calendar entries associated with Google I/O 2012.
*/
private ArrayList<ContentProviderOperation> processClearAllSessions(
ContentResolver resolver, long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Delete all calendar entries matching the given title within the given time period
batch.add(ContentProviderOperation
.newDelete(CalendarContract.Events.CONTENT_URI)
.withSelection(
CalendarContract.Events.CALENDAR_ID + " = ? and "
+ CalendarContract.Events.TITLE + " LIKE ? and "
+ CalendarContract.Events.DTSTART + ">= ? and "
+ CalendarContract.Events.DTEND + "<= ?",
new String[]{
Long.toString(calendarId),
CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
})
.build());
return batch;
}
private interface SessionsQuery {
String[] PROJECTION = {
ScheduleContract.Sessions._ID,
ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.ROOM_NAME,
ScheduleContract.Sessions.SESSION_STARRED,
};
int _ID = 0;
int BLOCK_START = 1;
int BLOCK_END = 2;
int SESSION_TITLE = 3;
int ROOM_NAME = 4;
int SESSION_STARRED = 5;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background service to handle scheduling of starred session notification via
* {@link android.app.AlarmManager}.
*/
public class SessionAlarmService extends IntentService {
private static final String TAG = makeLogTag(SessionAlarmService.class);
public static final String ACTION_NOTIFY_SESSION =
"com.google.android.apps.iosched.action.NOTIFY_SESSION";
public static final String ACTION_SCHEDULE_STARRED_BLOCK =
"com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK";
public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS =
"com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS";
public static final String EXTRA_SESSION_START =
"com.google.android.apps.iosched.extra.SESSION_START";
public static final String EXTRA_SESSION_END =
"com.google.android.apps.iosched.extra.SESSION_END";
public static final String EXTRA_SESSION_ALARM_OFFSET =
"com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET";
private static final int NOTIFICATION_ID = 100;
// pulsate every 1 second, indicating a relatively high degree of urgency
private static final int NOTIFICATION_LED_ON_MS = 100;
private static final int NOTIFICATION_LED_OFF_MS = 1000;
private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan
private static final long ONE_MINUTE_MILLIS = 1 * 60 * 1000;
private static final long TEN_MINUTES_MILLIS = 10 * ONE_MINUTE_MILLIS;
private static final long UNDEFINED_ALARM_OFFSET = -1;
public SessionAlarmService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) {
scheduleAllStarredBlocks();
return;
}
final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, -1);
if (sessionStart == -1) {
return;
}
final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, -1);
if (sessionEnd == -1) {
return;
}
final long sessionAlarmOffset =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
UNDEFINED_ALARM_OFFSET);
if (ACTION_NOTIFY_SESSION.equals(action)) {
notifySession(sessionStart, sessionEnd, sessionAlarmOffset);
} else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) {
scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset);
}
}
private void scheduleAlarm(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
final long currentTime = System.currentTimeMillis();
// If the session is already started, do not schedule system notification.
if (currentTime > sessionStart) {
return;
}
// By default, sets alarm to go off at 10 minutes before session start time. If alarm
// offset is provided, alarm is set to go off by that much time from now.
long alarmTime;
if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
alarmTime = sessionStart - TEN_MINUTES_MILLIS;
} else {
alarmTime = currentTime + alarmOffset;
}
final Intent alarmIntent = new Intent(
ACTION_NOTIFY_SESSION,
null,
this,
SessionAlarmService.class);
// Setting data to ensure intent's uniqueness for different session start times.
alarmIntent.setData(
new Uri.Builder()
.authority(ScheduleContract.CONTENT_AUTHORITY)
.path(String.valueOf(sessionStart))
.build());
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Schedule an alarm to be fired to notify user of added sessions are about to begin.
am.set(AlarmManager.RTC_WAKEUP, alarmTime,
PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}
/**
* Constructs and triggers system notification for when starred sessions are about to begin.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notifySession(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
long currentTime = System.currentTimeMillis();
if (sessionStart < currentTime) {
return;
}
// Avoid repeated notifications.
if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(
this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
return;
}
final ContentResolver resolver = getContentResolver();
final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri(
ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
Cursor cursor = resolver.query(starredBlockUri,
new String[]{
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Sessions.SESSION_TITLE
},
null, null, null);
int starredCount = 0;
ArrayList<String> starredSessionTitles = new ArrayList<String>();
while (cursor.moveToNext()) {
starredSessionTitles.add(cursor.getString(1));
starredCount = cursor.getInt(0);
}
if (starredCount < 1) {
return;
}
// Generates the pending intent which gets fired when the user touches on the notification.
Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri);
sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
final Resources res = getResources();
String contentText;
int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
if (minutesLeft < 1) {
minutesLeft = 1;
}
if (starredCount == 1) {
contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
} else {
contentText = res.getQuantityString(R.plurals.session_notification_text,
starredCount - 1,
minutesLeft,
starredCount - 1);
}
// Construct a notification. Use Jelly Bean (API 16) rich notifications if possible.
Notification notification;
if (UIUtils.hasJellyBean()) {
// Rich notifications
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
if (minutesLeft > 5) {
builder.addAction(R.drawable.ic_alarm_holo_dark,
String.format(res.getString(R.string.snooze_x_min), 5),
createSnoozeIntent(sessionStart, sessionEnd, 5));
}
Notification.InboxStyle richNotification = new Notification.InboxStyle(
builder)
.setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title,
starredCount,
minutesLeft,
starredCount));
// Adds starred sessions starting at this time block to the notification.
for (int i = 0; i < starredCount; i++) {
richNotification.addLine(starredSessionTitles.get(i));
}
notification = richNotification.build();
} else {
// Pre-Jelly Bean non-rich notifications
notification = new NotificationCompat.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.getNotification();
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, notification);
}
private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
final int snoozeMinutes) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, this, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
snoozeMinutes * ONE_MINUTE_MILLIS);
return PendingIntent.getService(this, 0, scheduleIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private void scheduleAllStarredBlocks() {
final Cursor cursor = getContentResolver().query(
ScheduleContract.Sessions.CONTENT_STARRED_URI,
new String[] {
"distinct " + ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END
},
null, null, null);
if (cursor == null) {
return;
}
while (cursor.moveToNext()) {
final long sessionStart = cursor.getLong(0);
final long sessionEnd = cursor.getLong(1);
scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched;
public class Config {
// OAuth 2.0 related config
public static final String APP_NAME = "Your-App-Name";
public static final String API_KEY = "API_KEY"; // from the APIs console
public static final String CLIENT_ID = "0000000000000.apps.googleusercontent.com"; // from the APIs console
// Conference API-specific config
// NOTE: the backend used for the Google I/O 2012 Android app is not currently open source, so
// you should modify these fields to reflect your own backend.
private static final String CONFERENCE_API_KEY = "API_KEY";
private static final String ROOT_EVENT_ID = "googleio2012";
private static final String BASE_URL = "https://google-developers.appspot.com/_ah/api/resources/v0.1";
public static final String GET_ALL_SESSIONS_URL = BASE_URL + "/sessions?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY;
public static final String GET_ALL_SPEAKERS_URL = BASE_URL + "/speakers?event_id=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY;
public static final String GET_ALL_ANNOUNCEMENTS_URL = BASE_URL + "/announcements?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY;
public static final String EDIT_MY_SCHEDULE_URL = BASE_URL + "/editmyschedule/o/";
// Static file host for the sandbox data
public static final String GET_SANDBOX_URL = "https://developers.google.com/events/io/sandbox-data";
// YouTube API config
public static final String YOUTUBE_API_KEY = "API_KEY";
// YouTube share URL
public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/";
// Livestream captions config
public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL = "TODO";
public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL = "TODO";
public static final String PRIMARY_LIVESTREAM_TRACK = "android";
public static final String SECONDARY_LIVESTREAM_TRACK = "chrome";
// GCM config
public static final String GCM_SERVER_URL = "https://yourapp-gcm.appspot.com";
public static final String GCM_SENDER_ID = "0000000000000"; // project ID from the APIs console
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.appwidget;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.SessionLivestreamActivity;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.widget.RemoteViews;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* The app widget's AppWidgetProvider.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyScheduleWidgetProvider extends AppWidgetProvider {
private static final String TAG = makeLogTag(MyScheduleWidgetProvider.class);
public static final String EXTRA_BLOCK_ID = "block_id";
public static final String EXTRA_STARRED_SESSION_ID = "star_session_id";
public static final String EXTRA_BLOCK_TYPE = "block_type";
public static final String EXTRA_STARRED_SESSION = "starred_session";
public static final String EXTRA_NUM_STARRED_SESSIONS = "num_starred_sessions";
public static final String EXTRA_BUTTON = "extra_button";
public static final String CLICK_ACTION =
"com.google.android.apps.iosched.appwidget.action.CLICK";
public static final String REFRESH_ACTION =
"com.google.android.apps.iosched.appwidget.action.REFRESH";
public static final String EXTRA_PERFORM_SYNC =
"com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC";
private static Handler sWorkerQueue;
// TODO: this will get destroyed when the app process is killed. need better observer strategy.
private static SessionDataProviderObserver sDataObserver;
public MyScheduleWidgetProvider() {
// Start the worker thread
HandlerThread sWorkerThread = new HandlerThread("MyScheduleWidgetProvider-worker");
sWorkerThread.start();
sWorkerQueue = new Handler(sWorkerThread.getLooper());
}
@Override
public void onEnabled(Context context) {
final ContentResolver r = context.getContentResolver();
if (sDataObserver == null) {
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class);
sDataObserver = new SessionDataProviderObserver(mgr, cn, sWorkerQueue);
r.registerContentObserver(ScheduleContract.Sessions.CONTENT_URI, true, sDataObserver);
}
}
@Override
public void onReceive(final Context context, Intent widgetIntent) {
final String action = widgetIntent.getAction();
if (REFRESH_ACTION.equals(action)) {
final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false);
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
// Trigger sync
String chosenAccountName = AccountUtils.getChosenAccountName(context);
if (shouldSync && chosenAccountName != null) {
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(
new Account(chosenAccountName, GoogleAccountManager.ACCOUNT_TYPE),
ScheduleContract.CONTENT_AUTHORITY, extras);
}
// Update widget
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context,
MyScheduleWidgetProvider.class);
mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn),
R.id.widget_schedule_list);
}
});
} else if (CLICK_ACTION.equals(action)) {
String blockId = widgetIntent.getStringExtra(EXTRA_BLOCK_ID);
int numStarredSessions = widgetIntent.getIntExtra(EXTRA_NUM_STARRED_SESSIONS, 0);
String starredSessionId = widgetIntent.getStringExtra(EXTRA_STARRED_SESSION_ID);
String blockType = widgetIntent.getStringExtra(EXTRA_BLOCK_TYPE);
boolean starredSession = widgetIntent.getBooleanExtra(EXTRA_STARRED_SESSION, false);
boolean extraButton = widgetIntent.getBooleanExtra(EXTRA_BUTTON, false);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "starredSession:" + starredSession);
LOGV(TAG, "blockType:" + blockType);
LOGV(TAG, "numStarredSessions:" + numStarredSessions);
LOGV(TAG, "extraButton:" + extraButton);
if (ParserUtils.BLOCK_TYPE_SESSION.equals(blockType)
|| ParserUtils.BLOCK_TYPE_CODE_LAB.equals(blockType)) {
Uri sessionsUri;
if (numStarredSessions == 0) {
sessionsUri = ScheduleContract.Blocks.buildSessionsUri(
blockId);
LOGV(TAG, "sessionsUri:" + sessionsUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else if (numStarredSessions == 1) {
if (extraButton) {
sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId);
LOGV(TAG, "sessionsUri extraButton:" + sessionsUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
sessionsUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId);
LOGV(TAG, "sessionsUri:" + sessionsUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
} else {
if (extraButton) {
sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId);
LOGV(TAG, "sessionsUri extraButton:" + sessionsUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
sessionsUri = ScheduleContract.Blocks.buildStarredSessionsUri(blockId);
LOGV(TAG, "sessionsUri:" + sessionsUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
} else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(blockType)) {
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId);
LOGV(TAG, "sessionUri:" + sessionUri);
Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri);
intent.setClass(context, SessionLivestreamActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
super.onReceive(context, widgetIntent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final boolean isAuthenticated = AccountUtils.isAuthenticated(context);
for (int appWidgetId : appWidgetIds) {
// Specify the service to provide data for the collection widget. Note that we need to
// embed the appWidgetId via the data otherwise it will be ignored.
final Intent intent = new Intent(context, MyScheduleWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
final RemoteViews rv = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
compatSetRemoteAdapter(rv, appWidgetId, intent);
// Set the empty view to be displayed if the collection is empty. It must be a sibling
// view of the collection view.
rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty);
rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated
? R.string.empty_widget_text
: R.string.empty_widget_text_signed_out));
final Intent onClickIntent = new Intent(context, MyScheduleWidgetProvider.class);
onClickIntent.setAction(MyScheduleWidgetProvider.CLICK_ACTION);
onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0,
onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent);
final Intent refreshIntent = new Intent(context, MyScheduleWidgetProvider.class);
refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION);
refreshIntent.putExtra(MyScheduleWidgetProvider.EXTRA_PERFORM_SYNC, true);
final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0,
refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent);
final Intent openAppIntent = new Intent(context, HomeActivity.class);
final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0,
openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, rv);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void compatSetRemoteAdapter(RemoteViews rv, int appWidgetId, Intent intent) {
if (UIUtils.hasICS()) {
rv.setRemoteAdapter(R.id.widget_schedule_list, intent);
} else {
//noinspection deprecation
rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent);
}
}
private static class SessionDataProviderObserver extends ContentObserver {
private AppWidgetManager mAppWidgetManager;
private ComponentName mComponentName;
SessionDataProviderObserver(AppWidgetManager appWidgetManager, ComponentName componentName,
Handler handler) {
super(handler);
mAppWidgetManager = appWidgetManager;
mComponentName = componentName;
}
@Override
public void onChange(boolean selfChange) {
// The data has changed, so notify the widget that the collection view needs to be updated.
// In response, the factory's onDataSetChanged() will be called which will requery the
// cursor for the new data.
mAppWidgetManager.notifyAppWidgetViewDataChanged(
mAppWidgetManager.getAppWidgetIds(mComponentName),
R.id.widget_schedule_list);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.appwidget;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter;
import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter.Section;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This is the service that provides the factory to be bound to the collection service.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyScheduleWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetRemoveViewsFactory(this.getApplicationContext());
}
/**
* This is the factory that will provide data to the collection widget.
*/
private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class);
private Context mContext;
private Cursor mCursor;
private SparseIntArray mPMap;
private List<SimpleSectionedListAdapter.Section> mSections;
private SparseBooleanArray mHeaderPositionMap;
public WidgetRemoveViewsFactory(Context context) {
mContext = context;
}
public void onCreate() {
// Since we reload the cursor in onDataSetChanged() which gets called immediately after
// onCreate(), we do nothing here.
}
public void onDestroy() {
if (mCursor != null) {
mCursor.close();
}
}
public int getCount() {
if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) {
return 0;
}
int size = mCursor.getCount() + mSections.size();
if (size < 10) {
init();
size = mCursor.getCount() + mSections.size();
}
LOGV(TAG, "size returned:" + size);
return size;
}
public RemoteViews getViewAt(int position) {
RemoteViews rv;
boolean isSectionHeader = mHeaderPositionMap.get(position);
int offset = mPMap.get(position);
if (isSectionHeader) {
rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header);
Section section = mSections.get(offset - 1);
rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle());
} else {
int cursorPosition = position - offset;
mCursor.moveToPosition(cursorPosition);
rv = new RemoteViews(mContext.getPackageName(),
R.layout.list_item_schedule_block_widget);
final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID);
final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE);
final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META);
final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START);
final Resources res = mContext.getResources();
if (ParserUtils.BLOCK_TYPE_SESSION.equals(type)
|| ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) {
final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
if (numStarredSessions == 0) {
// No sessions starred
rv.setTextViewText(R.id.block_title, mContext.getString(
R.string.schedule_empty_slot_title_template,
TextUtils.isEmpty(blockTitle)
? ""
: (" " + blockTitle.toLowerCase())));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1_positive));
rv.setTextViewText(R.id.block_subtitle, mContext.getString(
R.string.schedule_empty_slot_subtitle));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, false);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
} else if (numStarredSessions == 1) {
// exactly 1 session starred
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
String starredSessionRoomName =
mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (starredSessionRoomName == null) {
// TODO: remove this WAR for API not returning rooms for code labs
starredSessionRoomName = mContext.getString(
starredSessionTitle.contains("Code Lab")
? R.string.codelab_room
: R.string.unknown_room);
}
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle, starredSessionRoomName);
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID,
starredSessionId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
final Intent fillInIntent2 = new Intent();
final Bundle extras2 = new Bundle();
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true);
extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent2.putExtras(extras2);
rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2);
} else {
// 2 or more sessions starred
rv.setTextViewText(R.id.block_title,
mContext.getString(R.string.schedule_conflict_title,
numStarredSessions));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle,
mContext.getString(R.string.schedule_conflict_subtitle));
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
final Intent fillInIntent2 = new Intent();
final Bundle extras2 = new Bundle();
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true);
extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent2.putExtras(extras2);
rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2);
}
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2));
} else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) {
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID,
starredSessionId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
} else {
rv.setTextViewText(R.id.block_title, blockTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled));
rv.setTextViewText(R.id.block_subtitle, blockMeta);
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, -1);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
}
rv.setTextViewText(R.id.block_time, DateUtils.formatDateTime(mContext, blockStart,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
}
return rv;
}
public RemoteViews getLoadingView() {
return null;
}
public int getViewTypeCount() {
return 2;
}
public long getItemId(int position) {
return position;
}
public boolean hasStableIds() {
return true;
}
public void onDataSetChanged() {
init();
}
private void init() {
if (mCursor != null) {
mCursor.close();
}
mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
ScheduleContract.Blocks.BLOCK_END + " >= ?",
new String[]{
Long.toString(UIUtils.getCurrentTime(mContext))
},
ScheduleContract.Blocks.DEFAULT_SORT);
mSections = new ArrayList<SimpleSectionedListAdapter.Section>();
mCursor.moveToFirst();
long previousTime = -1;
long time;
mPMap = new SparseIntArray();
mHeaderPositionMap = new SparseBooleanArray();
int offset = 0;
int globalPosition = 0;
while (!mCursor.isAfterLast()) {
time = mCursor.getLong(BlocksQuery.BLOCK_START);
if (!UIUtils.isSameDay(previousTime, time)) {
mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(),
DateUtils.formatDateTime(mContext, time,
DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_WEEKDAY)));
++offset;
mHeaderPositionMap.put(globalPosition, true);
mPMap.put(globalPosition, offset);
++globalPosition;
}
mHeaderPositionMap.put(globalPosition, false);
mPMap.put(globalPosition, offset);
++globalPosition;
previousTime = time;
mCursor.moveToNext();
}
LOGV(TAG, "Leaving init()");
}
}
public interface BlocksQuery {
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Blocks.BLOCK_ID,
ScheduleContract.Blocks.BLOCK_TITLE,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Blocks.BLOCK_TYPE,
ScheduleContract.Blocks.BLOCK_META,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_ID,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
};
int _ID = 0;
int BLOCK_ID = 1;
int BLOCK_TITLE = 2;
int BLOCK_START = 3;
int BLOCK_END = 4;
int BLOCK_TYPE = 5;
int BLOCK_META = 6;
int NUM_STARRED_SESSIONS = 7;
int STARRED_SESSION_ID = 8;
int STARRED_SESSION_TITLE = 9;
int STARRED_SESSION_ROOM_NAME = 10;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables;
import com.google.android.apps.iosched.util.SelectionBuilder;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various
* {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = makeLogTag(ScheduleProvider.class);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int BLOCKS_ID_SESSIONS_STARRED = 104;
private static final int TRACKS = 200;
private static final int TRACKS_ID = 201;
private static final int TRACKS_ID_SESSIONS = 202;
private static final int TRACKS_ID_VENDORS = 203;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_WITH_TRACK = 402;
private static final int SESSIONS_SEARCH = 403;
private static final int SESSIONS_AT = 404;
private static final int SESSIONS_ID = 405;
private static final int SESSIONS_ID_SPEAKERS = 406;
private static final int SESSIONS_ID_TRACKS = 407;
private static final int SESSIONS_ID_WITH_TRACK = 408;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_ID_SESSIONS = 502;
private static final int VENDORS = 600;
private static final int VENDORS_STARRED = 601;
private static final int VENDORS_SEARCH = 603;
private static final int VENDORS_ID = 604;
private static final int ANNOUNCEMENTS = 700;
private static final int ANNOUNCEMENTS_ID = 701;
private static final int SEARCH_SUGGEST = 800;
private static final String MIME_XML = "text/xml";
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED);
matcher.addURI(authority, "tracks", TRACKS);
matcher.addURI(authority, "tracks/*", TRACKS_ID);
matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS);
matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS);
matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS);
matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS);
matcher.addURI(authority, "vendors", VENDORS);
matcher.addURI(authority, "vendors/starred", VENDORS_STARRED);
matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH);
matcher.addURI(authority, "vendors/*", VENDORS_ID);
matcher.addURI(authority, "announcements", ANNOUNCEMENTS);
matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new ScheduleDatabase(getContext());
return true;
}
private void deleteDatabase() {
// TODO: wait for content provider operations to finish, then tear down
mOpenHelper.close();
Context context = getContext();
ScheduleDatabase.deleteDatabase(context);
mOpenHelper = new ScheduleDatabase(getContext());
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case BLOCKS_ID_SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case TRACKS:
return Tracks.CONTENT_TYPE;
case TRACKS_ID:
return Tracks.CONTENT_ITEM_TYPE;
case TRACKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TRACKS_ID_VENDORS:
return Vendors.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SESSIONS_ID_SPEAKERS:
return Speakers.CONTENT_TYPE;
case SESSIONS_ID_TRACKS:
return Tracks.CONTENT_TYPE;
case SESSIONS_ID_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case VENDORS:
return Vendors.CONTENT_TYPE;
case VENDORS_STARRED:
return Vendors.CONTENT_TYPE;
case VENDORS_SEARCH:
return Vendors.CONTENT_TYPE;
case VENDORS_ID:
return Vendors.CONTENT_ITEM_TYPE;
case ANNOUNCEMENTS:
return Announcements.CONTENT_TYPE;
case ANNOUNCEMENTS_ID:
return Announcements.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
case SEARCH_SUGGEST: {
final SelectionBuilder builder = new SelectionBuilder();
// Adjust incoming query to become SQL text match
selectionArgs[0] = selectionArgs[0] + "%";
builder.table(Tables.SEARCH_SUGGEST);
builder.where(selection, selectionArgs);
builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_TEXT_1);
projection = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_QUERY
};
final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
}
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TRACKS: {
db.insertOrThrow(Tables.TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SESSIONS_ID_SPEAKERS: {
db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID));
}
case SESSIONS_ID_TRACKS: {
db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
case VENDORS: {
db.insertOrThrow(Tables.VENDORS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID));
}
case ANNOUNCEMENTS: {
db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Announcements.buildAnnouncementUri(values
.getAsString(Announcements.ANNOUNCEMENT_ID));
}
case SEARCH_SUGGEST: {
db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return SearchSuggest.CONTENT_URI;
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
LOGV(TAG, "delete(uri=" + uri + ")");
if (uri == ScheduleContract.BASE_CONTENT_URI) {
// Handle whole database deletes (e.g. when signing out)
deleteDatabase();
getContext().getContentResolver().notifyChange(uri, null, false);
return 1;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
getContext().getContentResolver().notifyChange(uri, null,
!ScheduleContract.hasCallerIsSyncAdapterParameter(uri));
return retVal;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TRACKS: {
return builder.table(Tables.TRACKS);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS);
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case SEARCH_SUGGEST: {
return builder.table(Tables.SEARCH_SUGGEST);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder
.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID)
.map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE)
.map(Blocks.STARRED_SESSION_HASHTAGS,
Subquery.BLOCK_STARRED_SESSION_HASHTAGS)
.map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL)
.map(Blocks.STARRED_SESSION_LIVESTREAM_URL,
Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL)
.map(Blocks.STARRED_SESSION_ROOM_NAME,
Subquery.BLOCK_STARRED_SESSION_ROOM_NAME)
.map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS_STARRED: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId)
.where(Qualified.SESSIONS_STARRED + "=1");
}
case TRACKS: {
return builder.table(Tables.TRACKS)
.map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT)
.map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SESSIONS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId);
}
case TRACKS_ID_VENDORS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Qualified.VENDORS_TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_WITH_TRACK: {
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS);
}
case SESSIONS_ID_WITH_TRACK: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS)
.mapToTable(Speakers._ID, Tables.SPEAKERS)
.mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS)
.where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS)
.mapToTable(Tracks._ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_ID_SESSIONS: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS);
}
case VENDORS_STARRED: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_STARRED + "=1");
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT "
+ Qualified.SESSIONS_LIVESTREAM_URL
+ " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")";
String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM "
+ Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "="
+ Qualified.TRACKS_TRACK_ID + ")";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.TRACK_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SPEAKER_ID;
String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID;
String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS;
String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL;
String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL;
String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME;
String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID;
String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for managing {@link SQLiteDatabase} that stores data for
* {@link ScheduleProvider}.
*/
public class ScheduleDatabase extends SQLiteOpenHelper {
private static final String TAG = makeLogTag(ScheduleDatabase.class);
private static final String DATABASE_NAME = "schedule.db";
// NOTE: carefully update onUpgrade() when bumping database versions to make
// sure user data is saved.
private static final int VER_LAUNCH = 25;
private static final int VER_SESSION_TYPE = 26;
private static final int DATABASE_VERSION = VER_SESSION_TYPE;
interface Tables {
String BLOCKS = "blocks";
String TRACKS = "tracks";
String ROOMS = "rooms";
String SESSIONS = "sessions";
String SPEAKERS = "speakers";
String SESSIONS_SPEAKERS = "sessions_speakers";
String SESSIONS_TRACKS = "sessions_tracks";
String VENDORS = "vendors";
String ANNOUNCEMENTS = "announcements";
String SESSIONS_SEARCH = "sessions_search";
String SEARCH_SUGGEST = "search_suggest";
String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_ROOMS = "sessions "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String VENDORS_JOIN_TRACKS = "vendors "
+ "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id";
String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers "
+ "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id";
String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers "
+ "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks "
+ "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id";
String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks "
+ "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search "
+ "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions "
+ "LEFT OUTER JOIN sessions_tracks ON "
+ "sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id";
String BLOCKS_JOIN_SESSIONS = "blocks "
+ "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id";
}
private interface Triggers {
String SESSIONS_SEARCH_INSERT = "sessions_search_insert";
String SESSIONS_SEARCH_DELETE = "sessions_search_delete";
String SESSIONS_SEARCH_UPDATE = "sessions_search_update";
// Deletes from session_tracks when corresponding sessions are deleted.
String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete";
}
public interface SessionsSpeakers {
String SESSION_ID = "session_id";
String SPEAKER_ID = "speaker_id";
}
public interface SessionsTracks {
String SESSION_ID = "session_id";
String TRACK_ID = "track_id";
}
interface SessionsSearchColumns {
String SESSION_ID = "session_id";
String BODY = "body";
}
/** Fully-qualified field names. */
private interface Qualified {
String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "."
+ SessionsSearchColumns.SESSION_ID;
String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID
+ "," + SessionsSearchColumns.BODY + ")";
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
}
/** {@code REFERENCES} clauses. */
private interface References {
String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")";
String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")";
String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")";
String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")";
String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")";
String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")";
}
private interface Subquery {
/**
* Subquery used to build the {@link SessionsSearchColumns#BODY} string
* used for indexing {@link Sessions} content.
*/
String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE
+ "||'; '||new." + Sessions.SESSION_ABSTRACT
+ "||'; '||" + "coalesce(new." + Sessions.SESSION_TAGS + ", '')"
+ ")";
}
public ScheduleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.BLOCKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BlocksColumns.BLOCK_ID + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_START + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_END + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_TYPE + " TEXT,"
+ BlocksColumns.BLOCK_META + " TEXT,"
+ "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TracksColumns.TRACK_ID + " TEXT NOT NULL,"
+ TracksColumns.TRACK_NAME + " TEXT,"
+ TracksColumns.TRACK_COLOR + " INTEGER,"
+ TracksColumns.TRACK_ABSTRACT + " TEXT,"
+ "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ROOMS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ RoomsColumns.ROOM_ID + " TEXT NOT NULL,"
+ RoomsColumns.ROOM_NAME + " TEXT,"
+ RoomsColumns.ROOM_FLOOR + " TEXT,"
+ "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SessionsColumns.SESSION_ID + " TEXT NOT NULL,"
+ Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ SessionsColumns.SESSION_TYPE + " TEXT,"
+ SessionsColumns.SESSION_LEVEL + " TEXT,"
+ SessionsColumns.SESSION_TITLE + " TEXT,"
+ SessionsColumns.SESSION_ABSTRACT + " TEXT,"
+ SessionsColumns.SESSION_REQUIREMENTS + " TEXT,"
+ SessionsColumns.SESSION_TAGS + " TEXT,"
+ SessionsColumns.SESSION_HASHTAGS + " TEXT,"
+ SessionsColumns.SESSION_URL + " TEXT,"
+ SessionsColumns.SESSION_YOUTUBE_URL + " TEXT,"
+ SessionsColumns.SESSION_PDF_URL + " TEXT,"
+ SessionsColumns.SESSION_NOTES_URL + " TEXT,"
+ SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0,"
+ SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER,"
+ SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT,"
+ "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL,"
+ SpeakersColumns.SPEAKER_NAME + " TEXT,"
+ SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT,"
+ SpeakersColumns.SPEAKER_COMPANY + " TEXT,"
+ SpeakersColumns.SPEAKER_ABSTRACT + " TEXT,"
+ SpeakersColumns.SPEAKER_URL + " TEXT,"
+ "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + ","
+ "UNIQUE (" + SessionsSpeakers.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID
+ ")");
db.execSQL("CREATE TABLE " + Tables.VENDORS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ VendorsColumns.VENDOR_ID + " TEXT NOT NULL,"
+ Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + ","
+ VendorsColumns.VENDOR_NAME + " TEXT,"
+ VendorsColumns.VENDOR_LOCATION + " TEXT,"
+ VendorsColumns.VENDOR_DESC + " TEXT,"
+ VendorsColumns.VENDOR_URL + " TEXT,"
+ VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT,"
+ VendorsColumns.VENDOR_LOGO_URL + " TEXT,"
+ VendorsColumns.VENDOR_STARRED + " INTEGER,"
+ "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_SUMMARY + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TRACKS + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)");
createSessionsSearch(db);
createSessionsDeleteTriggers(db);
db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)");
}
/**
* Create triggers that automatically build {@link Tables#SESSIONS_SEARCH}
* as values are changed in {@link Tables#SESSIONS}.
*/
private static void createSessionsSearch(SQLiteDatabase db) {
// Using the "porter" tokenizer for simple stemming, so that
// "frustration" matches "frustrated."
db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSearchColumns.BODY + " TEXT NOT NULL,"
+ SessionsSearchColumns.SESSION_ID
+ " TEXT NOT NULL " + References.SESSION_ID + ","
+ "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE,"
+ "tokenize=porter)");
// TODO: handle null fields in body, which cause trigger to fail
// TODO: implement update trigger, not currently exercised
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON "
+ Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " "
+ " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");"
+ " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " "
+ " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE
+ " AFTER UPDATE ON " + Tables.SESSIONS
+ " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = "
+ Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id"
+ "; END;");
}
private void createSessionsDeleteTriggers(SQLiteDatabase db) {
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " "
+ " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
// NOTE: This switch statement is designed to handle cascading database
// updates, starting at the current version and falling through to all
// future upgrade cases. Only use "break;" when you want to drop and
// recreate the entire database.
int version = oldVersion;
switch (version) {
case VER_LAUNCH:
// VER_SESSION_TYPE added column for session feedback URL.
db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
+ SessionsColumns.SESSION_TYPE + " TEXT");
version = VER_SESSION_TYPE;
}
LOGD(TAG, "after upgrade logic, at version " + version);
if (version != DATABASE_VERSION) {
LOGW(TAG, "Destroying old data during upgrade");
db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_UPDATE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.util.ParserUtils;
import android.app.SearchManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.util.List;
/**
* Contract class for interacting with {@link ScheduleProvider}. Unless
* otherwise noted, all time-based fields are milliseconds since epoch and can
* be compared against {@link System#currentTimeMillis()}.
* <p>
* The backing {@link android.content.ContentProvider} assumes that {@link Uri}
* are generated using stronger {@link String} identifiers, instead of
* {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during
* sync.
*/
public class ScheduleContract {
/**
* Special value for {@link SyncColumns#UPDATED} indicating that an entry
* has never been updated, or doesn't exist yet.
*/
public static final long UPDATED_NEVER = -2;
/**
* Special value for {@link SyncColumns#UPDATED} indicating that the last
* update time is unknown, usually when inserted from a local file source.
*/
public static final long UPDATED_UNKNOWN = -1;
public interface SyncColumns {
/** Last time this entry was updated or synchronized. */
String UPDATED = "updated";
}
interface BlocksColumns {
/** Unique string identifying this block of time. */
String BLOCK_ID = "block_id";
/** Title describing this block of time. */
String BLOCK_TITLE = "block_title";
/** Time when this block starts. */
String BLOCK_START = "block_start";
/** Time when this block ends. */
String BLOCK_END = "block_end";
/** Type describing this block. */
String BLOCK_TYPE = "block_type";
/** Extra string metadata for the block. */
String BLOCK_META = "block_meta";
}
interface TracksColumns {
/** Unique string identifying this track. */
String TRACK_ID = "track_id";
/** Name describing this track. */
String TRACK_NAME = "track_name";
/** Color used to identify this track, in {@link Color#argb} format. */
String TRACK_COLOR = "track_color";
/** Body of text explaining this track in detail. */
String TRACK_ABSTRACT = "track_abstract";
}
interface RoomsColumns {
/** Unique string identifying this room. */
String ROOM_ID = "room_id";
/** Name describing this room. */
String ROOM_NAME = "room_name";
/** Building floor this room exists on. */
String ROOM_FLOOR = "room_floor";
}
interface SessionsColumns {
/** Unique string identifying this session. */
String SESSION_ID = "session_id";
/** The type of session (session, keynote, codelab, etc). */
String SESSION_TYPE = "session_type";
/** Difficulty level of the session. */
String SESSION_LEVEL = "session_level";
/** Title describing this track. */
String SESSION_TITLE = "session_title";
/** Body of text explaining this session in detail. */
String SESSION_ABSTRACT = "session_abstract";
/** Requirements that attendees should meet. */
String SESSION_REQUIREMENTS = "session_requirements";
/** Keywords/tags for this session. */
String SESSION_TAGS = "session_keywords";
/** Hashtag for this session. */
String SESSION_HASHTAGS = "session_hashtag";
/** Full URL to session online. */
String SESSION_URL = "session_url";
/** Full URL to YouTube. */
String SESSION_YOUTUBE_URL = "session_youtube_url";
/** Full URL to PDF. */
String SESSION_PDF_URL = "session_pdf_url";
/** Full URL to official session notes. */
String SESSION_NOTES_URL = "session_notes_url";
/** User-specific flag indicating starred status. */
String SESSION_STARRED = "session_starred";
/** Key for session Calendar event. (Used in ICS or above) */
String SESSION_CAL_EVENT_ID = "session_cal_event_id";
/** The YouTube live stream URL. */
String SESSION_LIVESTREAM_URL = "session_livestream_url";
}
interface SpeakersColumns {
/** Unique string identifying this speaker. */
String SPEAKER_ID = "speaker_id";
/** Name of this speaker. */
String SPEAKER_NAME = "speaker_name";
/** Profile photo of this speaker. */
String SPEAKER_IMAGE_URL = "speaker_image_url";
/** Company this speaker works for. */
String SPEAKER_COMPANY = "speaker_company";
/** Body of text describing this speaker in detail. */
String SPEAKER_ABSTRACT = "speaker_abstract";
/** Full URL to the speaker's profile. */
String SPEAKER_URL = "speaker_url";
}
interface VendorsColumns {
/** Unique string identifying this vendor. */
String VENDOR_ID = "vendor_id";
/** Name of this vendor. */
String VENDOR_NAME = "vendor_name";
/** Location or city this vendor is based in. */
String VENDOR_LOCATION = "vendor_location";
/** Body of text describing this vendor. */
String VENDOR_DESC = "vendor_desc";
/** Link to vendor online. */
String VENDOR_URL = "vendor_url";
/** Body of text describing the product of this vendor. */
String VENDOR_PRODUCT_DESC = "vendor_product_desc";
/** Link to vendor logo. */
String VENDOR_LOGO_URL = "vendor_logo_url";
/** User-specific flag indicating starred status. */
String VENDOR_STARRED = "vendor_starred";
}
interface AnnouncementsColumns {
/** Unique string identifying this announcment. */
String ANNOUNCEMENT_ID = "announcement_id";
/** Title of the announcement. */
String ANNOUNCEMENT_TITLE = "announcement_title";
/** Summary of the announcement. */
String ANNOUNCEMENT_SUMMARY = "announcement_summary";
/** Track announcement belongs to. */
String ANNOUNCEMENT_TRACKS = "announcement_tracks";
/** Full URL for the announcement. */
String ANNOUNCEMENT_URL = "announcement_url";
/** Date of the announcement. */
String ANNOUNCEMENT_DATE = "announcement_date";
}
public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_BLOCKS = "blocks";
private static final String PATH_AT = "at";
private static final String PATH_BETWEEN = "between";
private static final String PATH_TRACKS = "tracks";
private static final String PATH_ROOMS = "rooms";
private static final String PATH_SESSIONS = "sessions";
private static final String PATH_WITH_TRACK = "with_track";
private static final String PATH_STARRED = "starred";
private static final String PATH_SPEAKERS = "speakers";
private static final String PATH_VENDORS = "vendors";
private static final String PATH_ANNOUNCEMENTS = "announcements";
private static final String PATH_SEARCH = "search";
private static final String PATH_SEARCH_SUGGEST = "search_suggest_query";
/**
* Blocks are generic timeslots that {@link Sessions} and other related
* events fall into.
*/
public static class Blocks implements BlocksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.block";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.block";
/** Count of {@link Sessions} inside given block. */
public static final String SESSIONS_COUNT = "sessions_count";
/**
* Flag indicating the number of sessions inside this block that have
* {@link Sessions#SESSION_STARRED} set.
*/
public static final String NUM_STARRED_SESSIONS = "num_starred_sessions";
/**
* The {@link Sessions#SESSION_ID} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ID = "starred_session_id";
/**
* The {@link Sessions#SESSION_TITLE} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_TITLE = "starred_session_title";
/**
* The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred
* session in this block.
*/
public static final String STARRED_SESSION_LIVESTREAM_URL =
"starred_session_livestream_url";
/**
* The {@link Rooms#ROOM_NAME} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name";
/**
* The {@link Rooms#ROOM_ID} of the first starred session in this block.
*/
public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id";
/**
* The {@link Sessions#SESSION_HASHTAGS} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags";
/**
* The {@link Sessions#SESSION_URL} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_URL = "starred_session_url";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, "
+ BlocksColumns.BLOCK_END + " ASC";
public static final String EMPTY_SESSIONS_SELECTION = "(" + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_SESSION + "' OR " + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_CODE_LAB + "') AND "
+ SESSIONS_COUNT + " = 0";
/** Build {@link Uri} for requested {@link #BLOCK_ID}. */
public static Uri buildBlockUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references starred {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildStarredSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)
.appendPath(PATH_STARRED).build();
}
/**
* Build {@link Uri} that references any {@link Blocks} that occur
* between the requested time boundaries.
*/
public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {
return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(
String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();
}
/** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */
public static String getBlockId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #BLOCK_ID} that will always match the requested
* {@link Blocks} details.
*/
public static String generateBlockId(long startTime, long endTime) {
startTime /= DateUtils.SECOND_IN_MILLIS;
endTime /= DateUtils.SECOND_IN_MILLIS;
return ParserUtils.sanitizeId(startTime + "-" + endTime);
}
}
/**
* Tracks are overall categories for {@link Sessions} and {@link Vendors},
* such as "Android" or "Enterprise."
*/
public static class Tracks implements TracksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.track";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.track";
/** "All tracks" ID. */
public static final String ALL_TRACK_ID = "all";
public static final String CODELABS_TRACK_ID = generateTrackId("Code Labs");
public static final String TECH_TALK_TRACK_ID = generateTrackId("Tech Talk");
/** Count of {@link Sessions} inside given track. */
public static final String SESSIONS_COUNT = "sessions_count";
/** Count of {@link Vendors} inside given track. */
public static final String VENDORS_COUNT = "vendors_count";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC";
/** Build {@link Uri} for requested {@link #TRACK_ID}. */
public static Uri buildTrackUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #TRACK_ID}.
*/
public static Uri buildSessionsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references any {@link Vendors} associated with
* the requested {@link #TRACK_ID}.
*/
public static Uri buildVendorsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build();
}
/** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */
public static String getTrackId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #TRACK_ID} that will always match the requested
* {@link Tracks} details.
*/
public static String generateTrackId(String name) {
return ParserUtils.sanitizeId(name);
}
}
/**
* Rooms are physical locations at the conference venue.
*/
public static class Rooms implements RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.room";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.room";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, "
+ RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ROOM_ID}. */
public static Uri buildRoomUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #ROOM_ID}.
*/
public static Uri buildSessionsDirUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */
public static String getRoomId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each session is a block of time that has a {@link Tracks}, a
* {@link Rooms}, and zero or more {@link Speakers}.
*/
public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,
SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();
public static final Uri CONTENT_STARRED_URI =
CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session";
public static final String BLOCK_ID = "block_id";
public static final String ROOM_ID = "room_id";
public static final String SEARCH_SNIPPET = "search_snippet";
// TODO: shortcut primary track to offer sub-sorting here
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC,"
+ SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC";
public static final String LIVESTREAM_SELECTION =
SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''";
// Used to fetch sessions for a particular time
public static final String AT_TIME_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeSelectionArgs(long time) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString };
}
// Used to fetch upcoming sessions
public static final String UPCOMING_SELECTION =
BLOCK_START + " = (select min(" + BLOCK_START + ") from " +
ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION +
" and " + BLOCK_START + " >" + " ?)";
// Builds selectionArgs for {@link UPCOMING_SELECTION}
public static String[] buildUpcomingSelectionArgs(long minTime) {
return new String[] { String.valueOf(minTime) };
}
/** Build {@link Uri} for requested {@link #SESSION_ID}. */
public static Uri buildSessionUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/**
* Build {@link Uri} that references any {@link Speakers} associated
* with the requested {@link #SESSION_ID}.
*/
public static Uri buildSpeakersDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();
}
/**
* Build {@link Uri} that includes track detail with list of sessions.
*/
public static Uri buildWithTracksUri() {
return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that includes track detail for a specific session.
*/
public static Uri buildWithTracksUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId)
.appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that references any {@link Tracks} associated with
* the requested {@link #SESSION_ID}.
*/
public static Uri buildTracksDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();
}
public static Uri buildSessionsAtDirUri(long time) {
return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))
.build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
}
/**
* Speakers are individual people that lead {@link Sessions}.
*/
public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.speaker";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.speaker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #SPEAKER_ID}. */
public static Uri buildSpeakerUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #SPEAKER_ID}.
*/
public static Uri buildSessionsDirUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */
public static String getSpeakerId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each vendor is a company appearing at the conference that may be
* associated with a specific {@link Tracks}.
*/
public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.vendor";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.vendor";
/** {@link Tracks#TRACK_ID} that this vendor belongs to. */
public static final String TRACK_ID = "track_id";
public static final String SEARCH_SNIPPET = "search_snippet";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #VENDOR_ID}. */
public static Uri buildVendorUri(String vendorId) {
return CONTENT_URI.buildUpon().appendPath(vendorId).build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */
public static String getVendorId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
/**
* Generate a {@link #VENDOR_ID} that will always match the requested
* {@link Vendors} details.
*/
public static String generateVendorId(String companyName) {
return ParserUtils.sanitizeId(companyName);
}
}
/**
* Announcements of breaking news
*/
public static class Announcements implements AnnouncementsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.announcement";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.announcement";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */
public static Uri buildAnnouncementUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId).build();
}
/**
* Build {@link Uri} that references any {@link Announcements}
* associated with the requested {@link #ANNOUNCEMENT_ID}.
*/
public static Uri buildAnnouncementsDirUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId)
.appendPath(PATH_ANNOUNCEMENTS).build();
}
/**
* Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.
*/
public static String getAnnouncementId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static class SearchSuggest {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();
public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1
+ " COLLATE NOCASE ASC";
}
public static Uri addCallerIsSyncAdapterParameter(Uri uri) {
return uri.buildUpon().appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
}
public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {
return TextUtils.equals("true",
uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));
}
private ScheduleContract() {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.Event;
import com.google.android.apps.iosched.io.model.SessionsResponse;
import com.google.android.apps.iosched.io.model.SessionsResult;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.Time;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses session JSON data into a list of content provider operations.
*/
public class SessionsHandler extends JSONHandler {
private static final String TAG = makeLogTag(SessionsHandler.class);
private static final String BASE_SESSION_URL
= "https://developers.google.com/events/io/sessions/";
private static final String EVENT_TYPE_KEYNOTE = "keynote";
private static final String EVENT_TYPE_CODELAB = "codelab";
private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1;
private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2;
private static final Time sTime = new Time();
private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//");
private boolean mLocal;
private boolean mThrowIfNoAuthToken;
public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) {
super(context);
mLocal = local;
mThrowIfNoAuthToken = throwIfNoAuthToken;
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SessionsResponse response = new Gson().fromJson(json, SessionsResponse.class);
int numEvents = 0;
if (response.result != null) {
numEvents = response.result[0].events.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating sessions data");
// by default retain locally starred if local sync
boolean retainLocallyStarredSessions = mLocal;
if (response.error != null && response.error.isJsonPrimitive()) {
String errorMessageLower = response.error.getAsString().toLowerCase();
if (!mLocal && (errorMessageLower.contains("no profile")
|| errorMessageLower.contains("no auth token"))) {
// There was some authentication issue; retain locally starred sessions.
retainLocallyStarredSessions = true;
LOGW(TAG, "The user has no developers.google.com profile or this call is "
+ "not authenticated. Retaining locally starred sessions.");
}
if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) {
throw new HandlerException.UnauthorizedException("No auth token but we tried "
+ "authenticating. Need to invalidate the auth token.");
}
}
Set<String> starredSessionIds = new HashSet<String>();
if (retainLocallyStarredSessions) {
// Collect the list of current starred sessions
Cursor starredSessionsCursor = mContext.getContentResolver().query(
Sessions.CONTENT_STARRED_URI,
new String[]{ScheduleContract.Sessions.SESSION_ID},
null, null, null);
while (starredSessionsCursor.moveToNext()) {
starredSessionIds.add(starredSessionsCursor.getString(0));
}
starredSessionsCursor.close();
}
// Clear out existing sessions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.build());
// Maintain a list of created block IDs
Set<String> blockIds = new HashSet<String>();
for (SessionsResult result : response.result) {
for (Event event : result.events) {
int flags = 0;
if (retainLocallyStarredSessions) {
flags = (starredSessionIds.contains(event.id)
? PARSE_FLAG_FORCE_SCHEDULE_ADD
: PARSE_FLAG_FORCE_SCHEDULE_REMOVE);
}
String sessionId = event.id;
if (TextUtils.isEmpty(sessionId)) {
LOGW(TAG, "Found session with empty ID in API response.");
continue;
}
// Session title
String sessionTitle = event.title;
if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
sessionTitle = mContext.getString(
R.string.codelab_title_template, sessionTitle);
}
// Whether or not it's in the schedule
boolean inSchedule = "Y".equals(event.attending);
if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0
|| (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) {
inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0;
}
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
// Keynotes are always in your schedule.
inSchedule = true;
}
// Re-order session tracks so that Code Lab is last
if (event.track != null) {
Arrays.sort(event.track, sTracksComparator);
}
// Hashtags
String hashtags = "";
if (event.track != null) {
StringBuilder hashtagsBuilder = new StringBuilder();
for (String trackName : event.track) {
if (trackName.trim().startsWith("Code Lab")) {
trackName = "Code Labs";
}
if (trackName.contains("Keynote")) {
continue;
}
hashtagsBuilder.append(" #");
hashtagsBuilder.append(
ScheduleContract.Tracks.generateTrackId(trackName));
}
hashtags = hashtagsBuilder.toString().trim();
}
// Pre-reqs
String prereqs = "";
if (event.prereq != null && event.prereq.length > 0) {
StringBuilder sb = new StringBuilder();
for (String prereq : event.prereq) {
sb.append(prereq);
sb.append(" ");
}
prereqs = sb.toString();
if (prereqs.startsWith("<br>")) {
prereqs = prereqs.substring(4);
}
}
String youtubeUrl = null;
if (event.youtube_url != null && event.youtube_url.length > 0) {
youtubeUrl = event.youtube_url[0];
}
// Insert session info
final ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Sessions.SESSION_ID, sessionId)
.withValue(Sessions.SESSION_TYPE, result.event_type)
.withValue(Sessions.SESSION_LEVEL, event.level)
.withValue(Sessions.SESSION_TITLE, sessionTitle)
.withValue(Sessions.SESSION_ABSTRACT, event._abstract)
.withValue(Sessions.SESSION_TAGS, event.tags)
.withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId))
.withValue(Sessions.SESSION_LIVESTREAM_URL, event.livestream_url)
.withValue(Sessions.SESSION_REQUIREMENTS, prereqs)
.withValue(Sessions.SESSION_STARRED, inSchedule)
.withValue(Sessions.SESSION_HASHTAGS, hashtags)
.withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl)
.withValue(Sessions.SESSION_PDF_URL, "")
.withValue(Sessions.SESSION_NOTES_URL, "")
.withValue(Sessions.ROOM_ID, sanitizeId(event.room));
long sessionStartTime = parseTime(event.start_date, event.start_time);
long sessionEndTime = parseTime(event.end_date, event.end_time);
String blockId = ScheduleContract.Blocks.generateBlockId(
sessionStartTime, sessionEndTime);
if (!blockIds.contains(blockId)) {
String blockType;
String blockTitle;
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_KEYNOTE;
blockTitle = mContext.getString(R.string.schedule_block_title_keynote);
} else if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_CODE_LAB;
blockTitle = mContext
.getString(R.string.schedule_block_title_code_labs);
} else {
blockType = ParserUtils.BLOCK_TYPE_SESSION;
blockTitle = mContext.getString(R.string.schedule_block_title_sessions);
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
blockIds.add(blockId);
}
builder.withValue(Sessions.BLOCK_ID, blockId);
batch.add(builder.build());
// Replace all session speakers
final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId);
batch.add(ContentProviderOperation
.newDelete(ScheduleContract
.addCallerIsSyncAdapterParameter(sessionSpeakersUri))
.build());
if (event.speaker_id != null) {
for (String speakerId : event.speaker_id) {
speakerId = sRemoveSpeakerIdPrefixPattern.matcher(speakerId).replaceAll(
"");
batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri)
.withValue(SessionsSpeakers.SESSION_ID, sessionId)
.withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build());
}
}
// Replace all session tracks
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build());
if (event.track != null) {
for (String trackName : event.track) {
if (trackName.contains("Code Lab")) {
trackName = "Code Labs";
}
String trackId = ScheduleContract.Tracks.generateTrackId(trackName);
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(SessionsTracks.SESSION_ID, sessionId)
.withValue(SessionsTracks.TRACK_ID, trackId).build());
}
}
}
}
}
return batch;
}
private Comparator<String> sTracksComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: improve performance of this comparator
return (s1.contains("Code Lab") ? "z" : s1).compareTo(
(s2.contains("Code Lab") ? "z" : s2));
}
};
private String makeSessionUrl(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return null;
}
return BASE_SESSION_URL + sessionId;
}
private static long parseTime(String date, String time) {
//change to this format : 2011-05-10T07:00:00.000-07:00
int index = time.indexOf(":");
if (index == 1) {
time = "0" + time;
}
final String composed = String.format("%sT%s:00.000-07:00", date, time);
//return sTimeFormat.parse(composed).getTime();
sTime.parse3339(composed);
return sTime.toMillis(false);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.SearchSuggestions;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.app.SearchManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses search suggestions JSON data into a list of content provider operations.
*/
public class SearchSuggestHandler extends JSONHandler {
public SearchSuggestHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class);
if (suggestions.words != null) {
// Clear out suggestions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.build());
// Rebuild suggestions
for (String word : suggestions.words) {
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word)
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.google.android.apps.iosched.io.model.Announcement;
import com.google.android.apps.iosched.io.model.AnnouncementsResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses announcements JSON data into a list of content provider operations.
*/
public class AnnouncementsHandler extends JSONHandler {
private static final String TAG = makeLogTag(AnnouncementsHandler.class);
public AnnouncementsHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
AnnouncementsResponse response = new Gson().fromJson(json, AnnouncementsResponse.class);
int numAnnouncements = 0;
if (response.announcements != null) {
numAnnouncements = response.announcements.length;
}
if (numAnnouncements > 0) {
LOGI(TAG, "Updating announcements data");
// Clear out existing announcements
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Announcements.CONTENT_URI))
.build());
for (Announcement announcement : response.announcements) {
// Save tracks as a json array
final String tracks =
(announcement.tracks != null && announcement.tracks.length > 0)
? new Gson().toJson(announcement.tracks)
: null;
// Insert announcement info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
// TODO: better announcements ID heuristic
.withValue(Announcements.ANNOUNCEMENT_ID,
(announcement.date + announcement.title).hashCode())
.withValue(Announcements.ANNOUNCEMENT_DATE, announcement.date)
.withValue(Announcements.ANNOUNCEMENT_TITLE, announcement.title)
.withValue(Announcements.ANNOUNCEMENT_SUMMARY, announcement.summary)
.withValue(Announcements.ANNOUNCEMENT_URL, announcement.link)
.withValue(Announcements.ANNOUNCEMENT_TRACKS, tracks)
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import java.io.IOException;
/**
* General {@link IOException} that indicates a problem occurred while parsing or applying a {@link
* JSONHandler}.
*/
public class HandlerException extends IOException {
public HandlerException() {
super();
}
public HandlerException(String message) {
super(message);
}
public HandlerException(String message, Throwable cause) {
super(message);
initCause(cause);
}
@Override
public String toString() {
if (getCause() != null) {
return getLocalizedMessage() + ": " + getCause();
} else {
return getLocalizedMessage();
}
}
public static class UnauthorizedException extends HandlerException {
public UnauthorizedException() {
}
public UnauthorizedException(String message) {
super(message);
}
public UnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
public static class NoDevsiteProfileException extends HandlerException {
public NoDevsiteProfileException() {
}
public NoDevsiteProfileException(String message) {
super(message);
}
public NoDevsiteProfileException(String message, Throwable cause) {
super(message, cause);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Day;
import com.google.android.apps.iosched.io.model.EventSlots;
import com.google.android.apps.iosched.io.model.TimeSlot;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class BlocksHandler extends JSONHandler {
private static final String TAG = makeLogTag(BlocksHandler.class);
public BlocksHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
try {
Gson gson = new Gson();
EventSlots eventSlots = gson.fromJson(json, EventSlots.class);
int numDays = eventSlots.day.length;
//2011-05-10T07:00:00.000-07:00
for (int i = 0; i < numDays; i++) {
Day day = eventSlots.day[i];
String date = day.date;
TimeSlot[] timeSlots = day.slot;
for (TimeSlot timeSlot : timeSlots) {
parseSlot(date, timeSlot, batch);
}
}
} catch (Throwable e) {
LOGE(TAG, e.toString());
}
return batch;
}
private static void parseSlot(String date, TimeSlot slot,
ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI));
//LOGD(TAG, "Inside parseSlot:" + date + ", " + slot);
String start = slot.start;
String end = slot.end;
String type = "N_D";
if (slot.type != null) {
type = slot.type;
}
String title = "N_D";
if (slot.title != null) {
title = slot.title;
}
String startTime = date + "T" + start + ":00.000-07:00";
String endTime = date + "T" + end + ":00.000-07:00";
LOGV(TAG, "startTime:" + startTime);
long startTimeL = ParserUtils.parseTime(startTime);
long endTimeL = ParserUtils.parseTime(endTime);
final String blockId = Blocks.generateBlockId(startTimeL, endTimeL);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "title:" + title);
LOGV(TAG, "start:" + startTimeL);
builder.withValue(Blocks.BLOCK_ID, blockId);
builder.withValue(Blocks.BLOCK_TITLE, title);
builder.withValue(Blocks.BLOCK_START, startTimeL);
builder.withValue(Blocks.BLOCK_END, endTimeL);
builder.withValue(Blocks.BLOCK_TYPE, type);
builder.withValue(Blocks.BLOCK_META, slot.meta);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.MyScheduleItem;
import com.google.android.apps.iosched.io.model.MyScheduleResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses "my schedule" JSON data into a list of content provider operations.
*/
public class MyScheduleHandler extends JSONHandler {
private static final String TAG = makeLogTag(MyScheduleHandler.class);
public MyScheduleHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
MyScheduleResponse response = new Gson().fromJson(json, MyScheduleResponse.class);
if (response.error == null) {
LOGI(TAG, "Updating user's schedule");
if (response.schedule_list != null) {
// Un-star all sessions first
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.withValue(Sessions.SESSION_STARRED, 0)
.build());
// Star only those sessions in the "my schedule" response
for (MyScheduleItem item : response.schedule_list) {
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildSessionUri(item.session_id)))
.withValue(Sessions.SESSION_STARRED, 1)
.build());
}
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class TimeSlot {
public String start;
public String end;
public String title;
public String type;
public String meta;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class EventSlots {
public Day[] day;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class MyScheduleResponse extends GenericResponse {
public MyScheduleItem[] schedule_list;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Speaker {
public String display_name;
public String bio;
public String plusone_url;
public String thumbnail_url;
public String user_id;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Tracks {
Track[] track;
public Track[] getTrack() {
return track;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class SpeakersResponse extends GenericResponse {
@SerializedName("devsite_speakers")
public Speaker[] speakers;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Rooms {
public Room[] rooms;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class SandboxCompany {
public String company_name;
public String company_description;
public String[] exhibitors;
public String logo_img;
public String product_description;
public String product_pod;
public String website;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Track {
public String name;
public String color;
@SerializedName("abstract")
public String _abstract;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
import com.google.gson.JsonElement;
public class GenericResponse {
public JsonElement error;
//
// public void checkResponseForAuthErrorsAndThrow() throws IOException {
// if (error != null && error.isJsonObject()) {
// JsonObject errorObject = error.getAsJsonObject();
// int errorCode = errorObject.get("code").getAsInt();
// String errorMessage = errorObject.get("message").getAsString();
// if (400 <= errorCode && errorCode < 500) {
// // The API currently only returns 400 unfortunately.
// throw ...
// }
// }
// }
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Announcement {
public String date;
public String[] tracks;
public String title;
public String link;
public String summary;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class SessionsResponse extends GenericResponse {
public SessionsResult[] result;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class ErrorResponse {
public Errors error;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class AnnouncementsResponse extends GenericResponse {
public Announcement[] announcements;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Room {
public String id;
public String name;
public String floor;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Location {
public String location;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Errors {
public Error[] errors;
public String code;
public String message;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class SearchSuggestions {
public String[] words;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Day {
public String date;
public TimeSlot[] slot;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class SessionsResult {
public Event[] events;
public String event_type;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Event {
public String room;
public String end_date;
public String level;
public String[] track;
public String start_time;
public String title;
@SerializedName("abstract")
public String _abstract;
public String start_date;
public String attending;
public String has_streaming;
public String end_time;
public String livestream_url;
public String[] youtube_url;
public String id;
public String tags;
public String[] speaker_id;
public String[] prereq;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class Error {
public String domain;
public String reason;
public String message;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class EditMyScheduleResponse {
public String message;
public boolean success;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io.model;
public class MyScheduleItem {
public String date;
public String time;
public String role;
public Location[] locations;
public String title;
public String session_id;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Track;
import com.google.android.apps.iosched.io.model.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.Color;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses track JSON data into a list of content provider operations.
*/
public class TracksHandler extends JSONHandler {
private static final String TAG = makeLogTag(TracksHandler.class);
public TracksHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI)).build());
Tracks tracksJson = new Gson().fromJson(json, Tracks.class);
int noOfTracks = tracksJson.getTrack().length;
for (int i = 0; i < noOfTracks; i++) {
parseTrack(tracksJson.getTrack()[i], batch);
}
return batch;
}
private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI));
builder.withValue(ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(track.name));
builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name);
builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color));
builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.SandboxCompany;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses developer sandbox JSON data into a list of content provider operations.
*/
public class SandboxHandler extends JSONHandler {
private static final String TAG = makeLogTag(SandboxHandler.class);
private static final String BASE_LOGO_URL
= "http://commondatastorage.googleapis.com/io2012/sandbox%20logos/";
public SandboxHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SandboxCompany[] companies = new Gson().fromJson(json, SandboxCompany[].class);
if (companies.length > 0) {
LOGI(TAG, "Updating developer sandbox data");
// Clear out existing sandbox companies
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Vendors.CONTENT_URI))
.build());
StringBuilder companyDescription = new StringBuilder();
String exhibitorsPrefix = mContext.getString(R.string.vendor_exhibitors_prefix);
for (SandboxCompany company : companies) {
// Insert sandbox company info
String website = company.website;
if (!TextUtils.isEmpty(website) && !website.startsWith("http")) {
website = "http://" + website;
}
companyDescription.setLength(0);
if (company.exhibitors != null && company.exhibitors.length > 0) {
companyDescription.append(exhibitorsPrefix);
companyDescription.append(" ");
for (int i = 0; i < company.exhibitors.length; i++) {
companyDescription.append(company.exhibitors[i]);
if (i >= company.exhibitors.length - 1) {
break;
}
companyDescription.append(", ");
}
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.company_description)) {
companyDescription.append(company.company_description);
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.product_description)) {
companyDescription.append(company.product_description);
}
// Clean up logo URL
String logoUrl = null;
if (!TextUtils.isEmpty(company.logo_img)) {
logoUrl = company.logo_img.replaceAll(" ", "%20");
if (!logoUrl.startsWith("http")) {
logoUrl = BASE_LOGO_URL + logoUrl;
}
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Vendors.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Vendors.VENDOR_ID,
Vendors.generateVendorId(company.company_name))
.withValue(Vendors.VENDOR_NAME, company.company_name)
.withValue(Vendors.VENDOR_DESC, companyDescription.toString())
.withValue(Vendors.VENDOR_PRODUCT_DESC, null) // merged into company desc
.withValue(Vendors.VENDOR_LOGO_URL, logoUrl)
.withValue(Vendors.VENDOR_URL, website)
.withValue(Vendors.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(company.product_pod))
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Speaker;
import com.google.android.apps.iosched.io.model.SpeakersResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses speaker JSON data into a list of content provider operations.
*/
public class SpeakersHandler extends JSONHandler {
private static final String TAG = makeLogTag(SpeakersHandler.class);
public SpeakersHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SpeakersResponse response = new Gson().fromJson(json, SpeakersResponse.class);
int numEvents = 0;
if (response.speakers != null) {
numEvents = response.speakers.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating speakers data");
// Clear out existing speakers
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Speakers.CONTENT_URI))
.build());
for (Speaker speaker : response.speakers) {
String speakerId = speaker.user_id;
// Insert speaker info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Speakers.SPEAKER_ID, speakerId)
.withValue(Speakers.SPEAKER_NAME, speaker.display_name)
.withValue(Speakers.SPEAKER_ABSTRACT, speaker.bio)
.withValue(Speakers.SPEAKER_IMAGE_URL, speaker.thumbnail_url)
.withValue(Speakers.SPEAKER_URL, speaker.plusone_url)
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
/**
* An abstract object that is in charge of parsing JSON data with a given, known structure, into
* a list of content provider operations (inserts, updates, etc.) representing the data.
*/
public abstract class JSONHandler {
protected static Context mContext;
protected JSONHandler(Context context) {
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
/**
* Loads the JSON text resource with the given ID and returns the JSON content.
*/
public static String loadResourceJson(Context context, int resource) throws IOException {
InputStream is = context.getResources().openRawResource(resource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Room;
import com.google.android.apps.iosched.io.model.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses room JSON data into a list of content provider operations.
*/
public class RoomsHandler extends JSONHandler {
private static final String TAG = makeLogTag(RoomsHandler.class);
public RoomsHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Rooms roomsJson = new Gson().fromJson(json, Rooms.class);
int noOfRooms = roomsJson.rooms.length;
for (int i = 0; i < noOfRooms; i++) {
parseRoom(roomsJson.rooms[i], batch);
}
return batch;
}
private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Rooms.CONTENT_URI));
builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id);
builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name);
builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import android.content.ContentProvider;
import android.net.Uri;
import android.text.format.Time;
import java.util.regex.Pattern;
/**
* Various utility methods used by {@link com.google.android.apps.iosched.io.JSONHandler}.
*/
public class ParserUtils {
public static final String BLOCK_TYPE_SESSION = "session";
public static final String BLOCK_TYPE_CODE_LAB = "codelab";
public static final String BLOCK_TYPE_KEYNOTE = "keynote";
/** Used to sanitize a string to be {@link Uri} safe. */
private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]");
private static final Time sTime = new Time();
/**
* Sanitize the given string to be {@link Uri} safe for building
* {@link ContentProvider} paths.
*/
public static String sanitizeId(String input) {
if (input == null) {
return null;
}
return sSanitizePattern.matcher(input.toLowerCase()).replaceAll("");
}
/**
* Parse the given string as a RFC 3339 timestamp, returning the value as
* milliseconds since the epoch.
*/
public static long parseTime(String time) {
sTime.parse3339(time);
return sTime.toMillis(false);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Parcelable;
import android.preference.PreferenceManager;
/**
* Android Beam helper methods.
*/
public class BeamUtils {
private static final byte[] DEFAULT_BEAM_MIME =
"application/vnd.google.iosched.default".getBytes();
private static final String PREF_BEAM_STATE = "beam_state";
private static final int BEAM_STATE_UNLOCKED = 0x1481;
private static final int BEAM_STATE_LOCKED = 0x0;
/**
* Sets this activity's Android Beam message to one representing the given session.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
if (UIUtils.hasICS()) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) {
// No NFC :-(
return;
}
nfcAdapter.setNdefPushMessage(new NdefMessage(
new NdefRecord[]{
new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
ScheduleContract.Sessions.CONTENT_ITEM_TYPE.getBytes(),
new byte[0],
sessionUri.toString().getBytes())
}), activity);
}
}
/**
* Sets this activity's Android Beam message to the default.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setDefaultBeamUri(Activity activity) {
if (UIUtils.hasICS()) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) {
// No NFC :-(
return;
}
nfcAdapter.setNdefPushMessage(new NdefMessage(
new NdefRecord[]{
new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
DEFAULT_BEAM_MIME,
new byte[0],
new byte[0])
}), activity);
}
}
public static boolean isBeamUnlocked(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return (prefs.getInt(PREF_BEAM_STATE, BEAM_STATE_LOCKED) == BEAM_STATE_UNLOCKED);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamUnlocked(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt(PREF_BEAM_STATE, BEAM_STATE_UNLOCKED).commit();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static boolean wasLaunchedThroughBeamFirstTime(Context context, Intent intent) {
return intent != null
&& UIUtils.hasICS()
&& NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
&& !isBeamUnlocked(context);
}
/**
* Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is
* an NFC intent that the app recognizes. If it is, then parse the NFC message and set the
* activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something
* the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void tryUpdateIntentFromBeam(Activity activity) {
if (UIUtils.hasICS()) {
Intent originalIntent = activity.getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) {
Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
// Record 0 contains the MIME type, record 1 is the AAR, if present.
// In iosched, AARs are not present.
NdefRecord mimeRecord = msg.getRecords()[0];
if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(
new String(mimeRecord.getType()))) {
// Re-set the activity's intent to one that represents session details.
Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(new String(mimeRecord.getPayload())));
activity.setIntent(sessionDetailIntent);
}
}
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamCompleteCallback(Activity activity,
NfcAdapter.OnNdefPushCompleteCallback callback) {
if (UIUtils.hasICS()) {
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
if (adapter == null) {
return;
}
adapter.setOnNdefPushCompleteCallback(callback, activity);
}
}
public static void launchBeamSession(Context context) {
context.startActivity(new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri("gooio2012/125/")));
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.ui.phone.MapActivity;
import com.google.android.apps.iosched.ui.phone.SessionDetailActivity;
import com.google.android.apps.iosched.ui.phone.SessionsActivity;
import com.google.android.apps.iosched.ui.phone.TrackDetailActivity;
import com.google.android.apps.iosched.ui.phone.VendorDetailActivity;
import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity;
import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
import java.util.TimeZone;
/**
* An assortment of UI helpers.
*/
public class UIUtils {
/**
* Time zone to use when formatting all session times. To always use the
* phone local time, use {@link TimeZone#getDefault()}.
*/
public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles");
public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime(
"2012-06-27T09:30:00.000-07:00");
public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime(
"2012-06-29T18:00:00.000-07:00");
public static final String CONFERENCE_HASHTAG = "#io12";
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
/** Flags used with {@link DateUtils#formatDateRange}. */
private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY;
/** {@link StringBuilder} used for formatting time block. */
private static StringBuilder sBuilder = new StringBuilder(50);
/** {@link Formatter} used for formatting time block. */
private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault());
private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);
private static CharSequence sEmptyRoomText;
private static CharSequence sCodeLabRoomText;
private static CharSequence sNowPlayingText;
private static CharSequence sLivestreamNowText;
private static CharSequence sLivestreamAvailableText;
public static final String GOOGLE_PLUS_PACKAGE_NAME = "com.google.android.apps.plus";
/**
* Format and return the given {@link Blocks} and {@link Rooms} values using
* {@link #CONFERENCE_TIME_ZONE}.
*/
public static String formatSessionSubtitle(String sessionTitle,
long blockStart, long blockEnd, String roomName, Context context) {
if (sEmptyRoomText == null || sCodeLabRoomText == null) {
sEmptyRoomText = context.getText(R.string.unknown_room);
sCodeLabRoomText = context.getText(R.string.codelab_room);
}
if (roomName == null) {
// TODO: remove the WAR for API not returning rooms for code labs
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, context),
sessionTitle.contains("Code Lab")
? sCodeLabRoomText
: sEmptyRoomText);
}
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, context), roomName);
}
/**
* Format and return the given {@link Blocks} values using
* {@link #CONFERENCE_TIME_ZONE}.
*/
public static String formatBlockTimeString(long blockStart, long blockEnd, Context context) {
TimeZone.setDefault(CONFERENCE_TIME_ZONE);
// NOTE: There is an efficient version of formatDateRange in Eclair and
// beyond that allows you to recycle a StringBuilder.
return DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS);
}
public static boolean isSameDay(long time1, long time2) {
TimeZone.setDefault(CONFERENCE_TIME_ZONE);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTimeInMillis(time1);
cal2.setTimeInMillis(time2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
}
public static String getTimeAgo(long time, Context ctx) {
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = getCurrentTime(ctx);
if (time > now || time <= 0) {
return null;
}
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "just now";
} else if (diff < 2 * MINUTE_MILLIS) {
return "a minute ago";
} else if (diff < 50 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + " minutes ago";
} else if (diff < 90 * MINUTE_MILLIS) {
return "an hour ago";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + " hours ago";
} else if (diff < 48 * HOUR_MILLIS) {
return "yesterday";
} else {
return diff / DAY_MILLIS + " days ago";
}
}
/**
* Populate the given {@link TextView} with the requested text, formatting
* through {@link Html#fromHtml(String)} when applicable. Also sets
* {@link TextView#setMovementMethod} so inline links are handled.
*/
public static void setTextMaybeHtml(TextView view, String text) {
if (TextUtils.isEmpty(text)) {
view.setText("");
return;
}
if (text.contains("<") && text.contains(">")) {
view.setText(Html.fromHtml(text));
view.setMovementMethod(LinkMovementMethod.getInstance());
} else {
view.setText(text);
}
}
public static void updateTimeAndLivestreamBlockUI(final Context context,
long blockStart, long blockEnd, boolean hasLivestream,
View backgroundView, TextView titleView, TextView subtitleView,
CharSequence subtitle) {
long currentTimeMillis = getCurrentTime(context);
boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS);
boolean present = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd);
final Resources res = context.getResources();
if (backgroundView != null) {
backgroundView.setBackgroundColor(past
? res.getColor(R.color.past_background_color)
: 0);
}
if (titleView != null) {
titleView.setTypeface(Typeface.SANS_SERIF, past ? Typeface.NORMAL : Typeface.BOLD);
}
if (subtitleView != null) {
boolean empty = true;
SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle
if (subtitle != null) {
sb.append(subtitle);
empty = false;
}
if (present) {
if (sNowPlayingText == null) {
sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sNowPlayingText);
if (hasLivestream) {
if (sLivestreamNowText == null) {
sLivestreamNowText = Html.fromHtml(" " +
context.getString(R.string.live_now_badge));
}
sb.append(sLivestreamNowText);
}
} else if (hasLivestream) {
if (sLivestreamAvailableText == null) {
sLivestreamAvailableText = Html.fromHtml(
context.getString(R.string.live_available_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sLivestreamAvailableText);
}
subtitleView.setText(sb);
}
}
/**
* Given a snippet string with matching segments surrounded by curly
* braces, turn those areas into bold spans, removing the curly braces.
*/
public static Spannable buildStyledSnippet(String snippet) {
final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);
// Walk through string, inserting bold snippet spans
int startIndex = -1, endIndex = -1, delta = 0;
while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
endIndex = snippet.indexOf('}', startIndex);
// Remove braces from both sides
builder.delete(startIndex - delta, startIndex - delta + 1);
builder.delete(endIndex - delta - 1, endIndex - delta);
// Insert bold style
builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
delta += 2;
}
return builder;
}
public static void preferPackageForIntent(Context context, Intent intent, String packageName) {
PackageManager pm = context.getPackageManager();
for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) {
if (resolveInfo.activityInfo.packageName.equals(packageName)) {
intent.setPackage(packageName);
break;
}
}
}
public static ImageFetcher getImageFetcher(final FragmentActivity activity) {
// The ImageFetcher takes care of loading remote images into our ImageView
ImageFetcher fetcher = new ImageFetcher(activity);
fetcher.addImageCache(activity);
return fetcher;
}
public static String getSessionHashtagsString(String hashtags) {
if (!TextUtils.isEmpty(hashtags)) {
if (!hashtags.startsWith("#")) {
hashtags = "#" + hashtags;
}
if (hashtags.contains(CONFERENCE_HASHTAG)) {
return hashtags;
}
return CONFERENCE_HASHTAG + " " + hashtags;
} else {
return CONFERENCE_HASHTAG;
}
}
private static final int BRIGHTNESS_THRESHOLD = 130;
/**
* Calculate whether a color is light or dark, based on a commonly known
* brightness formula.
*
* @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness}
*/
public static boolean isColorDark(int color) {
return ((30 * Color.red(color) +
59 * Color.green(color) +
11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD;
}
// Shows whether a notification was fired for a particular session time block. In the
// event that notification has not been fired yet, return false and set the bit.
public static boolean isNotificationFiredForBlock(Context context, String blockId) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
final String key = String.format("notification_fired_%s", blockId);
boolean fired = sp.getBoolean(key, false);
sp.edit().putBoolean(key, true).commit();
return fired;
}
private static final long sAppLoadTime = System.currentTimeMillis();
public static long getCurrentTime(final Context context) {
if (BuildConfig.DEBUG) {
return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE)
.getLong("mock_current_time", System.currentTimeMillis())
+ System.currentTimeMillis() - sAppLoadTime;
} else {
return System.currentTimeMillis();
}
}
public static void safeOpenLink(Context context, Intent linkIntent) {
try {
context.startActivity(linkIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Couldn't open link", Toast.LENGTH_SHORT) .show();
}
}
// TODO: use <meta-data> element instead
private static final Class[] sPhoneActivities = new Class[]{
MapActivity.class,
SessionDetailActivity.class,
SessionsActivity.class,
TrackDetailActivity.class,
VendorDetailActivity.class,
};
// TODO: use <meta-data> element instead
private static final Class[] sTabletActivities = new Class[]{
MapMultiPaneActivity.class,
SessionsVendorsMultiPaneActivity.class,
};
public static void enableDisableActivities(final Context context) {
boolean isHoneycombTablet = isHoneycombTablet(context);
PackageManager pm = context.getPackageManager();
// Enable/disable phone activities
for (Class a : sPhoneActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
: PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
// Enable/disable tablet activities
for (Class a : sTabletActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
public static Class getMapActivityClass(Context context) {
if (UIUtils.isHoneycombTablet(context)) {
return MapMultiPaneActivity.class;
}
return MapActivity.class;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void setActivatedCompat(View view, boolean activated) {
if (hasHoneycomb()) {
view.setActivated(activated);
}
}
public static boolean isGoogleTV(Context context) {
return context.getPackageManager().hasSystemFeature("com.google.android.tv");
}
public static boolean hasFroyo() {
// Can use static final constants like FROYO, declared in later versions
// of the OS since they are inlined at compile time. This is guaranteed behavior.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
public static boolean hasGingerbread() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
public static boolean hasICS() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
public static boolean hasJellyBean() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public static boolean isHoneycombTablet(Context context) {
return hasHoneycomb() && isTablet(context);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import java.util.HashMap;
/**
* Provides static methods for creating mutable {@code Maps} instances easily.
*/
public class Maps {
/**
* Creates a {@code HashMap} instance.
*
* @return a newly-created, initially-empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
/*
* Modifications:
* -Imported from AOSP frameworks/base/core/java/com/android/internal/content
* -Changed package name
*/
package com.google.android.apps.iosched.util;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for building selection clauses for {@link SQLiteDatabase}. Each
* appended clause is combined using {@code AND}. This class is <em>not</em>
* thread safe.
*/
public class SelectionBuilder {
private static final String TAG = makeLogTag(SelectionBuilder.class);
private String mTable = null;
private Map<String, String> mProjectionMap = Maps.newHashMap();
private StringBuilder mSelection = new StringBuilder();
private ArrayList<String> mSelectionArgs = Lists.newArrayList();
/**
* Reset any internal state, allowing this builder to be recycled.
*/
public SelectionBuilder reset() {
mTable = null;
mSelection.setLength(0);
mSelectionArgs.clear();
return this;
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using {@code AND}.
*/
public SelectionBuilder where(String selection, String... selectionArgs) {
if (TextUtils.isEmpty(selection)) {
if (selectionArgs != null && selectionArgs.length > 0) {
throw new IllegalArgumentException(
"Valid selection required when including arguments=");
}
// Shortcut when clause is empty
return this;
}
if (mSelection.length() > 0) {
mSelection.append(" AND ");
}
mSelection.append("(").append(selection).append(")");
if (selectionArgs != null) {
Collections.addAll(mSelectionArgs, selectionArgs);
}
return this;
}
public SelectionBuilder table(String table) {
mTable = table;
return this;
}
private void assertTable() {
if (mTable == null) {
throw new IllegalStateException("Table not specified");
}
}
public SelectionBuilder mapToTable(String column, String table) {
mProjectionMap.put(column, table + "." + column);
return this;
}
public SelectionBuilder map(String fromColumn, String toClause) {
mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn);
return this;
}
/**
* Return selection string for current internal state.
*
* @see #getSelectionArgs()
*/
public String getSelection() {
return mSelection.toString();
}
/**
* Return selection arguments for current internal state.
*
* @see #getSelection()
*/
public String[] getSelectionArgs() {
return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
}
private void mapColumns(String[] columns) {
for (int i = 0; i < columns.length; i++) {
final String target = mProjectionMap.get(columns[i]);
if (target != null) {
columns[i] = target;
}
}
}
@Override
public String toString() {
return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection()
+ ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
return query(db, columns, null, null, orderBy, null);
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
String having, String orderBy, String limit) {
assertTable();
if (columns != null) mapColumns(columns);
LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
orderBy, limit);
}
/**
* Execute update using the current internal state as {@code WHERE} clause.
*/
public int update(SQLiteDatabase db, ContentValues values) {
assertTable();
LOGV(TAG, "update() " + this);
return db.update(mTable, values, getSelection(), getSelectionArgs());
}
/**
* Execute delete using the current internal state as {@code WHERE} clause.
*/
public int delete(SQLiteDatabase db) {
assertTable();
LOGV(TAG, "delete() " + this);
return db.delete(mTable, getSelection(), getSelectionArgs());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A subclass of {@link ImageWorker} that fetches images from a URL.
*/
public class ImageFetcher extends ImageWorker {
private static final String TAG = makeLogTag(ImageFetcher.class);
public static final int IO_BUFFER_SIZE_BYTES = 4 * 1024; // 4KB
// Default fetcher params
private static final int MAX_THUMBNAIL_BYTES = 70 * 1024; // 70KB
private static final int HTTP_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
private static final String HTTP_CACHE_DIR = "http";
private static final int DEFAULT_IMAGE_HEIGHT = 1024;
private static final int DEFAULT_IMAGE_WIDTH = 1024;
protected int mImageWidth;
protected int mImageHeight;
private DiskLruCache mHttpDiskCache;
private File mHttpCacheDir;
private boolean mHttpDiskCacheStarting = true;
private final Object mHttpDiskCacheLock = new Object();
private static final int DISK_CACHE_INDEX = 0;
/**
* Create an ImageFetcher specifying max image loading width/height.
*/
public ImageFetcher(Context context, int imageWidth, int imageHeight) {
super(context);
init(context, imageWidth, imageHeight);
}
/**
* Create an ImageFetcher using defaults.
*/
public ImageFetcher(Context context) {
super(context);
init(context, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
}
private void init(Context context, int imageWidth, int imageHeight) {
mImageWidth = imageWidth;
mImageHeight = imageHeight;
mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR);
if (!mHttpCacheDir.exists()) {
mHttpCacheDir.mkdirs();
}
}
public void loadThumbnailImage(String key, ImageView imageView, Bitmap loadingBitmap) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, loadingBitmap);
}
public void loadThumbnailImage(String key, ImageView imageView, int resId) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, resId);
}
public void loadThumbnailImage(String key, ImageView imageView) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, mLoadingBitmap);
}
public void loadImage(String key, ImageView imageView, Bitmap loadingBitmap) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, loadingBitmap);
}
public void loadImage(String key, ImageView imageView, int resId) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, resId);
}
public void loadImage(String key, ImageView imageView) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, mLoadingBitmap);
}
/**
* Set the target image width and height.
*/
public void setImageSize(int width, int height) {
mImageWidth = width;
mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* @param key The key to load the bitmap, in this case, a regular http URL
* @return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String key, int type) {
LOGD(TAG, "processBitmap - " + key);
if (type == ImageData.IMAGE_TYPE_NORMAL) {
return processNormalBitmap(key); // Process a regular, full sized bitmap
} else if (type == ImageData.IMAGE_TYPE_THUMBNAIL) {
return processThumbnailBitmap(key); // Process a smaller, thumbnail bitmap
}
return null;
}
@Override
protected Bitmap processBitmap(Object key) {
final ImageData imageData = (ImageData) key;
return processBitmap(imageData.mKey, imageData.mType);
}
/**
* Download and resize a normal sized remote bitmap from a HTTP URL using a HTTP cache.
* @param urlString The URL of the image to download
* @return The scaled bitmap
*/
private Bitmap processNormalBitmap(String urlString) {
final String key = ImageCache.hashKeyForDisk(urlString);
FileDescriptor fileDescriptor = null;
FileInputStream fileInputStream = null;
DiskLruCache.Snapshot snapshot;
synchronized (mHttpDiskCacheLock) {
// Wait for disk cache to initialize
while (mHttpDiskCacheStarting) {
try {
mHttpDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mHttpDiskCache != null) {
try {
snapshot = mHttpDiskCache.get(key);
if (snapshot == null) {
LOGD(TAG, "processBitmap, not found in http cache, downloading...");
DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
if (editor != null) {
if (downloadUrlToStream(urlString,
editor.newOutputStream(DISK_CACHE_INDEX))) {
editor.commit();
} else {
editor.abort();
}
}
snapshot = mHttpDiskCache.get(key);
}
if (snapshot != null) {
fileInputStream =
(FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
fileDescriptor = fileInputStream.getFD();
}
} catch (IOException e) {
LOGE(TAG, "processBitmap - " + e);
} catch (IllegalStateException e) {
LOGE(TAG, "processBitmap - " + e);
} finally {
if (fileDescriptor == null && fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
}
}
}
Bitmap bitmap = null;
if (fileDescriptor != null) {
bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight);
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
return bitmap;
}
/**
* Download a thumbnail sized remote bitmap from a HTTP URL. No HTTP caching is done (the
* {@link ImageCache} that this eventually gets passed to will do it's own disk caching.
* @param urlString The URL of the image to download
* @return The bitmap
*/
private Bitmap processThumbnailBitmap(String urlString) {
final byte[] bitmapBytes =
downloadBitmapToMemory(urlString, MAX_THUMBNAIL_BYTES);
if (bitmapBytes != null) {
// Caution: we don't check the size of the bitmap here, we are relying on the output
// of downloadBitmapToMemory to not exceed our memory limits and load a huge bitmap
// into memory.
return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
}
return null;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param urlString The URL to fetch
* @param maxBytes The maximum number of bytes to read before returning null to protect against
* OutOfMemory exceptions.
* @return A File pointing to the fetched bitmap
*/
public static byte[] downloadBitmapToMemory(String urlString, int maxBytes) {
LOGD(TAG, "downloadBitmapToMemory - downloading - " + urlString);
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
ByteArrayOutputStream out = null;
InputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES);
final byte[] buffer = new byte[128];
int total = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
total += bytesRead;
if (total > maxBytes) {
return null;
}
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmapToMemory - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (final IOException e) {}
}
return null;
}
/**
* Download a bitmap from a URL and write the content to an output stream.
*
* @param urlString The URL to fetch
* @param outputStream The outputStream to write to
* @return true if successful, false otherwise
*/
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {}
}
return false;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param urlString The URL to fetch
* @param cacheDir The directory to store the downloaded file
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmapToFile(String urlString, File cacheDir) {
LOGD(TAG, "downloadBitmap - downloading - " + urlString);
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final File tempFile = File.createTempFile("bitmap", null, cacheDir);
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return tempFile;
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (final IOException e) {}
}
return null;
}
/**
* Decode and sample down a bitmap from a file to the requested width and
* height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect
* ratio and dimensions that are equal to or greater than the
* requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
/**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
/**
* Calculate an inSampleSize for use in a
* {@link android.graphics.BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This
* implementation calculates the closest inSampleSize that will result in
* the final decoded bitmap having a width and height equal to or larger
* than the requested width and height. This implementation does not ensure
* a power of 2 is returned for inSampleSize which can be faster when
* decoding but results in a larger bitmap which isn't as useful for caching
* purposes.
*
* @param options An options object with out* params already populated (run
* through a decode* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger
// inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further.
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (hasHttpConnectionBug()) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Check if OS version has a http URLConnection bug. See here for more
* information:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*
* @return true if this OS version is affected, false otherwise
*/
public static boolean hasHttpConnectionBug() {
return !UIUtils.hasFroyo();
}
@Override
protected void initDiskCacheInternal() {
super.initDiskCacheInternal();
initHttpDiskCache();
}
private void initHttpDiskCache() {
if (!mHttpCacheDir.exists()) {
mHttpCacheDir.mkdirs();
}
synchronized (mHttpDiskCacheLock) {
if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) {
try {
mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE);
LOGD(TAG, "HTTP cache initialized");
} catch (IOException e) {
mHttpDiskCache = null;
}
}
mHttpDiskCacheStarting = false;
mHttpDiskCacheLock.notifyAll();
}
}
@Override
protected void clearCacheInternal() {
super.clearCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) {
try {
mHttpDiskCache.delete();
LOGD(TAG, "HTTP cache cleared");
} catch (IOException e) {
LOGE(TAG, "clearCacheInternal - " + e);
}
mHttpDiskCache = null;
mHttpDiskCacheStarting = true;
initHttpDiskCache();
}
}
}
@Override
protected void flushCacheInternal() {
super.flushCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
mHttpDiskCache.flush();
LOGD(TAG, "HTTP cache flushed");
} catch (IOException e) {
LOGE(TAG, "flush - " + e);
}
}
}
}
@Override
protected void closeCacheInternal() {
super.closeCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
if (!mHttpDiskCache.isClosed()) {
mHttpDiskCache.close();
mHttpDiskCache = null;
LOGD(TAG, "HTTP cache closed");
}
} catch (IOException e) {
LOGE(TAG, "closeCacheInternal - " + e);
}
}
}
}
private static class ImageData {
public static final int IMAGE_TYPE_THUMBNAIL = 0;
public static final int IMAGE_TYPE_NORMAL = 1;
public String mKey;
public int mType;
public ImageData(String key, int type) {
mKey = key;
mType = type;
}
@Override
public String toString() {
return mKey;
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This class wraps up completing some arbitrary long running work when loading a bitmap to an
* ImageView. It handles things like using a memory and disk cache, running the work in a background
* thread and setting a placeholder image.
*/
public abstract class ImageWorker {
private static final String TAG = makeLogTag(ImageWorker.class);
private static final int FADE_IN_TIME = 200;
protected ImageCache mImageCache;
protected ImageCache.ImageCacheParams mImageCacheParams;
protected Bitmap mLoadingBitmap;
protected boolean mFadeInBitmap = true;
private boolean mExitTasksEarly = false;
protected boolean mPauseWork = false;
private final Object mPauseWorkLock = new Object();
private final Hashtable<Integer, Bitmap> loadingBitmaps = new Hashtable<Integer, Bitmap>(2);
protected Resources mResources;
private static final int MESSAGE_CLEAR = 0;
private static final int MESSAGE_INIT_DISK_CACHE = 1;
private static final int MESSAGE_FLUSH = 2;
private static final int MESSAGE_CLOSE = 3;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
// Dual thread executor for main AsyncTask
public static final Executor DUAL_THREAD_EXECUTOR =
Executors.newFixedThreadPool(2, sThreadFactory);
protected ImageWorker(Context context) {
mResources = context.getResources();
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing
* logic). A memory and disk cache will be used if an {@link ImageCache} has
* been set using {@link ImageWorker#addImageCache}. If the
* image is found in the memory cache, it is set immediately, otherwise an
* {@link AsyncTask} will be created to asynchronously load the bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
*/
protected void loadImage(Object data, ImageView imageView) {
loadImage(data, imageView, mLoadingBitmap);
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing
* logic). A memory and disk cache will be used if an {@link ImageCache} has
* been set using {@link ImageWorker#addImageCache}. If the
* image is found in the memory cache, it is set immediately, otherwise an
* {@link AsyncTask} will be created to asynchronously load the bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
* @param resId Resource of placeholder bitmap while the image loads.
*/
protected void loadImage(Object data, ImageView imageView, int resId) {
if (!loadingBitmaps.containsKey(resId)) {
// Store loading bitmap in a hash table to prevent continual decoding
loadingBitmaps.put(resId, BitmapFactory.decodeResource(mResources, resId));
}
loadImage(data, imageView, loadingBitmaps.get(resId));
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and disk
* cache will be used if an {@link ImageCache} has been set using
* {@link ImageWorker#addImageCache}. If the image is found in the memory cache, it
* is set immediately, otherwise an {@link AsyncTask} will be created to asynchronously load the
* bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
*/
public void loadImage(Object data, ImageView imageView, Bitmap loadingBitmap) {
if (data == null) {
return;
}
Bitmap bitmap = null;
if (mImageCache != null) {
bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data));
}
if (bitmap != null) {
// Bitmap found in memory cache
imageView.setImageBitmap(bitmap);
} else if (cancelPotentialWork(data, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable =
new AsyncDrawable(mResources, loadingBitmap, task);
imageView.setImageDrawable(asyncDrawable);
if (UIUtils.hasHoneycomb()) {
// On HC+ we execute on a dual thread executor. There really isn't much extra
// benefit to having a really large pool of threads. Having more than one will
// likely benefit network bottlenecks though.
task.executeOnExecutor(DUAL_THREAD_EXECUTOR, data);
} else {
// Otherwise pre-HC the default is a thread pool executor (not ideal, serial
// execution or a smaller number of threads would be better).
task.execute(data);
}
}
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param bitmap
*/
public void setLoadingImage(Bitmap bitmap) {
mLoadingBitmap = bitmap;
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param resId
*/
public void setLoadingImage(int resId) {
mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId);
}
/**
* Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI
* thread).
* @param fragmentManager The FragmentManager to initialize and add the cache
* @param cacheParams The cache parameters to use
*/
public void addImageCache(FragmentManager fragmentManager,
ImageCache.ImageCacheParams cacheParams) {
mImageCacheParams = cacheParams;
setImageCache(ImageCache.findOrCreateCache(fragmentManager, mImageCacheParams));
new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}
/**
* Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI
* thread) using default cache parameters.
* @param fragmentActivity The FragmentActivity to initialize and add the cache
*/
public void addImageCache(FragmentActivity fragmentActivity) {
addImageCache(fragmentActivity.getSupportFragmentManager(),
new ImageCache.ImageCacheParams(fragmentActivity));
}
/**
* Sets the {@link ImageCache} object to use with this ImageWorker. Usually you will not need
* to call this directly, instead use {@link ImageWorker#addImageCache} which will create and
* add the {@link ImageCache} object in a background thread (to ensure no disk access on the
* main/UI thread).
*
* @param imageCache
*/
public void setImageCache(ImageCache imageCache) {
mImageCache = imageCache;
}
/**
* If set to true, the image will fade-in once it has been loaded by the background thread.
*/
public void setImageFadeIn(boolean fadeIn) {
mFadeInBitmap = fadeIn;
}
/**
* Setting this to true will signal the working tasks to exit processing at the next chance.
* This helps finish up pending work when the activity is no longer in the foreground and
* completing the tasks is no longer useful.
* @param exitTasksEarly
*/
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
setPauseWork(false);
}
/**
* Subclasses should override this to define any processing or work that must happen to produce
* the final bitmap. This will be executed in a background thread and be long running. For
* example, you could resize a large bitmap here, or pull down an image from the network.
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
/**
* Cancels any pending work attached to the provided ImageView.
* @param imageView
*/
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
LOGD(TAG, "cancelWork - cancelled work for " + bitmapWorkerTask.data);
}
}
}
/**
* Returns true if the current work has been canceled or if there was no work in
* progress on this image view.
* Returns false if the work in progress deals with the same data. The work is not
* stopped in that case.
*/
public static boolean cancelPotentialWork(Object data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.data;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true);
LOGD(TAG, "cancelPotentialWork - cancelled work for " + data);
} else {
// The same work is already in progress.
return false;
}
}
return true;
}
/**
* @param imageView Any imageView
* @return Retrieve the currently active work task (if any) associated with this imageView.
* null if there is no such task.
*/
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
/**
* The actual AsyncTask that will asynchronously process the image.
*/
private class BitmapWorkerTask extends AsyncTask<Object, Void, Bitmap> {
private Object data;
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
/**
* Background processing.
*/
@Override
protected Bitmap doInBackground(Object... params) {
LOGD(TAG, "doInBackground - starting work");
data = params[0];
final String dataString = String.valueOf(data);
Bitmap bitmap = null;
// Wait here if work is paused and the task is not cancelled
synchronized (mPauseWorkLock) {
while (mPauseWork && !isCancelled()) {
try {
mPauseWorkLock.wait();
} catch (InterruptedException e) {}
}
}
// If the image cache is available and this task has not been cancelled by another
// thread and the ImageView that was originally bound to this task is still bound back
// to this task and our "exit early" flag is not set then try and fetch the bitmap from
// the cache
if (mImageCache != null && !isCancelled() && getAttachedImageView() != null
&& !mExitTasksEarly) {
bitmap = mImageCache.getBitmapFromDiskCache(dataString);
}
// If the bitmap was not found in the cache and this task has not been cancelled by
// another thread and the ImageView that was originally bound to this task is still
// bound back to this task and our "exit early" flag is not set, then call the main
// process method (as implemented by a subclass)
if (bitmap == null && !isCancelled() && getAttachedImageView() != null
&& !mExitTasksEarly) {
bitmap = processBitmap(params[0]);
}
// If the bitmap was processed and the image cache is available, then add the processed
// bitmap to the cache for future use. Note we don't check if the task was cancelled
// here, if it was, and the thread is still running, we may as well add the processed
// bitmap to our cache as it might be used again in the future
if (bitmap != null && mImageCache != null) {
mImageCache.addBitmapToCache(dataString, bitmap);
}
LOGD(TAG, "doInBackground - finished work");
return bitmap;
}
/**
* Once the image is processed, associates it to the imageView
*/
@Override
protected void onPostExecute(Bitmap bitmap) {
// if cancel was called on this task or the "exit early" flag is set then we're done
if (isCancelled() || mExitTasksEarly) {
bitmap = null;
}
final ImageView imageView = getAttachedImageView();
if (bitmap != null && imageView != null) {
LOGD(TAG, "onPostExecute - setting bitmap");
setImageBitmap(imageView, bitmap);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
synchronized (mPauseWorkLock) {
mPauseWorkLock.notifyAll();
}
}
/**
* Returns the ImageView associated with this task as long as the ImageView's task still
* points to this task as well. Returns null otherwise.
*/
private ImageView getAttachedImageView() {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask) {
return imageView;
}
return null;
}
}
/**
* A custom Drawable that will be attached to the imageView while the work is in progress.
* Contains a reference to the actual worker task, so that it can be stopped if a new binding is
* required, and makes sure that only the last started worker process can bind its result,
* independently of the finish order.
*/
private static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
/**
* Called when the processing is complete and the final bitmap should be set on the ImageView.
*
* @param imageView
* @param bitmap
*/
private void setImageBitmap(ImageView imageView, Bitmap bitmap) {
if (mFadeInBitmap) {
// Use TransitionDrawable to fade in
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {
new ColorDrawable(android.R.color.transparent),
new BitmapDrawable(mResources, bitmap)
});
//noinspection deprecation
imageView.setBackgroundDrawable(imageView.getDrawable());
imageView.setImageDrawable(td);
td.startTransition(FADE_IN_TIME);
} else {
imageView.setImageBitmap(bitmap);
}
}
/**
* Pause any ongoing background work. This can be used as a temporary
* measure to improve performance. For example background work could
* be paused when a ListView or GridView is being scrolled using a
* {@link android.widget.AbsListView.OnScrollListener} to keep
* scrolling smooth.
* <p>
* If work is paused, be sure setPauseWork(false) is called again
* before your fragment or activity is destroyed (for example during
* {@link android.app.Activity#onPause()}), or there is a risk the
* background thread will never finish.
*/
public void setPauseWork(boolean pauseWork) {
synchronized (mPauseWorkLock) {
mPauseWork = pauseWork;
if (!mPauseWork) {
mPauseWorkLock.notifyAll();
}
}
}
protected class CacheAsyncTask extends AsyncTask<Object, Void, Void> {
@Override
protected Void doInBackground(Object... params) {
switch ((Integer)params[0]) {
case MESSAGE_CLEAR:
clearCacheInternal();
break;
case MESSAGE_INIT_DISK_CACHE:
initDiskCacheInternal();
break;
case MESSAGE_FLUSH:
flushCacheInternal();
break;
case MESSAGE_CLOSE:
closeCacheInternal();
break;
}
return null;
}
}
protected void initDiskCacheInternal() {
if (mImageCache != null) {
mImageCache.initDiskCache();
}
}
protected void clearCacheInternal() {
if (mImageCache != null) {
mImageCache.clearCache();
}
}
protected void flushCacheInternal() {
if (mImageCache != null) {
mImageCache.flush();
}
}
protected void closeCacheInternal() {
if (mImageCache != null) {
mImageCache.close();
mImageCache = null;
}
}
public void clearCache() {
new CacheAsyncTask().execute(MESSAGE_CLEAR);
}
public void flushCache() {
new CacheAsyncTask().execute(MESSAGE_FLUSH);
}
public void closeCache() {
new CacheAsyncTask().execute(MESSAGE_CLOSE);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
/**
* A set of helper methods for showing contextual help information in the app.
*/
public class HelpUtils {
public static boolean hasSeenTutorial(final Context context, String id) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean("seen_tutorial_" + id, false);
}
private static void setSeenTutorial(final Context context, final String id) {
//noinspection unchecked
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean("seen_tutorial_" + id, true).commit();
return null;
}
}.execute();
}
public static void maybeShowAddToScheduleTutorial(FragmentActivity activity) {
if (hasSeenTutorial(activity, "add_to_schedule")) {
return;
}
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_add_to_schedule");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AddToScheduleTutorialDialog().show(ft, "dialog_add_to_schedule");
setSeenTutorial(activity, "add_to_schedule");
}
public static class AddToScheduleTutorialDialog extends DialogFragment implements
Html.ImageGetter {
public AddToScheduleTutorialDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView tutorialBodyView = (TextView) layoutInflater.inflate(
R.layout.dialog_tutorial_message, null);
tutorialBodyView.setText(
Html.fromHtml(getString(R.string.help_add_to_schedule), this, null));
tutorialBodyView.setContentDescription(
Html.fromHtml(getString(R.string.help_add_to_schedule_alt)));
return new AlertDialog.Builder(getActivity())
.setView(tutorialBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
@Override
public Drawable getDrawable(String url) {
if ("add_to_schedule".equals(url)) {
Resources res = getActivity().getResources();
Drawable d = res.getDrawable(R.drawable.help_add_to_schedule);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
return null;
}
}
public static void showAbout(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_about");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "dialog_about");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
// Build the about body view and append the link to see OSS licenses
SpannableStringBuilder aboutBody = new SpannableStringBuilder();
aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));
licensesLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showOpenSourceLicenses(getActivity());
}
}, 0, licensesLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(licensesLink);
SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));
eulaLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showEula(getActivity());
}
}, 0, eulaLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(eulaLink);
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);
aboutBodyView.setText(aboutBody);
aboutBodyView.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.title_about)
.setView(aboutBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showOpenSourceLicenses(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_licenses");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new OpenSourceLicensesDialog().show(ft, "dialog_licenses");
}
public static class OpenSourceLicensesDialog extends DialogFragment {
public OpenSourceLicensesDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
WebView webView = new WebView(getActivity());
webView.loadUrl("file:///android_asset/licenses.html");
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_licenses)
.setView(webView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showEula(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_eula");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new EulaDialog().show(ft, "dialog_eula");
}
public static class EulaDialog extends DialogFragment {
public EulaDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
TextView eulaTextView = new TextView(getActivity());
eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));
eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());
eulaTextView.setPadding(padding, padding, padding, padding);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_eula)
.setView(eulaTextView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.calendar.SessionCalendarService;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.AccountActivity;
import com.google.android.gcm.GCMRegistrar;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.widget.Toast;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An assortment of authentication and login helper utilities.
*/
public class AccountUtils {
private static final String TAG = makeLogTag(AccountUtils.class);
private static final String PREF_CHOSEN_ACCOUNT = "chosen_account";
private static final String PREF_AUTH_TOKEN = "auth_token";
// The auth scope required for the app. In our case we use the "conference API"
// (not currently open source) which requires the developerssite (and readonly variant) scope.
private static final String AUTH_TOKEN_TYPE =
"oauth2:"
+ "https://www.googleapis.com/auth/developerssite "
+ "https://www.googleapis.com/auth/developerssite.readonly ";
public static boolean isAuthenticated(final Context context) {
return !TextUtils.isEmpty(getChosenAccountName(context));
}
public static String getChosenAccountName(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_CHOSEN_ACCOUNT, null);
}
private static void setChosenAccountName(final Context context, final String accountName) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_CHOSEN_ACCOUNT, accountName).commit();
}
public static String getAuthToken(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_AUTH_TOKEN, null);
}
private static void setAuthToken(final Context context, final String authToken) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_AUTH_TOKEN, authToken).commit();
}
public static void invalidateAuthToken(final Context context) {
AccountManager am = AccountManager.get(context);
am.invalidateAuthToken(GoogleAccountManager.ACCOUNT_TYPE, getAuthToken(context));
setAuthToken(context, null);
}
public static interface AuthenticateCallback {
public boolean shouldCancelAuthentication();
public void onAuthTokenAvailable(String authToken);
}
public static void tryAuthenticate(Activity activity, AuthenticateCallback callback,
int activityRequestCode, Account account) {
//noinspection deprecation
AccountManager.get(activity).getAuthToken(
account,
AUTH_TOKEN_TYPE,
false,
getAccountManagerCallback(callback, account, activity, activity,
activityRequestCode),
null);
}
public static void tryAuthenticateWithErrorNotification(Context context,
AuthenticateCallback callback, Account account) {
//noinspection deprecation
AccountManager.get(context).getAuthToken(
account,
AUTH_TOKEN_TYPE,
true,
getAccountManagerCallback(callback, account, context, null, 0),
null);
}
private static AccountManagerCallback<Bundle> getAccountManagerCallback(
final AuthenticateCallback callback, final Account account,
final Context context, final Activity activity, final int activityRequestCode) {
return new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
if (callback != null && callback.shouldCancelAuthentication()) {
return;
}
try {
Bundle bundle = future.getResult();
if (activity != null && bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, activityRequestCode);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
final String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
setAuthToken(context, token);
setChosenAccountName(context, account.name);
if (callback != null) {
callback.onAuthTokenAvailable(token);
}
}
} catch (Exception e) {
LOGE(TAG, "Authentication error", e);
}
}
};
}
public static void signOut(final Context context) {
// Clear out all Google I/O-created sessions from Calendar
if (UIUtils.hasICS()) {
LOGI(TAG, "Clearing all sessions from Google Calendar using SessionCalendarService.");
Toast.makeText(context, R.string.toast_deleting_sessions_from_calendar,
Toast.LENGTH_LONG).show();
context.startService(
new Intent(SessionCalendarService.ACTION_CLEAR_ALL_SESSIONS_CALENDAR)
.setClass(context, SessionCalendarService.class)
.putExtra(SessionCalendarService.EXTRA_ACCOUNT_NAME,
getChosenAccountName(context)));
}
invalidateAuthToken(context);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().clear().commit();
context.getContentResolver().delete(ScheduleContract.BASE_CONTENT_URI, null, null);
GCMRegistrar.unregister(context);
}
public static void startAuthenticationFlow(final Context context, final Intent finishIntent) {
Intent loginFlowIntent = new Intent(context, AccountActivity.class);
loginFlowIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
loginFlowIntent.putExtra(AccountActivity.EXTRA_FINISH_INTENT, finishIntent);
context.startActivity(loginFlowIntent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
******************************************************************************
* Taken from the JB source code, can be found in:
* libcore/luni/src/main/java/libcore/io/DiskLruCache.java
* or direct link:
* https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java
******************************************************************************
*
* A cache that uses a bounded amount of space on a filesystem. Each cache
* entry has a string key and a fixed number of values. Values are byte
* sequences, accessible as streams or files. Each value must be between {@code
* 0} and {@code Integer.MAX_VALUE} bytes in length.
*
* <p>The cache stores its data in a directory on the filesystem. This
* directory must be exclusive to the cache; the cache may delete or overwrite
* files from its directory. It is an error for multiple processes to use the
* same cache directory at the same time.
*
* <p>This cache limits the number of bytes that it will store on the
* filesystem. When the number of stored bytes exceeds the limit, the cache will
* remove entries in the background until the limit is satisfied. The limit is
* not strict: the cache may temporarily exceed it while waiting for files to be
* deleted. The limit does not include filesystem overhead or the cache
* journal so space-sensitive applications should set a conservative limit.
*
* <p>Clients call {@link #edit} to create or update the values of an entry. An
* entry may have only one editor at one time; if a value is not available to be
* edited then {@link #edit} will return null.
* <ul>
* <li>When an entry is being <strong>created</strong> it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* <li>When an entry is being <strong>edited</strong>, it is not necessary
* to supply data for every value; values default to their previous
* value.
* </ul>
* Every {@link #edit} call must be matched by a call to {@link Editor#commit}
* or {@link Editor#abort}. Committing is atomic: a read observes the full set
* of values as they were before or after the commit, but never a mix of values.
*
* <p>Clients call {@link #get} to read a snapshot of an entry. The read will
* observe the value at the time that {@link #get} was called. Updates and
* removals after the call do not impact ongoing reads.
*
* <p>This class is tolerant of some I/O errors. If files are missing from the
* filesystem, the corresponding entries will be dropped from the cache. If
* an error occurs while writing a cache value, the edit will fail silently.
* Callers should handle other problems by catching {@code IOException} and
* responding appropriately.
*/
public final class DiskLruCache implements Closeable {
static final String JOURNAL_FILE = "journal";
static final String JOURNAL_FILE_TMP = "journal.tmp";
static final String MAGIC = "libcore.io.DiskLruCache";
static final String VERSION_1 = "1";
static final long ANY_SEQUENCE_NUMBER = -1;
private static final String CLEAN = "CLEAN";
private static final String DIRTY = "DIRTY";
private static final String REMOVE = "REMOVE";
private static final String READ = "READ";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final int IO_BUFFER_SIZE = 8 * 1024;
/*
* This cache uses a journal file named "journal". A typical journal file
* looks like this:
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the
* constant string "libcore.io.DiskLruCache", the disk cache's version,
* the application's version, the value count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a
* cache entry. Each line contains space-separated values: a state, a key,
* and optional state-specific values.
* o DIRTY lines track that an entry is actively being created or updated.
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
* temporary files may need to be deleted.
* o CLEAN lines track a cache entry that has been successfully published
* and may be read. A publish line is followed by the lengths of each of
* its values.
* o READ lines track accesses for LRU.
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may
* occasionally be compacted by dropping redundant lines. A temporary file named
* "journal.tmp" will be used during compaction; that file should be deleted if
* it exists when the cache is opened.
*/
private final File directory;
private final File journalFile;
private final File journalFileTmp;
private final int appVersion;
private final long maxSize;
private final int valueCount;
private long size = 0;
private Writer journalWriter;
private final LinkedHashMap<String, Entry> lruEntries
= new LinkedHashMap<String, Entry>(0, 0.75f, true);
private int redundantOpCount;
/**
* To differentiate between old and current snapshots, each entry is given
* a sequence number each time an edit is committed. A snapshot is stale if
* its sequence number is not equal to its entry's sequence number.
*/
private long nextSequenceNumber = 0;
/* From java.util.Arrays */
@SuppressWarnings("unchecked")
private static <T> T[] copyOfRange(T[] original, int start, int end) {
final int originalLength = original.length; // For exception priority compatibility.
if (start > end) {
throw new IllegalArgumentException();
}
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
final int resultLength = end - start;
final int copyLength = Math.min(resultLength, originalLength - start);
final T[] result = (T[]) Array
.newInstance(original.getClass().getComponentType(), resultLength);
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Returns the remainder of 'reader' as a string, closing it when done.
*/
public static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
/**
* Returns the ASCII characters up to but not including the next "\r\n", or
* "\n".
*
* @throws java.io.EOFException if the stream is exhausted before the next newline
* character.
*/
public static String readAsciiLine(InputStream in) throws IOException {
// TODO: support UTF-8 here instead
StringBuilder result = new StringBuilder(80);
while (true) {
int c = in.read();
if (c == -1) {
throw new EOFException();
} else if (c == '\n') {
break;
}
result.append((char) c);
}
int length = result.length();
if (length > 0 && result.charAt(length - 1) == '\r') {
result.setLength(length - 1);
}
return result.toString();
}
/**
* Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* Recursively delete everything in {@code dir}.
*/
// TODO: this should specify paths as Strings rather than as Files
public static void deleteContents(File dir) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IllegalArgumentException("not a directory: " + dir);
}
for (File file : files) {
if (file.isDirectory()) {
deleteContents(file);
}
if (!file.delete()) {
throw new IOException("failed to delete file: " + file);
}
}
}
/** This cache uses a single background thread to evict entries. */
private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Callable<Void> cleanupCallable = new Callable<Void>() {
@Override public Void call() throws Exception {
synchronized (DiskLruCache.this) {
if (journalWriter == null) {
return null; // closed
}
trimToSize();
if (journalRebuildRequired()) {
rebuildJournal();
redundantOpCount = 0;
}
}
return null;
}
};
private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
this.directory = directory;
this.appVersion = appVersion;
this.journalFile = new File(directory, JOURNAL_FILE);
this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP);
this.valueCount = valueCount;
this.maxSize = maxSize;
}
/**
* Opens the cache in {@code directory}, creating a cache if none exists
* there.
*
* @param directory a writable directory
* @param appVersion
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// prefer to pick up where we left off
DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true),
IO_BUFFER_SIZE);
return cache;
} catch (IOException journalIsCorrupt) {
// System.logW("DiskLruCache " + directory + " is corrupt: "
// + journalIsCorrupt.getMessage() + ", removing");
cache.delete();
}
}
// create a new empty cache
directory.mkdirs();
cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
cache.rebuildJournal();
return cache;
}
private void readJournal() throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
try {
String magic = readAsciiLine(in);
String version = readAsciiLine(in);
String appVersionString = readAsciiLine(in);
String valueCountString = readAsciiLine(in);
String blank = readAsciiLine(in);
if (!MAGIC.equals(magic)
|| !VERSION_1.equals(version)
|| !Integer.toString(appVersion).equals(appVersionString)
|| !Integer.toString(valueCount).equals(valueCountString)
|| !"".equals(blank)) {
throw new IOException("unexpected journal header: ["
+ magic + ", " + version + ", " + valueCountString + ", " + blank + "]");
}
while (true) {
try {
readJournalLine(readAsciiLine(in));
} catch (EOFException endOfJournal) {
break;
}
}
} finally {
closeQuietly(in);
}
}
private void readJournalLine(String line) throws IOException {
String[] parts = line.split(" ");
if (parts.length < 2) {
throw new IOException("unexpected journal line: " + line);
}
String key = parts[1];
if (parts[0].equals(REMOVE) && parts.length == 2) {
lruEntries.remove(key);
return;
}
Entry entry = lruEntries.get(key);
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
}
if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) {
entry.readable = true;
entry.currentEditor = null;
entry.setLengths(copyOfRange(parts, 2, parts.length));
} else if (parts[0].equals(DIRTY) && parts.length == 2) {
entry.currentEditor = new Editor(entry);
} else if (parts[0].equals(READ) && parts.length == 2) {
// this work was already done by calling lruEntries.get()
} else {
throw new IOException("unexpected journal line: " + line);
}
}
/**
* Computes the initial size and collects garbage as a part of opening the
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
*/
private void processJournal() throws IOException {
deleteIfExists(journalFileTmp);
for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
Entry entry = i.next();
if (entry.currentEditor == null) {
for (int t = 0; t < valueCount; t++) {
size += entry.lengths[t];
}
} else {
entry.currentEditor = null;
for (int t = 0; t < valueCount; t++) {
deleteIfExists(entry.getCleanFile(t));
deleteIfExists(entry.getDirtyFile(t));
}
i.remove();
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the
* current journal if it exists.
*/
private synchronized void rebuildJournal() throws IOException {
if (journalWriter != null) {
journalWriter.close();
}
Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE);
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for (Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key + '\n');
} else {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
}
}
writer.close();
journalFileTmp.renameTo(journalFile);
journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE);
}
private static void deleteIfExists(File file) throws IOException {
// try {
// Libcore.os.remove(file.getPath());
// } catch (ErrnoException errnoException) {
// if (errnoException.errno != OsConstants.ENOENT) {
// throw errnoException.rethrowAsIOException();
// }
// }
if (file.exists() && !file.delete()) {
throw new IOException();
}
}
/**
* Returns a snapshot of the entry named {@code key}, or null if it doesn't
* exist is not currently readable. If a value is returned, it is moved to
* the head of the LRU queue.
*/
public synchronized Snapshot get(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
/*
* Open all streams eagerly to guarantee that we see a single published
* snapshot. If we opened streams lazily then the streams could come
* from different edits.
*/
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch (FileNotFoundException e) {
// a file must have been deleted manually!
return null;
}
redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Snapshot(key, entry.sequenceNumber, ins);
}
/**
* Returns an editor for the entry named {@code key}, or null if another
* edit is in progress.
*/
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
}
private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER
&& (entry == null || entry.sequenceNumber != expectedSequenceNumber)) {
return null; // snapshot is stale
}
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
} else if (entry.currentEditor != null) {
return null; // another edit is in progress
}
Editor editor = new Editor(entry);
entry.currentEditor = editor;
// flush the journal before creating files to prevent file leaks
journalWriter.write(DIRTY + ' ' + key + '\n');
journalWriter.flush();
return editor;
}
/**
* Returns the directory where this cache stores its data.
*/
public File getDirectory() {
return directory;
}
/**
* Returns the maximum number of bytes that this cache should use to store
* its data.
*/
public long maxSize() {
return maxSize;
}
/**
* Returns the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
public synchronized long size() {
return size;
}
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
Entry entry = editor.entry;
if (entry.currentEditor != editor) {
throw new IllegalStateException();
}
// if this edit is creating the entry for the first time, every index must have a value
if (success && !entry.readable) {
for (int i = 0; i < valueCount; i++) {
if (!entry.getDirtyFile(i).exists()) {
editor.abort();
throw new IllegalStateException("edit didn't create file " + i);
}
}
}
for (int i = 0; i < valueCount; i++) {
File dirty = entry.getDirtyFile(i);
if (success) {
if (dirty.exists()) {
File clean = entry.getCleanFile(i);
dirty.renameTo(clean);
long oldLength = entry.lengths[i];
long newLength = clean.length();
entry.lengths[i] = newLength;
size = size - oldLength + newLength;
}
} else {
deleteIfExists(dirty);
}
}
redundantOpCount++;
entry.currentEditor = null;
if (entry.readable | success) {
entry.readable = true;
journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
if (success) {
entry.sequenceNumber = nextSequenceNumber++;
}
} else {
lruEntries.remove(entry.key);
journalWriter.write(REMOVE + ' ' + entry.key + '\n');
}
if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
}
/**
* We only rebuild the journal when it will halve the size of the journal
* and eliminate at least 2000 ops.
*/
private boolean journalRebuildRequired() {
final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000;
return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD
&& redundantOpCount >= lruEntries.size();
}
/**
* Drops the entry for {@code key} if it exists and can be removed. Entries
* actively being edited cannot be removed.
*
* @return true if an entry was removed.
*/
public synchronized boolean remove(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null || entry.currentEditor != null) {
return false;
}
for (int i = 0; i < valueCount; i++) {
File file = entry.getCleanFile(i);
if (!file.delete()) {
throw new IOException("failed to delete " + file);
}
size -= entry.lengths[i];
entry.lengths[i] = 0;
}
redundantOpCount++;
journalWriter.append(REMOVE + ' ' + key + '\n');
lruEntries.remove(key);
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return true;
}
/**
* Returns true if this cache has been closed.
*/
public boolean isClosed() {
return journalWriter == null;
}
private void checkNotClosed() {
if (journalWriter == null) {
throw new IllegalStateException("cache is closed");
}
}
/**
* Force buffered operations to the filesystem.
*/
public synchronized void flush() throws IOException {
checkNotClosed();
trimToSize();
journalWriter.flush();
}
/**
* Closes this cache. Stored values will remain on the filesystem.
*/
public synchronized void close() throws IOException {
if (journalWriter == null) {
return; // already closed
}
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
}
private void trimToSize() throws IOException {
while (size > maxSize) {
// Map.Entry<String, Entry> toEvict = lruEntries.eldest();
final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
remove(toEvict.getKey());
}
}
/**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/
public void delete() throws IOException {
close();
deleteContents(directory);
}
private void validateKey(String key) {
if (key.contains(" ") || key.contains("\n") || key.contains("\r")) {
throw new IllegalArgumentException(
"keys must not contain spaces or newlines: \"" + key + "\"");
}
}
private static String inputStreamToString(InputStream in) throws IOException {
return readFully(new InputStreamReader(in, UTF_8));
}
/**
* A snapshot of the values for an entry.
*/
public final class Snapshot implements Closeable {
private final String key;
private final long sequenceNumber;
private final InputStream[] ins;
private Snapshot(String key, long sequenceNumber, InputStream[] ins) {
this.key = key;
this.sequenceNumber = sequenceNumber;
this.ins = ins;
}
/**
* Returns an editor for this snapshot's entry, or null if either the
* entry has changed since this snapshot was created or if another edit
* is in progress.
*/
public Editor edit() throws IOException {
return DiskLruCache.this.edit(key, sequenceNumber);
}
/**
* Returns the unbuffered stream with the value for {@code index}.
*/
public InputStream getInputStream(int index) {
return ins[index];
}
/**
* Returns the string value for {@code index}.
*/
public String getString(int index) throws IOException {
return inputStreamToString(getInputStream(index));
}
@Override public void close() {
for (InputStream in : ins) {
closeQuietly(in);
}
}
}
/**
* Edits the values for an entry.
*/
public final class Editor {
private final Entry entry;
private boolean hasErrors;
private Editor(Entry entry) {
this.entry = entry;
}
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
public InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
return new FileInputStream(entry.getCleanFile(index));
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
public String getString(int index) throws IOException {
InputStream in = newInputStream(index);
return in != null ? inputStreamToString(in) : null;
}
/**
* Returns a new unbuffered output stream to write the value at
* {@code index}. If the underlying output stream encounters errors
* when writing to the filesystem, this edit will be aborted when
* {@link #commit} is called. The returned output stream does not throw
* IOExceptions.
*/
public OutputStream newOutputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index)));
}
}
/**
* Sets the value at {@code index} to {@code value}.
*/
public void set(int index, String value) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(newOutputStream(index), UTF_8);
writer.write(value);
} finally {
closeQuietly(writer);
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
public void commit() throws IOException {
if (hasErrors) {
completeEdit(this, false);
remove(entry.key); // the previous entry is stale
} else {
completeEdit(this, true);
}
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
public void abort() throws IOException {
completeEdit(this, false);
}
private class FaultHidingOutputStream extends FilterOutputStream {
private FaultHidingOutputStream(OutputStream out) {
super(out);
}
@Override public void write(int oneByte) {
try {
out.write(oneByte);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void write(byte[] buffer, int offset, int length) {
try {
out.write(buffer, offset, length);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void close() {
try {
out.close();
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void flush() {
try {
out.flush();
} catch (IOException e) {
hasErrors = true;
}
}
}
}
private final class Entry {
private final String key;
/** Lengths of this entry's files. */
private final long[] lengths;
/** True if this entry has ever been published */
private boolean readable;
/** The ongoing edit or null if this entry is not being edited. */
private Editor currentEditor;
/** The sequence number of the most recently committed edit to this entry. */
private long sequenceNumber;
private Entry(String key) {
this.key = key;
this.lengths = new long[valueCount];
}
public String getLengths() throws IOException {
StringBuilder result = new StringBuilder();
for (long size : lengths) {
result.append(' ').append(size);
}
return result.toString();
}
/**
* Set lengths using decimal numbers like "10123".
*/
private void setLengths(String[] strings) throws IOException {
if (strings.length != valueCount) {
throw invalidLengths(strings);
}
try {
for (int i = 0; i < strings.length; i++) {
lengths[i] = Long.parseLong(strings[i]);
}
} catch (NumberFormatException e) {
throw invalidLengths(strings);
}
}
private IOException invalidLengths(String[] strings) throws IOException {
throw new IOException("unexpected journal line: " + Arrays.toString(strings));
}
public File getCleanFile(int i) {
return new File(directory, key + "." + i);
}
public File getDirtyFile(int i) {
return new File(directory, key + "." + i + ".tmp");
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
/**
* {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing
* then against fractional dimensions of the source view.
* <p>
* This is particularly useful when you want to define a rectangle in terms of
* the source dimensions, but when those dimensions might change due to pending
* or future layout passes.
* <p>
* One example is catching touches that occur in the top-right quadrant of
* {@code sourceParent}, and relaying them to {@code targetChild}. This could be
* done with: <code>
* FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f));
* </code>
*/
public class FractionalTouchDelegate extends TouchDelegate {
private View mSource;
private View mTarget;
private RectF mSourceFraction;
private Rect mScrap = new Rect();
/** Cached full dimensions of {@link #mSource}. */
private Rect mSourceFull = new Rect();
/** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */
private Rect mSourcePartial = new Rect();
private boolean mDelegateTargeted;
public FractionalTouchDelegate(View source, View target, RectF sourceFraction) {
super(new Rect(0, 0, 0, 0), target);
mSource = source;
mTarget = target;
mSourceFraction = sourceFraction;
}
/**
* Helper to create and setup a {@link FractionalTouchDelegate} between the
* given {@link View}.
*
* @param source Larger source {@link View}, usually a parent, that will be
* assigned {@link View#setTouchDelegate(TouchDelegate)}.
* @param target Smaller target {@link View} which will receive
* {@link MotionEvent} that land in requested fractional area.
* @param sourceFraction Fractional area projected onto source {@link View}
* which determines when {@link MotionEvent} will be passed to
* target {@link View}.
*/
public static void setupDelegate(View source, View target, RectF sourceFraction) {
source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
/**
* Consider updating {@link #mSourcePartial} when {@link #mSource}
* dimensions have changed.
*/
private void updateSourcePartial() {
mSource.getHitRect(mScrap);
if (!mScrap.equals(mSourceFull)) {
// Copy over and calculate fractional rectangle
mSourceFull.set(mScrap);
final int width = mSourceFull.width();
final int height = mSourceFull.height();
mSourcePartial.left = (int) (mSourceFraction.left * width);
mSourcePartial.top = (int) (mSourceFraction.top * height);
mSourcePartial.right = (int) (mSourceFraction.right * width);
mSourcePartial.bottom = (int) (mSourceFraction.bottom * height);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
updateSourcePartial();
// The logic below is mostly copied from the parent class, since we
// can't update private mBounds variable.
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
// f=core/java/android/view/TouchDelegate.java;hb=eclair#l98
final Rect sourcePartial = mSourcePartial;
final View target = mTarget;
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (sourcePartial.contains(x, y)) {
mDelegateTargeted = true;
sendToDelegate = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
if (!sourcePartial.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
if (hit) {
event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
} else {
event.setLocation(-1, -1);
}
handled = target.dispatchTouchEvent(event);
}
return handled;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
*
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
*
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
*
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import java.lang.reflect.InvocationTargetException;
/**
* A set of helper methods for best-effort method calls via reflection.
*/
public class ReflectionUtils {
public static Object tryInvoke(Object target, String methodName, Object... args) {
Class<?>[] argTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
return tryInvoke(target, methodName, argTypes, args);
}
public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes,
Object... args) {
try {
return target.getClass().getMethod(methodName, argTypes).invoke(target, args);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return null;
}
public static <E> E callWithDefault(Object target, String methodName, E defaultValue) {
try {
//noinspection unchecked
return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return defaultValue;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.util.Log;
/**
* Helper methods that make logging more consistent throughout the app.
*/
public class LogUtils {
private static final String LOG_PREFIX = "iosched_";
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
private static final int MAX_LOG_TAG_LENGTH = 23;
public static String makeLogTag(String str) {
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* WARNING: Don't use this when obfuscating class names with Proguard!
*/
public static String makeLogTag(Class cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGV(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message);
}
}
public static void LOGV(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message, cause);
}
}
public static void LOGI(final String tag, String message) {
Log.i(tag, message);
}
public static void LOGI(final String tag, String message, Throwable cause) {
Log.i(tag, message, cause);
}
public static void LOGW(final String tag, String message) {
Log.w(tag, message);
}
public static void LOGW(final String tag, String message, Throwable cause) {
Log.w(tag, message, cause);
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
private LogUtils() {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.appwidget.MyScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.ScheduleUpdaterService;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SocialStreamActivity;
import com.google.android.apps.iosched.ui.SocialStreamFragment;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ShareCompat;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper class for dealing with common actions to take on a session.
*/
public final class SessionsHelper {
private static final String TAG = makeLogTag(SessionsHelper.class);
private final Activity mActivity;
public SessionsHelper(Activity activity) {
mActivity = activity;
}
public void startMapActivity(String roomId) {
Intent intent = new Intent(mActivity.getApplicationContext(),
UIUtils.getMapActivityClass(mActivity));
intent.putExtra(MapFragment.EXTRA_ROOM, roomId);
mActivity.startActivity(intent);
}
public Intent createShareIntent(int messageTemplateResId, String title, String hashtags,
String url) {
ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity)
.setType("text/plain")
.setText(mActivity.getString(messageTemplateResId,
title, UIUtils.getSessionHashtagsString(hashtags), url));
return builder.getIntent();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId,
final String title, String hashtags, String url) {
// TODO: uncomment pending ShareActionProvider fixes for split AB
// if (UIUtils.hasICS()) {
// ActionProvider itemProvider = menuItem.getActionProvider();
// ShareActionProvider provider;
// if (!(itemProvider instanceof ShareActionProvider)) {
// provider = new ShareActionProvider(mActivity);
// } else {
// provider = (ShareActionProvider) itemProvider;
// }
// provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url));
// provider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
// @Override
// public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
// EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
// LOGD("Tracker", "Shared: " + title);
// return false;
// }
// });
//
// menuItem.setActionProvider(provider);
// }
}
public void shareSession(Context context, int messageTemplateResId, String title,
String hashtags, String url) {
EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
LOGD("Tracker", "Shared: " + title);
context.startActivity(Intent.createChooser(
createShareIntent(messageTemplateResId, title, hashtags, url),
context.getString(R.string.title_share)));
}
public void setSessionStarred(Uri sessionUri, boolean starred, String title) {
LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" +
starred + " title=" + title);
sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri);
final ContentValues values = new ContentValues();
values.put(ScheduleContract.Sessions.SESSION_STARRED, starred);
AsyncQueryHandler handler =
new AsyncQueryHandler(mActivity.getContentResolver()) {
};
handler.startUpdate(-1, null, sessionUri, values, null, null);
EasyTracker.getTracker().trackEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
// Because change listener is set to null during initialization, these
// won't fire on pageview.
final Intent refreshIntent = new Intent(mActivity, MyScheduleWidgetProvider.class);
refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION);
mActivity.sendBroadcast(refreshIntent);
// Sync to the cloud.
final Intent updateServerIntent = new Intent(mActivity, ScheduleUpdaterService.class);
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID,
ScheduleContract.Sessions.getSessionId(sessionUri));
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred);
mActivity.startService(updateServerIntent);
}
public void startSocialStream(String hashtags) {
Intent intent = new Intent(mActivity, SocialStreamActivity.class);
intent.putExtra(SocialStreamFragment.EXTRA_QUERY, hashtags);
mActivity.startActivity(intent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* A pre-Honeycomb, simple implementation of {@link ActionMode} that simply shows a context menu
* for the action mode.
*/
class ActionModeBase extends ActionMode implements DialogInterface.OnClickListener {
private FragmentActivity mActivity;
private Callback mCallback;
private MenuInflater mMenuInflater;
private ContextMenuDialog mDialog;
private CharSequence mTitle;
private SimpleMenu mMenu;
private ArrayAdapter<MenuItem> mMenuItemArrayAdapter;
ActionModeBase(FragmentActivity activity, Callback callback) {
mActivity = activity;
mCallback = callback;
}
static ActionModeBase startInternal(final FragmentActivity activity,
Callback callback) {
final ActionModeBase actionMode = new ActionModeBase(activity, callback);
actionMode.startInternal();
return actionMode;
}
void startInternal() {
mMenu = new SimpleMenu(mActivity);
mCallback.onCreateActionMode(this, mMenu);
mCallback.onPrepareActionMode(this, mMenu);
mMenuItemArrayAdapter = new ArrayAdapter<MenuItem>(mActivity,
android.R.layout.simple_list_item_1,
android.R.id.text1);
invalidate();
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentManager fm = mActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("action_mode_context_menu");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
mDialog = new ContextMenuDialog();
mDialog.mActionModeBase = this;
mDialog.show(ft, "action_mode_context_menu");
}
/**{@inheritDoc}*/
@Override
public void setTitle(CharSequence title) {
mTitle = title;
}
/**{@inheritDoc}*/
@Override
public void setTitle(int resId) {
mTitle = mActivity.getResources().getString(resId);
}
/**{@inheritDoc}*/
@Override
public void invalidate() {
mMenuItemArrayAdapter.clear();
List<MenuItem> items = new ArrayList<MenuItem>();
for (int i = 0; i < mMenu.size(); i++) {
MenuItem item = mMenu.getItem(i);
if (item.isVisible()) {
items.add(item);
}
}
Collections.sort(items, new Comparator<MenuItem>() {
@Override
public int compare(MenuItem a, MenuItem b) {
return a.getOrder() - b.getOrder();
}
});
for (MenuItem item : items) {
mMenuItemArrayAdapter.add(item);
}
}
/**{@inheritDoc}*/
@Override
public void finish() {
if (mDialog != null) {
mDialog.dismiss();
}
mCallback.onDestroyActionMode(this);
mDialog = null;
mMenu = null;
mMenuItemArrayAdapter = null;
mTitle = null;
}
/**{@inheritDoc}*/
@Override
public CharSequence getTitle() {
return mTitle;
}
/**{@inheritDoc}*/
@Override
public MenuInflater getMenuInflater() {
if (mMenuInflater == null) {
mMenuInflater = mActivity.getMenuInflater();
}
return mMenuInflater;
}
public static void beginMultiChoiceMode(ListView listView, final FragmentActivity activity,
final MultiChoiceModeListener listener) {
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int position, long id) {
ActionMode mode = ActionModeBase.start(activity, listener);
listener.onItemCheckedStateChanged(mode, position, id, true);
return true;
}
});
}
@Override
public void onClick(DialogInterface dialogInterface, int position) {
mCallback.onActionItemClicked(this, mMenuItemArrayAdapter.getItem(position));
}
public static class ContextMenuDialog extends DialogFragment {
ActionModeBase mActionModeBase;
public ContextMenuDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (mActionModeBase == null) {
// TODO: support orientation changes and avoid this awful hack.
final Dialog d = new AlertDialog.Builder(getActivity()).create();
new Handler().post(new Runnable() {
@Override
public void run() {
d.dismiss();
}
});
return d;
}
return new AlertDialog.Builder(getActivity())
.setTitle(mActionModeBase.mTitle)
.setAdapter(mActionModeBase.mMenuItemArrayAdapter, mActionModeBase)
.create();
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mActionModeBase == null) {
return;
}
mActionModeBase.mDialog = null;
mActionModeBase.finish();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ListView;
/**
* An implementation of {@link ActionMode} that proxies to the native
* {@link android.view.ActionMode} implementation (shows the contextual action bar).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class ActionModeHoneycomb extends ActionMode {
android.view.ActionMode mNativeActionMode;
ActionModeHoneycomb() {
}
static ActionModeHoneycomb startInternal(final FragmentActivity activity,
final Callback callback) {
final ActionModeHoneycomb actionMode = new ActionModeHoneycomb();
activity.startActionMode(new android.view.ActionMode.Callback() {
@Override
public boolean onCreateActionMode(android.view.ActionMode nativeActionMode, Menu menu) {
actionMode.mNativeActionMode = nativeActionMode;
return callback.onCreateActionMode(actionMode, menu);
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode nativeActionMode,
Menu menu) {
return callback.onPrepareActionMode(actionMode, menu);
}
@Override
public boolean onActionItemClicked(android.view.ActionMode nativeActionMode,
MenuItem menuItem) {
return callback.onActionItemClicked(actionMode, menuItem);
}
@Override
public void onDestroyActionMode(android.view.ActionMode nativeActionMode) {
callback.onDestroyActionMode(actionMode);
}
});
return actionMode;
}
/**{@inheritDoc}*/
@Override
public void setTitle(CharSequence title) {
mNativeActionMode.setTitle(title);
}
/**{@inheritDoc}*/
@Override
public void setTitle(int resId) {
mNativeActionMode.setTitle(resId);
}
/**{@inheritDoc}*/
@Override
public void invalidate() {
mNativeActionMode.invalidate();
}
/**{@inheritDoc}*/
@Override
public void finish() {
mNativeActionMode.finish();
}
/**{@inheritDoc}*/
@Override
public CharSequence getTitle() {
return mNativeActionMode.getTitle();
}
/**{@inheritDoc}*/
@Override
public MenuInflater getMenuInflater() {
return mNativeActionMode.getMenuInflater();
}
public static void beginMultiChoiceMode(ListView listView, FragmentActivity activity,
final MultiChoiceModeListener listener) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
ActionModeHoneycomb mWrappedActionMode;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int position,
long id, boolean checked) {
listener.onItemCheckedStateChanged(mWrappedActionMode, position, id, checked);
}
@Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
if (mWrappedActionMode == null) {
mWrappedActionMode = new ActionModeHoneycomb();
mWrappedActionMode.mNativeActionMode = actionMode;
}
return listener.onCreateActionMode(mWrappedActionMode, menu);
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
if (mWrappedActionMode == null) {
mWrappedActionMode = new ActionModeHoneycomb();
mWrappedActionMode.mNativeActionMode = actionMode;
}
return listener.onPrepareActionMode(mWrappedActionMode, menu);
}
@Override
public boolean onActionItemClicked(android.view.ActionMode actionMode,
MenuItem menuItem) {
return listener.onActionItemClicked(mWrappedActionMode, menuItem);
}
@Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
listener.onDestroyActionMode(mWrappedActionMode);
}
});
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import java.util.ArrayList;
/**
* A <em>really</em> dumb implementation of the {@link android.view.Menu} interface, that's only
* useful for our actionbar-compat purposes. See
* <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for a more complete
* implementation.
*/
public class SimpleMenu implements Menu {
private Context mContext;
private Resources mResources;
private ArrayList<SimpleMenuItem> mItems;
public SimpleMenu(Context context) {
mContext = context;
mResources = context.getResources();
mItems = new ArrayList<SimpleMenuItem>();
}
public Context getContext() {
return mContext;
}
public Resources getResources() {
return mResources;
}
public MenuItem add(CharSequence title) {
return addInternal(0, 0, title);
}
public MenuItem add(int titleRes) {
return addInternal(0, 0, mResources.getString(titleRes));
}
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
return addInternal(itemId, order, title);
}
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
return addInternal(itemId, order, mResources.getString(titleRes));
}
/**
* Adds an item to the menu. The other add methods funnel to this.
*/
private MenuItem addInternal(int itemId, int order, CharSequence title) {
final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title);
mItems.add(findInsertIndex(mItems, order), item);
return item;
}
private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) {
for (int i = items.size() - 1; i >= 0; i--) {
MenuItem item = items.get(i);
if (item.getOrder() <= order) {
return i + 1;
}
}
return 0;
}
public int findItemIndex(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
SimpleMenuItem item = mItems.get(i);
if (item.getItemId() == id) {
return i;
}
}
return -1;
}
public void removeItem(int itemId) {
removeItemAtInt(findItemIndex(itemId));
}
private void removeItemAtInt(int index) {
if ((index < 0) || (index >= mItems.size())) {
return;
}
mItems.remove(index);
}
public void clear() {
mItems.clear();
}
public MenuItem findItem(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
SimpleMenuItem item = mItems.get(i);
if (item.getItemId() == id) {
return item;
}
}
return null;
}
public int size() {
return mItems.size();
}
public MenuItem getItem(int index) {
return mItems.get(index);
}
// Unsupported operations.
public SubMenu addSubMenu(CharSequence charSequence) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int titleRes) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public int addIntentOptions(int i, int i1, int i2, ComponentName componentName,
Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void removeGroup(int i) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupCheckable(int i, boolean b, boolean b1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupVisible(int i, boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupEnabled(int i, boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean hasVisibleItems() {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void close() {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean performShortcut(int i, KeyEvent keyEvent, int i1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean isShortcutKey(int i, KeyEvent keyEvent) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean performIdentifierAction(int i, int i1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setQwertyMode(boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
/**
* A <em>really</em> dumb implementation of the {@link android.view.MenuItem} interface, that's only
* useful for our actionbar-compat purposes. See
* <code>com.android.internal.view.menu.MenuItemImpl</code> in AOSP for a more complete
* implementation.
*/
public class SimpleMenuItem implements MenuItem {
private SimpleMenu mMenu;
private final int mId;
private final int mOrder;
private CharSequence mTitle;
private CharSequence mTitleCondensed;
private Drawable mIconDrawable;
private int mIconResId = 0;
private boolean mEnabled = true;
public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) {
mMenu = menu;
mId = id;
mOrder = order;
mTitle = title;
}
public int getItemId() {
return mId;
}
public int getOrder() {
return mOrder;
}
public MenuItem setTitle(CharSequence title) {
mTitle = title;
return this;
}
public MenuItem setTitle(int titleRes) {
return setTitle(mMenu.getContext().getString(titleRes));
}
public CharSequence getTitle() {
return mTitle;
}
public MenuItem setTitleCondensed(CharSequence title) {
mTitleCondensed = title;
return this;
}
public CharSequence getTitleCondensed() {
return mTitleCondensed != null ? mTitleCondensed : mTitle;
}
public MenuItem setIcon(Drawable icon) {
mIconResId = 0;
mIconDrawable = icon;
return this;
}
public MenuItem setIcon(int iconResId) {
mIconDrawable = null;
mIconResId = iconResId;
return this;
}
public Drawable getIcon() {
if (mIconDrawable != null) {
return mIconDrawable;
}
if (mIconResId != 0) {
return mMenu.getResources().getDrawable(mIconResId);
}
return null;
}
public MenuItem setEnabled(boolean enabled) {
mEnabled = enabled;
return this;
}
public boolean isEnabled() {
return mEnabled;
}
// No-op operations. We use no-ops to allow inflation from menu XML.
public int getGroupId() {
// Noop
return 0;
}
public View getActionView() {
// Noop
return null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public MenuItem setActionProvider(ActionProvider actionProvider) {
// Noop
return this;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public ActionProvider getActionProvider() {
// Noop
return null;
}
public boolean expandActionView() {
// Noop
return false;
}
public boolean collapseActionView() {
// Noop
return false;
}
public boolean isActionViewExpanded() {
// Noop
return false;
}
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) {
// Noop
return this;
}
public MenuItem setIntent(Intent intent) {
// Noop
return this;
}
public Intent getIntent() {
// Noop
return null;
}
public MenuItem setShortcut(char c, char c1) {
// Noop
return this;
}
public MenuItem setNumericShortcut(char c) {
// Noop
return this;
}
public char getNumericShortcut() {
// Noop
return 0;
}
public MenuItem setAlphabeticShortcut(char c) {
// Noop
return this;
}
public char getAlphabeticShortcut() {
// Noop
return 0;
}
public MenuItem setCheckable(boolean b) {
// Noop
return this;
}
public boolean isCheckable() {
// Noop
return false;
}
public MenuItem setChecked(boolean b) {
// Noop
return this;
}
public boolean isChecked() {
// Noop
return false;
}
public MenuItem setVisible(boolean b) {
// Noop
return this;
}
public boolean isVisible() {
// Noop
return true;
}
public boolean hasSubMenu() {
// Noop
return false;
}
public SubMenu getSubMenu() {
// Noop
return null;
}
public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) {
// Noop
return this;
}
public ContextMenu.ContextMenuInfo getMenuInfo() {
// Noop
return null;
}
public void setShowAsAction(int i) {
// Noop
}
public MenuItem setShowAsActionFlags(int i) {
// Noop
return null;
}
public MenuItem setActionView(View view) {
// Noop
return this;
}
public MenuItem setActionView(int i) {
// Noop
return this;
}
@Override
public String toString() {
return mTitle == null ? "" : mTitle.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
import com.google.android.apps.iosched.util.UIUtils;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
/**
* A compatibility shim for {@link android.view.ActionMode} that shows context menus
* on pre-Honeycomb devices.
*/
public abstract class ActionMode {
private Object mTag;
public static ActionMode start(FragmentActivity activity, Callback callback) {
if (UIUtils.hasHoneycomb()) {
return ActionModeHoneycomb.startInternal(activity, callback);
} else {
return ActionModeBase.startInternal(activity, callback);
}
}
public static void setMultiChoiceMode(ListView listView, FragmentActivity activity,
MultiChoiceModeListener listener) {
if (UIUtils.hasHoneycomb()) {
ActionModeHoneycomb.beginMultiChoiceMode(listView, activity, listener);
} else {
ActionModeBase.beginMultiChoiceMode(listView, activity, listener);
}
}
/**
* Set a tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @param tag Tag to associate with this ActionMode
*
* @see #getTag()
*/
public void setTag(Object tag) {
mTag = tag;
}
/**
* Retrieve the tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @return Tag associated with this ActionMode
*
* @see #setTag(Object)
*/
public Object getTag() {
return mTag;
}
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param title Title string to set
*
* @see #setTitle(int)
* @see #setCustomView(View)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the title
*
* @see #setTitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setTitle(int resId);
/**
* Invalidate the action mode and refresh menu content. The mode's
* {@link ActionMode.Callback} will have its
* {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called.
* If it returns true the menu will be scanned for updated content and any relevant changes
* will be reflected to the user.
*/
public abstract void invalidate();
/**
* Finish and close this action mode. The action mode's {@link ActionMode.Callback} will
* have its {@link Callback#onDestroyActionMode(ActionMode)} method called.
*/
public abstract void finish();
/**
* Returns the current title of this action mode.
* @return Title text
*/
public abstract CharSequence getTitle();
/**
* Returns a {@link MenuInflater} with the ActionMode's context.
*/
public abstract MenuInflater getMenuInflater();
/**
* Returns whether the UI presenting this action mode can take focus or not.
* This is used by internal components within the framework that would otherwise
* present an action mode UI that requires focus, such as an EditText as a custom view.
*
* @return true if the UI used to show this action mode can take focus
* @hide Internal use only
*/
public boolean isUiFocusable() {
return true;
}
/**
* Callback interface for action modes. Supplied to
* {@link View#startActionMode(Callback)}, a Callback
* configures and handles events raised by a user's interaction with an action mode.
*
* <p>An action mode's lifecycle is as follows:
* <ul>
* <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial
* creation</li>
* <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation
* and any time the {@link ActionMode} is invalidated</li>
* <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a
* contextual action button is clicked</li>
* <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode
* is closed</li>
* </ul>
*/
public interface Callback {
/**
* Called when action mode is first created. The menu supplied will be used to
* generate action buttons for the action mode.
*
* @param mode ActionMode being created
* @param menu Menu used to populate action buttons
* @return true if the action mode should be created, false if entering this
* mode should be aborted.
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu);
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
public boolean onPrepareActionMode(ActionMode mode, Menu menu);
/**
* Called to report a user click on an action button.
*
* @param mode The current ActionMode
* @param item The item that was clicked
* @return true if this callback handled the event, false if the standard MenuItem
* invocation should continue.
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item);
/**
* Called when an action mode is about to be exited and destroyed.
*
* @param mode The current ActionMode being destroyed
*/
public void onDestroyActionMode(ActionMode mode);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util.actionmodecompat;
/**
* A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
* It acts as the {@link ActionMode.Callback} for the selection mode and also receives {@link
* #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user selects and
* deselects list items.
*/
public interface MultiChoiceModeListener extends ActionMode.Callback {
/**
* Called when an item is checked or unchecked during selection mode.
*
* @param mode The {@link ActionMode} providing the selection mode
* @param position Adapter position of the item that was checked or unchecked
* @param id Adapter ID of the item that was checked or unchecked
* @param checked <code>true</code> if the item is now checked, <code>false</code> if the
* item is now unchecked.
*/
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked);
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.util;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This class holds our bitmap caches (memory and disk).
*/
public class ImageCache {
private static final String TAG = makeLogTag(ImageCache.class);
// Default memory cache size as a percent of device memory class
private static final float DEFAULT_MEM_CACHE_PERCENT = 0.15f;
// Default disk cache size
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
// Default disk cache directory name
private static final String DEFAULT_DISK_CACHE_DIR = "images";
// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 75;
private static final int DISK_CACHE_INDEX = 0;
// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_CLEAR_DISK_CACHE_ON_START = false;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;
private DiskLruCache mDiskLruCache;
private LruCache<String, Bitmap> mMemoryCache;
private ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
/**
* Creating a new ImageCache object using the specified parameters.
*
* @param cacheParams The cache parameters to use to initialize the cache
*/
public ImageCache(ImageCacheParams cacheParams) {
init(cacheParams);
}
/**
* Creating a new ImageCache object using the default parameters.
*
* @param context The context to use
*/
public ImageCache(Context context) {
init(new ImageCacheParams(context));
}
/**
* Find and return an existing ImageCache stored in a {@link RetainFragment}, if not found a new
* one is created using the supplied params and saved to a {@link RetainFragment}.
*
* @param fragmentManager The fragment manager to use when dealing with the retained fragment.
* @param cacheParams The cache parameters to use if creating the ImageCache
* @return An existing retained ImageCache object or a new one if one did not exist
*/
public static ImageCache findOrCreateCache(
FragmentManager fragmentManager, ImageCacheParams cacheParams) {
// Search for, or create an instance of the non-UI RetainFragment
final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);
// See if we already have an ImageCache stored in RetainFragment
ImageCache imageCache = (ImageCache) mRetainFragment.getObject();
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(cacheParams);
mRetainFragment.setObject(imageCache);
}
return imageCache;
}
/**
* Initialize the cache, providing all parameters.
*
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
// Set up memory cache
if (mCacheParams.memoryCacheEnabled) {
LOGD(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
mMemoryCache = new LruCache<String, Bitmap>(mCacheParams.memCacheSize) {
/**
* Measure item size in kilobytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
final int bitmapSize = getBitmapSize(bitmap) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
};
}
// By default the disk cache is not initialized here as it should be initialized
// on a separate thread due to disk access.
if (cacheParams.initDiskCacheOnCreate) {
// Set up disk cache
initDiskCache();
}
}
/**
* Initializes the disk cache. Note that this includes disk access so this should not be
* executed on the main/UI thread. By default an ImageCache does not initialize the disk
* cache when it is created, instead you should call initDiskCache() to initialize it on a
* background thread.
*/
public void initDiskCache() {
// Set up disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
File diskCacheDir = mCacheParams.diskCacheDir;
if (mCacheParams.diskCacheEnabled && diskCacheDir != null) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdirs();
}
if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) {
try {
mDiskLruCache = DiskLruCache.open(
diskCacheDir, 1, 1, mCacheParams.diskCacheSize);
LOGD(TAG, "Disk cache initialized");
} catch (final IOException e) {
mCacheParams.diskCacheDir = null;
LOGE(TAG, "initDiskCache - " + e);
}
}
}
}
mDiskCacheStarting = false;
mDiskCacheLock.notifyAll();
}
}
/**
* Adds a bitmap to both memory and disk cache.
* @param data Unique identifier for the bitmap to store
* @param bitmap The bitmap to store
*/
public void addBitmapToCache(String data, Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
// Add to memory cache
if (mMemoryCache != null && mMemoryCache.get(data) == null) {
mMemoryCache.put(data, bitmap);
}
synchronized (mDiskCacheLock) {
// Add to disk cache
if (mDiskLruCache != null) {
final String key = hashKeyForDisk(data);
OutputStream out = null;
try {
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot == null) {
final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
out = editor.newOutputStream(DISK_CACHE_INDEX);
bitmap.compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
out.close();
}
} else {
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
} catch (final IOException e) {
LOGE(TAG, "addBitmapToCache - " + e);
} catch (Exception e) {
LOGE(TAG, "addBitmapToCache - " + e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {}
}
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
LOGD(TAG, "Memory cache hit");
return memBitmap;
}
}
return null;
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
final String key = hashKeyForDisk(data);
synchronized (mDiskCacheLock) {
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
InputStream inputStream = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot != null) {
LOGD(TAG, "Disk cache hit");
inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
if (inputStream != null) {
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
}
} catch (final IOException e) {
LOGE(TAG, "getBitmapFromDiskCache - " + e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {}
}
}
return null;
}
}
/**
* Clears both the memory and disk cache associated with this ImageCache object. Note that
* this includes disk access so this should not be executed on the main/UI thread.
*/
public void clearCache() {
if (mMemoryCache != null) {
mMemoryCache.evictAll();
LOGD(TAG, "Memory cache cleared");
}
synchronized (mDiskCacheLock) {
mDiskCacheStarting = true;
if (mDiskLruCache != null && !mDiskLruCache.isClosed()) {
try {
mDiskLruCache.delete();
LOGD(TAG, "Disk cache cleared");
} catch (IOException e) {
LOGE(TAG, "clearCache - " + e);
}
mDiskLruCache = null;
initDiskCache();
}
}
}
/**
* Flushes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void flush() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
mDiskLruCache.flush();
LOGD(TAG, "Disk cache flushed");
} catch (IOException e) {
LOGE(TAG, "flush - " + e);
}
}
}
}
/**
* Closes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void close() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
if (!mDiskLruCache.isClosed()) {
mDiskLruCache.close();
mDiskLruCache = null;
LOGD(TAG, "Disk cache closed");
}
} catch (IOException e) {
LOGE(TAG, "close - " + e);
}
}
}
}
/**
* A holder class that contains cache parameters.
*/
public static class ImageCacheParams {
public int memCacheSize;
public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
public File diskCacheDir;
public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
public int compressQuality = DEFAULT_COMPRESS_QUALITY;
public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
public boolean clearDiskCacheOnStart = DEFAULT_CLEAR_DISK_CACHE_ON_START;
public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;
public ImageCacheParams(Context context) {
init(getDiskCacheDir(context, DEFAULT_DISK_CACHE_DIR));
}
public ImageCacheParams(Context context, String uniqueName) {
init(getDiskCacheDir(context, uniqueName));
}
public ImageCacheParams(File diskCacheDir) {
init(diskCacheDir);
}
private void init(File diskCacheDir) {
setMemCacheSizePercent(DEFAULT_MEM_CACHE_PERCENT);
this.diskCacheDir = diskCacheDir;
}
/**
* Sets the memory cache size based on a percentage of the max available VM memory.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the avilable
* memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8.
* memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
* to construct a LruCache which takes an int in its constructor.
*
* This value should be chosen carefully based on a number of factors
* Refer to the corresponding Android Training class for more discussion:
* http://developer.android.com/training/displaying-bitmaps/
*
* @param percent Percent of memory class to use to size memory cache
*/
public void setMemCacheSizePercent(float percent) {
if (percent < 0.05f || percent > 0.8f) {
throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
+ "between 0.05 and 0.8 (inclusive)");
}
memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
}
private static int getMemoryClass(Context context) {
return ((ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE)).getMemoryClass();
}
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context The context to use
* @param uniqueName A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable for using as a
* disk filename.
*/
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* Get the size in bytes of a bitmap.
* @param bitmap
* @return size in bytes
*/
@TargetApi(12)
public static int getBitmapSize(Bitmap bitmap) {
if (UIUtils.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/**
* Check if external storage is built-in or removable.
*
* @return True if external storage is removable (like an SD card), false
* otherwise.
*/
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
if (UIUtils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
if (UIUtils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
/**
* Check how much usable space is available at a given path.
*
* @param path The path to check
* @return The space available in bytes
*/
@TargetApi(9)
public static long getUsableSpace(File path) {
if (UIUtils.hasGingerbread()) {
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
/**
* Locate an existing instance of this Fragment or if not found, create and
* add it using FragmentManager.
*
* @param fm The FragmentManager manager to use.
* @return The existing instance of the Fragment or the new instance if just
* created.
*/
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
// Check to see if we have retained the worker fragment.
RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG);
// If not retained (or first time running), we need to create and add it.
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment();
fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss();
}
return mRetainFragment;
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over configuration
* changes. It will be used to retain the ImageCache object.
*/
public static class RetainFragment extends Fragment {
private Object mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* @param object The object to store
*/
public void setObject(Object object) {
mObject = object;
}
/**
* Get the stored object.
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.sync;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.util.AccountUtils;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a
* "conference API" that is not currently open source.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.",
throwable);
}
});
}
}
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
final ContentProviderClient provider, final SyncResult syncResult) {
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
final String logSanitizedAccountName = sSanitizeAccountNamePattern
.matcher(account.name).replaceAll("$1...$2@");
if (uploadOnly) {
return;
}
LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," +
" uploadOnly=" + uploadOnly +
" manualSync=" + manualSync +
" initialize=" + initialize);
if (initialize) {
String chosenAccountName = AccountUtils.getChosenAccountName(mContext);
boolean isChosenAccount =
chosenAccountName != null && chosenAccountName.equals(account.name);
ContentResolver.setIsSyncable(account, authority, isChosenAccount ? 1 : 0);
if (!isChosenAccount) {
++syncResult.stats.numAuthExceptions;
return;
}
}
// Perform a sync using SyncHelper
if (mSyncHelper == null) {
mSyncHelper = new SyncHelper(mContext);
}
try {
mSyncHelper.performSync(syncResult,
SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE);
} catch (IOException e) {
++syncResult.stats.numIoExceptions;
LOGE(TAG, "Error syncing data for I/O 2012.", e);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.sync;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background {@link android.app.Service} that adds or removes sessions from your calendar via the
* Conference API.
*
* @see com.google.android.apps.iosched.sync.SyncHelper
*/
public class ScheduleUpdaterService extends Service {
private static final String TAG = makeLogTag(ScheduleUpdaterService.class);
public static final String EXTRA_SESSION_ID
= "com.google.android.apps.iosched.extra.SESSION_ID";
public static final String EXTRA_IN_SCHEDULE
= "com.google.android.apps.iosched.extra.IN_SCHEDULE";
private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000;
private final Handler mUiThreadHandler = new Handler();
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>();
// Handler pattern copied from IntentService
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
processPendingScheduleUpdates();
int numRemainingUpdates;
synchronized (mScheduleUpdates) {
numRemainingUpdates = mScheduleUpdates.size();
}
if (numRemainingUpdates == 0) {
stopSelf();
} else {
// More updates were added since the current pending set was processed. Reschedule
// another pass.
removeMessages(0);
sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
}
}
}
public ScheduleUpdaterService() {
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName());
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// When receiving a new intent, delay the schedule until 5 seconds from now.
mServiceHandler.removeMessages(0);
mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
// Remove pending updates involving this session ID.
String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
Iterator<Intent> updatesIterator = mScheduleUpdates.iterator();
while (updatesIterator.hasNext()) {
Intent existingIntent = updatesIterator.next();
if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) {
updatesIterator.remove();
}
}
// Queue this schedule update.
synchronized (mScheduleUpdates) {
mScheduleUpdates.add(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (HandlerException.NoDevsiteProfileException e) {
// The user doesn't have a profile, message this to them.
// TODO: better UX for this type of error
LOGW(TAG, "To sync your schedule to the web, login to developers.google.com.", e);
mUiThreadHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ScheduleUpdaterService.this,
"To sync your schedule to the web, login to developers.google.com.",
Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.sync;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.AnnouncementsHandler;
import com.google.android.apps.iosched.io.BlocksHandler;
import com.google.android.apps.iosched.io.HandlerException;
import com.google.android.apps.iosched.io.JSONHandler;
import com.google.android.apps.iosched.io.RoomsHandler;
import com.google.android.apps.iosched.io.SandboxHandler;
import com.google.android.apps.iosched.io.SearchSuggestHandler;
import com.google.android.apps.iosched.io.SessionsHandler;
import com.google.android.apps.iosched.io.SpeakersHandler;
import com.google.android.apps.iosched.io.TracksHandler;
import com.google.android.apps.iosched.io.model.EditMyScheduleResponse;
import com.google.android.apps.iosched.io.model.ErrorResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.calendar.SessionCalendarService;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import android.accounts.Account;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A helper class for dealing with sync and other remote persistence operations.
* All operations occur on the thread they're called from, so it's best to wrap
* calls in an {@link android.os.AsyncTask}, or better yet, a
* {@link android.app.Service}.
*/
public class SyncHelper {
private static final String TAG = makeLogTag(SyncHelper.class);
static {
// Per http://android-developers.blogspot.com/2011/09/androids-http-clients.html
if (!UIUtils.hasFroyo()) {
System.setProperty("http.keepAlive", "false");
}
}
public static final int FLAG_SYNC_LOCAL = 0x1;
public static final int FLAG_SYNC_REMOTE = 0x2;
private static final int LOCAL_VERSION_CURRENT = 19;
private Context mContext;
private String mAuthToken;
private String mUserAgent;
public SyncHelper(Context context) {
mContext = context;
mUserAgent = buildUserAgent(context);
}
/**
* Loads conference information (sessions, rooms, tracks, speakers, etc.)
* from a local static cache data and then syncs down data from the
* Conference API.
*
* @param syncResult Optional {@link SyncResult} object to populate.
* @throws IOException
*/
public void performSync(SyncResult syncResult, int flags) throws IOException {
mAuthToken = AccountUtils.getAuthToken(mContext);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
final int localVersion = prefs.getInt("local_data_version", 0);
// Bulk of sync work, performed by executing several fetches from
// local and online sources.
final ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
LOGI(TAG, "Performing sync");
if ((flags & FLAG_SYNC_LOCAL) != 0) {
final long startLocal = System.currentTimeMillis();
final boolean localParse = localVersion < LOCAL_VERSION_CURRENT;
LOGD(TAG, "found localVersion=" + localVersion + " and LOCAL_VERSION_CURRENT="
+ LOCAL_VERSION_CURRENT);
// Only run local sync if there's a newer version of data available
// than what was last locally-sync'd.
if (localParse) {
// Load static local data
batch.addAll(new RoomsHandler(mContext).parse(
JSONHandler.loadResourceJson(mContext, R.raw.rooms)));
batch.addAll(new BlocksHandler(mContext).parse(
JSONHandler.loadResourceJson(mContext, R.raw.common_slots)));
batch.addAll(new TracksHandler(mContext).parse(
JSONHandler.loadResourceJson(mContext, R.raw.tracks)));
batch.addAll(new SpeakersHandler(mContext, true).parse(
JSONHandler.loadResourceJson(mContext, R.raw.speakers)));
batch.addAll(new SessionsHandler(mContext, true, false).parse(
JSONHandler.loadResourceJson(mContext, R.raw.sessions)));
batch.addAll(new SandboxHandler(mContext, true).parse(
JSONHandler.loadResourceJson(mContext, R.raw.sandbox)));
batch.addAll(new SearchSuggestHandler(mContext).parse(
JSONHandler.loadResourceJson(mContext, R.raw.search_suggest)));
prefs.edit().putInt("local_data_version", LOCAL_VERSION_CURRENT).commit();
if (syncResult != null) {
++syncResult.stats.numUpdates;
++syncResult.stats.numEntries;
}
}
LOGD(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms");
try {
// Apply all queued up batch operations for local data.
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
batch = new ArrayList<ContentProviderOperation>();
}
if ((flags & FLAG_SYNC_REMOTE) != 0 && isOnline()) {
try {
boolean auth = !UIUtils.isGoogleTV(mContext) &&
AccountUtils.isAuthenticated(mContext);
final long startRemote = System.currentTimeMillis();
LOGI(TAG, "Remote syncing speakers");
batch.addAll(executeGet(Config.GET_ALL_SPEAKERS_URL,
new SpeakersHandler(mContext, false), auth));
LOGI(TAG, "Remote syncing sessions");
batch.addAll(executeGet(Config.GET_ALL_SESSIONS_URL,
new SessionsHandler(mContext, false, mAuthToken != null), auth));
LOGI(TAG, "Remote syncing sandbox");
batch.addAll(executeGet(Config.GET_SANDBOX_URL,
new SandboxHandler(mContext, false), auth));
LOGI(TAG, "Remote syncing announcements");
batch.addAll(executeGet(Config.GET_ALL_ANNOUNCEMENTS_URL,
new AnnouncementsHandler(mContext, false), auth));
// GET_ALL_SESSIONS covers the functionality GET_MY_SCHEDULE provides here.
LOGD(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
if (syncResult != null) {
++syncResult.stats.numUpdates;
++syncResult.stats.numEntries;
}
EasyTracker.getTracker().dispatch();
} catch (HandlerException.UnauthorizedException e) {
LOGI(TAG, "Unauthorized; getting a new auth token.", e);
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
AccountUtils.invalidateAuthToken(mContext);
AccountUtils.tryAuthenticateWithErrorNotification(mContext, null,
new Account(AccountUtils.getChosenAccountName(mContext),
GoogleAccountManager.ACCOUNT_TYPE));
}
// all other IOExceptions are thrown
}
try {
// Apply all queued up remaining batch operations (only remote content at this point).
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
// Delete empty blocks
Cursor emptyBlocksCursor = resolver.query(ScheduleContract.Blocks.CONTENT_URI,
new String[]{ScheduleContract.Blocks.BLOCK_ID,ScheduleContract.Blocks.SESSIONS_COUNT},
ScheduleContract.Blocks.EMPTY_SESSIONS_SELECTION, null, null);
batch = new ArrayList<ContentProviderOperation>();
int numDeletedEmptyBlocks = 0;
while (emptyBlocksCursor.moveToNext()) {
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.Blocks.buildBlockUri(
emptyBlocksCursor.getString(0)))
.build());
++numDeletedEmptyBlocks;
}
emptyBlocksCursor.close();
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
LOGD(TAG, "Deleted " + numDeletedEmptyBlocks + " empty session blocks.");
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
if (UIUtils.hasICS()) {
LOGD(TAG, "Done with sync'ing conference data. Starting to sync "
+ "session with Calendar.");
syncCalendar();
}
}
private void syncCalendar() {
Intent intent = new Intent(SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR);
intent.setClass(mContext, SessionCalendarService.class);
mContext.startService(intent);
}
/**
* Build and return a user-agent string that can identify this application
* to remote servers. Contains the package name and version code.
*/
private static String buildUserAgent(Context context) {
String versionName = "unknown";
int versionCode = 0;
try {
final PackageInfo info = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
versionName = info.versionName;
versionCode = info.versionCode;
} catch (PackageManager.NameNotFoundException ignored) {
}
return context.getPackageName() + "/" + versionName + " (" + versionCode + ") (gzip)";
}
public void addOrRemoveSessionFromSchedule(Context context, String sessionId,
boolean inSchedule) throws IOException {
mAuthToken = AccountUtils.getAuthToken(mContext);
JsonObject starredSession = new JsonObject();
starredSession.addProperty("sessionid", sessionId);
byte[] postJsonBytes = new Gson().toJson(starredSession).getBytes();
URL url = new URL(Config.EDIT_MY_SCHEDULE_URL + (inSchedule ? "add" : "remove"));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", mUserAgent);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Bearer " + mAuthToken);
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(postJsonBytes.length);
LOGD(TAG, "Posting to URL: " + url);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(postJsonBytes);
out.flush();
urlConnection.connect();
throwErrors(urlConnection);
String json = readInputStream(urlConnection.getInputStream());
EditMyScheduleResponse response = new Gson().fromJson(json,
EditMyScheduleResponse.class);
if (!response.success) {
String responseMessageLower = (response.message != null)
? response.message.toLowerCase()
: "";
if (responseMessageLower.contains("no profile")) {
throw new HandlerException.NoDevsiteProfileException();
}
}
}
private ArrayList<ContentProviderOperation> executeGet(String urlString, JSONHandler handler,
boolean authenticated) throws IOException {
LOGD(TAG, "Requesting URL: " + urlString);
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", mUserAgent);
if (authenticated && mAuthToken != null) {
urlConnection.setRequestProperty("Authorization", "Bearer " + mAuthToken);
}
urlConnection.connect();
throwErrors(urlConnection);
String response = readInputStream(urlConnection.getInputStream());
LOGV(TAG, "HTTP response: " + response);
return handler.parse(response);
}
private void throwErrors(HttpURLConnection urlConnection) throws IOException {
final int status = urlConnection.getResponseCode();
if (status < 200 || status >= 300) {
String errorMessage = null;
try {
String errorContent = readInputStream(urlConnection.getErrorStream());
LOGV(TAG, "Error content: " + errorContent);
ErrorResponse errorResponse = new Gson().fromJson(
errorContent, ErrorResponse.class);
errorMessage = errorResponse.error.message;
} catch (IOException ignored) {
} catch (JsonSyntaxException ignored) {
}
String exceptionMessage = "Error response "
+ status + " "
+ urlConnection.getResponseMessage()
+ (errorMessage == null ? "" : (": " + errorMessage))
+ " for " + urlConnection.getURL();
// TODO: the API should return 401, and we shouldn't have to parse the message
throw (errorMessage != null && errorMessage.toLowerCase().contains("auth"))
? new HandlerException.UnauthorizedException(exceptionMessage)
: new HandlerException(exceptionMessage);
}
}
private static String readInputStream(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String responseLine;
StringBuilder responseBuilder = new StringBuilder();
while ((responseLine = bufferedReader.readLine()) != null) {
responseBuilder.append(responseLine);
}
return responseBuilder.toString();
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service that handles sync. It simply instantiates a SyncAdapter and returns its IBinder.
*/
public class SyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static SyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), false);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.apps.iosched.sync;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import android.accounts.Account;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
/**
* A simple {@link BroadcastReceiver} that triggers a sync. This is used by the GCM code to trigger
* jittered syncs using {@link android.app.AlarmManager}.
*/
public class TriggerSyncReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String accountName = AccountUtils.getChosenAccountName(context);
if (TextUtils.isEmpty(accountName)) {
return;
}
ContentResolver.requestSync(
new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE),
ScheduleContract.CONTENT_AUTHORITY, new Bundle());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.youtube.api;
/**
* Temporarily just a stub.
*/
public interface YouTubePlayer {
public static int FULLSCREEN_FLAG_CONTROL_ORIENTATION = 1;
public static int FULLSCREEN_FLAG_CONTROL_SYSTEM_UI = 2;
public static int FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE = 4;
public void cueVideo(java.lang.String s);
public void loadVideo(java.lang.String s);
public void cuePlaylist(java.lang.String s);
public void loadPlaylist(java.lang.String s);
public void cueVideos(java.util.List<java.lang.String> strings);
public void loadVideos(java.util.List<java.lang.String> strings);
public void play();
public void pause();
public void release();
public boolean hasNext();
public boolean hasPrevious();
public void next();
public void previous();
public int getCurrentTimeMillis();
public void seekToMillis(int i);
public void seekRelativeMillis(int i);
public void setFullscreen(boolean b);
public void enableCustomFullscreen(com.google.android.youtube.api.YouTubePlayer.OnFullscreenListener onFullscreenListener);
public void setFullscreenControlFlags(int i);
public void setShowControls(boolean b);
public void setManageAudioFocus(boolean b);
public void setOnPlaybackEventsListener(com.google.android.youtube.api.YouTubePlayer.OnPlaybackEventsListener onPlaybackEventsListener);
public void setUseSurfaceTexture(boolean b);
public static interface OnFullscreenListener {
void onFullscreen(boolean b);
}
public static interface OnPlaybackEventsListener {
void onLoaded(java.lang.String s);
void onPlaying();
void onPaused();
void onBuffering(boolean b);
void onEnded();
void onError();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.youtube.api;
import android.content.Context;
/**
* Temporarily just a stub.
*/
public class YouTube {
public static void initialize(Context context, String key) {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.google.android.youtube.api;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Temporarily just a stub.
*/
public class YouTubePlayerSupportFragment extends Fragment implements YouTubePlayer {
public YouTubePlayerSupportFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = new View(getActivity());
v.setBackgroundColor(0);
return v;
}
@Override
public void cueVideo(String s) {
}
@Override
public void loadVideo(String s) {
}
@Override
public void cuePlaylist(String s) {
}
@Override
public void loadPlaylist(String s) {
}
@Override
public void cueVideos(List<String> strings) {
}
@Override
public void loadVideos(List<String> strings) {
}
@Override
public void play() {
}
@Override
public void pause() {
}
@Override
public void release() {
}
@Override
public boolean hasNext() {
return false;
}
@Override
public boolean hasPrevious() {
return false;
}
@Override
public void next() {
}
@Override
public void previous() {
}
@Override
public int getCurrentTimeMillis() {
return 0;
}
@Override
public void seekToMillis(int i) {
}
@Override
public void seekRelativeMillis(int i) {
}
@Override
public void setFullscreen(boolean b) {
}
@Override
public void enableCustomFullscreen(OnFullscreenListener onFullscreenListener) {
}
@Override
public void setFullscreenControlFlags(int i) {
}
@Override
public void setShowControls(boolean b) {
}
@Override
public void setManageAudioFocus(boolean b) {
}
@Override
public void setOnPlaybackEventsListener(OnPlaybackEventsListener onPlaybackEventsListener) {
}
@Override
public void setUseSurfaceTexture(boolean b) {
}
}
| Java |
package android.support.v4.app;
import android.util.Log;
import android.view.View;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import java.util.ArrayList;
/** I'm in ur package. Stealing ur variables. */
public abstract class _ActionBarSherlockTrojanHorse extends FragmentActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener {
private static final boolean DEBUG = false;
private static final String TAG = "_ActionBarSherlockTrojanHorse";
/** Fragment interface for menu creation callback. */
public interface OnCreateOptionsMenuListener {
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater);
}
/** Fragment interface for menu preparation callback. */
public interface OnPrepareOptionsMenuListener {
public void onPrepareOptionsMenu(Menu menu);
}
/** Fragment interface for menu item selection callback. */
public interface OnOptionsItemSelectedListener {
public boolean onOptionsItemSelected(MenuItem item);
}
private ArrayList<Fragment> mCreatedMenus;
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean result = onCreateOptionsMenu(menu);
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] activity create result: " + result);
MenuInflater inflater = getSupportMenuInflater();
boolean show = false;
ArrayList<Fragment> newMenus = null;
if (mFragments.mActive != null) {
for (int i = 0; i < mFragments.mAdded.size(); i++) {
Fragment f = mFragments.mAdded.get(i);
if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnCreateOptionsMenuListener) {
show = true;
((OnCreateOptionsMenuListener)f).onCreateOptionsMenu(menu, inflater);
if (newMenus == null) {
newMenus = new ArrayList<Fragment>();
}
newMenus.add(f);
}
}
}
if (mCreatedMenus != null) {
for (int i = 0; i < mCreatedMenus.size(); i++) {
Fragment f = mCreatedMenus.get(i);
if (newMenus == null || !newMenus.contains(f)) {
f.onDestroyOptionsMenu();
}
}
}
mCreatedMenus = newMenus;
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] fragments create result: " + show);
result |= show;
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result);
return result;
}
return false;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + " menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean result = onPrepareOptionsMenu(menu);
if (DEBUG) Log.d(TAG, "[onPreparePanel] activity prepare result: " + result);
boolean show = false;
if (mFragments.mActive != null) {
for (int i = 0; i < mFragments.mAdded.size(); i++) {
Fragment f = mFragments.mAdded.get(i);
if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnPrepareOptionsMenuListener) {
show = true;
((OnPrepareOptionsMenuListener)f).onPrepareOptionsMenu(menu);
}
}
}
if (DEBUG) Log.d(TAG, "[onPreparePanel] fragments prepare result: " + show);
result |= show;
result &= menu.hasVisibleItems();
if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result);
return result;
}
return false;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
if (onOptionsItemSelected(item)) {
return true;
}
if (mFragments.mActive != null) {
for (int i = 0; i < mFragments.mAdded.size(); i++) {
Fragment f = mFragments.mAdded.get(i);
if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnOptionsItemSelectedListener) {
if (((OnOptionsItemSelectedListener)f).onOptionsItemSelected(item)) {
return true;
}
}
}
}
}
return false;
}
public abstract boolean onCreateOptionsMenu(Menu menu);
public abstract boolean onPrepareOptionsMenu(Menu menu);
public abstract boolean onOptionsItemSelected(MenuItem item);
public abstract MenuInflater getSupportMenuInflater();
}
| 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.actionbarsherlock.app;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.SpinnerAdapter;
/**
* A window feature at the top of the activity that may display the activity title, navigation
* modes, and other interactive items.
* <p>Beginning with Android 3.0 (API level 11), the action bar appears at the top of an
* activity's window when the activity uses the system's {@link
* android.R.style#Theme_Holo Holo} theme (or one of its descendant themes), which is the default.
* You may otherwise add the action bar by calling {@link
* android.view.Window#requestFeature requestFeature(FEATURE_ACTION_BAR)} or by declaring it in a
* custom theme with the {@link android.R.styleable#Theme_windowActionBar windowActionBar} property.
* <p>By default, the action bar shows the application icon on
* the left, followed by the activity title. If your activity has an options menu, you can make
* select items accessible directly from the action bar as "action items". You can also
* modify various characteristics of the action bar or remove it completely.</p>
* <p>From your activity, you can retrieve an instance of {@link ActionBar} by calling {@link
* android.app.Activity#getActionBar getActionBar()}.</p>
* <p>In some cases, the action bar may be overlayed by another bar that enables contextual actions,
* using an {@link android.view.ActionMode}. For example, when the user selects one or more items in
* your activity, you can enable an action mode that offers actions specific to the selected
* items, with a UI that temporarily replaces the action bar. Although the UI may occupy the
* same space, the {@link android.view.ActionMode} APIs are distinct and independent from those for
* {@link ActionBar}.
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about how to use the action bar, including how to add action items, navigation
* modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action
* Bar</a> developer guide.</p>
* </div>
*/
public abstract class ActionBar {
/**
* Standard navigation mode. Consists of either a logo or icon
* and title text with an optional subtitle. Clicking any of these elements
* will dispatch onOptionsItemSelected to the host Activity with
* a MenuItem with item ID android.R.id.home.
*/
public static final int NAVIGATION_MODE_STANDARD = android.app.ActionBar.NAVIGATION_MODE_STANDARD;
/**
* List navigation mode. Instead of static title text this mode
* presents a list menu for navigation within the activity.
* e.g. this might be presented to the user as a dropdown list.
*/
public static final int NAVIGATION_MODE_LIST = android.app.ActionBar.NAVIGATION_MODE_LIST;
/**
* Tab navigation mode. Instead of static title text this mode
* presents a series of tabs for navigation within the activity.
*/
public static final int NAVIGATION_MODE_TABS = android.app.ActionBar.NAVIGATION_MODE_TABS;
/**
* Use logo instead of icon if available. This flag will cause appropriate
* navigation modes to use a wider logo in place of the standard icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_USE_LOGO = android.app.ActionBar.DISPLAY_USE_LOGO;
/**
* Show 'home' elements in this action bar, leaving more space for other
* navigation elements. This includes logo and icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_HOME = android.app.ActionBar.DISPLAY_SHOW_HOME;
/**
* Display the 'home' element such that it appears as an 'up' affordance.
* e.g. show an arrow to the left indicating the action that will be taken.
*
* Set this flag if selecting the 'home' button in the action bar to return
* up by a single level in your UI rather than back to the top level or front page.
*
* <p>Setting this option will implicitly enable interaction with the home/up
* button. See {@link #setHomeButtonEnabled(boolean)}.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_HOME_AS_UP = android.app.ActionBar.DISPLAY_HOME_AS_UP;
/**
* Show the activity title and subtitle, if present.
*
* @see #setTitle(CharSequence)
* @see #setTitle(int)
* @see #setSubtitle(CharSequence)
* @see #setSubtitle(int)
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_TITLE = android.app.ActionBar.DISPLAY_SHOW_TITLE;
/**
* Show the custom view if one has been set.
* @see #setCustomView(View)
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_CUSTOM = android.app.ActionBar.DISPLAY_SHOW_CUSTOM;
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.
*
* @param view Custom navigation view to place in the ActionBar.
*/
public abstract void setCustomView(View view);
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* <p>Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.</p>
*
* <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for
* the custom view to be displayed.</p>
*
* @param view Custom navigation view to place in the ActionBar.
* @param layoutParams How this custom view should layout in the bar.
*
* @see #setDisplayOptions(int, int)
*/
public abstract void setCustomView(View view, LayoutParams layoutParams);
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* <p>Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.</p>
*
* <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for
* the custom view to be displayed.</p>
*
* @param resId Resource ID of a layout to inflate into the ActionBar.
*
* @see #setDisplayOptions(int, int)
*/
public abstract void setCustomView(int resId);
/**
* Set the icon to display in the 'home' section of the action bar.
* The action bar will use an icon specified by its style or the
* activity icon by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param resId Resource ID of a drawable to show as an icon.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setIcon(int resId);
/**
* Set the icon to display in the 'home' section of the action bar.
* The action bar will use an icon specified by its style or the
* activity icon by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param icon Drawable to show as an icon.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setIcon(Drawable icon);
/**
* Set the logo to display in the 'home' section of the action bar.
* The action bar will use a logo specified by its style or the
* activity logo by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param resId Resource ID of a drawable to show as a logo.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setLogo(int resId);
/**
* Set the logo to display in the 'home' section of the action bar.
* The action bar will use a logo specified by its style or the
* activity logo by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param logo Drawable to show as a logo.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setLogo(Drawable logo);
/**
* Set the adapter and navigation callback for list navigation mode.
*
* The supplied adapter will provide views for the expanded list as well as
* the currently selected item. (These may be displayed differently.)
*
* The supplied OnNavigationListener will alert the application when the user
* changes the current list selection.
*
* @param adapter An adapter that will provide views both to display
* the current navigation selection and populate views
* within the dropdown navigation menu.
* @param callback An OnNavigationListener that will receive events when the user
* selects a navigation item.
*/
public abstract void setListNavigationCallbacks(SpinnerAdapter adapter,
OnNavigationListener callback);
/**
* Set the selected navigation item in list or tabbed navigation modes.
*
* @param position Position of the item to select.
*/
public abstract void setSelectedNavigationItem(int position);
/**
* Get the position of the selected navigation item in list or tabbed navigation modes.
*
* @return Position of the selected item.
*/
public abstract int getSelectedNavigationIndex();
/**
* Get the number of navigation items present in the current navigation mode.
*
* @return Number of navigation items.
*/
public abstract int getNavigationItemCount();
/**
* Set the action bar's title. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param title Title to set
*
* @see #setTitle(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the action bar's title. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param resId Resource ID of title string to set
*
* @see #setTitle(CharSequence)
* @see #setDisplayOptions(int, int)
*/
public abstract void setTitle(int resId);
/**
* Set the action bar's subtitle. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set. Set to null to disable the
* subtitle entirely.
*
* @param subtitle Subtitle to set
*
* @see #setSubtitle(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setSubtitle(CharSequence subtitle);
/**
* Set the action bar's subtitle. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param resId Resource ID of subtitle string to set
*
* @see #setSubtitle(CharSequence)
* @see #setDisplayOptions(int, int)
*/
public abstract void setSubtitle(int resId);
/**
* Set display options. This changes all display option bits at once. To change
* a limited subset of display options, see {@link #setDisplayOptions(int, int)}.
*
* @param options A combination of the bits defined by the DISPLAY_ constants
* defined in ActionBar.
*/
public abstract void setDisplayOptions(int options);
/**
* Set selected display options. Only the options specified by mask will be changed.
* To change all display option bits at once, see {@link #setDisplayOptions(int)}.
*
* <p>Example: setDisplayOptions(0, DISPLAY_SHOW_HOME) will disable the
* {@link #DISPLAY_SHOW_HOME} option.
* setDisplayOptions(DISPLAY_SHOW_HOME, DISPLAY_SHOW_HOME | DISPLAY_USE_LOGO)
* will enable {@link #DISPLAY_SHOW_HOME} and disable {@link #DISPLAY_USE_LOGO}.
*
* @param options A combination of the bits defined by the DISPLAY_ constants
* defined in ActionBar.
* @param mask A bit mask declaring which display options should be changed.
*/
public abstract void setDisplayOptions(int options, int mask);
/**
* Set whether to display the activity logo rather than the activity icon.
* A logo is often a wider, more detailed image.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param useLogo true to use the activity logo, false to use the activity icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayUseLogoEnabled(boolean useLogo);
/**
* Set whether to include the application home affordance in the action bar.
* Home is presented as either an activity icon or logo.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showHome true to show home, false otherwise.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowHomeEnabled(boolean showHome);
/**
* Set whether home should be displayed as an "up" affordance.
* Set this to true if selecting "home" returns up by a single level in your UI
* rather than back to the top level or front page.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showHomeAsUp true to show the user that selecting home will return one
* level up rather than to the top level of the app.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayHomeAsUpEnabled(boolean showHomeAsUp);
/**
* Set whether an activity title/subtitle should be displayed.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showTitle true to display a title/subtitle if present.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowTitleEnabled(boolean showTitle);
/**
* Set whether a custom view should be displayed, if set.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showCustom true if the currently set custom view should be displayed, false otherwise.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowCustomEnabled(boolean showCustom);
/**
* Set the ActionBar's background. This will be used for the primary
* action bar.
*
* @param d Background drawable
* @see #setStackedBackgroundDrawable(Drawable)
* @see #setSplitBackgroundDrawable(Drawable)
*/
public abstract void setBackgroundDrawable(Drawable d);
/**
* Set the ActionBar's stacked background. This will appear
* in the second row/stacked bar on some devices and configurations.
*
* @param d Background drawable for the stacked row
*/
public void setStackedBackgroundDrawable(Drawable d) { }
/**
* Set the ActionBar's split background. This will appear in
* the split action bar containing menu-provided action buttons
* on some devices and configurations.
* <p>You can enable split action bar with {@link android.R.attr#uiOptions}
*
* @param d Background drawable for the split bar
*/
public void setSplitBackgroundDrawable(Drawable d) { }
/**
* @return The current custom view.
*/
public abstract View getCustomView();
/**
* Returns the current ActionBar title in standard mode.
* Returns null if {@link #getNavigationMode()} would not return
* {@link #NAVIGATION_MODE_STANDARD}.
*
* @return The current ActionBar title or null.
*/
public abstract CharSequence getTitle();
/**
* Returns the current ActionBar subtitle in standard mode.
* Returns null if {@link #getNavigationMode()} would not return
* {@link #NAVIGATION_MODE_STANDARD}.
*
* @return The current ActionBar subtitle or null.
*/
public abstract CharSequence getSubtitle();
/**
* Returns the current navigation mode. The result will be one of:
* <ul>
* <li>{@link #NAVIGATION_MODE_STANDARD}</li>
* <li>{@link #NAVIGATION_MODE_LIST}</li>
* <li>{@link #NAVIGATION_MODE_TABS}</li>
* </ul>
*
* @return The current navigation mode.
*/
public abstract int getNavigationMode();
/**
* Set the current navigation mode.
*
* @param mode The new mode to set.
* @see #NAVIGATION_MODE_STANDARD
* @see #NAVIGATION_MODE_LIST
* @see #NAVIGATION_MODE_TABS
*/
public abstract void setNavigationMode(int mode);
/**
* @return The current set of display options.
*/
public abstract int getDisplayOptions();
/**
* Create and return a new {@link Tab}.
* This tab will not be included in the action bar until it is added.
*
* <p>Very often tabs will be used to switch between {@link Fragment}
* objects. Here is a typical implementation of such tabs:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.java
* complete}
*
* @return A new Tab
*
* @see #addTab(Tab)
*/
public abstract Tab newTab();
/**
* Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list.
* If this is the first tab to be added it will become the selected tab.
*
* @param tab Tab to add
*/
public abstract void addTab(Tab tab);
/**
* Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list.
*
* @param tab Tab to add
* @param setSelected True if the added tab should become the selected tab.
*/
public abstract void addTab(Tab tab, boolean setSelected);
/**
* Add a tab for use in tabbed navigation mode. The tab will be inserted at
* <code>position</code>. If this is the first tab to be added it will become
* the selected tab.
*
* @param tab The tab to add
* @param position The new position of the tab
*/
public abstract void addTab(Tab tab, int position);
/**
* Add a tab for use in tabbed navigation mode. The tab will be insterted at
* <code>position</code>.
*
* @param tab The tab to add
* @param position The new position of the tab
* @param setSelected True if the added tab should become the selected tab.
*/
public abstract void addTab(Tab tab, int position, boolean setSelected);
/**
* Remove a tab from the action bar. If the removed tab was selected it will be deselected
* and another tab will be selected if present.
*
* @param tab The tab to remove
*/
public abstract void removeTab(Tab tab);
/**
* Remove a tab from the action bar. If the removed tab was selected it will be deselected
* and another tab will be selected if present.
*
* @param position Position of the tab to remove
*/
public abstract void removeTabAt(int position);
/**
* Remove all tabs from the action bar and deselect the current tab.
*/
public abstract void removeAllTabs();
/**
* Select the specified tab. If it is not a child of this action bar it will be added.
*
* <p>Note: If you want to select by index, use {@link #setSelectedNavigationItem(int)}.</p>
*
* @param tab Tab to select
*/
public abstract void selectTab(Tab tab);
/**
* Returns the currently selected tab if in tabbed navigation mode and there is at least
* one tab present.
*
* @return The currently selected tab or null
*/
public abstract Tab getSelectedTab();
/**
* Returns the tab at the specified index.
*
* @param index Index value in the range 0-get
* @return
*/
public abstract Tab getTabAt(int index);
/**
* Returns the number of tabs currently registered with the action bar.
* @return Tab count
*/
public abstract int getTabCount();
/**
* Retrieve the current height of the ActionBar.
*
* @return The ActionBar's height
*/
public abstract int getHeight();
/**
* Show the ActionBar if it is not currently showing.
* If the window hosting the ActionBar does not have the feature
* {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application
* content to fit the new space available.
*/
public abstract void show();
/**
* Hide the ActionBar if it is currently showing.
* If the window hosting the ActionBar does not have the feature
* {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application
* content to fit the new space available.
*/
public abstract void hide();
/**
* @return <code>true</code> if the ActionBar is showing, <code>false</code> otherwise.
*/
public abstract boolean isShowing();
/**
* Add a listener that will respond to menu visibility change events.
*
* @param listener The new listener to add
*/
public abstract void addOnMenuVisibilityListener(OnMenuVisibilityListener listener);
/**
* Remove a menu visibility listener. This listener will no longer receive menu
* visibility change events.
*
* @param listener A listener to remove that was previously added
*/
public abstract void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener);
/**
* Enable or disable the "home" button in the corner of the action bar. (Note that this
* is the application home/up affordance on the action bar, not the systemwide home
* button.)
*
* <p>This defaults to true for packages targeting < API 14. For packages targeting
* API 14 or greater, the application should call this method to enable interaction
* with the home/up affordance.
*
* <p>Setting the {@link #DISPLAY_HOME_AS_UP} display option will automatically enable
* the home button.
*
* @param enabled true to enable the home button, false to disable the home button.
*/
public void setHomeButtonEnabled(boolean enabled) { }
/**
* Returns a {@link Context} with an appropriate theme for creating views that
* will appear in the action bar. If you are inflating or instantiating custom views
* that will appear in an action bar, you should use the Context returned by this method.
* (This includes adapters used for list navigation mode.)
* This will ensure that views contrast properly against the action bar.
*
* @return A themed Context for creating views
*/
public Context getThemedContext() { return null; }
/**
* Listener interface for ActionBar navigation events.
*/
public interface OnNavigationListener {
/**
* This method is called whenever a navigation item in your action bar
* is selected.
*
* @param itemPosition Position of the item clicked.
* @param itemId ID of the item clicked.
* @return True if the event was handled, false otherwise.
*/
public boolean onNavigationItemSelected(int itemPosition, long itemId);
}
/**
* Listener for receiving events when action bar menus are shown or hidden.
*/
public interface OnMenuVisibilityListener {
/**
* Called when an action bar menu is shown or hidden. Applications may want to use
* this to tune auto-hiding behavior for the action bar or pause/resume video playback,
* gameplay, or other activity within the main content area.
*
* @param isVisible True if an action bar menu is now visible, false if no action bar
* menus are visible.
*/
public void onMenuVisibilityChanged(boolean isVisible);
}
/**
* A tab in the action bar.
*
* <p>Tabs manage the hiding and showing of {@link Fragment}s.
*/
public static abstract class Tab {
/**
* An invalid position for a tab.
*
* @see #getPosition()
*/
public static final int INVALID_POSITION = -1;
/**
* Return the current position of this tab in the action bar.
*
* @return Current position, or {@link #INVALID_POSITION} if this tab is not currently in
* the action bar.
*/
public abstract int getPosition();
/**
* Return the icon associated with this tab.
*
* @return The tab's icon
*/
public abstract Drawable getIcon();
/**
* Return the text of this tab.
*
* @return The tab's text
*/
public abstract CharSequence getText();
/**
* Set the icon displayed on this tab.
*
* @param icon The drawable to use as an icon
* @return The current instance for call chaining
*/
public abstract Tab setIcon(Drawable icon);
/**
* Set the icon displayed on this tab.
*
* @param resId Resource ID referring to the drawable to use as an icon
* @return The current instance for call chaining
*/
public abstract Tab setIcon(int resId);
/**
* Set the text displayed on this tab. Text may be truncated if there is not
* room to display the entire string.
*
* @param text The text to display
* @return The current instance for call chaining
*/
public abstract Tab setText(CharSequence text);
/**
* Set the text displayed on this tab. Text may be truncated if there is not
* room to display the entire string.
*
* @param resId A resource ID referring to the text that should be displayed
* @return The current instance for call chaining
*/
public abstract Tab setText(int resId);
/**
* Set a custom view to be used for this tab. This overrides values set by
* {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}.
*
* @param view Custom view to be used as a tab.
* @return The current instance for call chaining
*/
public abstract Tab setCustomView(View view);
/**
* Set a custom view to be used for this tab. This overrides values set by
* {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}.
*
* @param layoutResId A layout resource to inflate and use as a custom tab view
* @return The current instance for call chaining
*/
public abstract Tab setCustomView(int layoutResId);
/**
* Retrieve a previously set custom view for this tab.
*
* @return The custom view set by {@link #setCustomView(View)}.
*/
public abstract View getCustomView();
/**
* Give this Tab an arbitrary object to hold for later use.
*
* @param obj Object to store
* @return The current instance for call chaining
*/
public abstract Tab setTag(Object obj);
/**
* @return This Tab's tag object.
*/
public abstract Object getTag();
/**
* Set the {@link TabListener} that will handle switching to and from this tab.
* All tabs must have a TabListener set before being added to the ActionBar.
*
* @param listener Listener to handle tab selection events
* @return The current instance for call chaining
*/
public abstract Tab setTabListener(TabListener listener);
/**
* Select this tab. Only valid if the tab has been added to the action bar.
*/
public abstract void select();
/**
* Set a description of this tab's content for use in accessibility support.
* If no content description is provided the title will be used.
*
* @param resId A resource ID referring to the description text
* @return The current instance for call chaining
* @see #setContentDescription(CharSequence)
* @see #getContentDescription()
*/
public abstract Tab setContentDescription(int resId);
/**
* Set a description of this tab's content for use in accessibility support.
* If no content description is provided the title will be used.
*
* @param contentDesc Description of this tab's content
* @return The current instance for call chaining
* @see #setContentDescription(int)
* @see #getContentDescription()
*/
public abstract Tab setContentDescription(CharSequence contentDesc);
/**
* Gets a brief description of this tab's content for use in accessibility support.
*
* @return Description of this tab's content
* @see #setContentDescription(CharSequence)
* @see #setContentDescription(int)
*/
public abstract CharSequence getContentDescription();
}
/**
* Callback interface invoked when a tab is focused, unfocused, added, or removed.
*/
public interface TabListener {
/**
* Called when a tab enters the selected state.
*
* @param tab The tab that was selected
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* during a tab switch. The previous tab's unselect and this tab's select will be
* executed in a single transaction. This FragmentTransaction does not support
* being added to the back stack.
*/
public void onTabSelected(Tab tab, FragmentTransaction ft);
/**
* Called when a tab exits the selected state.
*
* @param tab The tab that was unselected
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* during a tab switch. This tab's unselect and the newly selected tab's select
* will be executed in a single transaction. This FragmentTransaction does not
* support being added to the back stack.
*/
public void onTabUnselected(Tab tab, FragmentTransaction ft);
/**
* Called when a tab that is already selected is chosen again by the user.
* Some applications may use this action to return to the top level of a category.
*
* @param tab The tab that was reselected.
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* once this method returns. This FragmentTransaction does not support
* being added to the back stack.
*/
public void onTabReselected(Tab tab, FragmentTransaction ft);
}
/**
* Per-child layout information associated with action bar custom views.
*
* @attr ref android.R.styleable#ActionBar_LayoutParams_layout_gravity
*/
public static class LayoutParams extends MarginLayoutParams {
/**
* Gravity for the view associated with these LayoutParams.
*
* @see android.view.Gravity
*/
@ViewDebug.ExportedProperty(mapping = {
@ViewDebug.IntToString(from = -1, to = "NONE"),
@ViewDebug.IntToString(from = Gravity.NO_GRAVITY, to = "NONE"),
@ViewDebug.IntToString(from = Gravity.TOP, to = "TOP"),
@ViewDebug.IntToString(from = Gravity.BOTTOM, to = "BOTTOM"),
@ViewDebug.IntToString(from = Gravity.LEFT, to = "LEFT"),
@ViewDebug.IntToString(from = Gravity.RIGHT, to = "RIGHT"),
@ViewDebug.IntToString(from = Gravity.CENTER_VERTICAL, to = "CENTER_VERTICAL"),
@ViewDebug.IntToString(from = Gravity.FILL_VERTICAL, to = "FILL_VERTICAL"),
@ViewDebug.IntToString(from = Gravity.CENTER_HORIZONTAL, to = "CENTER_HORIZONTAL"),
@ViewDebug.IntToString(from = Gravity.FILL_HORIZONTAL, to = "FILL_HORIZONTAL"),
@ViewDebug.IntToString(from = Gravity.CENTER, to = "CENTER"),
@ViewDebug.IntToString(from = Gravity.FILL, to = "FILL")
})
public int gravity = -1;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
this.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
}
public LayoutParams(int width, int height, int gravity) {
super(width, height);
this.gravity = gravity;
}
public LayoutParams(int gravity) {
this(WRAP_CONTENT, FILL_PARENT, gravity);
}
public LayoutParams(LayoutParams source) {
super(source);
this.gravity = source.gravity;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.ListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockListActivity extends ListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onDestroy() {
getSherlock().dispatchDestroy();
super.onDestroy();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.Activity;
import android.support.v4.app.Fragment;
import com.actionbarsherlock.internal.view.menu.MenuItemWrapper;
import com.actionbarsherlock.internal.view.menu.MenuWrapper;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener;
public class SherlockFragment extends Fragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener {
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public void onDetach() {
mActivity = null;
super.onDetach();
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
onPrepareOptionsMenu(new MenuWrapper(menu));
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return onOptionsItemSelected(new MenuItemWrapper(item));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockActivity extends Activity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onDestroy() {
getSherlock().dispatchDestroy();
super.onDestroy();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.Activity;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.internal.view.menu.MenuItemWrapper;
import com.actionbarsherlock.internal.view.menu.MenuWrapper;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener;
public class SherlockListFragment extends ListFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener {
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public void onDetach() {
mActivity = null;
super.onDetach();
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
onPrepareOptionsMenu(new MenuWrapper(menu));
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return onOptionsItemSelected(new MenuItemWrapper(item));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| Java |
package com.actionbarsherlock.app;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app._ActionBarSherlockTrojanHorse;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import static com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import static com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
/** @see {@link _ActionBarSherlockTrojanHorse} */
public class SherlockFragmentActivity extends _ActionBarSherlockTrojanHorse implements OnActionModeStartedListener, OnActionModeFinishedListener {
private static final boolean DEBUG = false;
private static final String TAG = "SherlockFragmentActivity";
private ActionBarSherlock mSherlock;
private boolean mIgnoreNativeCreate = false;
private boolean mIgnoreNativePrepare = false;
private boolean mIgnoreNativeSelected = false;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onDestroy() {
getSherlock().dispatchDestroy();
super.onDestroy();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
if (DEBUG) Log.d(TAG, "[getSupportMenuInflater]");
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[invalidateOptionsMenu]");
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[supportInvalidateOptionsMenu]");
invalidateOptionsMenu();
}
@Override
public final boolean onCreatePanelMenu(int featureId, android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeCreate) {
mIgnoreNativeCreate = true;
boolean result = getSherlock().dispatchCreateOptionsMenu(menu);
mIgnoreNativeCreate = false;
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result);
return result;
}
return super.onCreatePanelMenu(featureId, menu);
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return true;
}
@Override
public final boolean onPreparePanel(int featureId, View view, android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativePrepare) {
mIgnoreNativePrepare = true;
boolean result = getSherlock().dispatchPrepareOptionsMenu(menu);
mIgnoreNativePrepare = false;
if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result);
return result;
}
return super.onPreparePanel(featureId, view, menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return true;
}
@Override
public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeSelected) {
mIgnoreNativeSelected = true;
boolean result = getSherlock().dispatchOptionsItemSelected(item);
mIgnoreNativeSelected = false;
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] returning " + result);
return result;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return false;
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.Activity;
import android.support.v4.app.DialogFragment;
import com.actionbarsherlock.internal.view.menu.MenuItemWrapper;
import com.actionbarsherlock.internal.view.menu.MenuWrapper;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener;
import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener;
public class SherlockDialogFragment extends DialogFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener {
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public void onDetach() {
mActivity = null;
super.onDetach();
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
onPrepareOptionsMenu(new MenuWrapper(menu));
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return onOptionsItemSelected(new MenuItemWrapper(item));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| Java |
package com.actionbarsherlock.app;
import android.app.ExpandableListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockExpandableListActivity extends ExpandableListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onDestroy() {
getSherlock().dispatchDestroy();
super.onDestroy();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| Java |
package com.actionbarsherlock.app;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockPreferenceActivity extends PreferenceActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onDestroy() {
getSherlock().dispatchDestroy();
super.onDestroy();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 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.actionbarsherlock.internal.app;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityEvent;
import android.widget.SpinnerAdapter;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.internal.nineoldandroids.animation.Animator;
import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorListenerAdapter;
import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet;
import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator;
import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener;
import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout;
import com.actionbarsherlock.internal.view.menu.MenuBuilder;
import com.actionbarsherlock.internal.view.menu.MenuPopupHelper;
import com.actionbarsherlock.internal.view.menu.SubMenuBuilder;
import com.actionbarsherlock.internal.widget.ActionBarContainer;
import com.actionbarsherlock.internal.widget.ActionBarContextView;
import com.actionbarsherlock.internal.widget.ActionBarView;
import com.actionbarsherlock.internal.widget.ScrollingTabContainerView;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean;
/**
* ActionBarImpl is the ActionBar implementation used
* by devices of all screen sizes. If it detects a compatible decor,
* it will split contextual modes across both the ActionBarView at
* the top of the screen and a horizontal LinearLayout at the bottom
* which is normally hidden.
*/
public class ActionBarImpl extends ActionBar {
//UNUSED private static final String TAG = "ActionBarImpl";
private Context mContext;
private Context mThemedContext;
private Activity mActivity;
//UNUSED private Dialog mDialog;
private ActionBarContainer mContainerView;
private ActionBarView mActionView;
private ActionBarContextView mContextView;
private ActionBarContainer mSplitView;
private NineFrameLayout mContentView;
private ScrollingTabContainerView mTabScrollView;
private ArrayList<TabImpl> mTabs = new ArrayList<TabImpl>();
private TabImpl mSelectedTab;
private int mSavedTabPosition = INVALID_POSITION;
ActionModeImpl mActionMode;
ActionMode mDeferredDestroyActionMode;
ActionMode.Callback mDeferredModeDestroyCallback;
private boolean mLastMenuVisibility;
private ArrayList<OnMenuVisibilityListener> mMenuVisibilityListeners =
new ArrayList<OnMenuVisibilityListener>();
private static final int CONTEXT_DISPLAY_NORMAL = 0;
private static final int CONTEXT_DISPLAY_SPLIT = 1;
private static final int INVALID_POSITION = -1;
private int mContextDisplayMode;
private boolean mHasEmbeddedTabs;
final Handler mHandler = new Handler();
Runnable mTabSelector;
private Animator mCurrentShowAnim;
private Animator mCurrentModeAnim;
private boolean mShowHideAnimationEnabled;
boolean mWasHiddenBeforeMode;
final AnimatorListener mHideListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mContentView != null) {
mContentView.setTranslationY(0);
mContainerView.setTranslationY(0);
}
if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) {
mSplitView.setVisibility(View.GONE);
}
mContainerView.setVisibility(View.GONE);
mContainerView.setTransitioning(false);
mCurrentShowAnim = null;
completeDeferredDestroyActionMode();
}
};
final AnimatorListener mShowListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentShowAnim = null;
mContainerView.requestLayout();
}
};
public ActionBarImpl(Activity activity, int features) {
mActivity = activity;
Window window = activity.getWindow();
View decor = window.getDecorView();
init(decor);
//window.hasFeature() workaround for pre-3.0
if ((features & (1 << Window.FEATURE_ACTION_BAR_OVERLAY)) == 0) {
mContentView = (NineFrameLayout)decor.findViewById(android.R.id.content);
}
}
public ActionBarImpl(Dialog dialog) {
//UNUSED mDialog = dialog;
init(dialog.getWindow().getDecorView());
}
private void init(View decor) {
mContext = decor.getContext();
mActionView = (ActionBarView) decor.findViewById(R.id.abs__action_bar);
mContextView = (ActionBarContextView) decor.findViewById(
R.id.abs__action_context_bar);
mContainerView = (ActionBarContainer) decor.findViewById(
R.id.abs__action_bar_container);
mSplitView = (ActionBarContainer) decor.findViewById(
R.id.abs__split_action_bar);
if (mActionView == null || mContextView == null || mContainerView == null) {
throw new IllegalStateException(getClass().getSimpleName() + " can only be used " +
"with a compatible window decor layout");
}
mActionView.setContextView(mContextView);
mContextDisplayMode = mActionView.isSplitActionBar() ?
CONTEXT_DISPLAY_SPLIT : CONTEXT_DISPLAY_NORMAL;
// Older apps get the home button interaction enabled by default.
// Newer apps need to enable it explicitly.
setHomeButtonEnabled(mContext.getApplicationInfo().targetSdkVersion < 14);
setHasEmbeddedTabs(getResources_getBoolean(mContext,
R.bool.abs__action_bar_embed_tabs));
}
public void onConfigurationChanged(Configuration newConfig) {
setHasEmbeddedTabs(getResources_getBoolean(mContext,
R.bool.abs__action_bar_embed_tabs));
//Manually dispatch a configuration change to the action bar view on pre-2.2
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
mActionView.onConfigurationChanged(newConfig);
if (mContextView != null) {
mContextView.onConfigurationChanged(newConfig);
}
}
}
private void setHasEmbeddedTabs(boolean hasEmbeddedTabs) {
mHasEmbeddedTabs = hasEmbeddedTabs;
// Switch tab layout configuration if needed
if (!mHasEmbeddedTabs) {
mActionView.setEmbeddedTabView(null);
mContainerView.setTabContainer(mTabScrollView);
} else {
mContainerView.setTabContainer(null);
mActionView.setEmbeddedTabView(mTabScrollView);
}
final boolean isInTabMode = getNavigationMode() == NAVIGATION_MODE_TABS;
if (mTabScrollView != null) {
mTabScrollView.setVisibility(isInTabMode ? View.VISIBLE : View.GONE);
}
mActionView.setCollapsable(!mHasEmbeddedTabs && isInTabMode);
}
private void ensureTabsExist() {
if (mTabScrollView != null) {
return;
}
ScrollingTabContainerView tabScroller = new ScrollingTabContainerView(mContext);
if (mHasEmbeddedTabs) {
tabScroller.setVisibility(View.VISIBLE);
mActionView.setEmbeddedTabView(tabScroller);
} else {
tabScroller.setVisibility(getNavigationMode() == NAVIGATION_MODE_TABS ?
View.VISIBLE : View.GONE);
mContainerView.setTabContainer(tabScroller);
}
mTabScrollView = tabScroller;
}
void completeDeferredDestroyActionMode() {
if (mDeferredModeDestroyCallback != null) {
mDeferredModeDestroyCallback.onDestroyActionMode(mDeferredDestroyActionMode);
mDeferredDestroyActionMode = null;
mDeferredModeDestroyCallback = null;
}
}
/**
* Enables or disables animation between show/hide states.
* If animation is disabled using this method, animations in progress
* will be finished.
*
* @param enabled true to animate, false to not animate.
*/
public void setShowHideAnimationEnabled(boolean enabled) {
mShowHideAnimationEnabled = enabled;
if (!enabled && mCurrentShowAnim != null) {
mCurrentShowAnim.end();
}
}
public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
mMenuVisibilityListeners.add(listener);
}
public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
mMenuVisibilityListeners.remove(listener);
}
public void dispatchMenuVisibilityChanged(boolean isVisible) {
if (isVisible == mLastMenuVisibility) {
return;
}
mLastMenuVisibility = isVisible;
final int count = mMenuVisibilityListeners.size();
for (int i = 0; i < count; i++) {
mMenuVisibilityListeners.get(i).onMenuVisibilityChanged(isVisible);
}
}
@Override
public void setCustomView(int resId) {
setCustomView(LayoutInflater.from(getThemedContext()).inflate(resId, mActionView, false));
}
@Override
public void setDisplayUseLogoEnabled(boolean useLogo) {
setDisplayOptions(useLogo ? DISPLAY_USE_LOGO : 0, DISPLAY_USE_LOGO);
}
@Override
public void setDisplayShowHomeEnabled(boolean showHome) {
setDisplayOptions(showHome ? DISPLAY_SHOW_HOME : 0, DISPLAY_SHOW_HOME);
}
@Override
public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) {
setDisplayOptions(showHomeAsUp ? DISPLAY_HOME_AS_UP : 0, DISPLAY_HOME_AS_UP);
}
@Override
public void setDisplayShowTitleEnabled(boolean showTitle) {
setDisplayOptions(showTitle ? DISPLAY_SHOW_TITLE : 0, DISPLAY_SHOW_TITLE);
}
@Override
public void setDisplayShowCustomEnabled(boolean showCustom) {
setDisplayOptions(showCustom ? DISPLAY_SHOW_CUSTOM : 0, DISPLAY_SHOW_CUSTOM);
}
@Override
public void setHomeButtonEnabled(boolean enable) {
mActionView.setHomeButtonEnabled(enable);
}
@Override
public void setTitle(int resId) {
setTitle(mContext.getString(resId));
}
@Override
public void setSubtitle(int resId) {
setSubtitle(mContext.getString(resId));
}
public void setSelectedNavigationItem(int position) {
switch (mActionView.getNavigationMode()) {
case NAVIGATION_MODE_TABS:
selectTab(mTabs.get(position));
break;
case NAVIGATION_MODE_LIST:
mActionView.setDropdownSelectedPosition(position);
break;
default:
throw new IllegalStateException(
"setSelectedNavigationIndex not valid for current navigation mode");
}
}
public void removeAllTabs() {
cleanupTabs();
}
private void cleanupTabs() {
if (mSelectedTab != null) {
selectTab(null);
}
mTabs.clear();
if (mTabScrollView != null) {
mTabScrollView.removeAllTabs();
}
mSavedTabPosition = INVALID_POSITION;
}
public void setTitle(CharSequence title) {
mActionView.setTitle(title);
}
public void setSubtitle(CharSequence subtitle) {
mActionView.setSubtitle(subtitle);
}
public void setDisplayOptions(int options) {
mActionView.setDisplayOptions(options);
}
public void setDisplayOptions(int options, int mask) {
final int current = mActionView.getDisplayOptions();
mActionView.setDisplayOptions((options & mask) | (current & ~mask));
}
public void setBackgroundDrawable(Drawable d) {
mContainerView.setPrimaryBackground(d);
}
public void setStackedBackgroundDrawable(Drawable d) {
mContainerView.setStackedBackground(d);
}
public void setSplitBackgroundDrawable(Drawable d) {
if (mSplitView != null) {
mSplitView.setSplitBackground(d);
}
}
public View getCustomView() {
return mActionView.getCustomNavigationView();
}
public CharSequence getTitle() {
return mActionView.getTitle();
}
public CharSequence getSubtitle() {
return mActionView.getSubtitle();
}
public int getNavigationMode() {
return mActionView.getNavigationMode();
}
public int getDisplayOptions() {
return mActionView.getDisplayOptions();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
boolean wasHidden = false;
if (mActionMode != null) {
wasHidden = mWasHiddenBeforeMode;
mActionMode.finish();
}
mContextView.killMode();
ActionModeImpl mode = new ActionModeImpl(callback);
if (mode.dispatchOnCreate()) {
mWasHiddenBeforeMode = !isShowing() || wasHidden;
mode.invalidate();
mContextView.initForMode(mode);
animateToMode(true);
if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) {
// TODO animate this
mSplitView.setVisibility(View.VISIBLE);
}
mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mActionMode = mode;
return mode;
}
return null;
}
private void configureTab(Tab tab, int position) {
final TabImpl tabi = (TabImpl) tab;
final ActionBar.TabListener callback = tabi.getCallback();
if (callback == null) {
throw new IllegalStateException("Action Bar Tab must have a Callback");
}
tabi.setPosition(position);
mTabs.add(position, tabi);
final int count = mTabs.size();
for (int i = position + 1; i < count; i++) {
mTabs.get(i).setPosition(i);
}
}
@Override
public void addTab(Tab tab) {
addTab(tab, mTabs.isEmpty());
}
@Override
public void addTab(Tab tab, int position) {
addTab(tab, position, mTabs.isEmpty());
}
@Override
public void addTab(Tab tab, boolean setSelected) {
ensureTabsExist();
mTabScrollView.addTab(tab, setSelected);
configureTab(tab, mTabs.size());
if (setSelected) {
selectTab(tab);
}
}
@Override
public void addTab(Tab tab, int position, boolean setSelected) {
ensureTabsExist();
mTabScrollView.addTab(tab, position, setSelected);
configureTab(tab, position);
if (setSelected) {
selectTab(tab);
}
}
@Override
public Tab newTab() {
return new TabImpl();
}
@Override
public void removeTab(Tab tab) {
removeTabAt(tab.getPosition());
}
@Override
public void removeTabAt(int position) {
if (mTabScrollView == null) {
// No tabs around to remove
return;
}
int selectedTabPosition = mSelectedTab != null
? mSelectedTab.getPosition() : mSavedTabPosition;
mTabScrollView.removeTabAt(position);
TabImpl removedTab = mTabs.remove(position);
if (removedTab != null) {
removedTab.setPosition(-1);
}
final int newTabCount = mTabs.size();
for (int i = position; i < newTabCount; i++) {
mTabs.get(i).setPosition(i);
}
if (selectedTabPosition == position) {
selectTab(mTabs.isEmpty() ? null : mTabs.get(Math.max(0, position - 1)));
}
}
@Override
public void selectTab(Tab tab) {
if (getNavigationMode() != NAVIGATION_MODE_TABS) {
mSavedTabPosition = tab != null ? tab.getPosition() : INVALID_POSITION;
return;
}
FragmentTransaction trans = null;
if (mActivity instanceof SherlockFragmentActivity) {
trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction()
.disallowAddToBackStack();
}
if (mSelectedTab == tab) {
if (mSelectedTab != null) {
mSelectedTab.getCallback().onTabReselected(mSelectedTab, trans);
mTabScrollView.animateToTab(tab.getPosition());
}
} else {
mTabScrollView.setTabSelected(tab != null ? tab.getPosition() : Tab.INVALID_POSITION);
if (mSelectedTab != null) {
mSelectedTab.getCallback().onTabUnselected(mSelectedTab, trans);
}
mSelectedTab = (TabImpl) tab;
if (mSelectedTab != null) {
mSelectedTab.getCallback().onTabSelected(mSelectedTab, trans);
}
}
if (trans != null && !trans.isEmpty()) {
trans.commit();
}
}
@Override
public Tab getSelectedTab() {
return mSelectedTab;
}
@Override
public int getHeight() {
return mContainerView.getHeight();
}
@Override
public void show() {
show(true);
}
void show(boolean markHiddenBeforeMode) {
if (mCurrentShowAnim != null) {
mCurrentShowAnim.end();
}
if (mContainerView.getVisibility() == View.VISIBLE) {
if (markHiddenBeforeMode) mWasHiddenBeforeMode = false;
return;
}
mContainerView.setVisibility(View.VISIBLE);
if (mShowHideAnimationEnabled) {
mContainerView.setAlpha(0);
AnimatorSet anim = new AnimatorSet();
AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 1));
if (mContentView != null) {
b.with(ObjectAnimator.ofFloat(mContentView, "translationY",
-mContainerView.getHeight(), 0));
mContainerView.setTranslationY(-mContainerView.getHeight());
b.with(ObjectAnimator.ofFloat(mContainerView, "translationY", 0));
}
if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) {
mSplitView.setAlpha(0);
mSplitView.setVisibility(View.VISIBLE);
b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 1));
}
anim.addListener(mShowListener);
mCurrentShowAnim = anim;
anim.start();
} else {
mContainerView.setAlpha(1);
mContainerView.setTranslationY(0);
mShowListener.onAnimationEnd(null);
}
}
@Override
public void hide() {
if (mCurrentShowAnim != null) {
mCurrentShowAnim.end();
}
if (mContainerView.getVisibility() == View.GONE) {
return;
}
if (mShowHideAnimationEnabled) {
mContainerView.setAlpha(1);
mContainerView.setTransitioning(true);
AnimatorSet anim = new AnimatorSet();
AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 0));
if (mContentView != null) {
b.with(ObjectAnimator.ofFloat(mContentView, "translationY",
0, -mContainerView.getHeight()));
b.with(ObjectAnimator.ofFloat(mContainerView, "translationY",
-mContainerView.getHeight()));
}
if (mSplitView != null && mSplitView.getVisibility() == View.VISIBLE) {
mSplitView.setAlpha(1);
b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 0));
}
anim.addListener(mHideListener);
mCurrentShowAnim = anim;
anim.start();
} else {
mHideListener.onAnimationEnd(null);
}
}
public boolean isShowing() {
return mContainerView.getVisibility() == View.VISIBLE;
}
void animateToMode(boolean toActionMode) {
if (toActionMode) {
show(false);
}
if (mCurrentModeAnim != null) {
mCurrentModeAnim.end();
}
mActionView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE);
mContextView.animateToVisibility(toActionMode ? View.VISIBLE : View.GONE);
if (mTabScrollView != null && !mActionView.hasEmbeddedTabs() && mActionView.isCollapsed()) {
mTabScrollView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE);
}
}
public Context getThemedContext() {
if (mThemedContext == null) {
TypedValue outValue = new TypedValue();
Resources.Theme currentTheme = mContext.getTheme();
currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme,
outValue, true);
final int targetThemeRes = outValue.resourceId;
if (targetThemeRes != 0) { //XXX && mContext.getThemeResId() != targetThemeRes) {
mThemedContext = new ContextThemeWrapper(mContext, targetThemeRes);
} else {
mThemedContext = mContext;
}
}
return mThemedContext;
}
/**
* @hide
*/
public class ActionModeImpl extends ActionMode implements MenuBuilder.Callback {
private ActionMode.Callback mCallback;
private MenuBuilder mMenu;
private WeakReference<View> mCustomView;
public ActionModeImpl(ActionMode.Callback callback) {
mCallback = callback;
mMenu = new MenuBuilder(getThemedContext())
.setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
mMenu.setCallback(this);
}
@Override
public MenuInflater getMenuInflater() {
return new MenuInflater(getThemedContext());
}
@Override
public Menu getMenu() {
return mMenu;
}
@Override
public void finish() {
if (mActionMode != this) {
// Not the active action mode - no-op
return;
}
// If we were hidden before the mode was shown, defer the onDestroy
// callback until the animation is finished and associated relayout
// is about to happen. This lets apps better anticipate visibility
// and layout behavior.
if (mWasHiddenBeforeMode) {
mDeferredDestroyActionMode = this;
mDeferredModeDestroyCallback = mCallback;
} else {
mCallback.onDestroyActionMode(this);
}
mCallback = null;
animateToMode(false);
// Clear out the context mode views after the animation finishes
mContextView.closeMode();
mActionView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mActionMode = null;
if (mWasHiddenBeforeMode) {
hide();
}
}
@Override
public void invalidate() {
mMenu.stopDispatchingItemsChanged();
try {
mCallback.onPrepareActionMode(this, mMenu);
} finally {
mMenu.startDispatchingItemsChanged();
}
}
public boolean dispatchOnCreate() {
mMenu.stopDispatchingItemsChanged();
try {
return mCallback.onCreateActionMode(this, mMenu);
} finally {
mMenu.startDispatchingItemsChanged();
}
}
@Override
public void setCustomView(View view) {
mContextView.setCustomView(view);
mCustomView = new WeakReference<View>(view);
}
@Override
public void setSubtitle(CharSequence subtitle) {
mContextView.setSubtitle(subtitle);
}
@Override
public void setTitle(CharSequence title) {
mContextView.setTitle(title);
}
@Override
public void setTitle(int resId) {
setTitle(mContext.getResources().getString(resId));
}
@Override
public void setSubtitle(int resId) {
setSubtitle(mContext.getResources().getString(resId));
}
@Override
public CharSequence getTitle() {
return mContextView.getTitle();
}
@Override
public CharSequence getSubtitle() {
return mContextView.getSubtitle();
}
@Override
public View getCustomView() {
return mCustomView != null ? mCustomView.get() : null;
}
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
if (mCallback != null) {
return mCallback.onActionItemClicked(this, item);
} else {
return false;
}
}
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
}
public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
if (mCallback == null) {
return false;
}
if (!subMenu.hasVisibleItems()) {
return true;
}
new MenuPopupHelper(getThemedContext(), subMenu).show();
return true;
}
public void onCloseSubMenu(SubMenuBuilder menu) {
}
public void onMenuModeChange(MenuBuilder menu) {
if (mCallback == null) {
return;
}
invalidate();
mContextView.showOverflowMenu();
}
}
/**
* @hide
*/
public class TabImpl extends ActionBar.Tab {
private ActionBar.TabListener mCallback;
private Object mTag;
private Drawable mIcon;
private CharSequence mText;
private CharSequence mContentDesc;
private int mPosition = -1;
private View mCustomView;
@Override
public Object getTag() {
return mTag;
}
@Override
public Tab setTag(Object tag) {
mTag = tag;
return this;
}
public ActionBar.TabListener getCallback() {
return mCallback;
}
@Override
public Tab setTabListener(ActionBar.TabListener callback) {
mCallback = callback;
return this;
}
@Override
public View getCustomView() {
return mCustomView;
}
@Override
public Tab setCustomView(View view) {
mCustomView = view;
if (mPosition >= 0) {
mTabScrollView.updateTab(mPosition);
}
return this;
}
@Override
public Tab setCustomView(int layoutResId) {
return setCustomView(LayoutInflater.from(getThemedContext())
.inflate(layoutResId, null));
}
@Override
public Drawable getIcon() {
return mIcon;
}
@Override
public int getPosition() {
return mPosition;
}
public void setPosition(int position) {
mPosition = position;
}
@Override
public CharSequence getText() {
return mText;
}
@Override
public Tab setIcon(Drawable icon) {
mIcon = icon;
if (mPosition >= 0) {
mTabScrollView.updateTab(mPosition);
}
return this;
}
@Override
public Tab setIcon(int resId) {
return setIcon(mContext.getResources().getDrawable(resId));
}
@Override
public Tab setText(CharSequence text) {
mText = text;
if (mPosition >= 0) {
mTabScrollView.updateTab(mPosition);
}
return this;
}
@Override
public Tab setText(int resId) {
return setText(mContext.getResources().getText(resId));
}
@Override
public void select() {
selectTab(this);
}
@Override
public Tab setContentDescription(int resId) {
return setContentDescription(mContext.getResources().getText(resId));
}
@Override
public Tab setContentDescription(CharSequence contentDesc) {
mContentDesc = contentDesc;
if (mPosition >= 0) {
mTabScrollView.updateTab(mPosition);
}
return this;
}
@Override
public CharSequence getContentDescription() {
return mContentDesc;
}
}
@Override
public void setCustomView(View view) {
mActionView.setCustomNavigationView(view);
}
@Override
public void setCustomView(View view, LayoutParams layoutParams) {
view.setLayoutParams(layoutParams);
mActionView.setCustomNavigationView(view);
}
@Override
public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) {
mActionView.setDropdownAdapter(adapter);
mActionView.setCallback(callback);
}
@Override
public int getSelectedNavigationIndex() {
switch (mActionView.getNavigationMode()) {
case NAVIGATION_MODE_TABS:
return mSelectedTab != null ? mSelectedTab.getPosition() : -1;
case NAVIGATION_MODE_LIST:
return mActionView.getDropdownSelectedPosition();
default:
return -1;
}
}
@Override
public int getNavigationItemCount() {
switch (mActionView.getNavigationMode()) {
case NAVIGATION_MODE_TABS:
return mTabs.size();
case NAVIGATION_MODE_LIST:
SpinnerAdapter adapter = mActionView.getDropdownAdapter();
return adapter != null ? adapter.getCount() : 0;
default:
return 0;
}
}
@Override
public int getTabCount() {
return mTabs.size();
}
@Override
public void setNavigationMode(int mode) {
final int oldMode = mActionView.getNavigationMode();
switch (oldMode) {
case NAVIGATION_MODE_TABS:
mSavedTabPosition = getSelectedNavigationIndex();
selectTab(null);
mTabScrollView.setVisibility(View.GONE);
break;
}
mActionView.setNavigationMode(mode);
switch (mode) {
case NAVIGATION_MODE_TABS:
ensureTabsExist();
mTabScrollView.setVisibility(View.VISIBLE);
if (mSavedTabPosition != INVALID_POSITION) {
setSelectedNavigationItem(mSavedTabPosition);
mSavedTabPosition = INVALID_POSITION;
}
break;
}
mActionView.setCollapsable(mode == NAVIGATION_MODE_TABS && !mHasEmbeddedTabs);
}
@Override
public Tab getTabAt(int index) {
return mTabs.get(index);
}
@Override
public void setIcon(int resId) {
mActionView.setIcon(resId);
}
@Override
public void setIcon(Drawable icon) {
mActionView.setIcon(icon);
}
@Override
public void setLogo(int resId) {
mActionView.setLogo(resId);
}
@Override
public void setLogo(Drawable logo) {
mActionView.setLogo(logo);
}
}
| Java |
package com.actionbarsherlock.internal.app;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.SpinnerAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ActionBarWrapper extends ActionBar implements android.app.ActionBar.OnNavigationListener, android.app.ActionBar.OnMenuVisibilityListener {
private final Activity mActivity;
private final android.app.ActionBar mActionBar;
private ActionBar.OnNavigationListener mNavigationListener;
private Set<OnMenuVisibilityListener> mMenuVisibilityListeners = new HashSet<OnMenuVisibilityListener>(1);
private FragmentTransaction mFragmentTransaction;
public ActionBarWrapper(Activity activity) {
mActivity = activity;
mActionBar = activity.getActionBar();
if (mActionBar != null) {
mActionBar.addOnMenuVisibilityListener(this);
}
}
@Override
public void setHomeButtonEnabled(boolean enabled) {
mActionBar.setHomeButtonEnabled(enabled);
}
@Override
public Context getThemedContext() {
return mActionBar.getThemedContext();
}
@Override
public void setCustomView(View view) {
mActionBar.setCustomView(view);
}
@Override
public void setCustomView(View view, LayoutParams layoutParams) {
android.app.ActionBar.LayoutParams lp = new android.app.ActionBar.LayoutParams(layoutParams);
lp.gravity = layoutParams.gravity;
lp.bottomMargin = layoutParams.bottomMargin;
lp.topMargin = layoutParams.topMargin;
lp.leftMargin = layoutParams.leftMargin;
lp.rightMargin = layoutParams.rightMargin;
mActionBar.setCustomView(view, lp);
}
@Override
public void setCustomView(int resId) {
mActionBar.setCustomView(resId);
}
@Override
public void setIcon(int resId) {
mActionBar.setIcon(resId);
}
@Override
public void setIcon(Drawable icon) {
mActionBar.setIcon(icon);
}
@Override
public void setLogo(int resId) {
mActionBar.setLogo(resId);
}
@Override
public void setLogo(Drawable logo) {
mActionBar.setLogo(logo);
}
@Override
public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) {
mNavigationListener = callback;
mActionBar.setListNavigationCallbacks(adapter, (callback != null) ? this : null);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//This should never be a NullPointerException since we only set
//ourselves as the listener when the callback is not null.
return mNavigationListener.onNavigationItemSelected(itemPosition, itemId);
}
@Override
public void setSelectedNavigationItem(int position) {
mActionBar.setSelectedNavigationItem(position);
}
@Override
public int getSelectedNavigationIndex() {
return mActionBar.getSelectedNavigationIndex();
}
@Override
public int getNavigationItemCount() {
return mActionBar.getNavigationItemCount();
}
@Override
public void setTitle(CharSequence title) {
mActionBar.setTitle(title);
}
@Override
public void setTitle(int resId) {
mActionBar.setTitle(resId);
}
@Override
public void setSubtitle(CharSequence subtitle) {
mActionBar.setSubtitle(subtitle);
}
@Override
public void setSubtitle(int resId) {
mActionBar.setSubtitle(resId);
}
@Override
public void setDisplayOptions(int options) {
mActionBar.setDisplayOptions(options);
}
@Override
public void setDisplayOptions(int options, int mask) {
mActionBar.setDisplayOptions(options, mask);
}
@Override
public void setDisplayUseLogoEnabled(boolean useLogo) {
mActionBar.setDisplayUseLogoEnabled(useLogo);
}
@Override
public void setDisplayShowHomeEnabled(boolean showHome) {
mActionBar.setDisplayShowHomeEnabled(showHome);
}
@Override
public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) {
mActionBar.setDisplayHomeAsUpEnabled(showHomeAsUp);
}
@Override
public void setDisplayShowTitleEnabled(boolean showTitle) {
mActionBar.setDisplayShowTitleEnabled(showTitle);
}
@Override
public void setDisplayShowCustomEnabled(boolean showCustom) {
mActionBar.setDisplayShowCustomEnabled(showCustom);
}
@Override
public void setBackgroundDrawable(Drawable d) {
mActionBar.setBackgroundDrawable(d);
}
@Override
public void setStackedBackgroundDrawable(Drawable d) {
mActionBar.setStackedBackgroundDrawable(d);
}
@Override
public void setSplitBackgroundDrawable(Drawable d) {
mActionBar.setSplitBackgroundDrawable(d);
}
@Override
public View getCustomView() {
return mActionBar.getCustomView();
}
@Override
public CharSequence getTitle() {
return mActionBar.getTitle();
}
@Override
public CharSequence getSubtitle() {
return mActionBar.getSubtitle();
}
@Override
public int getNavigationMode() {
return mActionBar.getNavigationMode();
}
@Override
public void setNavigationMode(int mode) {
mActionBar.setNavigationMode(mode);
}
@Override
public int getDisplayOptions() {
return mActionBar.getDisplayOptions();
}
public class TabWrapper extends ActionBar.Tab implements android.app.ActionBar.TabListener {
final android.app.ActionBar.Tab mNativeTab;
private Object mTag;
private TabListener mListener;
public TabWrapper(android.app.ActionBar.Tab nativeTab) {
mNativeTab = nativeTab;
mNativeTab.setTag(this);
}
@Override
public int getPosition() {
return mNativeTab.getPosition();
}
@Override
public Drawable getIcon() {
return mNativeTab.getIcon();
}
@Override
public CharSequence getText() {
return mNativeTab.getText();
}
@Override
public Tab setIcon(Drawable icon) {
mNativeTab.setIcon(icon);
return this;
}
@Override
public Tab setIcon(int resId) {
mNativeTab.setIcon(resId);
return this;
}
@Override
public Tab setText(CharSequence text) {
mNativeTab.setText(text);
return this;
}
@Override
public Tab setText(int resId) {
mNativeTab.setText(resId);
return this;
}
@Override
public Tab setCustomView(View view) {
mNativeTab.setCustomView(view);
return this;
}
@Override
public Tab setCustomView(int layoutResId) {
mNativeTab.setCustomView(layoutResId);
return this;
}
@Override
public View getCustomView() {
return mNativeTab.getCustomView();
}
@Override
public Tab setTag(Object obj) {
mTag = obj;
return this;
}
@Override
public Object getTag() {
return mTag;
}
@Override
public Tab setTabListener(TabListener listener) {
mNativeTab.setTabListener(listener != null ? this : null);
mListener = listener;
return this;
}
@Override
public void select() {
mNativeTab.select();
}
@Override
public Tab setContentDescription(int resId) {
mNativeTab.setContentDescription(resId);
return this;
}
@Override
public Tab setContentDescription(CharSequence contentDesc) {
mNativeTab.setContentDescription(contentDesc);
return this;
}
@Override
public CharSequence getContentDescription() {
return mNativeTab.getContentDescription();
}
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if (mListener != null) {
FragmentTransaction trans = null;
if (mActivity instanceof SherlockFragmentActivity) {
trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction()
.disallowAddToBackStack();
}
mListener.onTabReselected(this, trans);
if (trans != null && !trans.isEmpty()) {
trans.commit();
}
}
}
@Override
public void onTabSelected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if (mListener != null) {
if (mFragmentTransaction == null && mActivity instanceof SherlockFragmentActivity) {
mFragmentTransaction = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction()
.disallowAddToBackStack();
}
mListener.onTabSelected(this, mFragmentTransaction);
if (mFragmentTransaction != null) {
if (!mFragmentTransaction.isEmpty()) {
mFragmentTransaction.commit();
}
mFragmentTransaction = null;
}
}
}
@Override
public void onTabUnselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if (mListener != null) {
FragmentTransaction trans = null;
if (mActivity instanceof SherlockFragmentActivity) {
trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction()
.disallowAddToBackStack();
mFragmentTransaction = trans;
}
mListener.onTabUnselected(this, trans);
}
}
}
@Override
public Tab newTab() {
return new TabWrapper(mActionBar.newTab());
}
@Override
public void addTab(Tab tab) {
mActionBar.addTab(((TabWrapper)tab).mNativeTab);
}
@Override
public void addTab(Tab tab, boolean setSelected) {
mActionBar.addTab(((TabWrapper)tab).mNativeTab, setSelected);
}
@Override
public void addTab(Tab tab, int position) {
mActionBar.addTab(((TabWrapper)tab).mNativeTab, position);
}
@Override
public void addTab(Tab tab, int position, boolean setSelected) {
mActionBar.addTab(((TabWrapper)tab).mNativeTab, position, setSelected);
}
@Override
public void removeTab(Tab tab) {
mActionBar.removeTab(((TabWrapper)tab).mNativeTab);
}
@Override
public void removeTabAt(int position) {
mActionBar.removeTabAt(position);
}
@Override
public void removeAllTabs() {
mActionBar.removeAllTabs();
}
@Override
public void selectTab(Tab tab) {
mActionBar.selectTab(((TabWrapper)tab).mNativeTab);
}
@Override
public Tab getSelectedTab() {
android.app.ActionBar.Tab selected = mActionBar.getSelectedTab();
return (selected != null) ? (Tab)selected.getTag() : null;
}
@Override
public Tab getTabAt(int index) {
android.app.ActionBar.Tab selected = mActionBar.getTabAt(index);
return (selected != null) ? (Tab)selected.getTag() : null;
}
@Override
public int getTabCount() {
return mActionBar.getTabCount();
}
@Override
public int getHeight() {
return mActionBar.getHeight();
}
@Override
public void show() {
mActionBar.show();
}
@Override
public void hide() {
mActionBar.hide();
}
@Override
public boolean isShowing() {
return mActionBar.isShowing();
}
@Override
public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
mMenuVisibilityListeners.add(listener);
}
@Override
public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
mMenuVisibilityListeners.remove(listener);
}
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
for (OnMenuVisibilityListener listener : mMenuVisibilityListeners) {
listener.onMenuVisibilityChanged(isVisible);
}
}
}
| Java |
package com.actionbarsherlock.internal;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.AndroidRuntimeException;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.app.ActionBarImpl;
import com.actionbarsherlock.internal.view.StandaloneActionMode;
import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter;
import com.actionbarsherlock.internal.view.menu.MenuBuilder;
import com.actionbarsherlock.internal.view.menu.MenuItemImpl;
import com.actionbarsherlock.internal.view.menu.MenuPresenter;
import com.actionbarsherlock.internal.widget.ActionBarContainer;
import com.actionbarsherlock.internal.widget.ActionBarContextView;
import com.actionbarsherlock.internal.widget.ActionBarView;
import com.actionbarsherlock.internal.widget.IcsProgressBar;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
@ActionBarSherlock.Implementation(api = 7)
public class ActionBarSherlockCompat extends ActionBarSherlock implements MenuBuilder.Callback, com.actionbarsherlock.view.Window.Callback, MenuPresenter.Callback, android.view.MenuItem.OnMenuItemClickListener {
/** Window features which are enabled by default. */
protected static final int DEFAULT_FEATURES = 0;
public ActionBarSherlockCompat(Activity activity, int flags) {
super(activity, flags);
}
///////////////////////////////////////////////////////////////////////////
// Properties
///////////////////////////////////////////////////////////////////////////
/** Whether or not the device has a dedicated menu key button. */
private boolean mReserveOverflow;
/** Lazy-load indicator for {@link #mReserveOverflow}. */
private boolean mReserveOverflowSet = false;
/** Current menu instance for managing action items. */
private MenuBuilder mMenu;
/** Map between native options items and sherlock items. */
protected HashMap<android.view.MenuItem, MenuItemImpl> mNativeItemMap;
/** Indication of a long-press on the hardware menu key. */
private boolean mMenuKeyIsLongPress = false;
/** Parent view of the window decoration (action bar, mode, etc.). */
private ViewGroup mDecor;
/** Parent view of the activity content. */
private ViewGroup mContentParent;
/** Whether or not the title is stable and can be displayed. */
private boolean mIsTitleReady = false;
/** Whether or not the parent activity has been destroyed. */
private boolean mIsDestroyed = false;
/* Emulate PanelFeatureState */
private boolean mClosingActionMenu;
private boolean mMenuIsPrepared;
private boolean mMenuRefreshContent;
private Bundle mMenuFrozenActionViewState;
/** Implementation which backs the action bar interface API. */
private ActionBarImpl aActionBar;
/** Main action bar view which displays the core content. */
private ActionBarView wActionBar;
/** Relevant window and action bar features flags. */
private int mFeatures = DEFAULT_FEATURES;
/** Relevant user interface option flags. */
private int mUiOptions = 0;
/** Decor indeterminate progress indicator. */
private IcsProgressBar mCircularProgressBar;
/** Decor progress indicator. */
private IcsProgressBar mHorizontalProgressBar;
/** Current displayed context action bar, if any. */
private ActionMode mActionMode;
/** Parent view in which the context action bar is displayed. */
private ActionBarContextView mActionModeView;
/** Title view used with dialogs. */
private TextView mTitleView;
/** Current activity title. */
private CharSequence mTitle = null;
/** Whether or not this "activity" is floating (i.e., a dialog) */
private boolean mIsFloating;
///////////////////////////////////////////////////////////////////////////
// Instance methods
///////////////////////////////////////////////////////////////////////////
@Override
public ActionBar getActionBar() {
if (DEBUG) Log.d(TAG, "[getActionBar]");
initActionBar();
return aActionBar;
}
private void initActionBar() {
if (DEBUG) Log.d(TAG, "[initActionBar]");
// Initializing the window decor can change window feature flags.
// Make sure that we have the correct set before performing the test below.
if (mDecor == null) {
installDecor();
}
if ((aActionBar != null) || !hasFeature(Window.FEATURE_ACTION_BAR) || hasFeature(Window.FEATURE_NO_TITLE) || mActivity.isChild()) {
return;
}
aActionBar = new ActionBarImpl(mActivity, mFeatures);
if (!mIsDelegate) {
//We may never get another chance to set the title
wActionBar.setWindowTitle(mActivity.getTitle());
}
}
@Override
protected Context getThemedContext() {
return aActionBar.getThemedContext();
}
@Override
public void setTitle(CharSequence title) {
if (DEBUG) Log.d(TAG, "[setTitle] title: " + title);
dispatchTitleChanged(title, 0);
}
@Override
public ActionMode startActionMode(ActionMode.Callback callback) {
if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback);
if (mActionMode != null) {
mActionMode.finish();
}
final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback);
ActionMode mode = null;
//Emulate Activity's onWindowStartingActionMode:
initActionBar();
if (aActionBar != null) {
mode = aActionBar.startActionMode(wrappedCallback);
}
if (mode != null) {
mActionMode = mode;
} else {
if (mActionModeView == null) {
ViewStub stub = (ViewStub)mDecor.findViewById(R.id.abs__action_mode_bar_stub);
if (stub != null) {
mActionModeView = (ActionBarContextView)stub.inflate();
}
}
if (mActionModeView != null) {
mActionModeView.killMode();
mode = new StandaloneActionMode(mActivity, mActionModeView, wrappedCallback, true);
if (callback.onCreateActionMode(mode, mode.getMenu())) {
mode.invalidate();
mActionModeView.initForMode(mode);
mActionModeView.setVisibility(View.VISIBLE);
mActionMode = mode;
mActionModeView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
} else {
mActionMode = null;
}
}
}
if (mActionMode != null && mActivity instanceof OnActionModeStartedListener) {
((OnActionModeStartedListener)mActivity).onActionModeStarted(mActionMode);
}
return mActionMode;
}
///////////////////////////////////////////////////////////////////////////
// Lifecycle and interaction callbacks for delegation
///////////////////////////////////////////////////////////////////////////
@Override
public void dispatchConfigurationChanged(Configuration newConfig) {
if (DEBUG) Log.d(TAG, "[dispatchConfigurationChanged] newConfig: " + newConfig);
if (aActionBar != null) {
aActionBar.onConfigurationChanged(newConfig);
}
}
@Override
public void dispatchPostResume() {
if (DEBUG) Log.d(TAG, "[dispatchPostResume]");
if (aActionBar != null) {
aActionBar.setShowHideAnimationEnabled(true);
}
}
@Override
public void dispatchPause() {
if (DEBUG) Log.d(TAG, "[dispatchPause]");
if (wActionBar != null && wActionBar.isOverflowMenuShowing()) {
wActionBar.hideOverflowMenu();
}
}
@Override
public void dispatchStop() {
if (DEBUG) Log.d(TAG, "[dispatchStop]");
if (aActionBar != null) {
aActionBar.setShowHideAnimationEnabled(false);
}
}
@Override
public void dispatchInvalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]");
Bundle savedActionViewStates = null;
if (mMenu != null) {
savedActionViewStates = new Bundle();
mMenu.saveActionViewStates(savedActionViewStates);
if (savedActionViewStates.size() > 0) {
mMenuFrozenActionViewState = savedActionViewStates;
}
// This will be started again when the panel is prepared.
mMenu.stopDispatchingItemsChanged();
mMenu.clear();
}
mMenuRefreshContent = true;
// Prepare the options panel if we have an action bar
if (wActionBar != null) {
mMenuIsPrepared = false;
preparePanel();
}
}
@Override
public boolean dispatchOpenOptionsMenu() {
if (DEBUG) Log.d(TAG, "[dispatchOpenOptionsMenu]");
if (!isReservingOverflow()) {
return false;
}
return wActionBar.showOverflowMenu();
}
@Override
public boolean dispatchCloseOptionsMenu() {
if (DEBUG) Log.d(TAG, "[dispatchCloseOptionsMenu]");
if (!isReservingOverflow()) {
return false;
}
return wActionBar.hideOverflowMenu();
}
@Override
public void dispatchPostCreate(Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "[dispatchOnPostCreate]");
if (mIsDelegate) {
mIsTitleReady = true;
}
if (mDecor == null) {
initActionBar();
}
}
@Override
public boolean dispatchCreateOptionsMenu(android.view.Menu menu) {
if (DEBUG) {
Log.d(TAG, "[dispatchCreateOptionsMenu] android.view.Menu: " + menu);
Log.d(TAG, "[dispatchCreateOptionsMenu] returning true");
}
return true;
}
@Override
public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] android.view.Menu: " + menu);
if (mActionMode != null) {
return false;
}
mMenuIsPrepared = false;
if (!preparePanel()) {
return false;
}
if (isReservingOverflow()) {
return false;
}
if (mNativeItemMap == null) {
mNativeItemMap = new HashMap<android.view.MenuItem, MenuItemImpl>();
} else {
mNativeItemMap.clear();
}
if (mMenu == null) {
return false;
}
boolean result = mMenu.bindNativeOverflow(menu, this, mNativeItemMap);
if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result);
return result;
}
@Override
public boolean dispatchOptionsItemSelected(android.view.MenuItem item) {
throw new IllegalStateException("Native callback invoked. Create a test case and report!");
}
@Override
public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[dispatchMenuOpened] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) {
if (aActionBar != null) {
aActionBar.dispatchMenuVisibilityChanged(true);
}
return true;
}
return false;
}
@Override
public void dispatchPanelClosed(int featureId, android.view.Menu menu){
if (DEBUG) Log.d(TAG, "[dispatchPanelClosed] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) {
if (aActionBar != null) {
aActionBar.dispatchMenuVisibilityChanged(false);
}
}
}
@Override
public void dispatchTitleChanged(CharSequence title, int color) {
if (DEBUG) Log.d(TAG, "[dispatchTitleChanged] title: " + title + ", color: " + color);
if (!mIsDelegate || mIsTitleReady) {
if (mTitleView != null) {
mTitleView.setText(title);
} else if (wActionBar != null) {
wActionBar.setWindowTitle(title);
}
}
mTitle = title;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] event: " + event);
final int keyCode = event.getKeyCode();
// Not handled by the view hierarchy, does the action bar want it
// to cancel out of something special?
if (keyCode == KeyEvent.KEYCODE_BACK) {
final int action = event.getAction();
// Back cancels action modes first.
if (mActionMode != null) {
if (action == KeyEvent.ACTION_UP) {
mActionMode.finish();
}
if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true");
return true;
}
// Next collapse any expanded action views.
if (wActionBar != null && wActionBar.hasExpandedActionView()) {
if (action == KeyEvent.ACTION_UP) {
wActionBar.collapseActionView();
}
if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true");
return true;
}
}
boolean result = false;
if (keyCode == KeyEvent.KEYCODE_MENU && isReservingOverflow()) {
if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) {
mMenuKeyIsLongPress = true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
if (!mMenuKeyIsLongPress) {
if (mActionMode == null && wActionBar != null) {
if (wActionBar.isOverflowMenuShowing()) {
wActionBar.hideOverflowMenu();
} else {
wActionBar.showOverflowMenu();
}
}
result = true;
}
mMenuKeyIsLongPress = false;
}
}
if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning " + result);
return result;
}
@Override
public void dispatchDestroy() {
mIsDestroyed = true;
}
///////////////////////////////////////////////////////////////////////////
// Menu callback lifecycle and creation
///////////////////////////////////////////////////////////////////////////
private boolean preparePanel() {
// Already prepared (isPrepared will be reset to false later)
if (mMenuIsPrepared) {
return true;
}
// Init the panel state's menu--return false if init failed
if (mMenu == null || mMenuRefreshContent) {
if (mMenu == null) {
if (!initializePanelMenu() || (mMenu == null)) {
return false;
}
}
if (wActionBar != null) {
wActionBar.setMenu(mMenu, this);
}
// Call callback, and return if it doesn't want to display menu.
// Creating the panel menu will involve a lot of manipulation;
// don't dispatch change events to presenters until we're done.
mMenu.stopDispatchingItemsChanged();
if (!callbackCreateOptionsMenu(mMenu)) {
// Ditch the menu created above
mMenu = null;
if (wActionBar != null) {
// Don't show it in the action bar either
wActionBar.setMenu(null, this);
}
return false;
}
mMenuRefreshContent = false;
}
// Callback and return if the callback does not want to show the menu
// Preparing the panel menu can involve a lot of manipulation;
// don't dispatch change events to presenters until we're done.
mMenu.stopDispatchingItemsChanged();
// Restore action view state before we prepare. This gives apps
// an opportunity to override frozen/restored state in onPrepare.
if (mMenuFrozenActionViewState != null) {
mMenu.restoreActionViewStates(mMenuFrozenActionViewState);
mMenuFrozenActionViewState = null;
}
if (!callbackPrepareOptionsMenu(mMenu)) {
if (wActionBar != null) {
// The app didn't want to show the menu for now but it still exists.
// Clear it out of the action bar.
wActionBar.setMenu(null, this);
}
mMenu.startDispatchingItemsChanged();
return false;
}
// Set the proper keymap
KeyCharacterMap kmap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
mMenu.setQwertyMode(kmap.getKeyboardType() != KeyCharacterMap.NUMERIC);
mMenu.startDispatchingItemsChanged();
// Set other state
mMenuIsPrepared = true;
return true;
}
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
return callbackOptionsItemSelected(item);
}
public void onMenuModeChange(MenuBuilder menu) {
reopenMenu(true);
}
private void reopenMenu(boolean toggleMenuMode) {
if (wActionBar != null && wActionBar.isOverflowReserved()) {
if (!wActionBar.isOverflowMenuShowing() || !toggleMenuMode) {
if (wActionBar.getVisibility() == View.VISIBLE) {
if (callbackPrepareOptionsMenu(mMenu)) {
wActionBar.showOverflowMenu();
}
}
} else {
wActionBar.hideOverflowMenu();
}
return;
}
}
private boolean initializePanelMenu() {
Context context = mActivity;//getContext();
// If we have an action bar, initialize the menu with a context themed for it.
if (wActionBar != null) {
TypedValue outValue = new TypedValue();
Resources.Theme currentTheme = context.getTheme();
currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme,
outValue, true);
final int targetThemeRes = outValue.resourceId;
if (targetThemeRes != 0 /*&& context.getThemeResId() != targetThemeRes*/) {
context = new ContextThemeWrapper(context, targetThemeRes);
}
}
mMenu = new MenuBuilder(context);
mMenu.setCallback(this);
return true;
}
void checkCloseActionMenu(Menu menu) {
if (mClosingActionMenu) {
return;
}
mClosingActionMenu = true;
wActionBar.dismissPopupMenus();
//Callback cb = getCallback();
//if (cb != null && !isDestroyed()) {
// cb.onPanelClosed(FEATURE_ACTION_BAR, menu);
//}
mClosingActionMenu = false;
}
@Override
public boolean onOpenSubMenu(MenuBuilder subMenu) {
return true;
}
@Override
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
checkCloseActionMenu(menu);
}
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[mNativeItemListener.onMenuItemClick] item: " + item);
final MenuItemImpl sherlockItem = mNativeItemMap.get(item);
if (sherlockItem != null) {
sherlockItem.invoke();
} else {
Log.e(TAG, "Options item \"" + item + "\" not found in mapping");
}
return true; //Do not allow continuation of native handling
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return callbackOptionsItemSelected(item);
}
///////////////////////////////////////////////////////////////////////////
// Progress bar interaction and internal handling
///////////////////////////////////////////////////////////////////////////
@Override
public void setProgressBarVisibility(boolean visible) {
if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible);
setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
Window.PROGRESS_VISIBILITY_OFF);
}
@Override
public void setProgressBarIndeterminateVisibility(boolean visible) {
if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible);
setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
}
@Override
public void setProgressBarIndeterminate(boolean indeterminate) {
if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate);
setFeatureInt(Window.FEATURE_PROGRESS,
indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
}
@Override
public void setProgress(int progress) {
if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress);
setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
}
@Override
public void setSecondaryProgress(int secondaryProgress) {
if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress);
setFeatureInt(Window.FEATURE_PROGRESS,
secondaryProgress + Window.PROGRESS_SECONDARY_START);
}
private void setFeatureInt(int featureId, int value) {
updateInt(featureId, value, false);
}
private void updateInt(int featureId, int value, boolean fromResume) {
// Do nothing if the decor is not yet installed... an update will
// need to be forced when we eventually become active.
if (mContentParent == null) {
return;
}
final int featureMask = 1 << featureId;
if ((getFeatures() & featureMask) == 0 && !fromResume) {
return;
}
onIntChanged(featureId, value);
}
private void onIntChanged(int featureId, int value) {
if (featureId == Window.FEATURE_PROGRESS || featureId == Window.FEATURE_INDETERMINATE_PROGRESS) {
updateProgressBars(value);
}
}
private void updateProgressBars(int value) {
IcsProgressBar circularProgressBar = getCircularProgressBar(true);
IcsProgressBar horizontalProgressBar = getHorizontalProgressBar(true);
final int features = mFeatures;//getLocalFeatures();
if (value == Window.PROGRESS_VISIBILITY_ON) {
if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) {
int level = horizontalProgressBar.getProgress();
int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
View.VISIBLE : View.INVISIBLE;
horizontalProgressBar.setVisibility(visibility);
}
if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) {
circularProgressBar.setVisibility(View.VISIBLE);
}
} else if (value == Window.PROGRESS_VISIBILITY_OFF) {
if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) {
horizontalProgressBar.setVisibility(View.GONE);
}
if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) {
circularProgressBar.setVisibility(View.GONE);
}
} else if (value == Window.PROGRESS_INDETERMINATE_ON) {
horizontalProgressBar.setIndeterminate(true);
} else if (value == Window.PROGRESS_INDETERMINATE_OFF) {
horizontalProgressBar.setIndeterminate(false);
} else if (Window.PROGRESS_START <= value && value <= Window.PROGRESS_END) {
// We want to set the progress value before testing for visibility
// so that when the progress bar becomes visible again, it has the
// correct level.
horizontalProgressBar.setProgress(value - Window.PROGRESS_START);
if (value < Window.PROGRESS_END) {
showProgressBars(horizontalProgressBar, circularProgressBar);
} else {
hideProgressBars(horizontalProgressBar, circularProgressBar);
}
} else if (Window.PROGRESS_SECONDARY_START <= value && value <= Window.PROGRESS_SECONDARY_END) {
horizontalProgressBar.setSecondaryProgress(value - Window.PROGRESS_SECONDARY_START);
showProgressBars(horizontalProgressBar, circularProgressBar);
}
}
private void showProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) {
final int features = mFeatures;//getLocalFeatures();
if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
spinnyProgressBar.getVisibility() == View.INVISIBLE) {
spinnyProgressBar.setVisibility(View.VISIBLE);
}
// Only show the progress bars if the primary progress is not complete
if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 &&
horizontalProgressBar.getProgress() < 10000) {
horizontalProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) {
final int features = mFeatures;//getLocalFeatures();
Animation anim = AnimationUtils.loadAnimation(mActivity, android.R.anim.fade_out);
anim.setDuration(1000);
if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
spinnyProgressBar.getVisibility() == View.VISIBLE) {
spinnyProgressBar.startAnimation(anim);
spinnyProgressBar.setVisibility(View.INVISIBLE);
}
if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 &&
horizontalProgressBar.getVisibility() == View.VISIBLE) {
horizontalProgressBar.startAnimation(anim);
horizontalProgressBar.setVisibility(View.INVISIBLE);
}
}
private IcsProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
if (mCircularProgressBar != null) {
return mCircularProgressBar;
}
if (mContentParent == null && shouldInstallDecor) {
installDecor();
}
mCircularProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_circular);
if (mCircularProgressBar != null) {
mCircularProgressBar.setVisibility(View.INVISIBLE);
}
return mCircularProgressBar;
}
private IcsProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
if (mHorizontalProgressBar != null) {
return mHorizontalProgressBar;
}
if (mContentParent == null && shouldInstallDecor) {
installDecor();
}
mHorizontalProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_horizontal);
if (mHorizontalProgressBar != null) {
mHorizontalProgressBar.setVisibility(View.INVISIBLE);
}
return mHorizontalProgressBar;
}
///////////////////////////////////////////////////////////////////////////
// Feature management and content interaction and creation
///////////////////////////////////////////////////////////////////////////
private int getFeatures() {
if (DEBUG) Log.d(TAG, "[getFeatures] returning " + mFeatures);
return mFeatures;
}
@Override
public boolean hasFeature(int featureId) {
if (DEBUG) Log.d(TAG, "[hasFeature] featureId: " + featureId);
boolean result = (mFeatures & (1 << featureId)) != 0;
if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result);
return result;
}
@Override
public boolean requestFeature(int featureId) {
if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId);
if (mContentParent != null) {
throw new AndroidRuntimeException("requestFeature() must be called before adding content");
}
switch (featureId) {
case Window.FEATURE_ACTION_BAR:
case Window.FEATURE_ACTION_BAR_OVERLAY:
case Window.FEATURE_ACTION_MODE_OVERLAY:
case Window.FEATURE_INDETERMINATE_PROGRESS:
case Window.FEATURE_NO_TITLE:
case Window.FEATURE_PROGRESS:
mFeatures |= (1 << featureId);
return true;
default:
return false;
}
}
@Override
public void setUiOptions(int uiOptions) {
if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions);
mUiOptions = uiOptions;
}
@Override
public void setUiOptions(int uiOptions, int mask) {
if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask);
mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask);
}
@Override
public void setContentView(int layoutResId) {
if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId);
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mActivity.getLayoutInflater().inflate(layoutResId, mContentParent);
android.view.Window.Callback callback = mActivity.getWindow().getCallback();
if (callback != null) {
callback.onContentChanged();
}
initActionBar();
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params);
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mContentParent.addView(view, params);
android.view.Window.Callback callback = mActivity.getWindow().getCallback();
if (callback != null) {
callback.onContentChanged();
}
initActionBar();
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params);
if (mContentParent == null) {
installDecor();
}
mContentParent.addView(view, params);
initActionBar();
}
private void installDecor() {
if (DEBUG) Log.d(TAG, "[installDecor]");
if (mDecor == null) {
mDecor = (ViewGroup)mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
}
if (mContentParent == null) {
//Since we are not operating at the window level we need to take
//into account the fact that the true decor may have already been
//initialized and had content attached to it. If that is the case,
//copy over its children to our new content container.
List<View> views = null;
if (mDecor.getChildCount() > 0) {
views = new ArrayList<View>(1); //Usually there's only one child
for (int i = 0, children = mDecor.getChildCount(); i < children; i++) {
View child = mDecor.getChildAt(0);
mDecor.removeView(child);
views.add(child);
}
}
mContentParent = generateLayout();
//Copy over the old children. See above for explanation.
if (views != null) {
for (View child : views) {
mContentParent.addView(child);
}
}
mTitleView = (TextView)mDecor.findViewById(android.R.id.title);
if (mTitleView != null) {
if (hasFeature(Window.FEATURE_NO_TITLE)) {
mTitleView.setVisibility(View.GONE);
if (mContentParent instanceof FrameLayout) {
((FrameLayout)mContentParent).setForeground(null);
}
} else {
mTitleView.setText(mTitle);
}
} else {
wActionBar = (ActionBarView)mDecor.findViewById(R.id.abs__action_bar);
if (wActionBar != null) {
wActionBar.setWindowCallback(this);
if (wActionBar.getTitle() == null) {
wActionBar.setWindowTitle(mActivity.getTitle());
}
if (hasFeature(Window.FEATURE_PROGRESS)) {
wActionBar.initProgress();
}
if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) {
wActionBar.initIndeterminateProgress();
}
//Since we don't require onCreate dispatching, parse for uiOptions here
int uiOptions = loadUiOptionsFromManifest(mActivity);
if (uiOptions != 0) {
mUiOptions = uiOptions;
}
boolean splitActionBar = false;
final boolean splitWhenNarrow = (mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0;
if (splitWhenNarrow) {
splitActionBar = getResources_getBoolean(mActivity, R.bool.abs__split_action_bar_is_narrow);
} else {
splitActionBar = mActivity.getTheme()
.obtainStyledAttributes(R.styleable.SherlockTheme)
.getBoolean(R.styleable.SherlockTheme_windowSplitActionBar, false);
}
final ActionBarContainer splitView = (ActionBarContainer)mDecor.findViewById(R.id.abs__split_action_bar);
if (splitView != null) {
wActionBar.setSplitView(splitView);
wActionBar.setSplitActionBar(splitActionBar);
wActionBar.setSplitWhenNarrow(splitWhenNarrow);
mActionModeView = (ActionBarContextView)mDecor.findViewById(R.id.abs__action_context_bar);
mActionModeView.setSplitView(splitView);
mActionModeView.setSplitActionBar(splitActionBar);
mActionModeView.setSplitWhenNarrow(splitWhenNarrow);
} else if (splitActionBar) {
Log.e(TAG, "Requested split action bar with incompatible window decor! Ignoring request.");
}
// Post the panel invalidate for later; avoid application onCreateOptionsMenu
// being called in the middle of onCreate or similar.
mDecor.post(new Runnable() {
@Override
public void run() {
//Invalidate if the panel menu hasn't been created before this.
if (!mIsDestroyed && !mActivity.isFinishing() && mMenu == null) {
dispatchInvalidateOptionsMenu();
}
}
});
}
}
}
}
private ViewGroup generateLayout() {
if (DEBUG) Log.d(TAG, "[generateLayout]");
// Apply data from current theme.
TypedArray a = mActivity.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme);
mIsFloating = a.getBoolean(R.styleable.SherlockTheme_android_windowIsFloating, false);
if (!a.hasValue(R.styleable.SherlockTheme_windowActionBar)) {
throw new IllegalStateException("You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.");
}
if (a.getBoolean(R.styleable.SherlockTheme_windowNoTitle, false)) {
requestFeature(Window.FEATURE_NO_TITLE);
} else if (a.getBoolean(R.styleable.SherlockTheme_windowActionBar, false)) {
// Don't allow an action bar if there is no title.
requestFeature(Window.FEATURE_ACTION_BAR);
}
if (a.getBoolean(R.styleable.SherlockTheme_windowActionBarOverlay, false)) {
requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
}
if (a.getBoolean(R.styleable.SherlockTheme_windowActionModeOverlay, false)) {
requestFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
}
a.recycle();
int layoutResource;
if (!hasFeature(Window.FEATURE_NO_TITLE)) {
if (mIsFloating) {
//Trash original dialog LinearLayout
mDecor = (ViewGroup)mDecor.getParent();
mDecor.removeAllViews();
layoutResource = R.layout.abs__dialog_title_holo;
} else {
if (hasFeature(Window.FEATURE_ACTION_BAR_OVERLAY)) {
layoutResource = R.layout.abs__screen_action_bar_overlay;
} else {
layoutResource = R.layout.abs__screen_action_bar;
}
}
} else if (hasFeature(Window.FEATURE_ACTION_MODE_OVERLAY) && !hasFeature(Window.FEATURE_NO_TITLE)) {
layoutResource = R.layout.abs__screen_simple_overlay_action_mode;
} else {
layoutResource = R.layout.abs__screen_simple;
}
if (DEBUG) Log.d(TAG, "[generateLayout] using screen XML " + mActivity.getResources().getString(layoutResource));
View in = mActivity.getLayoutInflater().inflate(layoutResource, null);
mDecor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
ViewGroup contentParent = (ViewGroup)mDecor.findViewById(R.id.abs__content);
if (contentParent == null) {
throw new RuntimeException("Couldn't find content container view");
}
//Make our new child the true content view (for fragments). VERY VOLATILE!
mDecor.setId(View.NO_ID);
contentParent.setId(android.R.id.content);
if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) {
IcsProgressBar progress = getCircularProgressBar(false);
if (progress != null) {
progress.setIndeterminate(true);
}
}
return contentParent;
}
///////////////////////////////////////////////////////////////////////////
// Miscellaneous
///////////////////////////////////////////////////////////////////////////
/**
* Determine whether or not the device has a dedicated menu key.
*
* @return {@code true} if native menu key is present.
*/
private boolean isReservingOverflow() {
if (!mReserveOverflowSet) {
mReserveOverflow = ActionMenuPresenter.reserveOverflow(mActivity);
mReserveOverflowSet = true;
}
return mReserveOverflow;
}
private static int loadUiOptionsFromManifest(Activity activity) {
int uiOptions = 0;
try {
final String thisPackage = activity.getClass().getName();
if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage);
final String packageName = activity.getApplicationInfo().packageName;
final AssetManager am = activity.createPackageContext(packageName, 0).getAssets();
final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml");
int eventType = xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String name = xml.getName();
if ("application".equals(name)) {
//Check if the <application> has the attribute
if (DEBUG) Log.d(TAG, "Got <application>");
for (int i = xml.getAttributeCount() - 1; i >= 0; i--) {
if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i));
if ("uiOptions".equals(xml.getAttributeName(i))) {
uiOptions = xml.getAttributeIntValue(i, 0);
break; //out of for loop
}
}
} else if ("activity".equals(name)) {
//Check if the <activity> is us and has the attribute
if (DEBUG) Log.d(TAG, "Got <activity>");
Integer activityUiOptions = null;
String activityPackage = null;
boolean isOurActivity = false;
for (int i = xml.getAttributeCount() - 1; i >= 0; i--) {
if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i));
//We need both uiOptions and name attributes
String attrName = xml.getAttributeName(i);
if ("uiOptions".equals(attrName)) {
activityUiOptions = xml.getAttributeIntValue(i, 0);
} else if ("name".equals(attrName)) {
activityPackage = cleanActivityName(packageName, xml.getAttributeValue(i));
if (!thisPackage.equals(activityPackage)) {
break; //out of for loop
}
isOurActivity = true;
}
//Make sure we have both attributes before processing
if ((activityUiOptions != null) && (activityPackage != null)) {
//Our activity, uiOptions specified, override with our value
uiOptions = activityUiOptions.intValue();
}
}
if (isOurActivity) {
//If we matched our activity but it had no logo don't
//do any more processing of the manifest
break;
}
}
}
eventType = xml.nextToken();
}
} catch (Exception e) {
e.printStackTrace();
}
if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(uiOptions));
return uiOptions;
}
public static String cleanActivityName(String manifestPackage, String activityName) {
if (activityName.charAt(0) == '.') {
//Relative activity name (e.g., android:name=".ui.SomeClass")
return manifestPackage + activityName;
}
if (activityName.indexOf('.', 1) == -1) {
//Unqualified activity name (e.g., android:name="SomeClass")
return manifestPackage + "." + activityName;
}
//Fully-qualified activity name (e.g., "com.my.package.SomeClass")
return activityName;
}
/**
* Clears out internal reference when the action mode is destroyed.
*/
private class ActionModeCallbackWrapper implements ActionMode.Callback {
private final ActionMode.Callback mWrapped;
public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
mWrapped = wrapped;
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return mWrapped.onCreateActionMode(mode, menu);
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return mWrapped.onPrepareActionMode(mode, menu);
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return mWrapped.onActionItemClicked(mode, item);
}
public void onDestroyActionMode(ActionMode mode) {
mWrapped.onDestroyActionMode(mode);
if (mActionModeView != null) {
mActionModeView.setVisibility(View.GONE);
mActionModeView.removeAllViews();
}
if (mActivity instanceof OnActionModeFinishedListener) {
((OnActionModeFinishedListener)mActivity).onActionModeFinished(mActionMode);
}
mActionMode = null;
}
}
}
| Java |
package com.actionbarsherlock.internal;
import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import com.actionbarsherlock.R;
public final class ResourcesCompat {
//No instances
private ResourcesCompat() {}
/**
* Support implementation of {@code getResources().getBoolean()} that we
* can use to simulate filtering based on width and smallest width
* qualifiers on pre-3.2.
*
* @param context Context to load booleans from on 3.2+ and to fetch the
* display metrics.
* @param id Id of boolean to load.
* @return Associated boolean value as reflected by the current display
* metrics.
*/
public static boolean getResources_getBoolean(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
return context.getResources().getBoolean(id);
}
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
float smallestWidthDp = (widthDp < heightDp) ? widthDp : heightDp;
if (id == R.bool.abs__action_bar_embed_tabs) {
if (widthDp >= 480) {
return true; //values-w480dp
}
return false; //values
}
if (id == R.bool.abs__split_action_bar_is_narrow) {
if (widthDp >= 480) {
return false; //values-w480dp
}
return true; //values
}
if (id == R.bool.abs__action_bar_expanded_action_views_exclusive) {
if (smallestWidthDp >= 600) {
return false; //values-sw600dp
}
return true; //values
}
if (id == R.bool.abs__config_allowActionMenuItemTextWithIcon) {
if (widthDp >= 480) {
return true; //values-w480dp
}
return false; //values
}
throw new IllegalArgumentException("Unknown boolean resource ID " + id);
}
/**
* Support implementation of {@code getResources().getInteger()} that we
* can use to simulate filtering based on width qualifiers on pre-3.2.
*
* @param context Context to load integers from on 3.2+ and to fetch the
* display metrics.
* @param id Id of integer to load.
* @return Associated integer value as reflected by the current display
* metrics.
*/
public static int getResources_getInteger(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
return context.getResources().getInteger(id);
}
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float widthDp = metrics.widthPixels / metrics.density;
if (id == R.integer.abs__max_action_buttons) {
if (widthDp >= 600) {
return 5; //values-w600dp
}
if (widthDp >= 500) {
return 4; //values-w500dp
}
if (widthDp >= 360) {
return 3; //values-w360dp
}
return 2; //values
}
throw new IllegalArgumentException("Unknown integer resource ID " + id);
}
}
| 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.actionbarsherlock.internal.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.actionbarsherlock.internal.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>
*/
@SuppressWarnings("rawtypes")
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.actionbarsherlock.internal.nineoldandroids.animation;
import java.util.ArrayList;
import android.view.animation.Interpolator;
import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe;
/**
* 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>
*/
@SuppressWarnings("unchecked")
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 |
/*
* 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.actionbarsherlock.internal.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.actionbarsherlock.internal.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>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
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 = 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.actionbarsherlock.internal.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.actionbarsherlock.internal.nineoldandroids.animation;
//import android.util.FloatProperty;
//import android.util.IntProperty;
import android.util.Log;
//import android.util.Property;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 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.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
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 = 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 = values[0].getType();
for (int i = 0; i < numKeyframes; ++i) {
keyframes[i] = 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) {
Log.e("PropertyValuesHolder", targetClass.getSimpleName() + " - " +
"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) {
// Swallow the error and keep trying other variants
}
}
// If we got here, then no appropriate function was found
Log.e("PropertyValuesHolder",
"Couldn't find " + prefix + "ter property " + mPropertyName +
" for " + targetClass.getSimpleName() +
" 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.actionbarsherlock.internal.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 |
/*
* 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.actionbarsherlock.internal.nineoldandroids.animation;
import android.util.Log;
//import android.util.Property;
//import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* 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)
*
*/
@SuppressWarnings("rawtypes")
public final class ObjectAnimator extends ValueAnimator {
private static final boolean DBG = false;
// 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.
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.actionbarsherlock.internal.nineoldandroids.animation;
import java.util.ArrayList;
import android.view.animation.Interpolator;
import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe;
/**
* 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>
*/
@SuppressWarnings("unchecked")
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 |
/*
* 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.actionbarsherlock.internal.nineoldandroids.animation;
import java.util.ArrayList;
import java.util.Arrays;
import android.view.animation.Interpolator;
import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe;
import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe;
import com.actionbarsherlock.internal.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.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
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.actionbarsherlock.internal.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.
*/
@SuppressWarnings("unchecked")
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>
*/
@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.
*/
@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);
}
}
}
}
}
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 = 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.actionbarsherlock.internal.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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.