code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* 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");
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/DiskLruCache.java | Java | asf20 | 33,892 |
/*
* 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() {
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/LogUtils.java | Java | asf20 | 3,045 |
/*
* 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>();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/Maps.java | Java | asf20 | 1,006 |
/*
* 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);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/UIUtils.java | Java | asf20 | 17,426 |
/*
* 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) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
// 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;
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/ImageFetcher.java | Java | asf20 | 22,306 |
/*
* 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);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/AccountUtils.java | Java | asf20 | 7,748 |
/*
* 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/")));
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/BeamUtils.java | Java | asf20 | 6,235 |
/*
* 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;
}
/**
* 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);
}
}
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);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/ImageWorker.java | Java | asf20 | 19,544 |
/*
* 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;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/ReflectionUtils.java | Java | asf20 | 1,986 |
/*
* 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);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/ParserUtils.java | Java | asf20 | 1,868 |
/*
* 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 bytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return getBitmapSize(bitmap);
}
};
}
// 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(context, getDiskCacheDir(context, DEFAULT_DISK_CACHE_DIR));
}
public ImageCacheParams(Context context, String uniqueName) {
init(context, getDiskCacheDir(context, uniqueName));
}
public ImageCacheParams(Context context, File diskCacheDir) {
init(context, diskCacheDir);
}
private void init(Context context, File diskCacheDir) {
setMemCacheSizePercent(context, DEFAULT_MEM_CACHE_PERCENT);
this.diskCacheDir = diskCacheDir;
}
/**
* Sets the memory cache size based on a percentage of the device memory class.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the device memory
* class. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8.
*
* 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 context Context to use to fetch memory class
* @param percent Percent of memory class to use to size memory cache
*/
public void setMemCacheSizePercent(Context context, 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 * getMemoryClass(context) * 1024 * 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;
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/ImageCache.java | Java | asf20 | 21,078 |
/*
* 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);
}
});
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionModeHoneycomb.java | Java | asf20 | 5,167 |
/*
* 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");
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/SimpleMenu.java | Java | asf20 | 6,416 |
/*
* 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();
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionModeBase.java | Java | asf20 | 6,806 |
/*
* 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);
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/MultiChoiceModeListener.java | Java | asf20 | 1,638 |
/*
* 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();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/SimpleMenuItem.java | Java | asf20 | 6,007 |
/*
* 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);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionMode.java | Java | asf20 | 6,836 |
/*
* 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;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/appwidget/MyScheduleWidgetService.java | Java | asf20 | 17,704 |
/*
* 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);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/appwidget/MyScheduleWidgetProvider.java | Java | asf20 | 13,326 |
/*
* 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.gcm;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.sync.TriggerSyncReceiver;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import java.util.Random;
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.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* {@link android.app.IntentService} responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = makeLogTag("GCM");
private static final int TRIGGER_SYNC_MAX_JITTER_MILLIS = 3 * 60 * 1000; // 3 minutes
private static final Random sRandom = new Random();
public GCMIntentService() {
super(Config.GCM_SENDER_ID);
}
@Override
protected void onRegistered(Context context, String regId) {
LOGI(TAG, "Device registered: regId=" + regId);
ServerUtilities.register(context, regId);
}
@Override
protected void onUnregistered(Context context, String regId) {
LOGI(TAG, "Device unregistered");
if (GCMRegistrar.isRegisteredOnServer(context)) {
ServerUtilities.unregister(context, regId);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
LOGD(TAG, "Ignoring unregister callback");
}
}
@Override
protected void onMessage(Context context, Intent intent) {
if (UIUtils.isGoogleTV(context)) {
// Google TV uses SyncHelper directly.
return;
}
String announcement = intent.getStringExtra("announcement");
if (announcement != null) {
displayNotification(context, announcement);
return;
}
int jitterMillis = (int) (sRandom.nextFloat() * TRIGGER_SYNC_MAX_JITTER_MILLIS);
final String debugMessage = "Received message to trigger sync; "
+ "jitter = " + jitterMillis + "ms";
LOGI(TAG, debugMessage);
if (BuildConfig.DEBUG) {
displayNotification(context, debugMessage);
}
((AlarmManager) context.getSystemService(ALARM_SERVICE))
.set(
AlarmManager.RTC,
System.currentTimeMillis() + jitterMillis,
PendingIntent.getBroadcast(
context,
0,
new Intent(context, TriggerSyncReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT));
}
private void displayNotification(Context context, String message) {
LOGI(TAG, "displayNotification: " + message);
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
.notify(0, new NotificationCompat.Builder(context)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_notification)
.setTicker(message)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(message)
.setContentIntent(
PendingIntent.getActivity(context, 0,
new Intent(context, HomeActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP),
0))
.setAutoCancel(true)
.getNotification());
}
@Override
public void onError(Context context, String errorId) {
LOGE(TAG, "Received error: " + errorId);
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
LOGW(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/gcm/GCMIntentService.java | Java | asf20 | 5,422 |
/*
* 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.gcm;
import com.google.android.apps.iosched.Config;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
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.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final String TAG = makeLogTag("GCM");
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLIS = 2000;
private static final Random sRandom = new Random();
/**
* Register this account/device pair within the server.
*
* @param context Current context
* @param regId The GCM registration ID for this device
* @return whether the registration succeeded or not.
*/
public static boolean register(final Context context, final String regId) {
LOGI(TAG, "registering device (regId = " + regId + ")");
String serverUrl = Config.GCM_SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
LOGV(TAG, "Attempt #" + i + " to register");
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
return true;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
LOGE(TAG, "Failed to register on attempt " + i, e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
LOGV(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return false;
}
// increase backoff exponentially
backoff *= 2;
}
}
return false;
}
/**
* Unregister this account/device pair within the server.
*
* @param context Current context
* @param regId The GCM registration ID for this device
*/
static void unregister(final Context context, final String regId) {
LOGI(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = Config.GCM_SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
LOGD(TAG, "Unable to unregister from application server", e);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
* @throws java.io.IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
LOGV(TAG, "Posting '" + body + "' to " + url);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(body.length()));
// post the request
OutputStream out = conn.getOutputStream();
out.write(body.getBytes());
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/gcm/ServerUtilities.java | Java | asf20 | 6,922 |
/*
* 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.gcm;
import com.google.android.gcm.GCMBroadcastReceiver;
import android.content.Context;
/**
* @author trevorjohns@google.com (Trevor Johns)
*/
public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver {
/**
* Gets the class name of the intent service that will handle GCM messages.
*
* Used to override class name, so that GCMIntentService can live in a
* subpackage.
*/
@Override
protected String getGCMIntentServiceClassName(Context context) {
return GCMIntentService.class.getCanonicalName();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/gcm/GCMRedirectedBroadcastReceiver.java | Java | asf20 | 1,209 |
/*
* 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);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/sync/SyncAdapter.java | Java | asf20 | 4,247 |
/*
* 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);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java | Java | asf20 | 6,382 |
/*
* 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();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/sync/SyncHelper.java | Java | asf20 | 16,614 |
/*
* 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());
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/sync/TriggerSyncReceiver.java | Java | asf20 | 1,733 |
/*
* 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();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/sync/SyncService.java | Java | asf20 | 1,345 |
/*
* 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
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/Config.java | Java | asf20 | 2,785 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
/**
* A retained, non-UI helper fragment that loads track information such as name, color, etc. and
* returns this information via {@link Callbacks#onTrackInfoAvailable(String, String, int)}.
*/
public class TrackInfoHelperFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
/**
* The track URI for which to load data.
*/
public static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK";
private Uri mTrackUri;
// To be loaded
private String mTrackId;
private String mTrackName;
private int mTrackColor;
private Handler mHandler = new Handler();
public interface Callbacks {
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) {
}
};
private Callbacks mCallbacks = sDummyCallbacks;
public static TrackInfoHelperFragment newFromSessionUri(Uri sessionUri) {
return newFromTrackUri(ScheduleContract.Sessions.buildTracksDirUri(
ScheduleContract.Sessions.getSessionId(sessionUri)));
}
public static TrackInfoHelperFragment newFromTrackUri(Uri trackUri) {
TrackInfoHelperFragment f = new TrackInfoHelperFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_TRACK, trackUri);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mTrackUri = getArguments().getParcelable(ARG_TRACK);
if (ScheduleContract.Tracks.ALL_TRACK_ID.equals(
ScheduleContract.Tracks.getTrackId(mTrackUri))) {
mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID;
mTrackName = getString(R.string.all_tracks);
mTrackColor = getResources().getColor(android.R.color.white);
mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor);
} else {
getLoaderManager().initLoader(0, null, this);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
if (mTrackId != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor);
}
});
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mTrackUri, TracksQuery.PROJECTION, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
try {
if (!cursor.moveToFirst()) {
return;
}
mTrackId = cursor.getString(TracksQuery.TRACK_ID);
mTrackName = cursor.getString(TracksQuery.TRACK_NAME);
mTrackColor = cursor.getInt(TracksQuery.TRACK_COLOR);
// Wrapping in a Handler.post allows users of this helper to commit fragment
// transactions in the callback.
new Handler().post(new Runnable() {
@Override
public void run() {
mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor);
}
});
} finally {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters.
*/
private interface TracksQuery {
String[] PROJECTION = {
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR,
};
int TRACK_ID = 0;
int TRACK_NAME = 1;
int TRACK_COLOR = 2;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/TrackInfoHelperFragment.java | Java | asf20 | 5,505 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity;
import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.apps.iosched.util.actionmodecompat.ActionMode;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows the user's customized schedule, including sessions that she has chosen,
* and common conference items such as keynote sessions, lunch breaks, after hours party, etc.
*/
public class MyScheduleFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>,
ActionMode.Callback {
private static final String TAG = makeLogTag(MyScheduleFragment.class);
private SimpleSectionedListAdapter mAdapter;
private MyScheduleAdapter mScheduleAdapter;
private SparseArray<String> mLongClickedItemData;
private View mLongClickedView;
private ActionMode mActionMode;
private boolean mScrollToNow;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The MyScheduleAdapter is wrapped in a SimpleSectionedListAdapter so that
// we can show list headers separating out the different days of the conference
// (Wednesday/Thursday/Friday).
mScheduleAdapter = new MyScheduleAdapter(getActivity());
mAdapter = new SimpleSectionedListAdapter(getActivity(),
R.layout.list_item_schedule_header, mScheduleAdapter);
setListAdapter(mAdapter);
if (savedInstanceState == null) {
mScrollToNow = true;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.fragment_list_with_empty_container, container, false);
inflater.inflate(R.layout.empty_waiting_for_sync,
(ViewGroup) root.findViewById(android.R.id.empty), true);
root.setBackgroundColor(Color.WHITE);
ListView listView = (ListView) root.findViewById(android.R.id.list);
listView.setItemsCanFocus(true);
listView.setCacheColorHint(Color.WHITE);
listView.setSelector(android.R.color.transparent);
//listView.setEmptyView(root.findViewById(android.R.id.empty));
return root;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// In support library r8, calling initLoader for a fragment in a
// FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be
// dealt to multiple fragments because their mIndex is -1 (haven't been added to the
// activity yet). Thus, we do this in onActivityCreated.
getLoaderManager().initLoader(0, null, this);
}
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (getActivity() == null) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(0);
if (loader != null) {
loader.forceLoad();
}
}
};
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activity.getContentResolver().registerContentObserver(
ScheduleContract.Sessions.CONTENT_URI, true, mObserver);
}
@Override
public void onDetach() {
super.onDetach();
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
// LoaderCallbacks
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(),
ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
null,
null,
ScheduleContract.Blocks.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
long currentTime = UIUtils.getCurrentTime(getActivity());
int firstNowPosition = ListView.INVALID_POSITION;
List<SimpleSectionedListAdapter.Section> sections =
new ArrayList<SimpleSectionedListAdapter.Section>();
cursor.moveToFirst();
long previousBlockStart = -1;
long blockStart, blockEnd;
while (!cursor.isAfterLast()) {
blockStart = cursor.getLong(BlocksQuery.BLOCK_START);
blockEnd = cursor.getLong(BlocksQuery.BLOCK_END);
if (!UIUtils.isSameDay(previousBlockStart, blockStart)) {
sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(),
DateUtils.formatDateTime(getActivity(), blockStart,
DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_WEEKDAY)));
}
if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION
// if we're currently in this block, or we're not in a block
// and this
// block is in the future, then this is the scroll position
&& ((blockStart < currentTime && currentTime < blockEnd)
|| blockStart > currentTime)) {
firstNowPosition = cursor.getPosition();
}
previousBlockStart = blockStart;
cursor.moveToNext();
}
mScheduleAdapter.changeCursor(cursor);
SimpleSectionedListAdapter.Section[] dummy =
new SimpleSectionedListAdapter.Section[sections.size()];
mAdapter.setSections(sections.toArray(dummy));
if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) {
firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition);
getListView().setSelectionFromTop(firstNowPosition,
getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset));
mScrollToNow = false;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
SessionsHelper helper = new SessionsHelper(getActivity());
String title = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_TITLE);
String hashtags = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS);
String url = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_URL);
boolean handled = false;
switch (item.getItemId()) {
case R.id.menu_map:
String roomId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID);
helper.startMapActivity(roomId);
handled = true;
break;
case R.id.menu_star:
String sessionId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID);
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId);
helper.setSessionStarred(sessionUri, false, title);
handled = true;
break;
case R.id.menu_share:
// On ICS+ devices, we normally won't reach this as ShareActionProvider will handle
// sharing.
helper.shareSession(getActivity(), R.string.share_template, title, hashtags, url);
handled = true;
break;
case R.id.menu_social_stream:
helper.startSocialStream(hashtags);
handled = true;
break;
default:
LOGW(TAG, "Unknown action taken");
}
mActionMode.finish();
return handled;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.sessions_context, menu);
MenuItem starMenuItem = menu.findItem(R.id.menu_star);
starMenuItem.setTitle(R.string.description_remove_schedule);
starMenuItem.setIcon(R.drawable.ic_action_remove_schedule);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
if (mLongClickedView != null) {
UIUtils.setActivatedCompat(mLongClickedView, false);
}
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
/**
* A list adapter that shows schedule blocks as list items. It handles a number of different
* cases, such as empty blocks where the user has not chosen a session, blocks with conflicts
* (i.e. multiple sessions chosen), non-session blocks, etc.
*/
private class MyScheduleAdapter extends CursorAdapter {
public MyScheduleAdapter(Context context) {
super(context, null, false);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_schedule_block,
parent, false);
}
@Override
public void bindView(View view, Context context, final Cursor cursor) {
final String type = cursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockId = cursor.getString(BlocksQuery.BLOCK_ID);
final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE);
final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START);
final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END);
final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META);
final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd,
context);
final TextView timeView = (TextView) view.findViewById(R.id.block_time);
final TextView titleView = (TextView) view.findViewById(R.id.block_title);
final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle);
final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button);
final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container);
final Resources res = getResources();
String subtitle;
boolean isLiveStreamed = false;
primaryTouchTargetView.setOnLongClickListener(null);
UIUtils.setActivatedCompat(primaryTouchTargetView, false);
if (ParserUtils.BLOCK_TYPE_SESSION.equals(type)
|| ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) {
final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID);
View.OnClickListener allSessionsListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId);
final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.putExtra(Intent.EXTRA_TITLE, blockTimeString);
startActivity(intent);
}
};
if (numStarredSessions == 0) {
// 0 sessions starred
titleView.setText(getString(R.string.schedule_empty_slot_title_template,
TextUtils.isEmpty(blockTitle)
? ""
: (" " + blockTitle.toLowerCase())));
titleView.setTextColor(res.getColorStateList(R.color.body_text_1_positive));
subtitle = getString(R.string.schedule_empty_slot_subtitle);
extraButton.setVisibility(View.GONE);
primaryTouchTargetView.setOnClickListener(allSessionsListener);
} else if (numStarredSessions == 1) {
// exactly 1 session starred
final String starredSessionTitle =
cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
titleView.setText(starredSessionTitle);
titleView.setTextColor(res.getColorStateList(R.color.body_text_1));
subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (subtitle == null) {
// TODO: remove this WAR for API not returning rooms for code labs
subtitle = getString(
starredSessionTitle.contains("Code Lab")
? R.string.codelab_room
: R.string.unknown_room);
}
isLiveStreamed = !TextUtils.isEmpty(
cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL));
extraButton.setVisibility(View.VISIBLE);
extraButton.setOnClickListener(allSessionsListener);
if (mLongClickedItemData != null && mActionMode != null
&& mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals(
starredSessionId)) {
UIUtils.setActivatedCompat(primaryTouchTargetView, true);
mLongClickedView = primaryTouchTargetView;
}
primaryTouchTargetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(
starredSessionId);
final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri);
intent.putExtra(SessionsVendorsMultiPaneActivity.EXTRA_MASTER_URI,
ScheduleContract.Blocks.buildSessionsUri(blockId));
intent.putExtra(Intent.EXTRA_TITLE, blockTimeString);
startActivity(intent);
}
});
primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mActionMode != null) {
// CAB already displayed, ignore
return true;
}
mLongClickedView = primaryTouchTargetView;
String hashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS);
String url = cursor.getString(BlocksQuery.STARRED_SESSION_URL);
String roomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID);
mLongClickedItemData = new SparseArray<String>();
mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ID,
starredSessionId);
mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_TITLE,
starredSessionTitle);
mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, hashtags);
mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_URL, url);
mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, roomId);
mActionMode = ActionMode.start(getActivity(), MyScheduleFragment.this);
UIUtils.setActivatedCompat(primaryTouchTargetView, true);
return true;
}
});
} else {
// 2 or more sessions starred
titleView.setText(getString(R.string.schedule_conflict_title,
numStarredSessions));
titleView.setTextColor(res.getColorStateList(R.color.body_text_1));
subtitle = getString(R.string.schedule_conflict_subtitle);
extraButton.setVisibility(View.VISIBLE);
extraButton.setOnClickListener(allSessionsListener);
primaryTouchTargetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Uri sessionsUri = ScheduleContract.Blocks
.buildStarredSessionsUri(
blockId);
final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri);
intent.putExtra(Intent.EXTRA_TITLE, blockTimeString);
startActivity(intent);
}
});
}
subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2));
primaryTouchTargetView.setEnabled(true);
} else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) {
final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID);
final String starredSessionTitle =
cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
long currentTimeMillis = UIUtils.getCurrentTime(context);
boolean past = (currentTimeMillis > blockEnd
&& currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS);
boolean present = !past && (currentTimeMillis >= blockStart);
boolean canViewStream = present && UIUtils.hasHoneycomb();
isLiveStreamed = true;
titleView.setTextColor(canViewStream
? res.getColorStateList(R.color.body_text_1)
: res.getColorStateList(R.color.body_text_disabled));
subtitleView.setTextColor(canViewStream
? res.getColorStateList(R.color.body_text_2)
: res.getColorStateList(R.color.body_text_disabled));
subtitle = getString(R.string.keynote_room);
titleView.setText(starredSessionTitle);
extraButton.setVisibility(View.GONE);
primaryTouchTargetView.setEnabled(canViewStream);
primaryTouchTargetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(
starredSessionId);
Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri);
livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class);
startActivity(livestreamIntent);
}
});
} else {
titleView.setTextColor(res.getColorStateList(R.color.body_text_disabled));
subtitleView.setTextColor(res.getColorStateList(R.color.body_text_disabled));
subtitle = blockMeta;
titleView.setText(blockTitle);
extraButton.setVisibility(View.GONE);
primaryTouchTargetView.setEnabled(false);
primaryTouchTargetView.setOnClickListener(null);
}
timeView.setText(DateUtils.formatDateTime(context, blockStart,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
// Show past/present/future and livestream status for this block.
UIUtils.updateTimeAndLivestreamBlockUI(context,
blockStart, blockEnd, isLiveStreamed,
view, titleView, subtitleView, subtitle);
}
}
private 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.SESSIONS_COUNT,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_ID,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID,
ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS,
ScheduleContract.Blocks.STARRED_SESSION_URL,
ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL,
};
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 SESSIONS_COUNT = 7;
int NUM_STARRED_SESSIONS = 8;
int STARRED_SESSION_ID = 9;
int STARRED_SESSION_TITLE = 10;
int STARRED_SESSION_ROOM_NAME = 11;
int STARRED_SESSION_ROOM_ID = 12;
int STARRED_SESSION_HASHTAGS = 13;
int STARRED_SESSION_URL = 14;
int STARRED_SESSION_LIVESTREAM_URL = 15;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/MyScheduleFragment.java | Java | asf20 | 24,254 |
/*
* 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.ui;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.util.BeamUtils;
/**
* Beam easter egg landing screen.
*/
public class BeamActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beam);
}
@Override
protected void onResume() {
super.onResume();
if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) {
BeamUtils.setBeamUnlocked(this);
showUnlockDialog();
}
}
void showUnlockDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.just_beamed)
.setMessage(R.string.beam_unlocked_default)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(BeamActivity.this);
di.dismiss();
}
})
.create()
.show();
}
void showHelpDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.title_beam)
.setMessage(R.string.beam_unlocked_help)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(BeamActivity.this);
di.dismiss();
}
})
.create()
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.beam, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_beam_help) {
showHelpDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/BeamActivity.java | Java | asf20 | 3,300 |
/*
* 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.ui;
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.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* The first activity most users see. This wizard-like activity first presents an account
* selection fragment ({@link ChooseAccountFragment}), and then an authentication progress fragment
* ({@link AuthProgressFragment}).
*/
public class AccountActivity extends SherlockFragmentActivity
implements AccountUtils.AuthenticateCallback {
private static final String TAG = makeLogTag(AccountActivity.class);
public static final String EXTRA_FINISH_INTENT
= "com.google.android.iosched.extra.FINISH_INTENT";
private static final int REQUEST_AUTHENTICATE = 100;
private final Handler mHandler = new Handler();
private Account mChosenAccount;
private Intent mFinishIntent;
private boolean mCancelAuth = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
if (getIntent().hasExtra(EXTRA_FINISH_INTENT)) {
mFinishIntent = getIntent().getParcelableExtra(EXTRA_FINISH_INTENT);
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new ChooseAccountFragment(), "choose_account")
.commit();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_AUTHENTICATE) {
if (resultCode == RESULT_OK) {
tryAuthenticate();
} else {
// go back to previous step
mHandler.post(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStack();
}
});
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void tryAuthenticate() {
AccountUtils.tryAuthenticate(AccountActivity.this,
AccountActivity.this,
REQUEST_AUTHENTICATE,
mChosenAccount);
}
@Override
public boolean shouldCancelAuthentication() {
return mCancelAuth;
}
@Override
public void onAuthTokenAvailable(String authToken) {
ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1);
if (mFinishIntent != null) {
mFinishIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mFinishIntent.setAction(Intent.ACTION_MAIN);
mFinishIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mFinishIntent);
}
finish();
}
/**
* A fragment that presents the user with a list of accounts to choose from. Once an account is
* selected, we move on to the login progress fragment ({@link AuthProgressFragment}).
*/
public static class ChooseAccountFragment extends SherlockListFragment {
public ChooseAccountFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
reloadAccountList();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.add_account, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_account) {
Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES,
new String[]{ScheduleContract.CONTENT_AUTHORITY});
startActivity(addAccountIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_login_choose_account, container, false);
TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro);
descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account)));
return rootView;
}
private AccountListAdapter mAccountListAdapter;
private void reloadAccountList() {
if (mAccountListAdapter != null) {
mAccountListAdapter = null;
}
AccountManager am = AccountManager.get(getActivity());
Account[] accounts = am.getAccountsByType(GoogleAccountManager.ACCOUNT_TYPE);
mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts));
setListAdapter(mAccountListAdapter);
}
private class AccountListAdapter extends ArrayAdapter<Account> {
private static final int LAYOUT_RESOURCE = android.R.layout.simple_list_item_1;
public AccountListAdapter(Context context, List<Account> accounts) {
super(context, LAYOUT_RESOURCE, accounts);
}
private class ViewHolder {
TextView text1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Account account = getItem(position);
if (account != null) {
holder.text1.setText(account.name);
} else {
holder.text1.setText("");
}
return convertView;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccountActivity activity = (AccountActivity) getActivity();
ConnectivityManager cm = (ConnectivityManager)
activity.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null || !activeNetwork.isConnected()) {
Toast.makeText(activity, R.string.no_connection_cant_login,
Toast.LENGTH_SHORT).show();
return;
}
activity.mCancelAuth = false;
activity.mChosenAccount = mAccountListAdapter.getItem(position);
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new AuthProgressFragment(),
"loading")
.addToBackStack("choose_account")
.commit();
activity.tryAuthenticate();
}
}
/**
* This fragment shows a login progress spinner. Upon reaching a timeout of 7 seconds (in case
* of a poor network connection), the user can try again.
*/
public static class AuthProgressFragment extends SherlockFragment {
private static final int TRY_AGAIN_DELAY_MILLIS = 7 * 1000; // 7 seconds
private final Handler mHandler = new Handler();
public AuthProgressFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_loading,
container, false);
final View takingAWhilePanel = rootView.findViewById(R.id.taking_a_while_panel);
final View tryAgainButton = rootView.findViewById(R.id.retry_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getFragmentManager().popBackStack();
}
});
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!isAdded()) {
return;
}
takingAWhilePanel.setVisibility(View.VISIBLE);
}
}, TRY_AGAIN_DELAY_MILLIS);
return rootView;
}
@Override
public void onDetach() {
super.onDetach();
((AccountActivity) getActivity()).mCancelAuth = true;
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/AccountActivity.java | Java | asf20 | 11,121 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
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;
/**
* Shows a {@link WebView} with a map of the conference venue.
*/
public class MapFragment extends SherlockFragment {
private static final String TAG = makeLogTag(MapFragment.class);
/**
* When specified, will automatically point the map to the requested room.
*/
public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM";
private static final String SYSTEM_FEATURE_MULTITOUCH
= "android.hardware.touchscreen.multitouch";
private static final String MAP_JSI_NAME = "MAP_CONTAINER";
private static final String MAP_URL = "http://ioschedmap.appspot.com/embed.html";
private static boolean CLEAR_CACHE_ON_LOAD = BuildConfig.DEBUG;
private WebView mWebView;
private View mLoadingSpinner;
private boolean mMapInitialized = false;
public interface Callbacks {
public void onRoomSelected(String roomId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onRoomSelected(String roomId) {
}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
EasyTracker.getTracker().trackView("Map");
LOGD("Tracker", "Map");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner,
container, false);
mLoadingSpinner = root.findViewById(R.id.loading_spinner);
mWebView = (WebView) root.findViewById(R.id.webview);
mWebView.setWebChromeClient(mWebChromeClient);
mWebView.setWebViewClient(mWebViewClient);
return root;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Initialize web view
if (CLEAR_CACHE_ON_LOAD) {
mWebView.clearCache(true);
}
boolean hideZoomControls =
getActivity().getPackageManager().hasSystemFeature(SYSTEM_FEATURE_MULTITOUCH)
&& UIUtils.hasHoneycomb();
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
mWebView.loadUrl(MAP_URL + "?multitouch=" + (hideZoomControls ? 1 : 0));
mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.map, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
mWebView.reload();
return true;
}
return super.onOptionsItemSelected(item);
}
private void runJs(final String js) {
Activity activity = getActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
LOGD(TAG, "Loading javascript:" + js);
mWebView.loadUrl("javascript:" + js);
}
});
}
/**
* Helper method to escape JavaScript strings. Useful when passing strings to a WebView via
* "javascript:" calls.
*/
private static String escapeJsString(String s) {
if (s == null) {
return "";
}
return s.replace("'", "\\'").replace("\"", "\\\"");
}
public void panBy(float xFraction, float yFraction) {
runJs("IoMap.panBy(" + xFraction + "," + yFraction + ");");
}
/**
* I/O Conference Map JavaScript interface.
*/
private interface MapJsi {
public void openContentInfo(final String roomId);
public void onMapReady();
}
private final WebChromeClient mWebChromeClient = new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
LOGD(TAG, "JS Console message: (" + consoleMessage.sourceId() + ": "
+ consoleMessage.lineNumber() + ") " + consoleMessage.message());
return false;
}
};
private final WebViewClient mWebViewClient = new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mLoadingSpinner.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.INVISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mLoadingSpinner.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description,
String failingUrl) {
LOGE(TAG, "Error " + errorCode + ": " + description);
Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description,
Toast.LENGTH_LONG).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
};
private final MapJsi mMapJsiImpl = new MapJsi() {
public void openContentInfo(final String roomId) {
Activity activity = getActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mCallbacks.onRoomSelected(roomId);
}
});
}
public void onMapReady() {
LOGD(TAG, "onMapReady");
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
String showRoomId = null;
if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) {
showRoomId = intent.getStringExtra(EXTRA_ROOM);
}
if (showRoomId != null) {
runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');");
}
mMapInitialized = true;
}
};
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/MapFragment.java | Java | asf20 | 8,494 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this
* activity is forwarded to the fragment as arguments during fragment instantiation. Derived
* activities should only need to implement {@link SimpleSinglePaneActivity#onCreatePane()}.
*/
public abstract class SimpleSinglePaneActivity extends BaseActivity {
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlepane_empty);
if (getIntent().hasExtra(Intent.EXTRA_TITLE)) {
setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE));
}
final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
setTitle(customTitle != null ? customTitle : getTitle());
if (savedInstanceState == null) {
mFragment = onCreatePane();
mFragment.setArguments(intentToFragmentArguments(getIntent()));
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container, mFragment, "single_pane")
.commit();
} else {
mFragment = getSupportFragmentManager().findFragmentByTag("single_pane");
}
}
/**
* Called in <code>onCreate</code> when the fragment constituting this activity is needed.
* The returned fragment's arguments will be set to the intent used to invoke this activity.
*/
protected abstract Fragment onCreatePane();
public Fragment getFragment() {
return mFragment;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SimpleSinglePaneActivity.java | Java | asf20 | 2,407 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.TracksAdapter.TracksQuery;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
/**
* A simple {@link ListFragment} that renders a list of tracks and a map button at the top.
*/
public class ExploreFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private TracksAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new TracksAdapter(getActivity());
setListAdapter(mAdapter);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ListView listView = getListView();
listView.setSelector(android.R.color.transparent);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// As of support library r8, calling initLoader for a fragment in a
// FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be
// dealt to multiple fragments because their mIndex is -1 (haven't been added to the
// activity yet). Thus, we do this in onActivityCreated.
getLoaderManager().initLoader(TracksQuery._TOKEN, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.fragment_list_with_empty_container, container, false);
root.setBackgroundColor(Color.WHITE);
return root;
}
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (getActivity() == null) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(TracksQuery._TOKEN);
if (loader != null) {
loader.forceLoad();
}
}
};
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activity.getContentResolver().registerContentObserver(
ScheduleContract.Sessions.CONTENT_URI, true, mObserver);
}
@Override
public void onDetach() {
super.onDetach();
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
/** {@inheritDoc} */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (mAdapter.isMapItem(position)) {
// Launch map of conference venue
EasyTracker.getTracker().trackEvent(
"Home Screen Dashboard", "Click", "Map", 0L);
startActivity(new Intent(getActivity(),
UIUtils.getMapActivityClass(getActivity())));
return;
}
final Cursor cursor = (Cursor) mAdapter.getItem(position);
final String trackId;
if (cursor != null) {
trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID);
} else {
trackId = ScheduleContract.Tracks.ALL_TRACK_ID;
}
final Intent intent = new Intent(Intent.ACTION_VIEW);
final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId);
intent.setData(trackUri);
startActivity(intent);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
Uri tracksUri = intent.getData();
if (tracksUri == null) {
tracksUri = ScheduleContract.Tracks.CONTENT_URI;
}
// Filter our tracks query to only include those with valid results
String[] projection = TracksAdapter.TracksQuery.PROJECTION;
String selection = null;
return new CursorLoader(getActivity(), tracksUri, projection, selection, null,
ScheduleContract.Tracks.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
mAdapter.setHasMapItem(true);
mAdapter.setHasAllItem(true);
mAdapter.changeCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/ExploreFragment.java | Java | asf20 | 5,900 |
/*
* 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.ui;
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.calendar.SessionAlarmService;
import com.google.android.apps.iosched.calendar.SessionCalendarService;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.FractionalTouchDelegate;
import com.google.android.apps.iosched.util.HelpUtils;
import com.google.android.apps.iosched.util.ImageFetcher;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.android.plus.GooglePlus;
import com.google.api.android.plus.PlusOneButton;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows detail information for a session, including session title, abstract,
* time information, speaker photos and bios, etc.
*
* <p>This fragment is used in a number of activities, including
* {@link com.google.android.apps.iosched.ui.phone.SessionDetailActivity},
* {@link com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity},
* {@link com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity}, etc.
*/
public class SessionDetailFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(SessionDetailFragment.class);
// Set this boolean extra to true to show a variable height header
public static final String EXTRA_VARIABLE_HEIGHT_HEADER =
"com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER";
private String mSessionId;
private Uri mSessionUri;
private long mSessionBlockStart;
private long mSessionBlockEnd;
private String mTitleString;
private String mHashtags;
private String mUrl;
private String mRoomId;
private String mRoomName;
private boolean mStarred;
private boolean mInitStarred;
private MenuItem mShareMenuItem;
private MenuItem mStarMenuItem;
private MenuItem mSocialStreamMenuItem;
private ViewGroup mRootView;
private TextView mTitle;
private TextView mSubtitle;
private PlusOneButton mPlusOneButton;
private TextView mAbstract;
private TextView mRequirements;
private boolean mSessionCursor = false;
private boolean mSpeakersCursor = false;
private boolean mHasSummaryContent = false;
private boolean mVariableHeightHeader = false;
private ImageFetcher mImageFetcher;
private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GooglePlus.initialize(getActivity(), Config.API_KEY, Config.CLIENT_ID);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
mSessionUri = intent.getData();
if (mSessionUri == null) {
return;
}
mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri);
mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false);
LoaderManager manager = getLoaderManager();
manager.restartLoader(SessionsQuery._TOKEN, null, this);
manager.restartLoader(SpeakersQuery._TOKEN, null, this);
mImageFetcher = UIUtils.getImageFetcher(getActivity());
mImageFetcher.setImageFadeIn(false);
setHasOptionsMenu(true);
HelpUtils.maybeShowAddToScheduleTutorial(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null);
mTitle = (TextView) mRootView.findViewById(R.id.session_title);
mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle);
// Larger target triggers plus one button
mPlusOneButton = (PlusOneButton) mRootView.findViewById(R.id.plus_one_button);
final View plusOneParent = mRootView.findViewById(R.id.header_session);
FractionalTouchDelegate.setupDelegate(plusOneParent, mPlusOneButton,
new RectF(0.6f, 0f, 1f, 1.0f));
mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract);
mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements);
if (mVariableHeightHeader) {
View headerView = mRootView.findViewById(R.id.header_session);
ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
headerView.setLayoutParams(layoutParams);
}
return mRootView;
}
@Override
public void onStop() {
super.onStop();
if (mInitStarred != mStarred) {
// Update Calendar event through the Calendar API on Android 4.0 or new versions.
if (UIUtils.hasICS()) {
Intent intent;
if (mStarred) {
// Set up intent to add session to Calendar, if it doesn't exist already.
intent = new Intent(SessionCalendarService.ACTION_ADD_SESSION_CALENDAR,
mSessionUri);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START,
mSessionBlockStart);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END,
mSessionBlockEnd);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_ROOM, mRoomName);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString);
} else {
// Set up intent to remove session from Calendar, if exists.
intent = new Intent(SessionCalendarService.ACTION_REMOVE_SESSION_CALENDAR,
mSessionUri);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START,
mSessionBlockStart);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END,
mSessionBlockEnd);
intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString);
}
intent.setClass(getActivity(), SessionCalendarService.class);
getActivity().startService(intent);
}
if (mStarred && System.currentTimeMillis() < mSessionBlockStart) {
setupNotification();
}
}
}
@Override
public void onPause() {
super.onPause();
mImageFetcher.flushCache();
}
@Override
public void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
private void setupNotification() {
// Schedule an alarm that fires a system notification when expires.
final Context ctx = getActivity();
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, ctx, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd);
ctx.startService(scheduleIntent);
}
/**
* Handle {@link SessionsQuery} {@link Cursor}.
*/
private void onSessionQueryComplete(Cursor cursor) {
mSessionCursor = true;
if (!cursor.moveToFirst()) {
return;
}
mTitleString = cursor.getString(SessionsQuery.TITLE);
// Format time block this session occupies
mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START);
mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
mRoomName = cursor.getString(SessionsQuery.ROOM_NAME);
final String subtitle = UIUtils.formatSessionSubtitle(
mTitleString, mSessionBlockStart, mSessionBlockEnd, mRoomName, getActivity());
mTitle.setText(mTitleString);
mUrl = cursor.getString(SessionsQuery.URL);
if (TextUtils.isEmpty(mUrl)) {
mUrl = "";
}
mHashtags = cursor.getString(SessionsQuery.HASHTAGS);
if (!TextUtils.isEmpty(mHashtags)) {
enableSocialStreamMenuItemDeferred();
}
mRoomId = cursor.getString(SessionsQuery.ROOM_ID);
setupShareMenuItemDeferred();
showStarredDeferred(mInitStarred = (cursor.getInt(SessionsQuery.STARRED) != 0));
final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT);
if (!TextUtils.isEmpty(sessionAbstract)) {
UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract);
mAbstract.setVisibility(View.VISIBLE);
mHasSummaryContent = true;
} else {
mAbstract.setVisibility(View.GONE);
}
mPlusOneButton.setSize(PlusOneButton.Size.TALL);
String url = cursor.getString(SessionsQuery.URL);
if (TextUtils.isEmpty(url)) {
mPlusOneButton.setVisibility(View.GONE);
} else {
mPlusOneButton.setUrl(url);
}
final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block);
final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS);
if (!TextUtils.isEmpty(sessionRequirements)) {
UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements);
requirementsBlock.setVisibility(View.VISIBLE);
mHasSummaryContent = true;
} else {
requirementsBlock.setVisibility(View.GONE);
}
// Show empty message when all data is loaded, and nothing to show
if (mSpeakersCursor && !mHasSummaryContent) {
mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
ViewGroup linksContainer = (ViewGroup) mRootView.findViewById(R.id.links_container);
linksContainer.removeAllViews();
LayoutInflater inflater = getLayoutInflater(null);
boolean hasLinks = false;
final Context context = mRootView.getContext();
// Render I/O live link
final boolean hasLivestream = !TextUtils.isEmpty(
cursor.getString(SessionsQuery.LIVESTREAM_URL));
long currentTimeMillis = UIUtils.getCurrentTime(context);
if (UIUtils.hasHoneycomb() // Needs Honeycomb+ for the live stream
&& hasLivestream
&& currentTimeMillis > mSessionBlockStart
&& currentTimeMillis <= mSessionBlockEnd) {
hasLinks = true;
// Create the link item
ViewGroup linkContainer = (ViewGroup)
inflater.inflate(R.layout.list_item_session_link, linksContainer, false);
((TextView) linkContainer.findViewById(R.id.link_text)).setText(
R.string.session_link_livestream);
linkContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fireLinkEvent(R.string.session_link_livestream);
Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, mSessionUri);
livestreamIntent.setClass(context, SessionLivestreamActivity.class);
startActivity(livestreamIntent);
}
});
linksContainer.addView(linkContainer);
}
// Render normal links
for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) {
final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]);
if (!TextUtils.isEmpty(linkUrl)) {
hasLinks = true;
// Create the link item
ViewGroup linkContainer = (ViewGroup)
inflater.inflate(R.layout.list_item_session_link, linksContainer, false);
((TextView) linkContainer.findViewById(R.id.link_text)).setText(
SessionsQuery.LINKS_TITLES[i]);
final int linkTitleIndex = i;
linkContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.safeOpenLink(context, intent);
}
});
linksContainer.addView(linkContainer);
}
}
// Show past/present/future and livestream status for this block.
UIUtils.updateTimeAndLivestreamBlockUI(context,
mSessionBlockStart, mSessionBlockEnd, hasLivestream,
null, null, mSubtitle, subtitle);
mRootView.findViewById(R.id.session_links_block)
.setVisibility(hasLinks ? View.VISIBLE : View.GONE);
EasyTracker.getTracker().trackView("Session: " + mTitleString);
LOGD("Tracker", "Session: " + mTitleString);
}
private void enableSocialStreamMenuItemDeferred() {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
mSocialStreamMenuItem.setVisible(true);
}
});
tryExecuteDeferredUiOperations();
}
private void showStarredDeferred(final boolean starred) {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
showStarred(starred);
}
});
tryExecuteDeferredUiOperations();
}
private void showStarred(boolean starred) {
mStarMenuItem.setTitle(starred
? R.string.description_remove_schedule
: R.string.description_add_schedule);
mStarMenuItem.setIcon(starred
? R.drawable.ic_action_remove_schedule
: R.drawable.ic_action_add_schedule);
mStarred = starred;
}
private void setupShareMenuItemDeferred() {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
new SessionsHelper(getActivity())
.tryConfigureShareMenuItem(mShareMenuItem, R.string.share_template,
mTitleString, mHashtags, mUrl);
}
});
tryExecuteDeferredUiOperations();
}
private void tryExecuteDeferredUiOperations() {
if (mStarMenuItem != null && mSocialStreamMenuItem != null) {
for (Runnable r : mDeferredUiOperations) {
r.run();
}
mDeferredUiOperations.clear();
}
}
private void onSpeakersQueryComplete(Cursor cursor) {
mSpeakersCursor = true;
// TODO: remove existing speakers from layout, since this cursor might be from a data change
final ViewGroup speakersGroup = (ViewGroup)
mRootView.findViewById(R.id.session_speakers_block);
final LayoutInflater inflater = getActivity().getLayoutInflater();
boolean hasSpeakers = false;
while (cursor.moveToNext()) {
final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME);
if (TextUtils.isEmpty(speakerName)) {
continue;
}
final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL);
final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY);
final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL);
final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT);
String speakerHeader = speakerName;
if (!TextUtils.isEmpty(speakerCompany)) {
speakerHeader += ", " + speakerCompany;
}
final View speakerView = inflater
.inflate(R.layout.speaker_detail, speakersGroup, false);
final TextView speakerHeaderView = (TextView) speakerView
.findViewById(R.id.speaker_header);
final ImageView speakerImageView = (ImageView) speakerView
.findViewById(R.id.speaker_image);
final TextView speakerAbstractView = (TextView) speakerView
.findViewById(R.id.speaker_abstract);
if (!TextUtils.isEmpty(speakerImageUrl)) {
mImageFetcher.loadThumbnailImage(speakerImageUrl, speakerImageView,
R.drawable.person_image_empty);
}
speakerHeaderView.setText(speakerHeader);
speakerImageView.setContentDescription(
getString(R.string.speaker_googleplus_profile, speakerHeader));
UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract);
if (!TextUtils.isEmpty(speakerUrl)) {
speakerImageView.setEnabled(true);
speakerImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(speakerUrl));
speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
UIUtils.safeOpenLink(getActivity(), speakerProfileIntent);
}
});
} else {
speakerImageView.setEnabled(false);
speakerImageView.setOnClickListener(null);
}
speakersGroup.addView(speakerView);
hasSpeakers = true;
mHasSummaryContent = true;
}
speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);
// Show empty message when all data is loaded, and nothing to show
if (mSessionCursor && !mHasSummaryContent) {
mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.session_detail, menu);
mStarMenuItem = menu.findItem(R.id.menu_star);
mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream);
mShareMenuItem = menu.findItem(R.id.menu_share);
tryExecuteDeferredUiOperations();
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SessionsHelper helper = new SessionsHelper(getActivity());
switch (item.getItemId()) {
case R.id.menu_map:
EasyTracker.getTracker().trackEvent(
"Session", "Map", mTitleString, 0L);
LOGD("Tracker", "Map: " + mTitleString);
helper.startMapActivity(mRoomId);
return true;
case R.id.menu_star:
boolean star = !mStarred;
showStarred(star);
helper.setSessionStarred(mSessionUri, star, mTitleString);
Toast.makeText(
getActivity(),
getResources().getQuantityString(star
? R.plurals.toast_added_to_schedule
: R.plurals.toast_removed_from_schedule, 1, 1),
Toast.LENGTH_SHORT).show();
EasyTracker.getTracker().trackEvent(
"Session", star ? "Starred" : "Unstarred", mTitleString, 0L);
LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString);
return true;
case R.id.menu_share:
// On ICS+ devices, we normally won't reach this as ShareActionProvider will handle
// sharing.
helper.shareSession(getActivity(), R.string.share_template, mTitleString,
mHashtags, mUrl);
return true;
case R.id.menu_social_stream:
EasyTracker.getTracker().trackEvent(
"Session", "Stream", mTitleString, 0L);
LOGD("Tracker", "Stream: " + mTitleString);
helper.startSocialStream(UIUtils.getSessionHashtagsString(mHashtags));
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* Event structure:
* Category -> "Session Details"
* Action -> Link Text
* Label -> Session's Title
* Value -> 0.
*/
public void fireLinkEvent(int actionId) {
EasyTracker.getTracker().trackEvent(
"Session", getActivity().getString(actionId), mTitleString, 0L);
LOGD("Tracker", getActivity().getString(actionId) + ": " + mTitleString);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
CursorLoader loader = null;
if (id == SessionsQuery._TOKEN){
loader = new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null,
null, null);
} else if (id == SpeakersQuery._TOKEN && mSessionUri != null){
Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId);
loader = new CursorLoader(getActivity(), speakersUri, SpeakersQuery.PROJECTION, null,
null, null);
}
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
if (loader.getId() == SessionsQuery._TOKEN) {
onSessionQueryComplete(cursor);
} else if (loader.getId() == SpeakersQuery._TOKEN) {
onSpeakersQueryComplete(cursor);
} else {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters.
*/
private interface SessionsQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Sessions.SESSION_LEVEL,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_ABSTRACT,
ScheduleContract.Sessions.SESSION_REQUIREMENTS,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_URL,
ScheduleContract.Sessions.SESSION_YOUTUBE_URL,
ScheduleContract.Sessions.SESSION_PDF_URL,
ScheduleContract.Sessions.SESSION_NOTES_URL,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
ScheduleContract.Sessions.ROOM_ID,
ScheduleContract.Rooms.ROOM_NAME,
};
int BLOCK_START = 0;
int BLOCK_END = 1;
int LEVEL = 2;
int TITLE = 3;
int ABSTRACT = 4;
int REQUIREMENTS = 5;
int STARRED = 6;
int HASHTAGS = 7;
int URL = 8;
int YOUTUBE_URL = 9;
int PDF_URL = 10;
int NOTES_URL = 11;
int LIVESTREAM_URL = 12;
int ROOM_ID = 13;
int ROOM_NAME = 14;
int[] LINKS_INDICES = {
URL,
YOUTUBE_URL,
PDF_URL,
NOTES_URL,
};
int[] LINKS_TITLES = {
R.string.session_link_main,
R.string.session_link_youtube,
R.string.session_link_pdf,
R.string.session_link_notes,
};
}
private interface SpeakersQuery {
int _TOKEN = 0x3;
String[] PROJECTION = {
ScheduleContract.Speakers.SPEAKER_NAME,
ScheduleContract.Speakers.SPEAKER_IMAGE_URL,
ScheduleContract.Speakers.SPEAKER_COMPANY,
ScheduleContract.Speakers.SPEAKER_ABSTRACT,
ScheduleContract.Speakers.SPEAKER_URL,
};
int SPEAKER_NAME = 0;
int SPEAKER_IMAGE_URL = 1;
int SPEAKER_COMPANY = 2;
int SPEAKER_ABSTRACT = 3;
int SPEAKER_URL = 4;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SessionDetailFragment.java | Java | asf20 | 26,488 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.util.UIUtils;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A fragment used in {@link HomeActivity} that shows either a countdown,
* announcements, or 'thank you' text, at different times (before/during/after
* the conference).
*/
public class WhatsOnFragment extends Fragment implements
LoaderCallbacks<Cursor> {
private Handler mHandler = new Handler();
private TextView mCountdownTextView;
private ViewGroup mRootView;
private Cursor mAnnouncementsCursor;
private LayoutInflater mInflater;
private int mTitleCol = -1;
private int mDateCol = -1;
private int mUrlCol = -1;
private static final int ANNOUNCEMENTS_LOADER_ID = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on,
container);
refresh();
return mRootView;
}
@Override
public void onDetach() {
super.onDetach();
mHandler.removeCallbacks(mCountdownRunnable);
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
private void refresh() {
mHandler.removeCallbacks(mCountdownRunnable);
mRootView.removeAllViews();
final long currentTimeMillis = UIUtils.getCurrentTime(getActivity());
// Show Loading... and load the view corresponding to the current state
if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) {
setupBefore();
} else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) {
setupAfter();
} else {
setupDuring();
}
}
private void setupBefore() {
// Before conference, show countdown.
mCountdownTextView = (TextView) mInflater
.inflate(R.layout.whats_on_countdown, mRootView, false);
mRootView.addView(mCountdownTextView);
mHandler.post(mCountdownRunnable);
}
private void setupAfter() {
// After conference, show canned text.
mInflater.inflate(R.layout.whats_on_thank_you,
mRootView, true);
}
private void setupDuring() {
// Start background query to load announcements
getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this);
getActivity().getContentResolver().registerContentObserver(
Announcements.CONTENT_URI, true, mObserver);
}
/**
* Event that updates countdown timer. Posts itself again to
* {@link #mHandler} to continue updating time.
*/
private final Runnable mCountdownRunnable = new Runnable() {
public void run() {
int remainingSec = (int) Math.max(0,
(UIUtils.CONFERENCE_START_MILLIS - UIUtils
.getCurrentTime(getActivity())) / 1000);
final boolean conferenceStarted = remainingSec == 0;
if (conferenceStarted) {
// Conference started while in countdown mode, switch modes and
// bail on future countdown updates.
mHandler.postDelayed(new Runnable() {
public void run() {
refresh();
}
}, 100);
return;
}
final int secs = remainingSec % 86400;
final int days = remainingSec / 86400;
final String str;
if (days == 0) {
str = getResources().getString(
R.string.whats_on_countdown_title_0,
DateUtils.formatElapsedTime(secs));
} else {
str = getResources().getQuantityString(
R.plurals.whats_on_countdown_title, days, days,
DateUtils.formatElapsedTime(secs));
}
mCountdownTextView.setText(str);
// Repost ourselves to keep updating countdown
mHandler.postDelayed(mCountdownRunnable, 1000);
}
};
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(),
Announcements.CONTENT_URI, null, null, null,
Announcements.ANNOUNCEMENT_DATE + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (getActivity() == null) {
return;
}
if (data != null && data.getCount() > 0) {
mTitleCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_TITLE);
mDateCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_DATE);
mUrlCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_URL);
showAnnouncements(data);
} else {
showNoAnnouncements();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAnnouncementsCursor = null;
}
/**
* Show the the announcements
*/
private void showAnnouncements(Cursor announcements) {
mAnnouncementsCursor = announcements;
ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate(
R.layout.whats_on_announcements, mRootView, false);
final ViewPager pager = (ViewPager) announcementsRootView.findViewById(
R.id.announcements_pager);
final View previousButton = announcementsRootView.findViewById(
R.id.announcements_previous_button);
final View nextButton = announcementsRootView.findViewById(
R.id.announcements_next_button);
final PagerAdapter adapter = new AnnouncementsAdapter();
pager.setAdapter(adapter);
pager.setPageMargin(
getResources().getDimensionPixelSize(R.dimen.announcements_margin_width));
pager.setPageMarginDrawable(R.drawable.announcements_divider);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
previousButton.setEnabled(position > 0);
nextButton.setEnabled(position < adapter.getCount() - 1);
}
});
previousButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(pager.getCurrentItem() - 1);
}
});
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
}
});
previousButton.setEnabled(false);
nextButton.setEnabled(adapter.getCount() > 1);
mRootView.removeAllViews();
mRootView.addView(announcementsRootView);
}
/**
* Show a placeholder message
*/
private void showNoAnnouncements() {
mInflater.inflate(R.layout.empty_announcements, mRootView, true);
}
public class AnnouncementsAdapter extends PagerAdapter {
@Override
public Object instantiateItem(ViewGroup pager, int position) {
mAnnouncementsCursor.moveToPosition(position);
LinearLayout rootView = (LinearLayout) mInflater.inflate(
R.layout.pager_item_announcement, pager, false);
TextView titleView = (TextView) rootView.findViewById(R.id.announcement_title);
TextView subtitleView = (TextView) rootView.findViewById(R.id.announcement_ago);
titleView.setText(mAnnouncementsCursor.getString(mTitleCol));
final long date = mAnnouncementsCursor.getLong(mDateCol);
final String when = UIUtils.getTimeAgo(date, getActivity());
final String url = mAnnouncementsCursor.getString(mUrlCol);
subtitleView.setText(when);
rootView.setTag(url);
if (!TextUtils.isEmpty(url)) {
rootView.setClickable(true);
rootView.setOnClickListener(mAnnouncementClick);
} else {
rootView.setClickable(false);
}
pager.addView(rootView, 0);
return rootView;
}
private final OnClickListener mAnnouncementClick = new OnClickListener() {
@Override
public void onClick(View v) {
String url = (String) v.getTag();
if (!TextUtils.isEmpty(url)) {
UIUtils.safeOpenLink(getActivity(),
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
}
};
@Override
public void destroyItem(ViewGroup pager, int position, Object view) {
pager.removeView((View) view);
}
@Override
public int getCount() {
return mAnnouncementsCursor.getCount();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (getActivity() == null) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID);
if (loader != null) {
loader.forceLoad();
}
}
};
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/WhatsOnFragment.java | Java | asf20 | 11,175 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.ImageFetcher;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows detail information for a developer sandbox company, including
* company name, description, logo, etc.
*/
public class VendorDetailFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(VendorDetailFragment.class);
private Uri mVendorUri;
private TextView mName;
private ImageView mLogo;
private TextView mUrl;
private TextView mDesc;
private ImageFetcher mImageFetcher;
public interface Callbacks {
public void onTrackIdAvailable(String trackId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onTrackIdAvailable(String trackId) {}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
mVendorUri = intent.getData();
if (mVendorUri == null) {
return;
}
mImageFetcher = UIUtils.getImageFetcher(getActivity());
mImageFetcher.setImageFadeIn(false);
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mVendorUri == null) {
return;
}
// Start background query to load vendor details
getLoaderManager().initLoader(VendorsQuery._TOKEN, null, this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onPause() {
super.onPause();
mImageFetcher.flushCache();
}
@Override
public void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null);
mName = (TextView) rootView.findViewById(R.id.vendor_name);
mLogo = (ImageView) rootView.findViewById(R.id.vendor_logo);
mUrl = (TextView) rootView.findViewById(R.id.vendor_url);
mDesc = (TextView) rootView.findViewById(R.id.vendor_desc);
return rootView;
}
public void buildUiFromCursor(Cursor cursor) {
if (getActivity() == null) {
return;
}
if (!cursor.moveToFirst()) {
return;
}
String nameString = cursor.getString(VendorsQuery.NAME);
mName.setText(nameString);
// Start background fetch to load vendor logo
final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL);
if (!TextUtils.isEmpty(logoUrl)) {
mImageFetcher.loadThumbnailImage(logoUrl, mLogo, R.drawable.sandbox_logo_empty);
}
mUrl.setText(cursor.getString(VendorsQuery.URL));
mDesc.setText(cursor.getString(VendorsQuery.DESC));
EasyTracker.getTracker().trackView("Sandbox Vendor: " + nameString);
LOGD("Tracker", "Sandbox Vendor: " + nameString);
mCallbacks.onTrackIdAvailable(cursor.getString(VendorsQuery.TRACK_ID));
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mVendorUri, VendorsQuery.PROJECTION, null, null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
buildUiFromCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors}
* query parameters.
*/
private interface VendorsQuery {
int _TOKEN = 0x4;
String[] PROJECTION = {
ScheduleContract.Vendors.VENDOR_NAME,
ScheduleContract.Vendors.VENDOR_DESC,
ScheduleContract.Vendors.VENDOR_URL,
ScheduleContract.Vendors.VENDOR_LOGO_URL,
ScheduleContract.Vendors.TRACK_ID,
};
int NAME = 0;
int DESC = 1;
int URL = 2;
int LOGO_URL = 3;
int TRACK_ID = 4;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/VendorDetailFragment.java | Java | asf20 | 6,277 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.gtv.GoogleTVSessionLivestreamActivity;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.HelpUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.gcm.GCMRegistrar;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.widget.SearchView;
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.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* The landing screen for the app, once the user has logged in.
*
* <p>This activity uses different layouts to present its various fragments, depending on the
* device configuration. {@link MyScheduleFragment}, {@link ExploreFragment}, and
* {@link SocialStreamFragment} are always available to the user. {@link WhatsOnFragment} is
* always available on tablets and phones in portrait, but is hidden on phones held in landscape.
*
* <p>On phone-size screens, the three fragments are represented by {@link ActionBar} tabs, and
* can are held inside a {@link ViewPager} to allow horizontal swiping.
*
* <p>On tablets, the three fragments are always visible and are presented as either three panes
* (landscape) or a grid (portrait).
*/
public class HomeActivity extends BaseActivity implements
ActionBar.TabListener,
ViewPager.OnPageChangeListener {
private static final String TAG = makeLogTag(HomeActivity.class);
private Object mSyncObserverHandle;
private MyScheduleFragment mMyScheduleFragment;
private ExploreFragment mExploreFragment;
private SocialStreamFragment mSocialStreamFragment;
private ViewPager mViewPager;
private Menu mOptionsMenu;
private AsyncTask<Void, Void, Void> mGCMRegisterTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We're on Google TV; immediately short-circuit the normal behavior and show the
// Google TV-specific landing page.
if (UIUtils.isGoogleTV(this)) {
Intent intent = new Intent(HomeActivity.this, GoogleTVSessionLivestreamActivity.class);
startActivity(intent);
finish();
}
if (isFinishing()) {
return;
}
UIUtils.enableDisableActivities(this);
EasyTracker.getTracker().setContext(this);
setContentView(R.layout.activity_home);
FragmentManager fm = getSupportFragmentManager();
mViewPager = (ViewPager) findViewById(R.id.pager);
String homeScreenLabel;
if (mViewPager != null) {
// Phone setup
mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(this);
mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
mViewPager.setPageMargin(getResources()
.getDimensionPixelSize(R.dimen.page_margin_width));
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_my_schedule)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_explore)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_stream)
.setTabListener(this));
homeScreenLabel = getString(R.string.title_my_schedule);
} else {
mExploreFragment = (ExploreFragment) fm.findFragmentById(R.id.fragment_tracks);
mMyScheduleFragment = (MyScheduleFragment) fm.findFragmentById(
R.id.fragment_my_schedule);
mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream);
homeScreenLabel = "Home";
}
getSupportActionBar().setHomeButtonEnabled(false);
EasyTracker.getTracker().trackView(homeScreenLabel);
LOGD("Tracker", homeScreenLabel);
// Sync data on load
if (savedInstanceState == null) {
triggerRefresh();
registerGCMClient();
}
}
private void registerGCMClient() {
GCMRegistrar.checkDevice(this);
if (BuildConfig.DEBUG) {
GCMRegistrar.checkManifest(this);
}
final String regId = GCMRegistrar.getRegistrationId(this);
if (TextUtils.isEmpty(regId)) {
// Automatically registers application on startup.
GCMRegistrar.register(this, Config.GCM_SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration
LOGI(TAG, "Already registered on the GCM server");
} else {
// Try to register again, but not on the UI thread.
// It's also necessary to cancel the task in onDestroy().
mGCMRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(HomeActivity.this, regId);
if (!registered) {
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
GCMRegistrar.unregister(HomeActivity.this);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mGCMRegisterTask = null;
}
};
mGCMRegisterTask.execute(null, null, null);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mGCMRegisterTask != null) {
mGCMRegisterTask.cancel(true);
}
try {
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
LOGW(TAG, "GCM unregistration error", e);
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
getSupportActionBar().setSelectedNavigationItem(position);
int titleId = -1;
switch (position) {
case 0:
titleId = R.string.title_my_schedule;
break;
case 1:
titleId = R.string.title_explore;
break;
case 2:
titleId = R.string.title_stream;
break;
}
String title = getString(titleId);
EasyTracker.getTracker().trackView(title);
LOGD("Tracker", title);
}
@Override
public void onPageScrollStateChanged(int i) {
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Since the pager fragments don't have known tags or IDs, the only way to persist the
// reference is to use putFragment/getFragment. Remember, we're not persisting the exact
// Fragment instance. This mechanism simply gives us a way to persist access to the
// 'current' fragment instance for the given fragment (which changes across orientation
// changes).
//
// The outcome of all this is that the "Refresh" menu button refreshes the stream across
// orientation changes.
if (mSocialStreamFragment != null) {
getSupportFragmentManager().putFragment(outState, "stream_fragment",
mSocialStreamFragment);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (mSocialStreamFragment == null) {
mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager()
.getFragment(savedInstanceState, "stream_fragment");
}
}
private class HomePagerAdapter extends FragmentPagerAdapter {
public HomePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return (mMyScheduleFragment = new MyScheduleFragment());
case 1:
return (mExploreFragment = new ExploreFragment());
case 2:
return (mSocialStreamFragment = new SocialStreamFragment());
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
mOptionsMenu = menu;
getSupportMenuInflater().inflate(R.menu.home, menu);
setupSearchMenuItem(menu);
if (!BeamUtils.isBeamUnlocked(this)) {
// Only show Beam unlocked after first Beam
MenuItem beamItem = menu.findItem(R.id.menu_beam);
if (beamItem != null) {
menu.removeItem(beamItem.getItemId());
}
}
return true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupSearchMenuItem(Menu menu) {
MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
triggerRefresh();
return true;
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
case R.id.menu_about:
HelpUtils.showAbout(this);
return true;
case R.id.menu_sign_out:
AccountUtils.signOut(this);
finish();
return true;
case R.id.menu_beam:
Intent beamIntent = new Intent(this, BeamActivity.class);
startActivity(beamIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void triggerRefresh() {
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
if (!UIUtils.isGoogleTV(this)) {
ContentResolver.requestSync(
new Account(AccountUtils.getChosenAccountName(this),
GoogleAccountManager.ACCOUNT_TYPE),
ScheduleContract.CONTENT_AUTHORITY, extras);
}
if (mSocialStreamFragment != null) {
mSocialStreamFragment.refresh();
}
}
@Override
protected void onPause() {
super.onPause();
if (mSyncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
mSyncObserverHandle = null;
}
}
@Override
protected void onResume() {
super.onResume();
mSyncStatusObserver.onStatusChanged(0);
// Watch for sync state changes
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
}
public void setRefreshActionButtonState(boolean refreshing) {
if (mOptionsMenu == null) {
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
if (refreshItem != null) {
if (refreshing) {
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
} else {
refreshItem.setActionView(null);
}
}
}
private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
@Override
public void onStatusChanged(int which) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String accountName = AccountUtils.getChosenAccountName(HomeActivity.this);
if (TextUtils.isEmpty(accountName)) {
setRefreshActionButtonState(false);
return;
}
Account account = new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE);
boolean syncActive = ContentResolver.isSyncActive(
account, ScheduleContract.CONTENT_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, ScheduleContract.CONTENT_AUTHORITY);
setRefreshActionButtonState(syncActive || syncPending);
}
});
}
};
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/HomeActivity.java | Java | asf20 | 16,365 |
/*
* 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.ui.tablet;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.BaseActivity;
import com.google.android.apps.iosched.ui.SessionDetailFragment;
import com.google.android.apps.iosched.ui.SessionsFragment;
import com.google.android.apps.iosched.ui.TrackInfoHelperFragment;
import com.google.android.apps.iosched.ui.VendorDetailFragment;
import com.google.android.apps.iosched.ui.VendorsFragment;
import com.google.android.apps.iosched.ui.widget.ShowHideMasterLayout;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.SearchView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
/**
* A multi-pane activity, consisting of a {@link TracksDropdownFragment} (top-left), a
* {@link SessionsFragment} or {@link VendorsFragment} (bottom-left), and
* a {@link SessionDetailFragment} or {@link VendorDetailFragment} (right pane).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SessionsVendorsMultiPaneActivity extends BaseActivity implements
ActionBar.TabListener,
SessionsFragment.Callbacks,
VendorsFragment.Callbacks,
VendorDetailFragment.Callbacks,
TracksDropdownFragment.Callbacks,
TrackInfoHelperFragment.Callbacks {
public static final String EXTRA_MASTER_URI =
"com.google.android.apps.iosched.extra.MASTER_URI";
private static final String STATE_VIEW_TYPE = "view_type";
private TracksDropdownFragment mTracksDropdownFragment;
private Fragment mDetailFragment;
private boolean mFullUI = false;
private ShowHideMasterLayout mShowHideMasterLayout;
private String mViewType;
private boolean mInitialTabSelect = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) {
BeamUtils.setBeamUnlocked(this);
showFirstBeamDialog();
}
BeamUtils.tryUpdateIntentFromBeam(this);
super.onCreate(savedInstanceState);
trySetBeamCallback();
setContentView(R.layout.activity_sessions_vendors);
final FragmentManager fm = getSupportFragmentManager();
mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById(
R.id.fragment_tracks_dropdown);
mShowHideMasterLayout = (ShowHideMasterLayout) findViewById(R.id.show_hide_master_layout);
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.setFlingToExposeMasterEnabled(true);
}
routeIntent(getIntent(), savedInstanceState != null);
if (savedInstanceState != null) {
if (mFullUI) {
getSupportActionBar().setSelectedNavigationItem(
TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(
savedInstanceState.getString(STATE_VIEW_TYPE)) ? 0 : 1);
}
mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail);
updateDetailBackground();
}
// This flag prevents onTabSelected from triggering extra master pane reloads
// unless it's actually being triggered by the user (and not automatically by
// the system)
mInitialTabSelect = false;
EasyTracker.getTracker().setContext(this);
}
private void routeIntent(Intent intent, boolean updateSurfaceOnly) {
Uri uri = intent.getData();
if (uri == null) {
return;
}
if (intent.hasExtra(Intent.EXTRA_TITLE)) {
setTitle(intent.getStringExtra(Intent.EXTRA_TITLE));
}
String mimeType = getContentResolver().getType(uri);
if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Load track details
showFullUI(true);
if (!updateSurfaceOnly) {
// TODO: don't assume the URI will contain the track ID
String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri);
loadTrackList(TracksDropdownFragment.VIEW_TYPE_SESSIONS, selectedTrackId);
onTrackSelected(selectedTrackId);
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE);
}
}
} else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) {
// Load a session list, hiding the tracks dropdown and the tabs
mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS;
showFullUI(false);
if (!updateSurfaceOnly) {
loadSessionList(uri, null);
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE);
}
}
} else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Load session details
if (intent.hasExtra(EXTRA_MASTER_URI)) {
mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS;
showFullUI(false);
if (!updateSurfaceOnly) {
loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI),
ScheduleContract.Sessions.getSessionId(uri));
loadSessionDetail(uri);
}
} else {
mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo...
showFullUI(true);
if (!updateSurfaceOnly) {
loadSessionDetail(uri);
loadTrackInfoFromSessionUri(uri);
}
}
} else if (ScheduleContract.Vendors.CONTENT_TYPE.equals(mimeType)) {
// Load a vendor list
mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS;
showFullUI(false);
if (!updateSurfaceOnly) {
loadVendorList(uri, null);
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE);
}
}
} else if (ScheduleContract.Vendors.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Load vendor details
mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS;
showFullUI(false);
if (!updateSurfaceOnly) {
Uri masterUri = (Uri) intent.getParcelableExtra(EXTRA_MASTER_URI);
if (masterUri == null) {
masterUri = ScheduleContract.Vendors.CONTENT_URI;
}
loadVendorList(masterUri, ScheduleContract.Vendors.getVendorId(uri));
loadVendorDetail(uri);
}
}
updateDetailBackground();
}
private void showFullUI(boolean fullUI) {
mFullUI = fullUI;
final ActionBar actionBar = getSupportActionBar();
final FragmentManager fm = getSupportFragmentManager();
if (fullUI) {
actionBar.removeAllTabs();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_sessions)
.setTag(TracksDropdownFragment.VIEW_TYPE_SESSIONS)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_vendors)
.setTag(TracksDropdownFragment.VIEW_TYPE_VENDORS)
.setTabListener(this));
fm.beginTransaction()
.show(fm.findFragmentById(R.id.fragment_tracks_dropdown))
.commit();
} else {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
fm.beginTransaction()
.hide(fm.findFragmentById(R.id.fragment_tracks_dropdown))
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mShowHideMasterLayout != null && !mShowHideMasterLayout.isMasterVisible()) {
// If showing the detail view, pressing Up should show the master pane.
mShowHideMasterLayout.showMaster(true, 0);
return true;
}
break;
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(STATE_VIEW_TYPE, mViewType);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
loadTrackList((String) tab.getTag());
if (!mInitialTabSelect) {
onTrackSelected(mTracksDropdownFragment.getSelectedTrackId());
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(true, 0);
}
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
private void loadTrackList(String viewType) {
loadTrackList(viewType, null);
}
private void loadTrackList(String viewType, String selectTrackId) {
if (mDetailFragment != null && !mViewType.equals(viewType)) {
getSupportFragmentManager().beginTransaction()
.remove(mDetailFragment)
.commit();
mDetailFragment = null;
}
mViewType = viewType;
if (selectTrackId != null) {
mTracksDropdownFragment.loadTrackList(viewType, selectTrackId);
} else {
mTracksDropdownFragment.loadTrackList(viewType);
}
updateDetailBackground();
}
private void updateDetailBackground() {
if (mDetailFragment == null) {
if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) {
findViewById(R.id.fragment_container_detail).setBackgroundResource(
R.drawable.grey_frame_on_white_empty_sessions);
} else {
findViewById(R.id.fragment_container_detail).setBackgroundResource(
R.drawable.grey_frame_on_white_empty_sandbox);
}
} else {
findViewById(R.id.fragment_container_detail).setBackgroundResource(
R.drawable.grey_frame_on_white);
}
}
private void loadSessionList(Uri sessionsUri, String selectSessionId) {
SessionsFragment fragment = new SessionsFragment();
fragment.setSelectedSessionId(selectSessionId);
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, sessionsUri)));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_master, fragment)
.commit();
}
private void loadSessionDetail(Uri sessionUri) {
BeamUtils.setBeamSessionUri(this, sessionUri);
SessionDetailFragment fragment = new SessionDetailFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, sessionUri)));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.commit();
mDetailFragment = fragment;
updateDetailBackground();
// If loading session details in portrait, hide the master pane
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(false, 0);
}
}
private void loadVendorList(Uri vendorsUri, String selectVendorId) {
VendorsFragment fragment = new VendorsFragment();
fragment.setSelectedVendorId(selectVendorId);
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, vendorsUri)));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_master, fragment)
.commit();
}
private void loadVendorDetail(Uri vendorUri) {
VendorDetailFragment fragment = new VendorDetailFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, vendorUri)));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.commit();
mDetailFragment = fragment;
updateDetailBackground();
// If loading session details in portrait, hide the master pane
if (mShowHideMasterLayout != null) {
mShowHideMasterLayout.showMaster(false, 0);
}
}
@Override
public void onTrackNameAvailable(String trackId, String trackName) {
String trackType;
if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) {
trackType = getString(R.string.title_sessions);
} else {
trackType = getString(R.string.title_vendors);
}
EasyTracker.getTracker().trackView(trackType + ": " + getTitle());
LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName());
}
@Override
public void onTrackSelected(String trackId) {
boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId));
if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) {
loadSessionList(allTracks
? ScheduleContract.Sessions.CONTENT_URI
: ScheduleContract.Tracks.buildSessionsUri(trackId), null);
} else {
loadVendorList(allTracks
? ScheduleContract.Vendors.CONTENT_URI
: ScheduleContract.Tracks.buildVendorsUri(trackId), null);
}
}
@Override
public boolean onSessionSelected(String sessionId) {
loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId));
return true;
}
@Override
public boolean onVendorSelected(String vendorId) {
loadVendorDetail(ScheduleContract.Vendors.buildVendorUri(vendorId));
return true;
}
private TrackInfoHelperFragment mTrackInfoHelperFragment;
private String mTrackInfoLoadCookie;
private void loadTrackInfoFromSessionUri(Uri sessionUri) {
mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri);
Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri(
ScheduleContract.Sessions.getSessionId(sessionUri));
android.support.v4.app.FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
if (mTrackInfoHelperFragment != null) {
ft.remove(mTrackInfoHelperFragment);
}
mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri);
ft.add(mTrackInfoHelperFragment, "track_info").commit();
}
@Override
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) {
loadTrackList(mViewType, trackId);
boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId));
if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) {
loadSessionList(allTracks
? ScheduleContract.Sessions.CONTENT_URI
: ScheduleContract.Tracks.buildSessionsUri(trackId),
mTrackInfoLoadCookie);
} else {
loadVendorList(allTracks
? ScheduleContract.Vendors.CONTENT_URI
: ScheduleContract.Tracks.buildVendorsUri(trackId),
mTrackInfoLoadCookie);
}
}
@Override
public void onTrackIdAvailable(String trackId) {
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void trySetBeamCallback() {
if (UIUtils.hasICS()) {
BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() {
@Override
public void onNdefPushComplete(NfcEvent event) {
// Beam has been sent
if (!BeamUtils.isBeamUnlocked(SessionsVendorsMultiPaneActivity.this)) {
BeamUtils.setBeamUnlocked(SessionsVendorsMultiPaneActivity.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
showFirstBeamDialog();
}
});
}
}
});
}
}
private void showFirstBeamDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.just_beamed)
.setMessage(R.string.beam_unlocked_session)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(SessionsVendorsMultiPaneActivity.this);
di.dismiss();
}
})
.create()
.show();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/tablet/SessionsVendorsMultiPaneActivity.java | Java | asf20 | 20,162 |
/*
* 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.ui.tablet;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.TracksAdapter;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockFragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
* A tablet-specific fragment that emulates a giant {@link android.widget.Spinner}-like widget.
* When touched, it shows a {@link ListPopupWindow} containing a list of tracks,
* using {@link TracksAdapter}. Requires API level 11 or later since {@link ListPopupWindow} is
* API level 11+.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TracksDropdownFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor>,
AdapterView.OnItemClickListener,
PopupWindow.OnDismissListener {
public static final String VIEW_TYPE_SESSIONS = "sessions";
public static final String VIEW_TYPE_VENDORS = "vendors";
private static final String STATE_VIEW_TYPE = "viewType";
private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId";
private TracksAdapter mAdapter;
private String mViewType;
private Handler mHandler = new Handler();
private ListPopupWindow mListPopupWindow;
private ViewGroup mRootView;
private TextView mTitle;
private TextView mAbstract;
private String mTrackId;
public interface Callbacks {
public void onTrackSelected(String trackId);
public void onTrackNameAvailable(String trackId, String trackName);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onTrackSelected(String trackId) {
}
@Override
public void onTrackNameAvailable(String trackId, String trackName) {}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new TracksAdapter(getActivity());
if (savedInstanceState != null) {
// Since this fragment doesn't rely on fragment arguments, we must
// handle
// state restores and saves ourselves.
mViewType = savedInstanceState.getString(STATE_VIEW_TYPE);
mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(STATE_VIEW_TYPE, mViewType);
outState.putString(STATE_SELECTED_TRACK_ID, mTrackId);
}
public String getSelectedTrackId() {
return mTrackId;
}
public void selectTrack(String trackId) {
loadTrackList(mViewType, trackId);
}
public void loadTrackList(String viewType) {
loadTrackList(viewType, mTrackId);
}
public void loadTrackList(String viewType, String selectTrackId) {
// Teardown from previous arguments
if (mListPopupWindow != null) {
mListPopupWindow.setAdapter(null);
}
mViewType = viewType;
mTrackId = selectTrackId;
// Start background query to load tracks
getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null);
mTitle = (TextView) mRootView.findViewById(R.id.track_title);
mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract);
mRootView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mListPopupWindow = new ListPopupWindow(getActivity());
mListPopupWindow.setAdapter(mAdapter);
mListPopupWindow.setModal(true);
mListPopupWindow.setContentWidth(
getResources().getDimensionPixelSize(R.dimen.track_dropdown_width));
mListPopupWindow.setAnchorView(mRootView);
mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this);
mListPopupWindow.show();
mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this);
}
});
return mRootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
if (mListPopupWindow != null) {
mListPopupWindow.dismiss();
}
}
/** {@inheritDoc} */
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Cursor cursor = (Cursor) mAdapter.getItem(position);
loadTrack(cursor, true);
if (mListPopupWindow != null) {
mListPopupWindow.dismiss();
}
}
public String getTrackName() {
return (String) mTitle.getText();
}
private void loadTrack(Cursor cursor, boolean triggerCallback) {
final int trackColor;
final Resources res = getResources();
if (cursor != null) {
trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR);
mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID);
mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME));
mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT));
} else {
trackColor = res.getColor(R.color.all_track_color);
mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID;
mTitle.setText(VIEW_TYPE_SESSIONS.equals(mViewType)
? R.string.all_tracks_sessions
: R.string.all_tracks_vendors);
mAbstract.setText(VIEW_TYPE_SESSIONS.equals(mViewType)
? R.string.all_tracks_subtitle_sessions
: R.string.all_tracks_subtitle_vendors);
}
boolean isDark = UIUtils.isColorDark(trackColor);
mRootView.setBackgroundColor(trackColor);
if (isDark) {
mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse));
mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse));
mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource(
R.drawable.track_dropdown_arrow_light);
} else {
mTitle.setTextColor(res.getColor(R.color.body_text_1));
mAbstract.setTextColor(res.getColor(R.color.body_text_2));
mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource(
R.drawable.track_dropdown_arrow_dark);
}
mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString());
if (triggerCallback) {
mHandler.post(new Runnable() {
@Override
public void run() {
mCallbacks.onTrackSelected(mTrackId);
}
});
}
}
public void onDismiss() {
mListPopupWindow = null;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
// Filter our tracks query to only include those with valid results
String[] projection = TracksAdapter.TracksQuery.PROJECTION;
String selection = null;
if (VIEW_TYPE_SESSIONS.equals(mViewType)) {
// Only show tracks with at least one session
projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT;
selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0";
} else if (VIEW_TYPE_VENDORS.equals(mViewType)) {
// Only show tracks with at least one vendor
projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT;
selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0";
}
return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI,
projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null || cursor == null) {
return;
}
boolean trackLoaded = false;
if (mTrackId != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) {
loadTrack(cursor, false);
trackLoaded = true;
break;
}
cursor.moveToNext();
}
}
if (!trackLoaded) {
loadTrack(null, false);
}
mAdapter.setHasAllItem(true);
mAdapter.changeCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursor) {
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/tablet/TracksDropdownFragment.java | Java | asf20 | 10,527 |
/*
* 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.ui.tablet;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.BaseActivity;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SessionDetailFragment;
import com.google.android.apps.iosched.ui.SessionsFragment;
import com.google.android.apps.iosched.ui.VendorDetailFragment;
import com.google.android.apps.iosched.ui.VendorsFragment;
import android.annotation.TargetApi;
import android.app.FragmentBreadCrumbs;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
/**
* A multi-pane activity, where the full-screen content is a {@link MapFragment} and popup content
* may be visible at any given time, containing either a {@link SessionsFragment} (representing
* sessions for a given room) or a {@link SessionDetailFragment}.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MapMultiPaneActivity extends BaseActivity implements
FragmentManager.OnBackStackChangedListener,
MapFragment.Callbacks,
SessionsFragment.Callbacks,
LoaderManager.LoaderCallbacks<Cursor> {
private boolean mPauseBackStackWatcher = false;
private FragmentBreadCrumbs mFragmentBreadCrumbs;
private String mSelectedRoomName;
private MapFragment mMapFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(this);
mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs);
mFragmentBreadCrumbs.setActivity(this);
mMapFragment = (MapFragment) fm.findFragmentByTag("map");
if (mMapFragment == null) {
mMapFragment = new MapFragment();
mMapFragment.setArguments(intentToFragmentArguments(getIntent()));
fm.beginTransaction()
.add(R.id.fragment_container_map, mMapFragment, "map")
.commit();
}
findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
clearBackStack(false);
}
});
updateBreadCrumbs();
onConfigurationChanged(getResources().getConfiguration());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer);
spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
spacerView.setGravity(landscape ? Gravity.RIGHT : Gravity.BOTTOM);
View popupView = findViewById(R.id.map_detail_popup);
LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams)
popupView.getLayoutParams();
popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT;
popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0;
popupView.setLayoutParams(popupLayoutParams);
popupView.requestLayout();
}
private void clearBackStack(boolean pauseWatcher) {
if (pauseWatcher) {
mPauseBackStackWatcher = true;
}
FragmentManager fm = getSupportFragmentManager();
while (fm.getBackStackEntryCount() > 0) {
fm.popBackStackImmediate();
}
if (pauseWatcher) {
mPauseBackStackWatcher = false;
}
}
public void onBackStackChanged() {
if (mPauseBackStackWatcher) {
return;
}
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
showDetailPane(false);
}
updateBreadCrumbs();
}
private void showDetailPane(boolean show) {
View detailPopup = findViewById(R.id.map_detail_spacer);
if (show != (detailPopup.getVisibility() == View.VISIBLE)) {
detailPopup.setVisibility(show ? View.VISIBLE : View.GONE);
// Pan the map left or up depending on the orientation.
boolean landscape = getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
mMapFragment.panBy(
landscape ? (show ? 0.25f : -0.25f) : 0,
landscape ? 0 : (show ? 0.25f : -0.25f));
}
}
public void updateBreadCrumbs() {
final String title = (mSelectedRoomName != null)
? mSelectedRoomName
: getString(R.string.title_sessions);
final String detailTitle = getString(R.string.title_session_detail);
if (getSupportFragmentManager().getBackStackEntryCount() >= 2) {
mFragmentBreadCrumbs.setParentTitle(title, title, mFragmentBreadCrumbsClickListener);
mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle);
} else {
mFragmentBreadCrumbs.setParentTitle(null, null, null);
mFragmentBreadCrumbs.setTitle(title, title);
}
}
private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
getSupportFragmentManager().popBackStack();
}
};
@Override
public void onRoomSelected(String roomId) {
// Load room details
mSelectedRoomName = null;
Bundle loadRoomDataArgs = new Bundle();
loadRoomDataArgs.putString("room_id", roomId);
getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); // force load
// Show the sessions in the room
clearBackStack(true);
showDetailPane(true);
SessionsFragment fragment = new SessionsFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW,
ScheduleContract.Rooms.buildSessionsDirUri(roomId))));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.addToBackStack(null)
.commit();
updateBreadCrumbs();
}
@Override
public boolean onSessionSelected(String sessionId) {
// Show the session details
showDetailPane(true);
SessionDetailFragment fragment = new SessionDetailFragment();
Intent intent = new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(sessionId));
intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true);
fragment.setArguments(BaseActivity.intentToFragmentArguments(intent));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.addToBackStack(null)
.commit();
updateBreadCrumbs();
return false;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(this,
ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")),
RoomsQuery.PROJECTION,
null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
try {
if (!cursor.moveToFirst()) {
return;
}
mSelectedRoomName = cursor.getString(RoomsQuery.ROOM_NAME);
updateBreadCrumbs();
} finally {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private interface RoomsQuery {
String[] PROJECTION = {
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_FLOOR,
};
int ROOM_ID = 0;
int ROOM_NAME = 1;
int ROOM_FLOOR = 2;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/tablet/MapMultiPaneActivity.java | Java | asf20 | 9,250 |
/*
* 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.ui.phone;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.SessionsFragment;
import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.SearchView;
/**
* A single-pane activity that shows a {@link SessionsFragment} containing a list of sessions.
* This is used when showing the sessions for a given time slot, or showing session search results.
*/
public class SessionsActivity extends SimpleSinglePaneActivity
implements SessionsFragment.Callbacks {
@Override
protected Fragment onCreatePane() {
return new SessionsFragment();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.search, menu);
setupSearchMenuItem(menu);
return true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupSearchMenuItem(Menu menu) {
MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSessionSelected(String sessionId) {
startActivity(new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(sessionId)));
return false;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/phone/SessionsActivity.java | Java | asf20 | 3,083 |
/*
* 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.ui.phone;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
/**
* A single-pane activity that shows a {@link MapFragment}.
*/
public class MapActivity extends SimpleSinglePaneActivity implements
MapFragment.Callbacks,
LoaderManager.LoaderCallbacks<Cursor> {
@Override
protected Fragment onCreatePane() {
return new MapFragment();
}
@Override
public void onRoomSelected(String roomId) {
Bundle loadRoomDataArgs = new Bundle();
loadRoomDataArgs.putString("room_id", roomId);
// force load (don't use previously used data)
getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(this,
ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")),
RoomsQuery.PROJECTION,
null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
try {
if (!cursor.moveToFirst()) {
return;
}
Intent roomIntent = new Intent(Intent.ACTION_VIEW,
ScheduleContract.Rooms.buildSessionsDirUri(
cursor.getString(RoomsQuery.ROOM_ID)));
roomIntent.putExtra(Intent.EXTRA_TITLE, cursor.getString(RoomsQuery.ROOM_NAME));
startActivity(roomIntent);
} finally {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private interface RoomsQuery {
String[] PROJECTION = {
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_FLOOR,
};
int ROOM_ID = 0;
int ROOM_NAME = 1;
int ROOM_FLOOR = 2;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/phone/MapActivity.java | Java | asf20 | 2,964 |
/*
* 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.ui.phone;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.BaseActivity;
import com.google.android.apps.iosched.ui.SessionsFragment;
import com.google.android.apps.iosched.ui.SocialStreamActivity;
import com.google.android.apps.iosched.ui.SocialStreamFragment;
import com.google.android.apps.iosched.ui.TrackInfoHelperFragment;
import com.google.android.apps.iosched.ui.VendorsFragment;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
/**
* A single-pane activity that shows a {@link SessionsFragment} in one tab and a
* {@link VendorsFragment} in another tab, representing the sessions and developer sandbox companies
* for the given conference track (Android, Chrome, etc.).
*/
public class TrackDetailActivity extends BaseActivity implements
ActionBar.TabListener,
ViewPager.OnPageChangeListener,
SessionsFragment.Callbacks,
VendorsFragment.Callbacks,
TrackInfoHelperFragment.Callbacks {
private ViewPager mViewPager;
private String mTrackId;
private Uri mTrackUri;
private boolean mShowVendors = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_detail);
mTrackUri = getIntent().getData();
mTrackId = ScheduleContract.Tracks.getTrackId(mTrackUri);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(this);
mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width));
mShowVendors = !ScheduleContract.Tracks.CODELABS_TRACK_ID.equals(mTrackId)
&& !ScheduleContract.Tracks.TECH_TALK_TRACK_ID.equals(mTrackId);
if (mShowVendors) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_sessions)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_vendors)
.setTabListener(this));
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(TrackInfoHelperFragment.newFromTrackUri(mTrackUri), "track_info")
.commit();
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
getSupportActionBar().setSelectedNavigationItem(position);
int titleId = -1;
switch (position) {
case 0:
titleId = R.string.title_sessions;
break;
case 1:
titleId = R.string.title_vendors;
break;
}
String title = getString(titleId);
EasyTracker.getTracker().trackView(title + ": " + getTitle());
LOGD("Tracker", title + ": " + getTitle());
}
@Override
public void onPageScrollStateChanged(int i) {
}
private class TrackDetailPagerAdapter extends FragmentPagerAdapter {
public TrackDetailPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId));
if (position == 0) {
Fragment fragment = new SessionsFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent(
Intent.ACTION_VIEW,
allTracks
? ScheduleContract.Sessions.CONTENT_URI
: ScheduleContract.Tracks.buildSessionsUri(mTrackId))));
return fragment;
} else {
Fragment fragment = new VendorsFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent(
Intent.ACTION_VIEW,
allTracks
? ScheduleContract.Vendors.CONTENT_URI
: ScheduleContract.Tracks.buildVendorsUri(mTrackId))));
return fragment;
}
}
@Override
public int getCount() {
return mShowVendors ? 2 : 1;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.track_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_social_stream:
Intent intent = new Intent(this, SocialStreamActivity.class);
intent.putExtra(SocialStreamFragment.EXTRA_QUERY,
UIUtils.getSessionHashtagsString(mTrackId));
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) {
setTitle(trackName);
setActionBarColor(trackColor);
EasyTracker.getTracker().trackView(getString(R.string.title_sessions) + ": " + getTitle());
LOGD("Tracker", getString(R.string.title_sessions) + ": " + getTitle());
}
@Override
public boolean onSessionSelected(String sessionId) {
startActivity(new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(sessionId)));
return false;
}
@Override
public boolean onVendorSelected(String vendorId) {
startActivity(new Intent(Intent.ACTION_VIEW,
ScheduleContract.Vendors.buildVendorUri(vendorId)));
return false;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/phone/TrackDetailActivity.java | Java | asf20 | 7,891 |
/*
* 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.ui.phone;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity;
import com.google.android.apps.iosched.ui.TrackInfoHelperFragment;
import com.google.android.apps.iosched.ui.VendorDetailFragment;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
/**
* A single-pane activity that shows a {@link VendorDetailFragment}.
*/
public class VendorDetailActivity extends SimpleSinglePaneActivity implements
VendorDetailFragment.Callbacks,
TrackInfoHelperFragment.Callbacks {
private String mTrackId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected Fragment onCreatePane() {
return new VendorDetailFragment();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// Up to this session's track details, or Home if no track is available
Intent parentIntent;
if (mTrackId != null) {
parentIntent = new Intent(Intent.ACTION_VIEW,
ScheduleContract.Tracks.buildTrackUri(mTrackId));
} else {
parentIntent = new Intent(this, HomeActivity.class);
}
NavUtils.navigateUpTo(this, parentIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) {
mTrackId = trackId;
setTitle(trackName);
setActionBarColor(trackColor);
}
@Override
public void onTrackIdAvailable(final String trackId) {
new Handler().post(new Runnable() {
@Override
public void run() {
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag("track_info") == null) {
fm.beginTransaction()
.add(TrackInfoHelperFragment.newFromTrackUri(
ScheduleContract.Tracks.buildTrackUri(trackId)),
"track_info")
.commit();
}
}
});
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/phone/VendorDetailActivity.java | Java | asf20 | 3,248 |
/*
* 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.ui.phone;
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.SessionDetailFragment;
import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity;
import com.google.android.apps.iosched.ui.TrackInfoHelperFragment;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
/**
* A single-pane activity that shows a {@link SessionDetailFragment}.
*/
public class SessionDetailActivity extends SimpleSinglePaneActivity implements
TrackInfoHelperFragment.Callbacks {
private String mTrackId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) {
BeamUtils.setBeamUnlocked(this);
showFirstBeamDialog();
}
BeamUtils.tryUpdateIntentFromBeam(this);
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Uri sessionUri = getIntent().getData();
BeamUtils.setBeamSessionUri(this, sessionUri);
trySetBeamCallback();
getSupportFragmentManager().beginTransaction()
.add(TrackInfoHelperFragment.newFromSessionUri(sessionUri),
"track_info")
.commit();
}
}
@Override
protected Fragment onCreatePane() {
return new SessionDetailFragment();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// Up to this session's track details, or Home if no track is available
Intent parentIntent;
if (mTrackId != null) {
parentIntent = new Intent(Intent.ACTION_VIEW,
ScheduleContract.Tracks.buildTrackUri(mTrackId));
} else {
parentIntent = new Intent(this, HomeActivity.class);
}
NavUtils.navigateUpTo(this, parentIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) {
mTrackId = trackId;
setTitle(trackName);
setActionBarColor(trackColor);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void trySetBeamCallback() {
if (UIUtils.hasICS()) {
BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() {
@Override
public void onNdefPushComplete(NfcEvent event) {
// Beam has been sent
if (!BeamUtils.isBeamUnlocked(SessionDetailActivity.this)) {
BeamUtils.setBeamUnlocked(SessionDetailActivity.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
showFirstBeamDialog();
}
});
}
}
});
}
}
private void showFirstBeamDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.just_beamed)
.setMessage(R.string.beam_unlocked_session)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(SessionDetailActivity.this);
di.dismiss();
}
})
.create()
.show();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/phone/SessionDetailActivity.java | Java | asf20 | 5,069 |
/*
* 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.ui;
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.util.ImageFetcher;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A {@link WebView}-based fragment that shows Google+ public search results for a given query,
* provided as the {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no
* search query is provided, the conference hashtag is used as the default query.
*
* <p>WARNING! This fragment uses the Google+ API, and is subject to quotas. If you expect to
* write a wildly popular app based on this code, please check the
* at <a href="https://developers.google.com/+/">Google+ Platform documentation</a> on latest
* best practices and quota details. You can check your current quota at the
* <a href="https://code.google.com/apis/console">APIs console</a>.
*/
public class SocialStreamFragment extends SherlockListFragment implements
AbsListView.OnScrollListener,
LoaderManager.LoaderCallbacks<List<Activity>> {
private static final String TAG = makeLogTag(SocialStreamFragment.class);
public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY";
private static final String STATE_POSITION = "position";
private static final String STATE_TOP = "top";
private static final long MAX_RESULTS_PER_REQUEST = 20;
private static final int STREAM_LOADER_ID = 0;
private String mSearchString;
private List<Activity> mStream = new ArrayList<Activity>();
private StreamAdapter mStreamAdapter = new StreamAdapter();
private int mListViewStatePosition;
private int mListViewStateTop;
private ImageFetcher mImageFetcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
// mSearchString can be populated before onCreate() by called refresh(String)
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = intent.getStringExtra(EXTRA_QUERY);
}
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = UIUtils.CONFERENCE_HASHTAG;
}
if (!mSearchString.startsWith("#")) {
mSearchString = "#" + mSearchString;
}
mImageFetcher = UIUtils.getImageFetcher(getActivity());
setListAdapter(mStreamAdapter);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1);
mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0);
} else {
mListViewStatePosition = -1;
mListViewStateTop = 0;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(getString(R.string.empty_social_stream));
// In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter
// in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple
// fragments because their mIndex is -1 (haven't been added to the activity yet). Thus,
// we do this in onActivityCreated.
getLoaderManager().initLoader(STREAM_LOADER_ID, null, this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setCacheColorHint(Color.WHITE);
listView.setOnScrollListener(this);
listView.setDrawSelectorOnTop(true);
TypedValue v = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true);
listView.setSelector(v.resourceId);
}
@Override
public void onPause() {
super.onPause();
mImageFetcher.flushCache();
}
@Override
public void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.social_stream, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_compose:
Intent intent = ShareCompat.IntentBuilder.from(getActivity())
.setType("text/plain")
.setText(mSearchString + "\n\n")
.getIntent();
UIUtils.preferPackageForIntent(getActivity(), intent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(intent);
EasyTracker.getTracker().trackEvent("Home Screen Dashboard", "Click",
"Post to Google+", 0L);
LOGD("Tracker", "Home Screen Dashboard: Click, post to Google+");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (isAdded()) {
View v = getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition());
outState.putInt(STATE_TOP, top);
}
super.onSaveInstanceState(outState);
}
public void refresh(String newQuery) {
mSearchString = newQuery;
refresh(true);
}
public void refresh() {
refresh(false);
}
public void refresh(boolean forceRefresh) {
if (isStreamLoading() && !forceRefresh) {
return;
}
// clear current items
mStream.clear();
mStreamAdapter.notifyDataSetInvalidated();
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
((StreamLoader) loader).init(mSearchString);
}
loadMoreResults();
}
public void loadMoreResults() {
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
loader.forceLoad();
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Activity activity = mStream.get(position);
Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl()));
postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), postDetailIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
UIUtils.safeOpenLink(getActivity(), postDetailIntent);
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
// Pause disk cache access to ensure smoother scrolling
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING ||
scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
mImageFetcher.setPauseWork(true);
} else {
mImageFetcher.setPauseWork(false);
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// Simple implementation of the infinite scrolling UI pattern; loads more Google+
// search results as the user scrolls to the end of the list.
if (!isStreamLoading()
&& streamHasMoreResults()
&& visibleItemCount != 0
&& firstVisibleItem + visibleItemCount >= totalItemCount - 1) {
loadMoreResults();
}
}
@Override
public Loader<List<Activity>> onCreateLoader(int id, Bundle args) {
return new StreamLoader(getActivity(), mSearchString);
}
@Override
public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) {
if (activities != null) {
mStream = activities;
}
mStreamAdapter.notifyDataSetChanged();
if (mListViewStatePosition != -1 && isAdded()) {
getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop);
mListViewStatePosition = -1;
}
}
@Override
public void onLoaderReset(Loader<List<Activity>> listLoader) {
}
private boolean isStreamLoading() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).isLoading();
}
}
return true;
}
private boolean streamHasMoreResults() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasMoreResults();
}
}
return false;
}
private boolean streamHasError() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasError();
}
}
return false;
}
/**
* An {@link AsyncTaskLoader} that loads activities from the public Google+ stream for
* a given search query. The loader maintains a page state with the Google+ API and thus
* supports pagination.
*/
private static class StreamLoader extends AsyncTaskLoader<List<Activity>> {
List<Activity> mActivities;
private String mSearchString;
private String mNextPageToken;
private boolean mIsLoading;
private boolean mHasError;
public StreamLoader(Context context, String searchString) {
super(context);
init(searchString);
}
private void init(String searchString) {
mSearchString = searchString;
mHasError = false;
mNextPageToken = null;
mIsLoading = true;
mActivities = null;
}
@Override
public List<Activity> loadInBackground() {
mIsLoading = true;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
JsonHttpRequestInitializer initializer = new GoogleKeyInitializer(
Config.API_KEY);
// Set up the main Google+ class
Plus plus = Plus.builder(httpTransport, jsonFactory)
.setApplicationName(Config.APP_NAME)
.setJsonHttpRequestInitializer(initializer)
.build();
ActivityFeed activities = null;
try {
activities = plus.activities().search(mSearchString)
.setPageToken(mNextPageToken)
.setMaxResults(MAX_RESULTS_PER_REQUEST)
.execute();
mHasError = false;
mNextPageToken = activities.getNextPageToken();
} catch (IOException e) {
e.printStackTrace();
mHasError = true;
mNextPageToken = null;
}
return (activities != null) ? activities.getItems() : null;
}
@Override
public void deliverResult(List<Activity> activities) {
mIsLoading = false;
if (activities != null) {
if (mActivities == null) {
mActivities = activities;
} else {
mActivities.addAll(activities);
}
}
if (isStarted()) {
// Need to return new ArrayList for some reason or onLoadFinished() is not called
super.deliverResult(mActivities == null ?
null : new ArrayList<Activity>(mActivities));
}
}
@Override
protected void onStartLoading() {
if (mActivities != null) {
// If we already have results and are starting up, deliver what we already have.
deliverResult(null);
} else {
forceLoad();
}
}
@Override
protected void onStopLoading() {
mIsLoading = false;
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
mActivities = null;
}
public boolean isLoading() {
return mIsLoading;
}
public boolean hasMoreResults() {
return mNextPageToken != null;
}
public boolean hasError() {
return mHasError;
}
public void setSearchString(String searchString) {
mSearchString = searchString;
}
public void refresh(String searchString) {
setSearchString(searchString);
refresh();
}
public void refresh() {
reset();
startLoading();
}
}
/**
* A list adapter that shows individual Google+ activities as list items.
* If another page is available, the last item is a "loading" view to support the
* infinite scrolling UI pattern.
*/
private class StreamAdapter extends BaseAdapter {
private static final int VIEW_TYPE_ACTIVITY = 0;
private static final int VIEW_TYPE_LOADING = 1;
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) == VIEW_TYPE_ACTIVITY;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mStream.size() + (
// show the status list row if...
((isStreamLoading() && mStream.size() == 0) // ...this is the first load
|| streamHasMoreResults() // ...or there's another page
|| streamHasError()) // ...or there's an error
? 1 : 0);
}
@Override
public int getItemViewType(int position) {
return (position >= mStream.size())
? VIEW_TYPE_LOADING
: VIEW_TYPE_ACTIVITY;
}
@Override
public Object getItem(int position) {
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position)
: null;
}
@Override
public long getItemId(int position) {
// TODO: better unique ID heuristic
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position).getId().hashCode()
: -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == VIEW_TYPE_LOADING) {
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_status, parent, false);
}
if (streamHasError()) {
convertView.findViewById(android.R.id.progress).setVisibility(View.GONE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.stream_error);
} else {
convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.loading);
}
return convertView;
} else {
Activity activity = (Activity) getItem(position);
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_activity, parent, false);
}
StreamRowViewBinder.bindActivityView(convertView, activity, mImageFetcher);
return convertView;
}
}
}
/**
* A helper class to bind data from a Google+ {@link Activity} to the list item view.
*/
private static class StreamRowViewBinder {
private static class ViewHolder {
private TextView[] detail;
private ImageView[] detailIcon;
private ImageView[] media;
private ImageView[] mediaOverlay;
private TextView originalAuthor;
private View reshareLine;
private View reshareSpacer;
private ImageView userImage;
private TextView userName;
private TextView content;
private View plusOneIcon;
private TextView plusOneCount;
private View commentIcon;
private TextView commentCount;
}
private static void bindActivityView(
final View rootView, Activity activity, ImageFetcher imageFetcher) {
// Prepare view holder.
ViewHolder temp = (ViewHolder) rootView.getTag();
final ViewHolder views;
if (temp != null) {
views = temp;
} else {
views = new ViewHolder();
rootView.setTag(views);
views.detail = new TextView[] {
(TextView) rootView.findViewById(R.id.stream_detail_text)
};
views.detailIcon = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_detail_media_small)
};
views.media = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_media_1_1),
(ImageView) rootView.findViewById(R.id.stream_media_1_2),
};
views.mediaOverlay = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_media_overlay_1_1),
(ImageView) rootView.findViewById(R.id.stream_media_overlay_1_2),
};
views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author);
views.reshareLine = rootView.findViewById(R.id.stream_reshare_line);
views.reshareSpacer = rootView.findViewById(R.id.stream_reshare_spacer);
views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image);
views.userName = (TextView) rootView.findViewById(R.id.stream_user_name);
views.content = (TextView) rootView.findViewById(R.id.stream_content);
views.plusOneIcon = rootView.findViewById(R.id.stream_plus_one_icon);
views.plusOneCount = (TextView) rootView.findViewById(R.id.stream_plus_one_count);
views.commentIcon = rootView.findViewById(R.id.stream_comment_icon);
views.commentCount = (TextView) rootView.findViewById(R.id.stream_comment_count);
}
final Resources res = rootView.getContext().getResources();
// Hide all the array items.
int detailIndex = 0;
int mediaIndex = 0;
for (View v : views.detail) {
v.setVisibility(View.GONE);
}
for (View v : views.detailIcon) {
v.setVisibility(View.GONE);
}
for (View v : views.media) {
v.setVisibility(View.GONE);
}
for (View v : views.mediaOverlay) {
v.setVisibility(View.GONE);
}
// Determine if this is a reshare (affects how activity fields are to be
// interpreted).
boolean isReshare = (activity.getObject().getActor() != null);
// Set user name.
views.userName.setText(activity.getActor().getDisplayName());
if (activity.getActor().getImage() != null) {
imageFetcher.loadThumbnailImage(activity.getActor().getImage().getUrl(), views.userImage,
R.drawable.person_image_empty);
} else {
views.userImage.setImageResource(R.drawable.person_image_empty);
}
// Set +1 and comment counts.
final int plusOneCount = (activity.getObject().getPlusoners() != null)
? activity.getObject().getPlusoners().getTotalItems().intValue() : 0;
if (plusOneCount == 0) {
views.plusOneIcon.setVisibility(View.GONE);
views.plusOneCount.setVisibility(View.GONE);
} else {
views.plusOneIcon.setVisibility(View.VISIBLE);
views.plusOneCount.setVisibility(View.VISIBLE);
views.plusOneCount.setText(Integer.toString(plusOneCount));
}
final int commentCount = (activity.getObject().getReplies() != null)
? activity.getObject().getReplies().getTotalItems().intValue() : 0;
if (commentCount == 0) {
views.commentIcon.setVisibility(View.GONE);
views.commentCount.setVisibility(View.GONE);
} else {
views.commentIcon.setVisibility(View.VISIBLE);
views.commentCount.setVisibility(View.VISIBLE);
views.commentCount.setText(Integer.toString(commentCount));
}
// Set content.
String selfContent = isReshare
? activity.getAnnotation()
: activity.getObject().getContent();
if (!TextUtils.isEmpty(selfContent)) {
views.content.setVisibility(View.VISIBLE);
views.content.setText(Html.fromHtml(selfContent));
} else {
views.content.setVisibility(View.GONE);
}
// Set original author.
if (activity.getObject().getActor() != null) {
views.originalAuthor.setVisibility(View.VISIBLE);
views.originalAuthor.setText(res.getString(R.string.stream_originally_shared,
activity.getObject().getActor().getDisplayName()));
views.reshareLine.setVisibility(View.VISIBLE);
views.reshareSpacer.setVisibility(View.INVISIBLE);
} else {
views.originalAuthor.setVisibility(View.GONE);
views.reshareLine.setVisibility(View.GONE);
views.reshareSpacer.setVisibility(View.GONE);
}
// Set document content.
if (isReshare && !TextUtils.isEmpty(activity.getObject().getContent())
&& detailIndex < views.detail.length) {
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_content_color));
views.detail[detailIndex].setText(Html.fromHtml(activity.getObject().getContent()));
++detailIndex;
}
// Set location.
String location = activity.getPlaceName();
if (!TextUtils.isEmpty(location)) {
location = activity.getAddress();
}
if (!TextUtils.isEmpty(location)) {
location = activity.getGeocode();
}
if (!TextUtils.isEmpty(location) && detailIndex < views.detail.length) {
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_link_color));
views.detailIcon[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setText(location);
if ("checkin".equals(activity.getVerb())) {
views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_checkin);
} else {
views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_location);
}
++detailIndex;
}
// Set media content.
if (activity.getObject().getAttachments() != null) {
for (Activity.PlusObject.Attachments attachment : activity.getObject().getAttachments()) {
String objectType = attachment.getObjectType();
if (("photo".equals(objectType) || "video".equals(objectType)) &&
mediaIndex < views.media.length) {
if (attachment.getImage() == null) {
continue;
}
final ImageView mediaView = views.media[mediaIndex];
mediaView.setVisibility(View.VISIBLE);
imageFetcher.loadThumbnailImage(attachment.getImage().getUrl(), mediaView);
if ("video".equals(objectType)) {
views.mediaOverlay[mediaIndex].setVisibility(View.VISIBLE);
}
++mediaIndex;
} else if (("article".equals(objectType)) &&
detailIndex < views.detail.length) {
try {
String faviconUrl = "http://www.google.com/s2/favicons?domain=" +
Uri.parse(attachment.getUrl()).getHost();
final ImageView iconView = views.detailIcon[detailIndex];
iconView.setVisibility(View.VISIBLE);
imageFetcher.loadThumbnailImage(faviconUrl, iconView);
} catch (ParseException ignored) {}
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(
res.getColor(R.color.stream_link_color));
views.detail[detailIndex].setText(attachment.getDisplayName());
++detailIndex;
}
}
}
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SocialStreamFragment.java | Java | asf20 | 29,567 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A single-pane activity that shows a {@link SocialStreamFragment}.
*/
public class SocialStreamActivity extends SimpleSinglePaneActivity {
@Override
protected Fragment onCreatePane() {
return new SocialStreamFragment();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.social_stream_standalone, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
((SocialStreamFragment) getFragment()).refresh();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SocialStreamActivity.java | Java | asf20 | 1,820 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
/**
* A base activity that handles common functionality in the app.
*/
public abstract class BaseActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EasyTracker.getTracker().setContext(this);
// If we're not on Google TV and we're not authenticated, finish this activity
// and show the authentication screen.
if (!UIUtils.isGoogleTV(this)) {
if (!AccountUtils.isAuthenticated(this)) {
AccountUtils.startAuthenticationFlow(this, getIntent());
finish();
}
}
// If Android Beam APIs are available, set up the Beam easter egg as the default Beam
// content. This can be overridden by subclasses.
if (UIUtils.hasICS()) {
BeamUtils.setDefaultBeamUri(this);
if (!BeamUtils.isBeamUnlocked(this)) {
BeamUtils.setBeamCompleteCallback(this,
new NfcAdapter.OnNdefPushCompleteCallback() {
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onNdefPushComplete(NfcEvent event) {
onBeamSent();
}
});
}
}
getSupportActionBar().setHomeButtonEnabled(true);
}
private void onBeamSent() {
if (!BeamUtils.isBeamUnlocked(this)) {
BeamUtils.setBeamUnlocked(this);
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(BaseActivity.this)
.setTitle(R.string.just_beamed)
.setMessage(R.string.beam_unlocked_default)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(BaseActivity.this);
di.dismiss();
}
})
.create()
.show();
}
});
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (this instanceof HomeActivity) {
return false;
}
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Sets the icon color using some fancy blending mode trickery.
*/
protected void setActionBarColor(int color) {
if (color == 0) {
color = 0xffffffff;
}
final Resources res = getResources();
Drawable maskDrawable = res.getDrawable(R.drawable.actionbar_icon_mask);
if (!(maskDrawable instanceof BitmapDrawable)) {
return;
}
Bitmap maskBitmap = ((BitmapDrawable) maskDrawable).getBitmap();
final int width = maskBitmap.getWidth();
final int height = maskBitmap.getHeight();
Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outBitmap);
canvas.drawBitmap(maskBitmap, 0, 0, null);
Paint maskedPaint = new Paint();
maskedPaint.setColor(color);
maskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
canvas.drawRect(0, 0, width, height, maskedPaint);
BitmapDrawable outDrawable = new BitmapDrawable(res, outBitmap);
getSupportActionBar().setIcon(outDrawable);
}
/**
* Converts an intent into a {@link Bundle} suitable for use as fragment arguments.
*/
public static Bundle intentToFragmentArguments(Intent intent) {
Bundle arguments = new Bundle();
if (intent == null) {
return arguments;
}
final Uri data = intent.getData();
if (data != null) {
arguments.putParcelable("_uri", data);
}
final Bundle extras = intent.getExtras();
if (extras != null) {
arguments.putAll(intent.getExtras());
}
return arguments;
}
/**
* Converts a fragment arguments bundle into an intent.
*/
public static Intent fragmentArgumentsToIntent(Bundle arguments) {
Intent intent = new Intent();
if (arguments == null) {
return intent;
}
final Uri data = arguments.getParcelable("_uri");
if (data != null) {
intent.setData(data);
}
intent.putExtras(arguments);
intent.removeExtra("_uri");
return intent;
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getTracker().trackActivityStart(this);
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getTracker().trackActivityStop(this);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/BaseActivity.java | Java | asf20 | 7,118 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.provider.BaseColumns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}, additionally showing
* "Map" and/or "All tracks" list items at the top.
*/
public class TracksAdapter extends CursorAdapter {
private static final int ALL_ITEM_ID = Integer.MAX_VALUE;
private static final int MAP_ITEM_ID = Integer.MAX_VALUE - 1;
private Activity mActivity;
private boolean mHasAllItem;
private boolean mHasMapItem;
private int mPositionDisplacement;
public TracksAdapter(Activity activity) {
super(activity, null, false);
mActivity = activity;
}
public void setHasAllItem(boolean hasAllItem) {
mHasAllItem = hasAllItem;
updatePositionDisplacement();
}
public void setHasMapItem(boolean hasMapItem) {
mHasMapItem = hasMapItem;
updatePositionDisplacement();
}
private void updatePositionDisplacement() {
mPositionDisplacement = (mHasAllItem ? 1 : 0) + (mHasMapItem ? 1 : 0);
}
public boolean isMapItem(int position) {
return mHasMapItem && position == 0;
}
public boolean isAllItem(int position) {
return mHasAllItem && position == (mHasMapItem ? 1 : 0);
}
@Override
public int getCount() {
return super.getCount() + mPositionDisplacement;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (isMapItem(position)) {
if (convertView == null) {
convertView = mActivity.getLayoutInflater().inflate(
R.layout.list_item_track_map, parent, false);
}
return convertView;
} else if (isAllItem(position)) {
if (convertView == null) {
convertView = mActivity.getLayoutInflater().inflate(
R.layout.list_item_track, parent, false);
}
// Custom binding for the first item
((TextView) convertView.findViewById(android.R.id.text1)).setText(
"(" + mActivity.getResources().getString(R.string.all_tracks) + ")");
convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE);
return convertView;
}
return super.getView(position - mPositionDisplacement, convertView, parent);
}
@Override
public Object getItem(int position) {
if (isMapItem(position) || isAllItem(position)) {
return null;
}
return super.getItem(position - mPositionDisplacement);
}
@Override
public long getItemId(int position) {
if (isMapItem(position)) {
return MAP_ITEM_ID;
} else if (isAllItem(position)) {
return ALL_ITEM_ID;
}
return super.getItemId(position - mPositionDisplacement);
}
@Override
public boolean isEnabled(int position) {
return (mHasAllItem && position == 0) || super.isEnabled(position - mPositionDisplacement);
}
@Override
public int getViewTypeCount() {
// Add an item type for the "All" and map views.
return super.getViewTypeCount() + 2;
}
@Override
public int getItemViewType(int position) {
if (isMapItem(position)) {
return getViewTypeCount() - 1;
} else if (isAllItem(position)) {
return getViewTypeCount() - 2;
}
return super.getItemViewType(position - mPositionDisplacement);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setText(cursor.getString(TracksQuery.TRACK_NAME));
// Assign track color to visible block
final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1);
iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR)));
}
/** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */
public interface TracksQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
};
String[] PROJECTION_WITH_SESSIONS_COUNT = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.SESSIONS_COUNT,
};
String[] PROJECTION_WITH_VENDORS_COUNT = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.VENDORS_COUNT,
};
int _ID = 0;
int TRACK_ID = 1;
int TRACK_NAME = 2;
int TRACK_ABSTRACT = 3;
int TRACK_COLOR = 4;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/TracksAdapter.java | Java | asf20 | 6,615 |
/*
* 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.ui.gtv;
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.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.ui.BaseActivity;
import com.google.android.apps.iosched.ui.SessionLivestreamActivity.SessionSummaryFragment;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.youtube.api.YouTube;
import com.google.android.youtube.api.YouTubePlayer;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
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 Google TV home activity for Google I/O 2012 that displays session live streams pulled in
* from YouTube.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class GoogleTVSessionLivestreamActivity extends BaseActivity implements
LoaderCallbacks<Cursor>,
YouTubePlayer.OnPlaybackEventsListener,
YouTubePlayer.OnFullscreenListener,
OnItemClickListener {
private static final String TAG = makeLogTag(GoogleTVSessionLivestreamActivity.class);
private static final String TAG_SESSION_SUMMARY = "session_summary";
private static final int UPCOMING_SESSIONS_QUERY_ID = 3;
private static final String PROMO_VIDEO_URL = "http://www.youtube.com/watch?v=gTA-5HM8Zhs";
private boolean mIsFullscreen = false;
private boolean mTrackPlay = true;
private YouTubePlayer mYouTubePlayer;
private FrameLayout mPlayerContainer;
private String mYouTubeVideoId;
private LinearLayout mMainLayout;
private LinearLayout mVideoLayout;
private LinearLayout mExtraLayout;
private FrameLayout mSummaryLayout;
private ListView mLiveListView;
private SyncHelper mGTVSyncHelper;
private LivestreamAdapter mLivestreamAdapter;
private String mSessionId;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
YouTube.initialize(this, Config.YOUTUBE_API_KEY);
setContentView(R.layout.activity_session_livestream);
// Set up YouTube player
mYouTubePlayer = (YouTubePlayer) getSupportFragmentManager().findFragmentById(
R.id.livestream_player);
mYouTubePlayer.setOnPlaybackEventsListener(this);
mYouTubePlayer.enableCustomFullscreen(this);
mYouTubePlayer.setFullscreenControlFlags(
YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
// Views that are common over all layouts
mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout);
mPlayerContainer = (FrameLayout) findViewById(R.id.livestream_player_container);
// Tablet UI specific views
getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary,
new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit();
mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout);
mExtraLayout = (LinearLayout) findViewById(R.id.googletv_livesextra_layout);
mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary);
// Reload all other data in this activity
reloadFromUri(getIntent().getData());
// Start sessions query to populate action bar navigation spinner
getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this);
// Set up left side listview
mLivestreamAdapter = new LivestreamAdapter(this);
mLiveListView = (ListView) findViewById(R.id.live_session_list);
mLiveListView.setAdapter(mLivestreamAdapter);
mLiveListView.setOnItemClickListener(this);
mLiveListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mLiveListView.setSelector(android.R.color.transparent);
getSupportActionBar().hide();
// Sync data from Conference API
new SyncOperationTask().execute((Void) null);
}
/**
* Reloads all data in the activity and fragments from a given uri
*/
private void reloadFromUri(Uri newUri) {
if (newUri != null && newUri.getPathSegments().size() >= 2) {
mSessionId = Sessions.getSessionId(newUri);
getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this);
}
}
@Override
public void onBackPressed() {
if (mIsFullscreen) {
// Exit full screen mode on back key
mYouTubePlayer.setFullscreen(false);
} else {
super.onBackPressed();
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int itemPosition, long itemId) {
final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition);
final String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId != null) {
reloadFromUri(Sessions.buildSessionUri(sessionId));
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case SessionSummaryQuery._TOKEN:
return new CursorLoader(
this, Sessions.buildWithTracksUri(mSessionId),
SessionSummaryQuery.PROJECTION, null, null, null);
case SessionsQuery._TOKEN:
final long currentTime = UIUtils.getCurrentTime(this);
String selection = Sessions.LIVESTREAM_SELECTION + " and "
+ Sessions.AT_TIME_SELECTION;
String[] selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime);
return new CursorLoader(this, Sessions.buildWithTracksUri(),
SessionsQuery.PROJECTION, selection,
selectionArgs, null);
case UPCOMING_SESSIONS_QUERY_ID:
final long newCurrentTime = UIUtils.getCurrentTime(this);
String sessionsSelection = Sessions.LIVESTREAM_SELECTION + " and "
+ Sessions.UPCOMING_SELECTION;
String[] sessionsSelectionArgs =
Sessions.buildUpcomingSelectionArgs(newCurrentTime);
return new CursorLoader(this, Sessions.buildWithTracksUri(),
SessionsQuery.PROJECTION, sessionsSelection,
sessionsSelectionArgs, null);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mHandler.removeCallbacks(mNextSessionStartsInCountdownRunnable);
switch (loader.getId()) {
case SessionSummaryQuery._TOKEN:
loadSession(data);
break;
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(data);
final int selected = locateSelectedItem(data);
if (data.getCount() == 0) {
handleNoLiveSessionsAvailable();
} else {
mLiveListView.setSelection(selected);
mLiveListView.requestFocus(selected);
final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(selected);
final String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId != null) {
reloadFromUri(Sessions.buildSessionUri(sessionId));
}
}
break;
case UPCOMING_SESSIONS_QUERY_ID:
if (data != null && data.getCount() > 0) {
data.moveToFirst();
handleUpdateNextUpcomingSession(data);
}
break;
}
}
public void handleNoLiveSessionsAvailable() {
getSupportLoaderManager().initLoader(UPCOMING_SESSIONS_QUERY_ID, null, this);
updateSessionViews(PROMO_VIDEO_URL,
getString(R.string.missed_io_title),
getString(R.string.missed_io_subtitle), UIUtils.CONFERENCE_HASHTAG);
//Make link in abstract view clickable
TextView abstractLinkTextView = (TextView) findViewById(R.id.session_abstract);
abstractLinkTextView.setMovementMethod(new LinkMovementMethod());
}
private String mNextSessionTitle;
private long mNextSessionStartTime;
private final Runnable mNextSessionStartsInCountdownRunnable = new Runnable() {
public void run() {
int remainingSec = (int) Math.max(0,
(mNextSessionStartTime - UIUtils.getCurrentTime(
GoogleTVSessionLivestreamActivity.this)) / 1000);
final int secs = remainingSec % 86400;
final int days = remainingSec / 86400;
final String str;
if (days == 0) {
str = getResources().getString(
R.string.starts_in_template_0_days,
DateUtils.formatElapsedTime(secs));
} else {
str = getResources().getQuantityString(
R.plurals.starts_in_template, days, days,
DateUtils.formatElapsedTime(secs));
}
updateSessionSummaryFragment(mNextSessionTitle, str);
if (remainingSec == 0) {
// Next session starting now!
mHandler.postDelayed(mRefreshSessionsRunnable, 1000);
return;
}
// Repost ourselves to keep updating countdown
mHandler.postDelayed(mNextSessionStartsInCountdownRunnable, 1000);
}
};
private final Runnable mRefreshSessionsRunnable = new Runnable() {
@Override
public void run() {
getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null,
GoogleTVSessionLivestreamActivity.this);
}
};
public void handleUpdateNextUpcomingSession(Cursor data) {
mNextSessionTitle = getString(R.string.next_live_stream_session_template,
data.getString(SessionsQuery.TITLE));
mNextSessionStartTime = data.getLong(SessionsQuery.BLOCK_START);
updateSessionViews(PROMO_VIDEO_URL, mNextSessionTitle, "", UIUtils.CONFERENCE_HASHTAG);
// Begin countdown til next session
mHandler.post(mNextSessionStartsInCountdownRunnable);
}
/**
* Locates which item should be selected in the action bar drop-down spinner based on the
* current active session uri
*/
private int locateSelectedItem(Cursor data) {
int selected = 0;
if (data != null && mSessionId != null) {
while (data.moveToNext()) {
if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) {
selected = data.getPosition();
}
}
}
return selected;
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
switch (loader.getId()) {
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(null);
break;
}
}
@Override
public void onFullscreen(boolean fullScreen) {
layoutFullscreenVideo(fullScreen);
}
@Override
public void onLoaded(String s) {
}
@Override
public void onPlaying() {
}
@Override
public void onPaused() {
}
@Override
public void onBuffering(boolean b) {
}
@Override
public void onEnded() {
mHandler.post(mRefreshSessionsRunnable);
}
@Override
public void onError() {
Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show();
LOGE(TAG, getString(R.string.session_livestream_error));
}
private void loadSession(Cursor data) {
if (data != null && data.moveToFirst()) {
// Schedule a data refresh after the session ends.
// NOTE: using postDelayed instead of postAtTime helps during debugging, using
// mock times.
mHandler.postDelayed(mRefreshSessionsRunnable,
data.getLong(SessionSummaryQuery.BLOCK_END) + 1000
- UIUtils.getCurrentTime(this));
updateSessionViews(
data.getString(SessionSummaryQuery.LIVESTREAM_URL),
data.getString(SessionSummaryQuery.TITLE),
data.getString(SessionSummaryQuery.ABSTRACT),
data.getString(SessionSummaryQuery.HASHTAGS));
}
}
/**
* Updates views that rely on session data from explicit strings.
*/
private void updateSessionViews(final String youtubeUrl, final String title,
final String sessionAbstract, final String hashTag) {
if (youtubeUrl == null) {
// Get out, nothing to do here
Toast.makeText(this, R.string.error_tv_no_url, Toast.LENGTH_SHORT).show();
LOGE(TAG, getString(R.string.error_tv_no_url));
return;
}
String youtubeVideoId = youtubeUrl;
if (youtubeUrl.startsWith("http")) {
final Uri youTubeUri = Uri.parse(youtubeUrl);
youtubeVideoId = youTubeUri.getQueryParameter("v");
}
playVideo(youtubeVideoId);
if (mTrackPlay) {
EasyTracker.getTracker().trackView("Live Streaming: " + title);
LOGD("Tracker", "Live Streaming: " + title);
}
updateSessionSummaryFragment(title, sessionAbstract);
mLiveListView.requestFocus();
}
private void updateSessionSummaryFragment(String title, String sessionAbstract) {
SessionSummaryFragment sessionSummaryFragment = (SessionSummaryFragment)
getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY);
if (sessionSummaryFragment != null) {
sessionSummaryFragment.setSessionSummaryInfo(title, sessionAbstract);
}
}
private void playVideo(String videoId) {
if ((mYouTubeVideoId == null || !mYouTubeVideoId.equals(videoId))
&& !TextUtils.isEmpty(videoId)) {
mYouTubeVideoId = videoId;
mYouTubePlayer.loadVideo(mYouTubeVideoId);
mTrackPlay = true;
} else {
mTrackPlay = false;
}
}
private void layoutFullscreenVideo(boolean fullscreen) {
if (mIsFullscreen != fullscreen) {
mIsFullscreen = fullscreen;
mYouTubePlayer.setFullscreen(fullscreen);
layoutGoogleTVFullScreen(fullscreen);
// Full screen layout changes for all form factors
final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams();
if (fullscreen) {
params.height = LayoutParams.MATCH_PARENT;
mMainLayout.setPadding(0, 0, 0, 0);
} else {
params.height = LayoutParams.WRAP_CONTENT;
}
mPlayerContainer.setLayoutParams(params);
}
}
/**
* Adjusts tablet layouts for full screen video.
*
* @param fullscreen True to layout in full screen, false to switch to regular layout
*/
private void layoutGoogleTVFullScreen(boolean fullscreen) {
if (fullscreen) {
mExtraLayout.setVisibility(View.GONE);
mSummaryLayout.setVisibility(View.GONE);
mMainLayout.setPadding(0, 0, 0, 0);
mVideoLayout.setPadding(0, 0, 0, 0);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(0, 0, 0, 0);
mVideoLayout.setLayoutParams(videoLayoutParams);
} else {
final int padding =
getResources().getDimensionPixelSize(R.dimen.multipane_half_padding);
mExtraLayout.setVisibility(View.VISIBLE);
mSummaryLayout.setVisibility(View.VISIBLE);
mMainLayout.setPadding(padding, padding, padding, padding);
mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(padding, padding, padding, padding);
mVideoLayout.setLayoutParams(videoLayoutParams);
}
}
/**
* Adapter that backs the action bar drop-down spinner.
*/
private class LivestreamAdapter extends CursorAdapter {
private LayoutInflater mLayoutInflater;
public LivestreamAdapter(Context context) {
super(context, null, false);
mLayoutInflater = (LayoutInflater)
context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public Object getItem(int position) {
mCursor.moveToPosition(position);
return mCursor;
}
@Override
public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the side list view
return mLayoutInflater.inflate(
R.layout.list_item_live_session, parent, false);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the side list view
return mLayoutInflater.inflate(R.layout.list_item_live_session,
parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView titleView = (TextView) view.findViewById(R.id.live_session_title);
final TextView subTitleView = (TextView) view.findViewById(R.id.live_session_subtitle);
String trackName = cursor.getString(SessionsQuery.TRACK_NAME);
if (TextUtils.isEmpty(trackName)) {
trackName = getString(R.string.app_name);
} else {
trackName = getString(R.string.session_livestream_track_title, trackName);
}
cursor.getInt(SessionsQuery.TRACK_COLOR);
String sessionTitle = cursor.getString(SessionsQuery.TITLE);
if (subTitleView != null) {
titleView.setText(trackName);
subTitleView.setText(sessionTitle);
} else { // Selected view
titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName);
}
}
}
// Enabling media keys for Google TV Devices
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MEDIA_PAUSE:
mYouTubePlayer.pause();
return true;
case KeyEvent.KEYCODE_MEDIA_PLAY:
mYouTubePlayer.play();
return true;
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
mYouTubePlayer.seekRelativeMillis(20000);
return true;
case KeyEvent.KEYCODE_MEDIA_REWIND:
mYouTubePlayer.seekRelativeMillis(-20000);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
// Need to sync with the conference API to get the livestream URLs
private class SyncOperationTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Perform a sync using SyncHelper
if (mGTVSyncHelper == null) {
mGTVSyncHelper = new SyncHelper(getApplicationContext());
}
try {
mGTVSyncHelper.performSync(null, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE);
} catch (IOException e) {
LOGE(TAG, "Error loading data for Google I/O 2012.", e);
}
return null;
}
}
/**
* Single session query
*/
public interface SessionSummaryQuery {
int _TOKEN = 0;
String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_ABSTRACT,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
int SESSION_ID = 0;
int TITLE = 1;
int ABSTRACT = 2;
int HASHTAGS = 3;
int LIVESTREAM_URL = 4;
int TRACK_NAME = 5;
int BLOCK_START= 6;
int BLOCK_END = 7;
}
/**
* List of sessions query
*/
public interface SessionsQuery {
int _TOKEN = 1;
String[] PROJECTION = {
BaseColumns._ID,
Sessions.SESSION_ID,
Sessions.SESSION_TITLE,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
int ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int TRACK_NAME = 3;
int TRACK_COLOR = 4;
int BLOCK_START= 5;
int BLOCK_END = 6;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/gtv/GoogleTVSessionLivestreamActivity.java | Java | asf20 | 23,470 |
/*
* 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.ui.widget;
import com.google.android.apps.iosched.util.UIUtils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
/**
* An extremely simple {@link LinearLayout} descendant that simply switches the order of its child
* views on Android 4.0+. The reason for this is that on Android, negative buttons should be shown
* to the left of positive buttons.
*/
public class ButtonBar extends LinearLayout {
public ButtonBar(Context context) {
super(context);
}
public ButtonBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ButtonBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public View getChildAt(int index) {
if (UIUtils.hasICS()) {
// Flip the buttons so that we get e.g. "Cancel | OK" on ICS
return super.getChildAt(getChildCount() - 1 - index);
}
return super.getChildAt(index);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/widget/ButtonBar.java | Java | asf20 | 1,695 |
/*
* 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.ui.widget;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a
* href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android
* Design > Patterns > Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for
* more details on this pattern. This layout should normally be used in association with the Up
* button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up
* button is pressed. If the master pane is visible, defer to normal Up behavior.
*
* <p>TODO: swiping should be more tactile and actually follow the user's finger.
*
* <p>Requires API level 11
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener {
private static final String TAG = makeLogTag(ShowHideMasterLayout.class);
/**
* A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should
* not be animated.
*/
public static final int FLAG_IMMEDIATE = 0x1;
private boolean mFirstShow = true;
private boolean mMasterVisible = true;
private View mMasterView;
private View mDetailView;
private OnMasterVisibilityChangedListener mOnMasterVisibilityChangedListener;
private GestureDetector mGestureDetector;
private boolean mFlingToExposeMaster;
private boolean mIsAnimating;
private Runnable mShowMasterCompleteRunnable;
// The last measured master width, including its margins.
private int mTranslateAmount;
public interface OnMasterVisibilityChangedListener {
public void onMasterVisibilityChanged(boolean visible);
}
public ShowHideMasterLayout(Context context) {
super(context);
init();
}
public ShowHideMasterLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ShowHideMasterLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mGestureDetector = new GestureDetector(getContext(), mGestureListener);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new MarginLayoutParams(p);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
// Measure once to find the maximum child size.
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth, child.getMeasuredWidth()
+ lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight, child.getMeasuredHeight()
+ lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingLeft() + getPaddingRight();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Set our own measured size
setMeasuredDimension(
resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
// Measure children for them to set their measured dimensions
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
getPaddingLeft() - getPaddingRight() -
lp.leftMargin - lp.rightMargin,
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() -
getPaddingTop() - getPaddingBottom() -
lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
updateChildReferences();
if (mMasterView == null || mDetailView == null) {
LOGW(TAG, "Master or detail is missing (need 2 children), can't layout.");
return;
}
int masterWidth = mMasterView.getMeasuredWidth();
MarginLayoutParams masterLp = (MarginLayoutParams) mMasterView.getLayoutParams();
MarginLayoutParams detailLp = (MarginLayoutParams) mDetailView.getLayoutParams();
mTranslateAmount = masterWidth + masterLp.leftMargin + masterLp.rightMargin;
mMasterView.layout(
l + masterLp.leftMargin,
t + masterLp.topMargin,
l + masterLp.leftMargin + masterWidth,
b - masterLp.bottomMargin);
mDetailView.layout(
l + detailLp.leftMargin + mTranslateAmount,
t + detailLp.topMargin,
r - detailLp.rightMargin + mTranslateAmount,
b - detailLp.bottomMargin);
// Update translationX values
if (!mIsAnimating) {
final float translationX = mMasterVisible ? 0 : -mTranslateAmount;
mMasterView.setTranslationX(translationX);
mDetailView.setTranslationX(translationX);
}
}
private void updateChildReferences() {
int childCount = getChildCount();
mMasterView = (childCount > 0) ? getChildAt(0) : null;
mDetailView = (childCount > 1) ? getChildAt(1) : null;
}
/**
* Allow or disallow the user to flick right on the detail pane to expose the master pane.
* @param enabled Whether or not to enable this interaction.
*/
public void setFlingToExposeMasterEnabled(boolean enabled) {
mFlingToExposeMaster = enabled;
}
/**
* Request the given listener be notified when the master pane is shown or hidden.
*
* @param listener The listener to notify when the master pane is shown or hidden.
*/
public void setOnMasterVisibilityChangedListener(OnMasterVisibilityChangedListener listener) {
mOnMasterVisibilityChangedListener = listener;
}
/**
* Returns whether or not the master pane is visible.
*
* @return True if the master pane is visible.
*/
public boolean isMasterVisible() {
return mMasterVisible;
}
/**
* Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable.
*/
public void showMaster(boolean show, int flags) {
showMaster(show, flags, null);
}
/**
* Shows or hides the master pane.
*
* @param show Whether or not to show the master pane.
* @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate.
* @param completeRunnable An optional runnable to run when any animations related to this are
* complete.
*/
public void showMaster(boolean show, int flags, Runnable completeRunnable) {
if (!mFirstShow && mMasterVisible == show) {
return;
}
mShowMasterCompleteRunnable = completeRunnable;
mFirstShow = false;
mMasterVisible = show;
if (mOnMasterVisibilityChangedListener != null) {
mOnMasterVisibilityChangedListener.onMasterVisibilityChanged(show);
}
updateChildReferences();
if (mMasterView == null || mDetailView == null) {
LOGW(TAG, "Master or detail is missing (need 2 children), can't change translation.");
return;
}
final float translationX = show ? 0 : -mTranslateAmount;
if ((flags & FLAG_IMMEDIATE) != 0) {
mMasterView.setTranslationX(translationX);
mDetailView.setTranslationX(translationX);
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
} else {
final long duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
// Animate if we have Honeycomb APIs, don't animate otherwise
mIsAnimating = true;
AnimatorSet animatorSet = new AnimatorSet();
mMasterView.setLayerType(LAYER_TYPE_HARDWARE, null);
mDetailView.setLayerType(LAYER_TYPE_HARDWARE, null);
animatorSet
.play(ObjectAnimator
.ofFloat(mMasterView, "translationX", translationX)
.setDuration(duration))
.with(ObjectAnimator
.ofFloat(mDetailView, "translationX", translationX)
.setDuration(duration));
animatorSet.addListener(this);
animatorSet.start();
// For API level 12+, use this instead:
// mMasterView.animate().translationX().setDuration(duration);
// mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration);
}
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// Really bad hack... we really shouldn't do this.
//super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mFlingToExposeMaster
&& !mMasterVisible) {
mGestureDetector.onTouchEvent(event);
}
if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) {
// If the master is visible, touching in the detail area should hide the master.
if (event.getX() > mTranslateAmount) {
return true;
}
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mFlingToExposeMaster
&& !mMasterVisible
&& mGestureDetector.onTouchEvent(event)) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) {
// If the master is visible, touching in the detail area should hide the master.
if (event.getX() > mTranslateAmount) {
showMaster(false, 0);
return true;
}
}
return super.onTouchEvent(event);
}
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
mIsAnimating = false;
mMasterView.setLayerType(LAYER_TYPE_NONE, null);
mDetailView.setLayerType(LAYER_TYPE_NONE, null);
requestLayout();
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
}
@Override
public void onAnimationCancel(Animator animator) {
mIsAnimating = false;
mMasterView.setLayerType(LAYER_TYPE_NONE, null);
mDetailView.setLayerType(LAYER_TYPE_NONE, null);
requestLayout();
if (mShowMasterCompleteRunnable != null) {
mShowMasterCompleteRunnable.run();
mShowMasterCompleteRunnable = null;
}
}
@Override
public void onAnimationRepeat(Animator animator) {
}
private final GestureDetector.OnGestureListener mGestureListener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
ViewConfiguration viewConfig = ViewConfiguration.get(getContext());
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
if (mFlingToExposeMaster
&& !mMasterVisible
&& velocityX > 0
&& absVelocityX >= absVelocityY // Fling at least as hard in X as in Y
&& absVelocityX > viewConfig.getScaledMinimumFlingVelocity()
&& absVelocityX < viewConfig.getScaledMaximumFlingVelocity()) {
showMaster(true, 0);
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
};
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java | Java | asf20 | 15,609 |
/*
* 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.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.FrameLayout;
/**
* A {@link Checkable} {@link FrameLayout}. When this is the root view for an item in a
* {@link android.widget.ListView} and the list view has a choice mode of
* {@link android.widget.ListView#CHOICE_MODE_MULTIPLE_MODAL }, the list view will
* set the item's state to CHECKED and not ACTIVATED. This is important to ensure that we can
* use the ACTIVATED state on tablet devices to represent the currently-viewed detail screen, while
* allowing multiple-selection.
*/
public class CheckableFrameLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableFrameLayout(Context context) {
super(context);
}
public CheckableFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private static final int[] CheckedStateSet = {
android.R.attr.state_checked
};
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(boolean checked) {
mChecked = checked;
refreshDrawableState();
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CheckedStateSet);
}
return drawableState;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/widget/CheckableFrameLayout.java | Java | asf20 | 2,376 |
/*
* 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.ui.widget;
import com.google.android.apps.iosched.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An {@link ImageView} that draws its contents inside a mask and draws a border drawable on top.
* This is useful for applying a beveled look to image contents, but is also flexible enough for use
* with other desired aesthetics.
*/
public class BezelImageView extends ImageView {
private static final String TAG = makeLogTag(BezelImageView.class);
private Paint mMaskedPaint;
private Rect mBounds;
private RectF mBoundsF;
private Drawable mBorderDrawable;
private Drawable mMaskDrawable;
private boolean mGuardInvalidate; // prevents stack overflows
public BezelImageView(Context context) {
this(context, null);
}
public BezelImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BezelImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView,
defStyle, 0);
mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable);
if (mMaskDrawable == null) {
mMaskDrawable = getResources().getDrawable(R.drawable.bezel_mask);
}
mMaskDrawable.setCallback(this);
mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable);
if (mBorderDrawable == null) {
mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border_default);
}
mBorderDrawable.setCallback(this);
a.recycle();
// Other initialization
mMaskedPaint = new Paint();
mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
}
private Bitmap mCached;
private void invalidateCache() {
if (mBounds == null || mBounds.width() == 0 || mBounds.height() == 0) {
return;
}
if (mCached != null) {
mCached.recycle();
mCached = null;
}
mCached = Bitmap.createBitmap(mBounds.width(), mBounds.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mCached);
int sc = canvas.saveLayer(mBoundsF, null,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
mMaskDrawable.draw(canvas);
canvas.saveLayer(mBoundsF, mMaskedPaint, 0);
// certain drawables invalidate themselves on draw, e.g. TransitionDrawable sets its alpha
// which invalidates itself. to prevent stack overflow errors, we must guard the
// invalidation (see specialized behavior when guarded in invalidate() below).
mGuardInvalidate = true;
super.onDraw(canvas);
mGuardInvalidate = false;
canvas.restoreToCount(sc);
mBorderDrawable.draw(canvas);
}
@Override
protected boolean setFrame(int l, int t, int r, int b) {
final boolean changed = super.setFrame(l, t, r, b);
mBounds = new Rect(0, 0, r - l, b - t);
mBoundsF = new RectF(mBounds);
mBorderDrawable.setBounds(mBounds);
mMaskDrawable.setBounds(mBounds);
if (changed) {
invalidateCache();
}
return changed;
}
@Override
protected void onDraw(Canvas canvas) {
if (mCached == null) {
invalidateCache();
}
if (mCached != null) {
canvas.drawBitmap(mCached, mBounds.left, mBounds.top, null);
}
//super.onDraw(canvas);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mBorderDrawable.isStateful()) {
mBorderDrawable.setState(getDrawableState());
}
if (mMaskDrawable.isStateful()) {
mMaskDrawable.setState(getDrawableState());
}
// TODO: may need to invalidate elsewhere
invalidate();
}
@Override
public void invalidate() {
if (mGuardInvalidate) {
removeCallbacks(mInvalidateCacheRunnable);
postDelayed(mInvalidateCacheRunnable, 16);
} else {
super.invalidate();
invalidateCache();
}
}
private Runnable mInvalidateCacheRunnable = new Runnable() {
@Override
public void run() {
invalidateCache();
BezelImageView.super.invalidate();
LOGD(TAG, "delayed invalidate");
}
};
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/widget/BezelImageView.java | Java | asf20 | 5,729 |
/*
* 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.ui.widget;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Arrays;
import java.util.Comparator;
public class SimpleSectionedListAdapter extends BaseAdapter {
private boolean mValid = true;
private int mSectionResourceId;
private LayoutInflater mLayoutInflater;
private ListAdapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public SimpleSectionedListAdapter(Context context, int sectionResourceId,
ListAdapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mBaseAdapter = baseAdapter;
mBaseAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
mValid = !mBaseAdapter.isEmpty();
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
mValid = false;
notifyDataSetInvalidated();
}
});
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
@Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return ListView.INVALID_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
@Override
public int getCount() {
return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0);
}
@Override
public Object getItem(int position) {
return isSectionHeaderPosition(position)
? mSections.get(position)
: mBaseAdapter.getItem(sectionedPositionToPosition(position));
}
@Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
@Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? getViewTypeCount() - 1
: mBaseAdapter.getItemViewType(position);
}
@Override
public boolean isEnabled(int position) {
//noinspection SimplifiableConditionalExpression
return isSectionHeaderPosition(position)
? false
: mBaseAdapter.isEnabled(sectionedPositionToPosition(position));
}
@Override
public int getViewTypeCount() {
return mBaseAdapter.getViewTypeCount() + 1; // the section headings
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean hasStableIds() {
return mBaseAdapter.hasStableIds();
}
@Override
public boolean isEmpty() {
return mBaseAdapter.isEmpty();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (isSectionHeaderPosition(position)) {
TextView view = (TextView) convertView;
if (view == null) {
view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false);
}
view.setText(mSections.get(position).title);
return view;
} else {
return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/widget/SimpleSectionedListAdapter.java | Java | asf20 | 6,081 |
/*
* 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.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet;
/**
* A {@link ListFragment} showing a list of developer sandbox companies.
*/
public class VendorsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(VendorsFragment.class);
private static final String STATE_SELECTED_ID = "selectedId";
private Uri mVendorsUri;
private CursorAdapter mAdapter;
private String mSelectedVendorId;
private boolean mHasSetEmptyText = false;
public interface Callbacks {
/** Return true to select (activate) the vendor in the list, false otherwise. */
public boolean onVendorSelected(String vendorId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public boolean onVendorSelected(String vendorId) {
return true;
}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mSelectedVendorId = savedInstanceState.getString(STATE_SELECTED_ID);
}
reloadFromArguments(getArguments());
}
public void reloadFromArguments(Bundle arguments) {
// Teardown from previous arguments
setListAdapter(null);
// Load new arguments
final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
mVendorsUri = intent.getData();
final int vendorQueryToken;
if (mVendorsUri == null) {
return;
}
mAdapter = new VendorsAdapter(getActivity());
vendorQueryToken = VendorsQuery._TOKEN;
setListAdapter(mAdapter);
// Start background query to load vendors
getLoaderManager().initLoader(vendorQueryToken, null, this);
}
public void setSelectedVendorId(String id) {
mSelectedVendorId = id;
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setSelector(android.R.color.transparent);
listView.setCacheColorHint(Color.WHITE);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mHasSetEmptyText) {
// Could be a bug, but calling this twice makes it become visible
// when it shouldn't be visible.
setEmptyText(getString(R.string.empty_vendors));
mHasSetEmptyText = true;
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedVendorId != null) {
outState.putString(STATE_SELECTED_ID, mSelectedVendorId);
}
}
/** {@inheritDoc} */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Cursor cursor = (Cursor) mAdapter.getItem(position);
String vendorId = cursor.getString(VendorsQuery.VENDOR_ID);
if (mCallbacks.onVendorSelected(vendorId)) {
mSelectedVendorId = vendorId;
mAdapter.notifyDataSetChanged();
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mVendorsUri, VendorsQuery.PROJECTION, null, null,
ScheduleContract.Vendors.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
int token = loader.getId();
if (token == VendorsQuery._TOKEN) {
mAdapter.changeCursor(cursor);
} else {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> cursor) {
}
/**
* {@link CursorAdapter} that renders a {@link VendorsQuery}.
*/
private class VendorsAdapter extends CursorAdapter {
public VendorsAdapter(Context context) {
super(context, null, false);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor,
parent, false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
UIUtils.setActivatedCompat(view, cursor.getString(VendorsQuery.VENDOR_ID)
.equals(mSelectedVendorId));
((TextView) view.findViewById(R.id.vendor_name)).setText(
cursor.getString(VendorsQuery.NAME));
}
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors}
* query parameters.
*/
private interface VendorsQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Vendors.VENDOR_ID,
ScheduleContract.Vendors.VENDOR_NAME,
};
int _ID = 0;
int VENDOR_ID = 1;
int NAME = 2;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/VendorsFragment.java | Java | asf20 | 7,539 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.apps.iosched.util.actionmodecompat.ActionMode;
import com.google.android.apps.iosched.util.actionmodecompat.MultiChoiceModeListener;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.LinkedHashSet;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
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.UIUtils.buildStyledSnippet;
import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle;
/**
* A {@link ListFragment} showing a list of sessions. This fragment supports multiple-selection
* using the contextual action bar (on API 11+ devices), and also supports a separate 'activated'
* state for indicating the currently-opened detail view on tablet devices.
*/
public class SessionsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>,
MultiChoiceModeListener {
private static final String TAG = makeLogTag(SessionsFragment.class);
private static final String STATE_SELECTED_ID = "selectedId";
private CursorAdapter mAdapter;
private String mSelectedSessionId;
private MenuItem mStarredMenuItem;
private MenuItem mMapMenuItem;
private MenuItem mShareMenuItem;
private MenuItem mSocialStreamMenuItem;
private boolean mHasSetEmptyText = false;
private int mSessionQueryToken;
private LinkedHashSet<Integer> mSelectedSessionPositions = new LinkedHashSet<Integer>();
private Handler mHandler = new Handler();
public interface Callbacks {
/** Return true to select (activate) the session in the list, false otherwise. */
public boolean onSessionSelected(String sessionId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public boolean onSessionSelected(String sessionId) {
return true;
}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID);
}
reloadFromArguments(getArguments());
}
protected void reloadFromArguments(Bundle arguments) {
// Teardown from previous arguments
setListAdapter(null);
// Load new arguments
final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
final Uri sessionsUri = intent.getData();
if (sessionsUri == null) {
return;
}
if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) {
mAdapter = new SessionsAdapter(getActivity());
mSessionQueryToken = SessionsQuery._TOKEN;
} else {
mAdapter = new SearchAdapter(getActivity());
mSessionQueryToken = SearchQuery._TOKEN;
}
setListAdapter(mAdapter);
// Force start background query to load sessions
getLoaderManager().restartLoader(mSessionQueryToken, arguments, this);
}
public void setSelectedSessionId(String id) {
mSelectedSessionId = id;
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setSelector(android.R.color.transparent);
listView.setCacheColorHint(Color.WHITE);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mHasSetEmptyText) {
// Could be a bug, but calling this twice makes it become visible
// when it shouldn't
// be visible.
setEmptyText(getString(R.string.empty_sessions));
mHasSetEmptyText = true;
}
ActionMode.setMultiChoiceMode(getListView(), getActivity(), this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
activity.getContentResolver().registerContentObserver(
ScheduleContract.Sessions.CONTENT_URI, true, mObserver);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
@Override
public void onResume() {
super.onResume();
mHandler.post(mRefreshSessionsRunnable);
}
@Override
public void onPause() {
super.onPause();
mHandler.removeCallbacks(mRefreshSessionsRunnable);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedSessionId != null) {
outState.putString(STATE_SELECTED_ID, mSelectedSessionId);
}
}
/** {@inheritDoc} */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Cursor cursor = (Cursor) mAdapter.getItem(position);
String sessionId = cursor.getString(cursor.getColumnIndex(
ScheduleContract.Sessions.SESSION_ID));
if (mCallbacks.onSessionSelected(sessionId)) {
mSelectedSessionId = sessionId;
mAdapter.notifyDataSetChanged();
}
}
// LoaderCallbacks interface
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
final Intent intent = BaseActivity.fragmentArgumentsToIntent(data);
final Uri sessionsUri = intent.getData();
Loader<Cursor> loader = null;
if (id == SessionsQuery._TOKEN) {
loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION,
null, null, ScheduleContract.Sessions.DEFAULT_SORT);
} else if (id == SearchQuery._TOKEN) {
loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, null,
null, ScheduleContract.Sessions.DEFAULT_SORT);
}
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
int token = loader.getId();
if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) {
mAdapter.changeCursor(cursor);
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey("_uri")) {
String uri = arguments.get("_uri").toString();
if(uri != null && uri.contains("blocks")) {
String title = arguments.getString(Intent.EXTRA_TITLE);
if (title == null) {
title = (String) this.getActivity().getTitle();
}
EasyTracker.getTracker().trackView("Session Block: " + title);
LOGD("Tracker", "Session Block: " + title);
}
}
} else {
LOGD(TAG, "Query complete, Not Actionable: " + token);
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
// MultiChoiceModeListener interface
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
SessionsHelper helper = new SessionsHelper(getActivity());
mode.finish();
switch (item.getItemId()) {
case R.id.menu_map: {
// multiple selection not supported
int position = mSelectedSessionPositions.iterator().next();
Cursor cursor = (Cursor) mAdapter.getItem(position);
String roomId = cursor.getString(SessionsQuery.ROOM_ID);
helper.startMapActivity(roomId);
String title = cursor.getString(SessionsQuery.TITLE);
EasyTracker.getTracker().trackEvent(
"Session", "Mapped", title, 0L);
LOGV(TAG, "Starred: " + title);
return true;
}
case R.id.menu_star: {
// multiple selection supported
boolean starred = false;
int numChanged = 0;
for (int position : mSelectedSessionPositions) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
String title = cursor.getString(SessionsQuery.TITLE);
String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId);
starred = cursor.getInt(SessionsQuery.STARRED) == 0;
helper.setSessionStarred(sessionUri, starred, title);
++numChanged;
EasyTracker.getTracker().trackEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
LOGV(TAG, "Starred: " + title);
}
Toast.makeText(
getActivity(),
getResources().getQuantityString(starred
? R.plurals.toast_added_to_schedule
: R.plurals.toast_removed_from_schedule, numChanged, numChanged),
Toast.LENGTH_SHORT).show();
setSelectedSessionStarred(starred);
return true;
}
case R.id.menu_share: {
// multiple selection not supported
int position = mSelectedSessionPositions.iterator().next();
// On ICS+ devices, we normally won't reach this as ShareActionProvider will handle
// sharing.
Cursor cursor = (Cursor) mAdapter.getItem(position);
new SessionsHelper(getActivity()).shareSession(getActivity(),
R.string.share_template,
cursor.getString(SessionsQuery.TITLE),
cursor.getString(SessionsQuery.HASHTAGS),
cursor.getString(SessionsQuery.URL));
return true;
}
case R.id.menu_social_stream:
StringBuilder hashtags = new StringBuilder();
for (int position : mSelectedSessionPositions) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
String term = cursor.getString(SessionsQuery.HASHTAGS);
if (!term.startsWith("#")) {
term = "#" + term;
}
if (hashtags.length() > 0) {
hashtags.append(" OR ");
}
hashtags.append(term);
String title = cursor.getString(SessionsQuery.TITLE);
EasyTracker.getTracker().trackEvent(
"Session", "Mapped", title, 0L);
LOGV(TAG, "Starred: " + title);
}
helper.startSocialStream(hashtags.toString());
return true;
default:
LOGW(TAG, "CAB unknown selection=" + item.getItemId());
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.sessions_context, menu);
mStarredMenuItem = menu.findItem(R.id.menu_star);
mMapMenuItem = menu.findItem(R.id.menu_map);
mShareMenuItem = menu.findItem(R.id.menu_share);
mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream);
mSelectedSessionPositions.clear();
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
mSelectedSessionPositions.add(position);
} else {
mSelectedSessionPositions.remove(position);
}
int numSelectedSessions = mSelectedSessionPositions.size();
mode.setTitle(getResources().getQuantityString(
R.plurals.title_selected_sessions,
numSelectedSessions, numSelectedSessions));
if (numSelectedSessions == 1) {
// activate all the menu item
mMapMenuItem.setVisible(true);
mShareMenuItem.setVisible(true);
mSocialStreamMenuItem.setVisible(true);
mStarredMenuItem.setVisible(true);
position = mSelectedSessionPositions.iterator().next();
Cursor cursor = (Cursor) mAdapter.getItem(position);
boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
setSelectedSessionStarred(starred);
} else {
mMapMenuItem.setVisible(false);
mShareMenuItem.setVisible(false);
mSocialStreamMenuItem.setVisible(false);
boolean allStarred = true;
boolean allUnstarred = true;
for (int pos : mSelectedSessionPositions) {
Cursor cursor = (Cursor) mAdapter.getItem(pos);
boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
allStarred = allStarred && starred;
allUnstarred = allUnstarred && !starred;
}
if (allStarred) {
setSelectedSessionStarred(true);
mStarredMenuItem.setVisible(true);
} else if (allUnstarred) {
setSelectedSessionStarred(false);
mStarredMenuItem.setVisible(true);
} else {
mStarredMenuItem.setVisible(false);
}
}
}
private void setSelectedSessionStarred(boolean starred) {
mStarredMenuItem.setTitle(starred
? R.string.description_remove_schedule
: R.string.description_add_schedule);
mStarredMenuItem.setIcon(starred
? R.drawable.ic_action_remove_schedule
: R.drawable.ic_action_add_schedule);
}
private final Runnable mRefreshSessionsRunnable = new Runnable() {
public void run() {
if (mAdapter != null) {
// This is used to refresh session title colors.
mAdapter.notifyDataSetChanged();
}
// Check again on the next quarter hour, with some padding to
// account for network
// time differences.
long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000;
mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour);
}
};
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (getActivity() == null) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken);
if (loader != null) {
loader.forceLoad();
}
}
};
/**
* {@link CursorAdapter} that renders a {@link SessionsQuery}.
*/
private class SessionsAdapter extends CursorAdapter {
public SessionsAdapter(Context context) {
super(context, null, false);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId == null) {
return;
}
if (sessionId.equals(mSelectedSessionId)){
UIUtils.setActivatedCompat(view, true);
} else {
UIUtils.setActivatedCompat(view, false);
}
final TextView titleView = (TextView) view.findViewById(R.id.session_title);
final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle);
final String sessionTitle = cursor.getString(SessionsQuery.TITLE);
titleView.setText(sessionTitle);
// Format time block this session occupies
final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START);
final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
final String roomName = cursor.getString(SessionsQuery.ROOM_NAME);
final String subtitle = formatSessionSubtitle(
sessionTitle, blockStart, blockEnd, roomName, context);
final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
view.findViewById(R.id.indicator_in_schedule).setVisibility(
starred ? View.VISIBLE : View.INVISIBLE);
final boolean hasLivestream = !TextUtils.isEmpty(
cursor.getString(SessionsQuery.LIVESTREAM_URL));
// Show past/present/future and livestream status for this block.
UIUtils.updateTimeAndLivestreamBlockUI(context,
blockStart, blockEnd, hasLivestream,
view.findViewById(R.id.list_item_session), titleView, subtitleView, subtitle);
}
}
/**
* {@link CursorAdapter} that renders a {@link SearchQuery}.
*/
private class SearchAdapter extends CursorAdapter {
public SearchAdapter(Context context) {
super(context, null, false);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID)
.equals(mSelectedSessionId));
((TextView) view.findViewById(R.id.session_title)).setText(cursor
.getString(SearchQuery.TITLE));
final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET);
final Spannable styledSnippet = buildStyledSnippet(snippet);
((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet);
final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0;
view.findViewById(R.id.indicator_in_schedule).setVisibility(
starred ? View.VISIBLE : View.INVISIBLE);
}
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions}
* query parameters.
*/
private interface SessionsQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_URL,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
};
int _ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int STARRED = 3;
int BLOCK_START = 4;
int BLOCK_END = 5;
int ROOM_NAME = 6;
int ROOM_ID = 7;
int HASHTAGS = 8;
int URL = 9;
int LIVESTREAM_URL = 10;
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions}
* search query parameters.
*/
private interface SearchQuery {
int _TOKEN = 0x3;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Sessions.SEARCH_SNIPPET,
ScheduleContract.Sessions.SESSION_LEVEL,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_URL
};
int _ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int STARRED = 3;
int SEARCH_SNIPPET = 4;
int LEVEL = 5;
int ROOM_NAME = 6;
int ROOM_ID = 7;
int HASHTAGS = 8;
int URL = 9;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SessionsFragment.java | Java | asf20 | 23,652 |
/*
* 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.ui;
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.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.youtube.api.YouTube;
import com.google.android.youtube.api.YouTubePlayer;
import com.google.android.youtube.api.YouTubePlayerSupportFragment;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.app.NavUtils;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
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;
/**
* An activity that displays the session live stream video which is pulled in from YouTube. The
* UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting
* and buffering again on orientation change, we handle configuration changes manually.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SessionLivestreamActivity extends BaseActivity implements
LoaderCallbacks<Cursor>,
YouTubePlayer.OnPlaybackEventsListener,
YouTubePlayer.OnFullscreenListener,
ActionBar.OnNavigationListener {
private static final String TAG = makeLogTag(SessionLivestreamActivity.class);
private static final String EXTRA_PREFIX = "com.google.android.iosched.extra.";
public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url";
public static final String EXTRA_TRACK = EXTRA_PREFIX + "track";
public static final String EXTRA_TITLE = EXTRA_PREFIX + "title";
public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract";
public static final String KEYNOTE_TRACK_NAME = "Keynote";
private static final String LOADER_SESSIONS_ARG = "futureSessions";
private static final String TAG_SESSION_SUMMARY = "session_summary";
private static final String TAG_CAPTIONS = "captions";
private static final int TABNUM_SESSION_SUMMARY = 0;
private static final int TABNUM_SOCIAL_STREAM = 1;
private static final int TABNUM_LIVE_CAPTIONS = 2;
private static final String EXTRA_TAB_STATE = "tag";
private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes
private boolean mIsTablet;
private boolean mIsFullscreen = false;
private boolean mLoadFromExtras = false;
private boolean mTrackPlay = true;
private int mNormalScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
private TabHost mTabHost;
private TabsAdapter mTabsAdapter;
private YouTubePlayerSupportFragment mYouTubePlayer;
private LinearLayout mPlayerContainer;
private String mYouTubeVideoId;
private LinearLayout mMainLayout;
private LinearLayout mVideoLayout;
private LinearLayout mExtraLayout;
private FrameLayout mSummaryLayout;
private FrameLayout mFullscreenCaptions;
private MenuItem mCaptionsMenuItem;
private MenuItem mShareMenuItem;
private Runnable mShareMenuDeferredSetup;
private Runnable mSessionSummaryDeferredSetup;
private SessionShareData mSessionShareData;
private boolean mSessionsFound;
private boolean isKeynote = false;
private Handler mHandler = new Handler();
private LivestreamAdapter mLivestreamAdapter;
private Uri mSessionUri;
private String mSessionId;
private String mTrackName;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (UIUtils.hasICS()) {
// We can't use this mode on HC as compatible ActionBar doesn't work well with the YT
// player in full screen mode (no overlays allowed).
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
}
super.onCreate(savedInstanceState);
YouTube.initialize(this, Config.YOUTUBE_API_KEY);
setContentView(R.layout.activity_session_livestream);
mIsTablet = UIUtils.isHoneycombTablet(this);
// Set up YouTube player
mYouTubePlayer = (YouTubePlayerSupportFragment) getSupportFragmentManager()
.findFragmentById(R.id.livestream_player);
mYouTubePlayer.enableCustomFullscreen(this);
mYouTubePlayer.setOnPlaybackEventsListener(this);
int fullscreenControlFlags = YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI
| YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION;
if (!mIsTablet) {
fullscreenControlFlags |= YouTubePlayer.FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
mYouTubePlayer.setFullscreenControlFlags(fullscreenControlFlags);
// Views that are common over all layouts
mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout);
adjustMainLayoutForActionBar();
mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container);
mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions);
final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams();
params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx());
mFullscreenCaptions.setLayoutParams(params);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(2);
viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
viewPager.setPageMargin(getResources()
.getDimensionPixelSize(R.dimen.page_margin_width));
// Set up tabs w/viewpager
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager);
if (mIsTablet) {
// Tablet UI specific views
getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary,
new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit();
mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout);
mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout);
mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary);
} else {
// Handset UI specific views
mTabsAdapter.addTab(
getString(R.string.session_livestream_info),
new SessionSummaryFragment(),
TABNUM_SESSION_SUMMARY);
}
mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(),
TABNUM_SOCIAL_STREAM);
mTabsAdapter.addTab(getString(R.string.session_livestream_captions),
new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE));
}
// Reload all other data in this activity
reloadFromIntent(getIntent());
// Update layout based on current configuration
updateLayout(getResources().getConfiguration());
// Set up action bar
if (!mLoadFromExtras) {
// Start sessions query to populate action bar navigation spinner
getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this);
// Set up action bar
mLivestreamAdapter = new LivestreamAdapter(this);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(mLivestreamAdapter, this);
actionBar.setDisplayShowTitleEnabled(false);
}
}
@Override
protected void onResume() {
super.onResume();
if (mSessionSummaryDeferredSetup != null) {
mSessionSummaryDeferredSetup.run();
mSessionSummaryDeferredSetup = null;
}
mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME);
}
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(mStreamRefreshRunnable);
}
/**
* Reloads all data in the activity and fragments from a given intent
* @param intent The intent to load from
*/
private void reloadFromIntent(Intent intent) {
final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL);
// Check if youtube url is set as an extra first
if (youtubeUrl != null) {
mLoadFromExtras = true;
String trackName = intent.getStringExtra(EXTRA_TRACK);
String actionBarTitle;
if (trackName == null) {
actionBarTitle = getString(R.string.session_livestream_title);
} else {
actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title);
}
getSupportActionBar().setTitle(actionBarTitle);
updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE),
intent.getStringExtra(EXTRA_ABSTRACT),
UIUtils.CONFERENCE_HASHTAG, trackName);
} else {
// Otherwise load from session uri
reloadFromUri(intent.getData());
}
}
/**
* Reloads all data in the activity and fragments from a given uri
* @param newUri The session uri to load from
*/
private void reloadFromUri(Uri newUri) {
mSessionUri = newUri;
if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) {
mSessionId = Sessions.getSessionId(mSessionUri);
getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this);
} else {
// No session uri, get out
mSessionUri = null;
navigateUpOrFinish();
}
}
/**
* Helper method to start this activity using only extras (rather than session uri).
* @param context The package context
* @param youtubeUrl The youtube url or video id to load
* @param track The track title (appears as part of action bar title), can be null
* @param title The title to show in the session info fragment, can be null
* @param sessionAbstract The session abstract to show in the session info fragment, can be null
*/
public static void startFromExtras(Context context, String youtubeUrl, String track,
String title, String sessionAbstract) {
if (youtubeUrl == null) {
return;
}
final Intent i = new Intent();
i.setClass(context, SessionLivestreamActivity.class);
i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl);
i.putExtra(EXTRA_TRACK, track);
i.putExtra(EXTRA_TITLE, title);
i.putExtra(EXTRA_ABSTRACT, sessionAbstract);
context.startActivity(i);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mTabHost != null) {
outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.session_livestream, menu);
mCaptionsMenuItem = menu.findItem(R.id.menu_captions);
mShareMenuItem = menu.findItem(R.id.menu_share);
if (mShareMenuDeferredSetup != null) {
mShareMenuDeferredSetup.run();
}
if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE ==
getResources().getConfiguration().orientation) {
mCaptionsMenuItem.setVisible(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mIsFullscreen) {
mYouTubePlayer.setFullscreen(false);
} else {
navigateUpOrFinish();
}
return true;
case R.id.menu_captions:
if (mIsFullscreen) {
if (mFullscreenCaptions.getVisibility() == View.GONE) {
mFullscreenCaptions.setVisibility(View.VISIBLE);
SessionLiveCaptionsFragment captionsFragment;
captionsFragment = (SessionLiveCaptionsFragment)
getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS);
if (captionsFragment == null) {
captionsFragment = new SessionLiveCaptionsFragment();
captionsFragment.setDarkTheme(true);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS);
ft.commit();
}
captionsFragment.setTrackName(mTrackName);
return true;
}
}
mFullscreenCaptions.setVisibility(View.GONE);
break;
case R.id.menu_share:
if (mSessionShareData != null) {
new SessionsHelper(this).shareSession(this,
R.string.share_livestream_template,
mSessionShareData.SESSION_TITLE,
mSessionShareData.SESSION_HASHTAG,
mSessionShareData.SESSION_URL);
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (mIsFullscreen) {
// Exit full screen mode on back key
mYouTubePlayer.setFullscreen(false);
} else {
super.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Need to handle configuration changes so as not to interrupt YT player and require
// buffering again
updateLayout(newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition);
setActionBarColor(cursor.getInt(SessionsQuery.TRACK_COLOR));
final String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId != null) {
reloadFromUri(Sessions.buildSessionUri(sessionId));
return true;
}
return false;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case SessionSummaryQuery._TOKEN:
return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId),
SessionSummaryQuery.PROJECTION, null, null, null);
case SessionsQuery._TOKEN:
boolean futureSessions = false;
if (args != null) {
futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false);
}
final long currentTime = UIUtils.getCurrentTime(this);
String selection = Sessions.LIVESTREAM_SELECTION + " and ";
String[] selectionArgs;
if (!futureSessions) {
selection += Sessions.AT_TIME_SELECTION;
selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime);
} else {
selection += Sessions.UPCOMING_SELECTION;
selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime);
}
return new CursorLoader(this, Sessions.buildWithTracksUri(),
SessionsQuery.PROJECTION, selection, selectionArgs, null);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case SessionSummaryQuery._TOKEN:
loadSession(data);
break;
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(data);
if (data != null && data.getCount() > 0) {
mSessionsFound = true;
final int selected = locateSelectedItem(data);
getSupportActionBar().setSelectedNavigationItem(selected);
} else if (mSessionsFound) {
mSessionsFound = false;
final Bundle bundle = new Bundle();
bundle.putBoolean(LOADER_SESSIONS_ARG, true);
getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this);
} else {
navigateUpOrFinish();
}
break;
}
}
/**
* Locates which item should be selected in the action bar drop-down spinner based on the
* current active session uri
* @param data The data
* @return The row num of the item that should be selected or 0 if not found
*/
private int locateSelectedItem(Cursor data) {
int selected = 0;
if (data != null && (mSessionId != null || mTrackName != null)) {
final boolean findNextSessionByTrack = mTrackName != null;
while (data.moveToNext()) {
if (findNextSessionByTrack) {
if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) {
selected = data.getPosition();
mTrackName = null;
break;
}
} else {
if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) {
selected = data.getPosition();
}
}
}
}
return selected;
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
switch (loader.getId()) {
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(null);
break;
}
}
@Override
public void onFullscreen(boolean fullScreen) {
layoutFullscreenVideo(fullScreen);
}
@Override
public void onLoaded(String s) {
}
@Override
public void onPlaying() {
}
@Override
public void onPaused() {
}
@Override
public void onBuffering(boolean b) {
}
@Override
public void onEnded() {
}
@Override
public void onError() {
Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show();
}
private void loadSession(Cursor data) {
if (data != null && data.moveToFirst()) {
mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME);
if (TextUtils.isEmpty(mTrackName)) {
mTrackName = KEYNOTE_TRACK_NAME;
isKeynote = true;
}
final long currentTime = UIUtils.getCurrentTime(this);
if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) {
getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this);
return;
}
updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS));
updateSessionViews(
data.getString(SessionSummaryQuery.LIVESTREAM_URL),
data.getString(SessionSummaryQuery.TITLE),
data.getString(SessionSummaryQuery.ABSTRACT),
data.getString(SessionSummaryQuery.HASHTAGS), mTrackName);
}
}
/**
* Updates views that rely on session data from explicit strings.
*/
private void updateSessionViews(final String youtubeUrl, final String title,
final String sessionAbstract, final String hashTag, final String trackName) {
if (youtubeUrl == null) {
// Get out, nothing to do here
navigateUpOrFinish();
return;
}
mTrackName = trackName;
String youtubeVideoId = youtubeUrl;
if (youtubeUrl.startsWith("http")) {
final Uri youTubeUri = Uri.parse(youtubeUrl);
youtubeVideoId = youTubeUri.getQueryParameter("v");
}
playVideo(youtubeVideoId);
if (mTrackPlay) {
EasyTracker.getTracker().trackView("Live Streaming: " + title);
LOGD("Tracker", "Live Streaming: " + title);
}
final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId;
mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl);
mShareMenuDeferredSetup = new Runnable() {
@Override
public void run() {
new SessionsHelper(SessionLivestreamActivity.this)
.tryConfigureShareMenuItem(mShareMenuItem,
R.string.share_livestream_template,
title, hashTag, newYoutubeUrl);
}
};
if (mShareMenuItem != null) {
mShareMenuDeferredSetup.run();
mShareMenuDeferredSetup = null;
}
mSessionSummaryDeferredSetup = new Runnable() {
@Override
public void run() {
updateSessionSummaryFragment(title, sessionAbstract);
updateSessionLiveCaptionsFragment(trackName);
}
};
if (!mLoadFromExtras) {
mSessionSummaryDeferredSetup.run();
mSessionSummaryDeferredSetup = null;
}
}
private void updateSessionSummaryFragment(String title, String sessionAbstract) {
SessionSummaryFragment sessionSummaryFragment;
if (mIsTablet) {
sessionSummaryFragment = (SessionSummaryFragment)
getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY);
} else {
sessionSummaryFragment = (SessionSummaryFragment)
mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY);
}
if (sessionSummaryFragment != null) {
sessionSummaryFragment.setSessionSummaryInfo(
isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title,
(isKeynote && TextUtils.isEmpty(sessionAbstract)) ?
getString(R.string.session_livestream_keynote_desc)
: sessionAbstract);
}
}
Runnable mStreamRefreshRunnable = new Runnable() {
@Override
public void run() {
if (mTabsAdapter != null && mTabsAdapter.mFragments != null) {
final SocialStreamFragment socialStreamFragment =
(SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM);
if (socialStreamFragment != null) {
socialStreamFragment.refresh();
}
}
mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME);
}
};
private void updateTagStreamFragment(String trackHashTag) {
String hashTags = UIUtils.CONFERENCE_HASHTAG;
if (!TextUtils.isEmpty(trackHashTag)) {
hashTags += " " + trackHashTag;
}
final SocialStreamFragment socialStreamFragment =
(SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM);
if (socialStreamFragment != null) {
socialStreamFragment.refresh(hashTags);
}
}
private void updateSessionLiveCaptionsFragment(String trackName) {
final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment)
mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS);
if (captionsFragment != null) {
captionsFragment.setTrackName(trackName);
}
}
private void playVideo(String videoId) {
if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId))
&& !TextUtils.isEmpty(videoId)) {
mYouTubeVideoId = videoId;
mYouTubePlayer.loadVideo(mYouTubeVideoId);
mTrackPlay = true;
if (mSessionShareData != null) {
mSessionShareData.SESSION_URL = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId;
}
}
}
private void navigateUpOrFinish() {
if (mLoadFromExtras || isKeynote) {
final Intent homeIntent = new Intent();
homeIntent.setClass(this, HomeActivity.class);
NavUtils.navigateUpTo(this, homeIntent);
} else if (mSessionUri != null) {
final Intent parentIntent = new Intent(Intent.ACTION_VIEW, mSessionUri);
NavUtils.navigateUpTo(this, parentIntent);
} else {
finish();
}
}
/**
* Updates the layout based on the provided configuration
*/
private void updateLayout(Configuration config) {
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (mIsTablet) {
layoutTabletForLandscape();
} else {
layoutPhoneForLandscape();
}
} else {
if (mIsTablet) {
layoutTabletForPortrait();
} else {
layoutPhoneForPortrait();
}
}
}
private void layoutPhoneForLandscape() {
layoutFullscreenVideo(true);
}
private void layoutPhoneForPortrait() {
layoutFullscreenVideo(false);
SessionSummaryFragment fragment = (SessionSummaryFragment)
mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY);
if (fragment != null) {
fragment.updateViews();
}
}
private void layoutTabletForLandscape() {
mMainLayout.setOrientation(LinearLayout.HORIZONTAL);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.height = LayoutParams.MATCH_PARENT;
videoLayoutParams.width = 0;
videoLayoutParams.weight = 1;
mVideoLayout.setLayoutParams(videoLayoutParams);
final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams();
extraLayoutParams.height = LayoutParams.MATCH_PARENT;
extraLayoutParams.width = 0;
extraLayoutParams.weight = 1;
mExtraLayout.setLayoutParams(extraLayoutParams);
}
private void layoutTabletForPortrait() {
mMainLayout.setOrientation(LinearLayout.VERTICAL);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.width = LayoutParams.MATCH_PARENT;
if (mLoadFromExtras) {
// Loading from extras, let the top fragment wrap_content
videoLayoutParams.height = LayoutParams.WRAP_CONTENT;
videoLayoutParams.weight = 0;
} else {
// Otherwise the session description will be longer, give it some space
videoLayoutParams.height = 0;
videoLayoutParams.weight = 7;
}
mVideoLayout.setLayoutParams(videoLayoutParams);
final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams();
extraLayoutParams.width = LayoutParams.MATCH_PARENT;
extraLayoutParams.height = 0;
extraLayoutParams.weight = 5;
mExtraLayout.setLayoutParams(extraLayoutParams);
}
private void layoutFullscreenVideo(boolean fullscreen) {
if (mIsFullscreen != fullscreen) {
mIsFullscreen = fullscreen;
if (mIsTablet) {
// Tablet specific full screen layout
layoutTabletFullScreen(fullscreen);
} else {
// Phone specific full screen layout
layoutPhoneFullScreen(fullscreen);
}
// Full screen layout changes for all form factors
final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams();
if (fullscreen) {
if (mCaptionsMenuItem != null) {
mCaptionsMenuItem.setVisible(true);
}
params.height = LayoutParams.MATCH_PARENT;
mMainLayout.setPadding(0, 0, 0, 0);
} else {
getSupportActionBar().show();
if (mCaptionsMenuItem != null) {
mCaptionsMenuItem.setVisible(false);
}
mFullscreenCaptions.setVisibility(View.GONE);
params.height = LayoutParams.WRAP_CONTENT;
adjustMainLayoutForActionBar();
}
View youTubePlayerView = mYouTubePlayer.getView();
if (youTubePlayerView != null) {
ViewGroup.LayoutParams playerParams = mYouTubePlayer.getView().getLayoutParams();
playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT
: LayoutParams.WRAP_CONTENT;
youTubePlayerView.setLayoutParams(playerParams);
}
mPlayerContainer.setLayoutParams(params);
}
}
private void adjustMainLayoutForActionBar() {
if (UIUtils.hasICS()) {
// On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to
// re-adjust layouts when hiding action bar. To account for this we add action bar
// height pack to the padding when not in full screen mode.
mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0);
}
}
/**
* Adjusts tablet layouts for full screen video.
*
* @param fullscreen True to layout in full screen, false to switch to regular layout
*/
private void layoutTabletFullScreen(boolean fullscreen) {
if (fullscreen) {
mExtraLayout.setVisibility(View.GONE);
mSummaryLayout.setVisibility(View.GONE);
mVideoLayout.setPadding(0, 0, 0, 0);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(0, 0, 0, 0);
mVideoLayout.setLayoutParams(videoLayoutParams);
} else {
final int padding =
getResources().getDimensionPixelSize(R.dimen.multipane_half_padding);
mExtraLayout.setVisibility(View.VISIBLE);
mSummaryLayout.setVisibility(View.VISIBLE);
mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(padding, padding, padding, padding);
mVideoLayout.setLayoutParams(videoLayoutParams);
}
}
/**
* Adjusts phone layouts for full screen video.
*/
private void layoutPhoneFullScreen(boolean fullscreen) {
if (fullscreen) {
mTabHost.setVisibility(View.GONE);
} else {
mTabHost.setVisibility(View.VISIBLE);
}
}
private int getActionBarHeightPx() {
int[] attrs = new int[] { android.R.attr.actionBarSize };
return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f);
}
/**
* Adapter that backs the action bar drop-down spinner.
*/
private class LivestreamAdapter extends CursorAdapter {
LayoutInflater mLayoutInflater;
public LivestreamAdapter(Context context) {
super(context, null, false);
if (UIUtils.hasICS()) {
mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
} else {
mLayoutInflater =
(LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
}
@Override
public Object getItem(int position) {
mCursor.moveToPosition(position);
return mCursor;
}
@Override
public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the drop-down spinner views
return mLayoutInflater.inflate(
R.layout.spinner_item_session_livestream, parent, false);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the selected spinner
return mLayoutInflater.inflate(android.R.layout.simple_spinner_item,
parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Bind view that appears in the selected spinner or in the drop-down
final TextView titleView = (TextView) view.findViewById(android.R.id.text1);
final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2);
String trackName = cursor.getString(SessionsQuery.TRACK_NAME);
if (TextUtils.isEmpty(trackName)) {
trackName = getString(R.string.app_name);
} else {
trackName = getString(R.string.session_livestream_track_title, trackName);
}
String sessionTitle = cursor.getString(SessionsQuery.TITLE);
if (subTitleView != null) { // Drop-down view
titleView.setText(trackName);
subTitleView.setText(sessionTitle);
} else { // Selected view
titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName);
}
}
}
/**
* Adapter that backs the viewpager tabs on the phone UI.
*/
private static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final FragmentActivity mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
public final SparseArray<Fragment> mFragments;
private final ArrayList<Integer> mTabNums;
private int mTabCount = 0;
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
mFragments = new SparseArray<Fragment>(3);
mTabNums = new ArrayList<Integer>(3);
}
public void addTab(String tabTitle, Fragment newFragment, int tabId) {
ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs);
TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate(
R.layout.tab_indicator_color, tabWidget, false);
tabIndicatorView.setText(tabTitle);
final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(mTabCount++));
tabSpec.setIndicator(tabIndicatorView);
tabSpec.setContent(new DummyTabFactory(mContext));
mTabHost.addTab(tabSpec);
mFragments.put(tabId, newFragment);
mTabNums.add(tabId);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public Fragment getItem(int position) {
return mFragments.get(mTabNums.get(position));
}
@Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly also takes care of
// putting focus on it when not in touch mode. The jerk. This hack tries to prevent
// this from pulling focus out of our ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
/**
* Simple fragment that inflates a session summary layout that displays session title and
* abstract.
*/
public static class SessionSummaryFragment extends Fragment {
private TextView mTitleView;
private TextView mAbstractView;
private String mTitle;
private String mAbstract;
public SessionSummaryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_session_summary, null);
mTitleView = (TextView) view.findViewById(R.id.session_title);
mAbstractView = (TextView) view.findViewById(R.id.session_abstract);
updateViews();
return view;
}
public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) {
mTitle = sessionTitle;
mAbstract = sessionAbstract;
updateViews();
}
public void updateViews() {
if (mTitleView != null && mAbstractView != null) {
mTitleView.setText(mTitle);
if (!TextUtils.isEmpty(mAbstract)) {
mAbstractView.setVisibility(View.VISIBLE);
mAbstractView.setText(mAbstract);
} else {
mAbstractView.setVisibility(View.GONE);
}
}
}
}
/**
* Simple fragment that shows the live captions.
*/
public static class SessionLiveCaptionsFragment extends Fragment {
private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark";
private FrameLayout mContainer;
private WebView mWebView;
private TextView mNoCaptionsTextView;
private boolean mDarkTheme = false;
private String mSessionTrack;
public SessionLiveCaptionsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_session_captions, null);
mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container);
mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty);
mWebView = (WebView) view.findViewById(R.id.session_caption_area);
mWebView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
// Disable text selection in WebView (doesn't work well with the YT player
// triggering full screen chrome after a timeout)
return true;
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description,
String failingUrl) {
showNoCaptionsAvailable();
}
});
updateViews();
return view;
}
public void setTrackName(String sessionTrack) {
mSessionTrack = sessionTrack;
updateViews();
}
public void setDarkTheme(boolean dark) {
mDarkTheme = dark;
}
public void updateViews() {
if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) {
if (mDarkTheme) {
mWebView.setBackgroundColor(Color.BLACK);
mContainer.setBackgroundColor(Color.BLACK);
mNoCaptionsTextView.setTextColor(Color.WHITE);
} else {
mWebView.setBackgroundColor(Color.WHITE);
mContainer.setBackgroundColor(Color.WHITE);
}
String captionsUrl;
final String trackLowerCase = mSessionTrack.toLowerCase();
if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)||
trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) {
// if keynote or primary track, use primary captions url
captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL;
} else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) {
// else if secondary track use secondary captions url
captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL;
} else {
// otherwise we don't have captions
captionsUrl = null;
}
if (captionsUrl != null) {
if (mDarkTheme) {
captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM;
}
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(captionsUrl);
mNoCaptionsTextView.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
} else {
showNoCaptionsAvailable();
}
}
}
private void showNoCaptionsAvailable() {
mWebView.setVisibility(View.GONE);
mNoCaptionsTextView.setVisibility(View.VISIBLE);
}
}
private static class SessionShareData {
String SESSION_TITLE;
String SESSION_HASHTAG;
String SESSION_URL;
public SessionShareData(String title, String hashTag, String url) {
SESSION_TITLE = title;
SESSION_HASHTAG = hashTag;
SESSION_URL = url;
}
}
/**
* Single session query
*/
public interface SessionSummaryQuery {
int _TOKEN = 0;
String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_ABSTRACT,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
Tracks.TRACK_NAME,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
int SESSION_ID = 0;
int TITLE = 1;
int ABSTRACT = 2;
int HASHTAGS = 3;
int LIVESTREAM_URL = 4;
int TRACK_NAME = 5;
int BLOCK_START= 6;
int BLOCK_END = 7;
}
/**
* List of sessions query
*/
public interface SessionsQuery {
int _TOKEN = 1;
String[] PROJECTION = {
BaseColumns._ID,
Sessions.SESSION_ID,
Sessions.SESSION_TITLE,
Tracks.TRACK_NAME,
Tracks.TRACK_COLOR,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
int ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int TRACK_NAME = 3;
int TRACK_COLOR = 4;
int BLOCK_START= 5;
int BLOCK_END = 6;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SessionLivestreamActivity.java | Java | asf20 | 47,101 |
/*
* 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.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.ReflectionUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.widget.SearchView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
/**
* An activity that shows session search results. This activity can be either single
* or multi-pane, depending on the device configuration.
*/
public class SearchActivity extends BaseActivity implements SessionsFragment.Callbacks {
private boolean mTwoPane;
private SessionsFragment mSessionsFragment;
private Fragment mDetailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mTwoPane = (findViewById(R.id.fragment_container_detail) != null);
FragmentManager fm = getSupportFragmentManager();
mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master);
if (mSessionsFragment == null) {
mSessionsFragment = new SessionsFragment();
fm.beginTransaction()
.add(R.id.fragment_container_master, mSessionsFragment)
.commit();
}
mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
String query = intent.getStringExtra(SearchManager.QUERY);
setTitle(Html.fromHtml(getString(R.string.title_search_query, query)));
mSessionsFragment.reloadFromArguments(intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query))));
EasyTracker.getTracker().trackView("Search: " + query);
LOGD("Tracker", "Search: " + query);
updateDetailBackground();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.search, menu);
setupSearchMenuItem(menu);
return true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupSearchMenuItem(Menu menu) {
final MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
ReflectionUtils.tryInvoke(searchItem, "collapseActionView");
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return false;
}
@Override
public boolean onSuggestionClick(int i) {
ReflectionUtils.tryInvoke(searchItem, "collapseActionView");
return false;
}
});
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
private void updateDetailBackground() {
if (mTwoPane) {
findViewById(R.id.fragment_container_detail).setBackgroundResource(
(mDetailFragment == null)
? R.drawable.grey_frame_on_white_empty_sessions
: R.drawable.grey_frame_on_white);
}
}
@Override
public boolean onSessionSelected(String sessionId) {
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId);
Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri);
if (mTwoPane) {
BeamUtils.setBeamSessionUri(this, sessionUri);
trySetBeamCallback();
SessionDetailFragment fragment = new SessionDetailFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.commit();
mDetailFragment = fragment;
updateDetailBackground();
return true;
} else {
startActivity(detailIntent);
return false;
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void trySetBeamCallback() {
if (UIUtils.hasICS()) {
BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() {
@Override
public void onNdefPushComplete(NfcEvent event) {
// Beam has been sent
if (!BeamUtils.isBeamUnlocked(SearchActivity.this)) {
BeamUtils.setBeamUnlocked(SearchActivity.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
showFirstBeamDialog();
}
});
}
}
});
}
}
private void showFirstBeamDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.just_beamed)
.setMessage(R.string.beam_unlocked_session)
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.view_beam_session,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
BeamUtils.launchBeamSession(SearchActivity.this);
di.dismiss();
}
})
.create()
.show();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/ui/SearchActivity.java | Java | asf20 | 8,467 |
/*
* 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) {
}
}
| zzxxasp-key | android/src/com/google/android/youtube/api/YouTube.java | Java | asf20 | 803 |
/*
* 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();
}
}
| zzxxasp-key | android/src/com/google/android/youtube/api/YouTubePlayer.java | Java | asf20 | 2,419 |
/*
* 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) {
}
}
| zzxxasp-key | android/src/com/google/android/youtube/api/YouTubePlayerSupportFragment.java | Java | asf20 | 2,768 |
/*
* 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.analytics.tracking.android;
import android.app.Activity;
import android.content.Context;
/**
* Temporarily just a stub.
*/
public class EasyTracker {
public static EasyTracker getTracker() {
return new EasyTracker();
}
public void trackView(String s) {
}
public void trackActivityStart(Activity activity) {
}
public void trackActivityStop(Activity activity) {
}
public void setContext(Context context) {
}
public void trackEvent(String s1, String s2, String s3, long l) {
}
public void dispatch() {
}
}
| zzxxasp-key | android/src/com/google/analytics/tracking/android/EasyTracker.java | Java | asf20 | 1,193 |
#!/bin/sh
if [[ -z $ADB ]]; then ADB=adb; fi
./kill_process.sh
$ADB shell rm -r /data/data/com.google.android.apps.iosched/* | zzxxasp-key | scripts/kill_data.sh | Shell | asf20 | 124 |
#!/bin/sh
adb shell cat /data/data/com.google.android.apps.iosched/shared_prefs/com.google.android.apps.iosched_preferences.xml | xmllint --format - | zzxxasp-key | scripts/cat_preferences.sh | Shell | asf20 | 148 |
#!/bin/sh
if [[ -z $ADB ]]; then ADB=adb; fi
$ADB shell am start \
-a android.intent.action.MAIN \
-c android.intent.category.LAUNCHER \
-n com.google.android.apps.iosched/.ui.HomeActivity
| zzxxasp-key | scripts/launch.sh | Shell | asf20 | 202 |
#!/bin/sh
adb shell pm clear com.google.android.apps.iosched | zzxxasp-key | scripts/cleardata.sh | Shell | asf20 | 60 |
#!/bin/sh
if [[ -z $ADB ]]; then ADB=adb; fi
$ADB shell am force-stop com.google.android.apps.iosched
| zzxxasp-key | scripts/kill_process.sh | Shell | asf20 | 102 |
#!/bin/sh
if [[ -z $ADB ]]; then ADB=adb; fi
MAC_UNAME="Darwin"
if [[ "`uname`" == ${MAC_UNAME} ]]; then
DATE_FORMAT="%Y-%m-%dT%H:%M:%S"
else
DATE_FORMAT="%Y-%m-%d %H:%M:%S"
fi
if [ -z "$1" ]; then
NOW_DATE=$(date "+${DATE_FORMAT}")
echo Please provide a mock time in the format \"${NOW_DATE}\" or \"d\" to delete the mock time. >&2
exit
fi
TEMP_FILE=$(mktemp -t iosched_mock_time.XXXXXXXX)
MOCK_TIME_STR="$1"
if [[ "d" == "${MOCK_TIME_STR}" ]]; then
echo Deleting mock time... >&2
./kill_process.sh
$ADB shell rm /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml
exit
fi
if [[ "`uname`" == ${MAC_UNAME} ]]; then
MOCK_TIME_MSEC=$(date -j -f ${DATE_FORMAT} ${MOCK_TIME_STR} "+%s")000
else
MOCK_TIME_MSEC=$(date -d "${MOCK_TIME_STR}" +%s)000
fi
echo Setting mock time to "${MOCK_TIME_STR}" == "${MOCK_TIME_MSEC}" ... >&2
cat >${TEMP_FILE}<<EOT
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<long name="mock_current_time" value="${MOCK_TIME_MSEC}"/>
</map>
EOT
./kill_process.sh
$ADB push ${TEMP_FILE} /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml
| zzxxasp-key | scripts/set_mock_time.sh | Shell | asf20 | 1,137 |
#!/usr/bin/python
# Copyright 2011 Google, Inc. All Rights Reserved.
# simple script to walk source tree looking for third-party licenses
# dumps resulting html page to stdout
import os, re, mimetypes, sys
# read source directories to scan from command line
SOURCE = sys.argv[1:]
# regex to find /* */ style comment blocks
COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL)
# regex used to detect if comment block is a license
COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE)
COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE)
EXCLUDE_TYPES = [
"application/xml",
"image/png",
]
# list of known licenses; keys are derived by stripping all whitespace and
# forcing to lowercase to help combine multiple files that have same license.
KNOWN_LICENSES = {}
class License:
def __init__(self, license_text):
self.license_text = license_text
self.filenames = []
# add filename to the list of files that have the same license text
def add_file(self, filename):
if filename not in self.filenames:
self.filenames.append(filename)
LICENSE_KEY = re.compile(r"[^\w]")
def find_license(license_text):
# TODO(alice): a lot these licenses are almost identical Apache licenses.
# Most of them differ in origin/modifications. Consider combining similar
# licenses.
license_key = LICENSE_KEY.sub("", license_text).lower()
if license_key not in KNOWN_LICENSES:
KNOWN_LICENSES[license_key] = License(license_text)
return KNOWN_LICENSES[license_key]
def discover_license(exact_path, filename):
# when filename ends with LICENSE, assume applies to filename prefixed
if filename.endswith("LICENSE"):
with open(exact_path) as file:
license_text = file.read()
target_filename = filename[:-len("LICENSE")]
if target_filename.endswith("."): target_filename = target_filename[:-1]
find_license(license_text).add_file(target_filename)
return None
# try searching for license blocks in raw file
mimetype = mimetypes.guess_type(filename)
if mimetype in EXCLUDE_TYPES: return None
with open(exact_path) as file:
raw_file = file.read()
# include comments that have both "license" and "copyright" in the text
for comment in COMMENT_BLOCK.finditer(raw_file):
comment = comment.group(1)
if COMMENT_LICENSE.search(comment) is None: continue
if COMMENT_COPYRIGHT.search(comment) is None: continue
find_license(comment).add_file(filename)
for source in SOURCE:
for root, dirs, files in os.walk(source):
for name in files:
discover_license(os.path.join(root, name), name)
print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>"
for license in KNOWN_LICENSES.values():
print "<h3>Notices for files:</h3><ul>"
filenames = license.filenames
filenames.sort()
for filename in filenames:
print "<li>%s</li>" % (filename)
print "</ul>"
print "<pre>%s</pre>" % license.license_text
print "</body></html>"
| zzxxasp-key | scripts/collect_licenses.py | Python | asf20 | 3,190 |
#!/bin/sh
# Remember VERBOSE only works on debug builds of the app
adb shell setprop log.tag.iosched_SyncHelper VERBOSE
adb shell setprop log.tag.iosched_SessionsHandler VERBOSE
adb shell setprop log.tag.iosched_ImageCache VERBOSE
adb shell setprop log.tag.iosched_ImageWorker VERBOSE
adb shell setprop log.tag.iosched_ImageFetcher VERBOSE | zzxxasp-key | scripts/increase_verbosity.sh | Shell | asf20 | 339 |
#!/bin/sh
if [[ -z $ADB ]]; then ADB=adb; fi
$ADB shell "echo '$*' | sqlite3 -header -column /data/data/com.google.android.apps.iosched/databases/schedule.db" | zzxxasp-key | scripts/dbquery.sh | Shell | asf20 | 158 |
#!/bin/sh
# Sessions list
#adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/sessions
# Vendors list
#adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/vendors
# Session detail
#adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/sessions/honeycombhighlights
# Vendor detail
#adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/vendors/bestbuy
# Track details
#adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/chrome
| zzxxasp-key | scripts/deeplinks.sh | Shell | asf20 | 676 |
<html>
<body>
<h2>Push request could not be queued!</h2>
</body>
</html> | zzxxasp-key | gcm-server/war/error.html | HTML | asf20 | 72 |
<html>
<body>
<h2>Push request queued successfully!</h2>
</body>
</html> | zzxxasp-key | gcm-server/war/success.html | HTML | asf20 | 72 |
/*
* 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.gcm.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections. This class is neither
* persistent (it will lost the data when the app is restarted) nor thread safe.
*/
public final class Datastore {
private static final Logger logger = Logger.getLogger(Datastore.class.getSimpleName());
static final String MULTICAST_TYPE = "Multicast";
static final String MULTICAST_REG_IDS_PROPERTY = "regIds";
static final String MULTICAST_ANNOUNCEMENT_PROPERTY = "announcement";
static final int MULTICAST_SIZE = 1000;
static final String DEVICE_TYPE = "Device";
static final String DEVICE_REG_ID_PROPERTY = "regid";
private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder
.withPrefetchSize(MULTICAST_SIZE)
.chunkSize(MULTICAST_SIZE);
private static final DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
Transaction txn = ds.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity != null) {
logger.fine(regId + " is already registered; ignoring.");
return;
}
entity = new Entity(DEVICE_TYPE);
entity.setProperty(DEVICE_REG_ID_PROPERTY, regId);
ds.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
Transaction txn = ds.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity == null) {
logger.warning("Device " + regId + " already unregistered");
} else {
Key key = entity.getKey();
ds.delete(key);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
Transaction txn = ds.beginTransaction();
try {
Entity entity = findDeviceByRegId(oldId);
if (entity == null) {
logger.warning("No device for registration id " + oldId);
return;
}
entity.setProperty(DEVICE_REG_ID_PROPERTY, newId);
ds.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets the number of total devices.
*/
public static int getTotalDevices() {
Transaction txn = ds.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE).setKeysOnly();
List<Entity> allKeys =
ds.prepare(query).asList(DEFAULT_FETCH_OPTIONS);
int total = allKeys.size();
logger.fine("Total number of devices: " + total);
txn.commit();
return total;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
List<String> devices;
Transaction txn = ds.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE);
Iterable<Entity> entities =
ds.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS);
devices = new ArrayList<String>();
for (Entity entity : entities) {
String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY);
devices.add(device);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return devices;
}
/**
* Returns the device object with the given registration ID.
*/
private static Entity findDeviceByRegId(String regId) {
Query query = new Query(DEVICE_TYPE)
.addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId);
PreparedQuery preparedQuery = ds.prepare(query);
List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS);
Entity entity = null;
if (!entities.isEmpty()) {
entity = entities.get(0);
}
int size = entities.size();
if (size > 0) {
logger.severe(
"Found " + size + " entities for regId " + regId + ": " + entities);
}
return entity;
}
/**
* Creates a persistent record with the devices to be notified using a multicast message.
*
* @param devices registration ids of the devices.
* @param announcement announcement messageage
* @return encoded key for the persistent record.
*/
public static String createMulticast(List<String> devices, String announcement) {
String type = (announcement == null || announcement.trim().length() == 0)
? "sync"
: ("announcement: " + announcement);
logger.info("Storing multicast (" + type + ") for " + devices.size() + " devices");
String encodedKey;
Transaction txn = ds.beginTransaction();
try {
Entity entity = new Entity(MULTICAST_TYPE);
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
entity.setProperty(MULTICAST_ANNOUNCEMENT_PROPERTY, announcement);
ds.put(entity);
Key key = entity.getKey();
encodedKey = KeyFactory.keyToString(key);
logger.fine("multicast key: " + encodedKey);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return encodedKey;
}
/**
* Gets a persistent record with the devices to be notified using a multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static Entity getMulticast(String encodedKey) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = ds.beginTransaction();
try {
entity = ds.get(key);
txn.commit();
return entity;
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return null;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates a persistent record with the devices to be notified using a multicast message.
*
* @param encodedKey encoded key for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(String encodedKey, List<String> devices) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = ds.beginTransaction();
try {
try {
entity = ds.get(key);
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return;
}
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
ds.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Deletes a persistent record with the devices to be notified using a multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static void deleteMulticast(String encodedKey) {
Transaction txn = ds.beginTransaction();
try {
Key key = KeyFactory.stringToKey(encodedKey);
ds.delete(key);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/Datastore.java | Java | asf20 | 9,856 |
/*
* 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.gcm.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by {@link
* #PARAMETER_REG_ID}. The client app should call this servlet every time it receives a {@code
* com.google.android.c2dm.intent.REGISTRATION} with an {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/UnregisterServlet.java | Java | asf20 | 1,455 |
/*
* 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.gcm.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that shows a simple admin console for sending multicast messages. This servlet is
* visible to administrators only.
*/
public class AdminServlet extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head><title>IOSched GCM Server</title>");
out.print("</head>");
String status = (String) req.getAttribute("status");
if (status != null) {
out.print(status);
}
out.print("</body></html>");
int total = Datastore.getTotalDevices();
out.print("<h2>" + total + " device(s) registered!</h2>");
out.print("<form method='POST' action='/sendall'>");
out.print("<table>");
out.print("<tr>");
out.print("<td>Announcement:</td>");
out.print("<td><input type='text' name='announcement' size='80'/></td>");
out.print("</tr>");
out.print("</table>");
out.print("<br/>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
resp.addHeader("X-FRAME-OPTIONS", "DENY");
resp.setStatus(HttpServletResponse.SC_OK);
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/AdminServlet.java | Java | asf20 | 2,204 |
/*
* 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.gcm.server;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that pushes a GCM message to all registered devices. This servlet creates multicast
* entities consisting of 1000 devices each, and creates tasks to send individual GCM messages to
* each device in the multicast.
*
* This servlet must be authenticated against with an administrator's Google account, ideally a
* shared role account.
*/
public class SendMessageToAllServlet extends BaseServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Queue queue = QueueFactory.getQueue("MulticastMessagesQueue");
String announcement = req.getParameter("announcement");
if (announcement == null) {
announcement = "";
}
List<String> devices = Datastore.getDevices();
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey =
Datastore.createMulticast(partialDevices, announcement);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param("multicastKey", multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
}
}
logger.fine("Queued message to " + counter + " devices");
resp.sendRedirect("/success.html");
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/SendMessageToAllServlet.java | Java | asf20 | 3,029 |
/*
* 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.gcm.server;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
abstract class BaseServlet extends HttpServlet {
protected final Logger logger = Logger.getLogger(getClass().getSimpleName());
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (value == null || value.trim().isEmpty()) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.info("parameters: " + parameters);
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(0);
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/BaseServlet.java | Java | asf20 | 2,087 |
/*
* 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.gcm.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.google.appengine.api.datastore.Entity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet, called from an App Engine task, that sends the given message (sync or announcement)
* to all devices in a given multicast group (up to 1000).
*/
public class SendMessageServlet extends BaseServlet {
private static final int ANNOUNCEMENT_TTL = (int) TimeUnit.MINUTES.toSeconds(300);
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
String multicastKey = req.getParameter("multicastKey");
Entity multicast = Datastore.getMulticast(multicastKey);
@SuppressWarnings("unchecked")
List<String> devices = (List<String>)
multicast.getProperty(Datastore.MULTICAST_REG_IDS_PROPERTY);
String announcement = (String)
multicast.getProperty(Datastore.MULTICAST_ANNOUNCEMENT_PROPERTY);
// Build the GCM message
Message.Builder builder = new Message.Builder()
.delayWhileIdle(true);
if (announcement != null && announcement.trim().length() > 0) {
builder
.collapseKey("announcement")
.addData("announcement", announcement)
.timeToLive(ANNOUNCEMENT_TTL);
} else {
builder
.collapseKey("sync");
}
Message message = builder.build();
// Send the GCM message.
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, devices);
logger.info("Result: " + multicastResult);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp, multicastKey);
return;
}
// check if any registration ids must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = devices.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
boolean allDone = true;
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retryableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = devices.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retryableRegIds.add(regId);
}
}
}
if (!retryableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retryableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
taskDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp, String multicastKey) {
Datastore.deleteMulticast(multicastKey);
resp.setStatus(200);
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/SendMessageServlet.java | Java | asf20 | 5,791 |
/*
* 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.gcm.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by {@link
* #PARAMETER_REG_ID}.
*
* The client app should call this servlet every time it receives a {@code
* com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an error or {@code unregistered}
* extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/RegisterServlet.java | Java | asf20 | 1,482 |
/*
* 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.gcm.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from the App Engine datastore.
*/
public class ApiKeyInitializer implements ServletContextListener {
private final Logger logger = Logger.getLogger(ApiKeyInitializer.class.getSimpleName());
// Don't actually hard code your key here; rather, edit the entity in the App Engine console.
static final String FAKE_API_KEY = "ENTER_KEY_HERE";
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
@Override
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD, FAKE_API_KEY);
datastore.put(entity);
logger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
/**
* Gets the access key.
*/
protected String getKey() {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
String apiKey = "";
try {
Entity entity = datastore.get(key);
apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
} catch (EntityNotFoundException e) {
logger.severe("Exception while retrieving the API Key" + e.toString());
}
return apiKey;
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
| zzxxasp-key | gcm-server/src/com/google/android/apps/iosched/gcm/server/ApiKeyInitializer.java | Java | asf20 | 3,560 |
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();
}
| zzxxasp-key | libprojects/abs/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java | Java | asf20 | 5,817 |
/*
* Copyright (C) 2006 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.view;
import android.content.ComponentName;
import android.content.Intent;
import android.view.KeyEvent;
/**
* Interface for managing the items in a menu.
* <p>
* By default, every Activity supports an options menu of actions or options.
* You can add items to this menu and handle clicks on your additions. The
* easiest way of adding menu items is inflating an XML file into the
* {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to
* clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and
* {@link Activity#onContextItemSelected(MenuItem)}.
* <p>
* Different menu types support different features:
* <ol>
* <li><b>Context menus</b>: Do not support item shortcuts and item icons.
* <li><b>Options menus</b>: The <b>icon menus</b> do not support item check
* marks and only show the item's
* {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The
* <b>expanded menus</b> (only available if six or more menu items are visible,
* reached via the 'More' item in the icon menu) do not show item icons, and
* item check marks are discouraged.
* <li><b>Sub menus</b>: Do not support item icons, or nested sub menus.
* </ol>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface Menu {
/**
* This is the part of an order integer that the user can provide.
* @hide
*/
static final int USER_MASK = 0x0000ffff;
/**
* Bit shift of the user portion of the order integer.
* @hide
*/
static final int USER_SHIFT = 0;
/**
* This is the part of an order integer that supplies the category of the
* item.
* @hide
*/
static final int CATEGORY_MASK = 0xffff0000;
/**
* Bit shift of the category portion of the order integer.
* @hide
*/
static final int CATEGORY_SHIFT = 16;
/**
* Value to use for group and item identifier integers when you don't care
* about them.
*/
static final int NONE = 0;
/**
* First value for group and item identifier integers.
*/
static final int FIRST = 1;
// Implementation note: Keep these CATEGORY_* in sync with the category enum
// in attrs.xml
/**
* Category code for the order integer for items/groups that are part of a
* container -- or/add this with your base value.
*/
static final int CATEGORY_CONTAINER = 0x00010000;
/**
* Category code for the order integer for items/groups that are provided by
* the system -- or/add this with your base value.
*/
static final int CATEGORY_SYSTEM = 0x00020000;
/**
* Category code for the order integer for items/groups that are
* user-supplied secondary (infrequently used) options -- or/add this with
* your base value.
*/
static final int CATEGORY_SECONDARY = 0x00030000;
/**
* Category code for the order integer for items/groups that are
* alternative actions on the data that is currently displayed -- or/add
* this with your base value.
*/
static final int CATEGORY_ALTERNATIVE = 0x00040000;
/**
* Flag for {@link #addIntentOptions}: if set, do not automatically remove
* any existing menu items in the same group.
*/
static final int FLAG_APPEND_TO_GROUP = 0x0001;
/**
* Flag for {@link #performShortcut}: if set, do not close the menu after
* executing the shortcut.
*/
static final int FLAG_PERFORM_NO_CLOSE = 0x0001;
/**
* Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always
* close the menu after executing the shortcut. Closing the menu also resets
* the prepared state.
*/
static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002;
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(CharSequence title);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int titleRes);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param groupId The group identifier that this item should be part of.
* This can be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, CharSequence title);
/**
* Variation on {@link #add(int, int, int, CharSequence)} that takes a
* string resource identifier instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final CharSequence title);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given
* <var>title</var> for its label. To modify other attributes on the
* submenu's menu item, use {@link SubMenu#getItem()}.
*<p>
* Note that you can only have one level of sub-menus, i.e. you cannnot add
* a subMenu to a subMenu: An {@link UnsupportedOperationException} will be
* thrown if you try.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title);
/**
* Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes
* a string resource identifier for the title instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care about the
* order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes);
/**
* Add a group of menu items corresponding to actions that can be performed
* for a particular Intent. The Intent is most often configured with a null
* action, the data that the current activity is working with, and includes
* either the {@link Intent#CATEGORY_ALTERNATIVE} or
* {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have
* said they would like to be included as optional action. You can, however,
* use any Intent you want.
*
* <p>
* See {@link android.content.pm.PackageManager#queryIntentActivityOptions}
* for more * details on the <var>caller</var>, <var>specifics</var>, and
* <var>intent</var> arguments. The list returned by that function is used
* to populate the resulting menu items.
*
* <p>
* All of the menu items of possible options for the intent will be added
* with the given group and id. You can use the group to control ordering of
* the items in relation to other items in the menu. Normally this function
* will automatically remove any existing items in the menu in the same
* group and place a divider above and below the added items; this behavior
* can be modified with the <var>flags</var> parameter. For each of the
* generated items {@link MenuItem#setIntent} is called to associate the
* appropriate Intent with the item; this means the activity will
* automatically be started for you without having to do anything else.
*
* @param groupId The group identifier that the items should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if the items should not be in
* a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the items. Use {@link #NONE} if you do not
* care about the order. See {@link MenuItem#getOrder()}.
* @param caller The current activity component name as defined by
* queryIntentActivityOptions().
* @param specifics Specific items to place first as defined by
* queryIntentActivityOptions().
* @param intent Intent describing the kinds of items to populate in the
* list as defined by queryIntentActivityOptions().
* @param flags Additional options controlling how the items are added.
* @param outSpecificItems Optional array in which to place the menu items
* that were generated for each of the <var>specifics</var> that were
* requested. Entries may be null if no activity was found for that
* specific action.
* @return The number of menu items that were added.
*
* @see #FLAG_APPEND_TO_GROUP
* @see MenuItem#setIntent
* @see android.content.pm.PackageManager#queryIntentActivityOptions
*/
public int addIntentOptions(int groupId, int itemId, int order,
ComponentName caller, Intent[] specifics,
Intent intent, int flags, MenuItem[] outSpecificItems);
/**
* Remove the item with the given identifier.
*
* @param id The item to be removed. If there is no item with this
* identifier, nothing happens.
*/
public void removeItem(int id);
/**
* Remove all items in the given group.
*
* @param groupId The group to be removed. If there are no items in this
* group, nothing happens.
*/
public void removeGroup(int groupId);
/**
* Remove all existing items from the menu, leaving it empty as if it had
* just been created.
*/
public void clear();
/**
* Control whether a particular group of items can show a check mark. This
* is similar to calling {@link MenuItem#setCheckable} on all of the menu items
* with the given group identifier, but in addition you can control whether
* this group contains a mutually-exclusive set items. This should be called
* after the items of the group have been added to the menu.
*
* @param group The group of items to operate on.
* @param checkable Set to true to allow a check mark, false to
* disallow. The default is false.
* @param exclusive If set to true, only one item in this group can be
* checked at a time; checking an item will automatically
* uncheck all others in the group. If set to false, each
* item can be checked independently of the others.
*
* @see MenuItem#setCheckable
* @see MenuItem#setChecked
*/
public void setGroupCheckable(int group, boolean checkable, boolean exclusive);
/**
* Show or hide all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param visible If true the items are visible, else they are hidden.
*
* @see MenuItem#setVisible
*/
public void setGroupVisible(int group, boolean visible);
/**
* Enable or disable all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param enabled If true the items will be enabled, else they will be disabled.
*
* @see MenuItem#setEnabled
*/
public void setGroupEnabled(int group, boolean enabled);
/**
* Return whether the menu currently has item items that are visible.
*
* @return True if there is one or more item visible,
* else false.
*/
public boolean hasVisibleItems();
/**
* Return the menu item with a particular identifier.
*
* @param id The identifier to find.
*
* @return The menu item object, or null if there is no item with
* this identifier.
*/
public MenuItem findItem(int id);
/**
* Get the number of items in the menu. Note that this will change any
* times items are added or removed from the menu.
*
* @return The item count.
*/
public int size();
/**
* Gets the menu item at the given index.
*
* @param index The index of the menu item to return.
* @return The menu item.
* @exception IndexOutOfBoundsException
* when {@code index < 0 || >= size()}
*/
public MenuItem getItem(int index);
/**
* Closes the menu, if open.
*/
public void close();
/**
* Execute the menu item action associated with the given shortcut
* character.
*
* @param keyCode The keycode of the shortcut key.
* @param event Key event message.
* @param flags Additional option flags or 0.
*
* @return If the given shortcut exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performShortcut(int keyCode, KeyEvent event, int flags);
/**
* Is a keypress one of the defined shortcut keys for this window.
* @param keyCode the key code from {@link KeyEvent} to check.
* @param event the {@link KeyEvent} to use to help check.
*/
boolean isShortcutKey(int keyCode, KeyEvent event);
/**
* Execute the menu item action associated with the given menu identifier.
*
* @param id Identifier associated with the menu item.
* @param flags Additional option flags or 0.
*
* @return If the given identifier exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performIdentifierAction(int id, int flags);
/**
* Control whether the menu should be running in qwerty mode (alphabetic
* shortcuts) or 12-key mode (numeric shortcuts).
*
* @param isQwerty If true the menu will use alphabetic shortcuts; else it
* will use numeric shortcuts.
*/
public void setQwertyMode(boolean isQwerty);
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/Menu.java | Java | asf20 | 17,460 |
/*
* Copyright (C) 2008 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.view;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
/**
* Interface for direct access to a previously created menu item.
* <p>
* An Item is returned by calling one of the {@link android.view.Menu#add}
* methods.
* <p>
* For a feature set of specific menu types, see {@link Menu}.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface MenuItem {
/*
* These should be kept in sync with attrs.xml enum constants for showAsAction
*/
/** Never show this item as a button in an Action Bar. */
public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER;
/** Show this item as a button in an Action Bar if the system decides there is room for it. */
public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM;
/**
* Always show this item as a button in an Action Bar.
* Use sparingly! If too many items are set to always show in the Action Bar it can
* crowd the Action Bar and degrade the user experience on devices with smaller screens.
* A good rule of thumb is to have no more than 2 items set to always show at a time.
*/
public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS;
/**
* When this item is in the action bar, always show it with a text label even if
* it also has an icon specified.
*/
public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT;
/**
* This item's action view collapses to a normal menu item.
* When expanded, the action view temporarily takes over
* a larger segment of its container.
*/
public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW;
/**
* Interface definition for a callback to be invoked when a menu item is
* clicked.
*
* @see Activity#onContextItemSelected(MenuItem)
* @see Activity#onOptionsItemSelected(MenuItem)
*/
public interface OnMenuItemClickListener {
/**
* Called when a menu item has been invoked. This is the first code
* that is executed; if it returns true, no other callbacks will be
* executed.
*
* @param item The menu item that was invoked.
*
* @return Return true to consume this click and prevent others from
* executing.
*/
public boolean onMenuItemClick(MenuItem item);
}
/**
* Interface definition for a callback to be invoked when a menu item
* marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is
* expanded or collapsed.
*
* @see MenuItem#expandActionView()
* @see MenuItem#collapseActionView()
* @see MenuItem#setShowAsActionFlags(int)
*/
public interface OnActionExpandListener {
/**
* Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}
* is expanded.
* @param item Item that was expanded
* @return true if the item should expand, false if expansion should be suppressed.
*/
public boolean onMenuItemActionExpand(MenuItem item);
/**
* Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}
* is collapsed.
* @param item Item that was collapsed
* @return true if the item should collapse, false if collapsing should be suppressed.
*/
public boolean onMenuItemActionCollapse(MenuItem item);
}
/**
* Return the identifier for this menu item. The identifier can not
* be changed after the menu is created.
*
* @return The menu item's identifier.
*/
public int getItemId();
/**
* Return the group identifier that this menu item is part of. The group
* identifier can not be changed after the menu is created.
*
* @return The menu item's group identifier.
*/
public int getGroupId();
/**
* Return the category and order within the category of this item. This
* item will be shown before all items (within its category) that have
* order greater than this value.
* <p>
* An order integer contains the item's category (the upper bits of the
* integer; set by or/add the category with the order within the
* category) and the ordering of the item within that category (the
* lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM},
* {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE},
* {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list.
*
* @return The order of this item.
*/
public int getOrder();
/**
* Change the title associated with this item.
*
* @param title The new text to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setTitle(CharSequence title);
/**
* Change the title associated with this item.
* <p>
* Some menu types do not sufficient space to show the full title, and
* instead a condensed title is preferred. See {@link Menu} for more
* information.
*
* @param title The resource id of the new text to be displayed.
* @return This Item so additional setters can be called.
* @see #setTitleCondensed(CharSequence)
*/
public MenuItem setTitle(int title);
/**
* Retrieve the current title of the item.
*
* @return The title.
*/
public CharSequence getTitle();
/**
* Change the condensed title associated with this item. The condensed
* title is used in situations where the normal title may be too long to
* be displayed.
*
* @param title The new text to be displayed as the condensed title.
* @return This Item so additional setters can be called.
*/
public MenuItem setTitleCondensed(CharSequence title);
/**
* Retrieve the current condensed title of the item. If a condensed
* title was never set, it will return the normal title.
*
* @return The condensed title, if it exists.
* Otherwise the normal title.
*/
public CharSequence getTitleCondensed();
/**
* Change the icon associated with this item. This icon will not always be
* shown, so the title should be sufficient in describing this item. See
* {@link Menu} for the menu types that support icons.
*
* @param icon The new icon (as a Drawable) to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setIcon(Drawable icon);
/**
* Change the icon associated with this item. This icon will not always be
* shown, so the title should be sufficient in describing this item. See
* {@link Menu} for the menu types that support icons.
* <p>
* This method will set the resource ID of the icon which will be used to
* lazily get the Drawable when this item is being shown.
*
* @param iconRes The new icon (as a resource ID) to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setIcon(int iconRes);
/**
* Returns the icon for this item as a Drawable (getting it from resources if it hasn't been
* loaded before).
*
* @return The icon as a Drawable.
*/
public Drawable getIcon();
/**
* Change the Intent associated with this item. By default there is no
* Intent associated with a menu item. If you set one, and nothing
* else handles the item, then the default behavior will be to call
* {@link android.content.Context#startActivity} with the given Intent.
*
* <p>Note that setIntent() can not be used with the versions of
* {@link Menu#add} that take a Runnable, because {@link Runnable#run}
* does not return a value so there is no way to tell if it handled the
* item. In this case it is assumed that the Runnable always handles
* the item, and the intent will never be started.
*
* @see #getIntent
* @param intent The Intent to associated with the item. This Intent
* object is <em>not</em> copied, so be careful not to
* modify it later.
* @return This Item so additional setters can be called.
*/
public MenuItem setIntent(Intent intent);
/**
* Return the Intent associated with this item. This returns a
* reference to the Intent which you can change as desired to modify
* what the Item is holding.
*
* @see #setIntent
* @return Returns the last value supplied to {@link #setIntent}, or
* null.
*/
public Intent getIntent();
/**
* Change both the numeric and alphabetic shortcut associated with this
* item. Note that the shortcut will be triggered when the key that
* generates the given character is pressed alone or along with with the alt
* key. Also note that case is not significant and that alphabetic shortcut
* characters will be displayed in lower case.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param numericChar The numeric shortcut key. This is the shortcut when
* using a numeric (e.g., 12-key) keyboard.
* @param alphaChar The alphabetic shortcut key. This is the shortcut when
* using a keyboard with alphabetic keys.
* @return This Item so additional setters can be called.
*/
public MenuItem setShortcut(char numericChar, char alphaChar);
/**
* Change the numeric shortcut associated with this item.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param numericChar The numeric shortcut key. This is the shortcut when
* using a 12-key (numeric) keyboard.
* @return This Item so additional setters can be called.
*/
public MenuItem setNumericShortcut(char numericChar);
/**
* Return the char for this menu item's numeric (12-key) shortcut.
*
* @return Numeric character to use as a shortcut.
*/
public char getNumericShortcut();
/**
* Change the alphabetic shortcut associated with this item. The shortcut
* will be triggered when the key that generates the given character is
* pressed alone or along with with the alt key. Case is not significant and
* shortcut characters will be displayed in lower case. Note that menu items
* with the characters '\b' or '\n' as shortcuts will get triggered by the
* Delete key or Carriage Return key, respectively.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param alphaChar The alphabetic shortcut key. This is the shortcut when
* using a keyboard with alphabetic keys.
* @return This Item so additional setters can be called.
*/
public MenuItem setAlphabeticShortcut(char alphaChar);
/**
* Return the char for this menu item's alphabetic shortcut.
*
* @return Alphabetic character to use as a shortcut.
*/
public char getAlphabeticShortcut();
/**
* Control whether this item can display a check mark. Setting this does
* not actually display a check mark (see {@link #setChecked} for that);
* rather, it ensures there is room in the item in which to display a
* check mark.
* <p>
* See {@link Menu} for the menu types that support check marks.
*
* @param checkable Set to true to allow a check mark, false to
* disallow. The default is false.
* @see #setChecked
* @see #isCheckable
* @see Menu#setGroupCheckable
* @return This Item so additional setters can be called.
*/
public MenuItem setCheckable(boolean checkable);
/**
* Return whether the item can currently display a check mark.
*
* @return If a check mark can be displayed, returns true.
*
* @see #setCheckable
*/
public boolean isCheckable();
/**
* Control whether this item is shown with a check mark. Note that you
* must first have enabled checking with {@link #setCheckable} or else
* the check mark will not appear. If this item is a member of a group that contains
* mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)},
* the other items in the group will be unchecked.
* <p>
* See {@link Menu} for the menu types that support check marks.
*
* @see #setCheckable
* @see #isChecked
* @see Menu#setGroupCheckable
* @param checked Set to true to display a check mark, false to hide
* it. The default value is false.
* @return This Item so additional setters can be called.
*/
public MenuItem setChecked(boolean checked);
/**
* Return whether the item is currently displaying a check mark.
*
* @return If a check mark is displayed, returns true.
*
* @see #setChecked
*/
public boolean isChecked();
/**
* Sets the visibility of the menu item. Even if a menu item is not visible,
* it may still be invoked via its shortcut (to completely disable an item,
* set it to invisible and {@link #setEnabled(boolean) disabled}).
*
* @param visible If true then the item will be visible; if false it is
* hidden.
* @return This Item so additional setters can be called.
*/
public MenuItem setVisible(boolean visible);
/**
* Return the visibility of the menu item.
*
* @return If true the item is visible; else it is hidden.
*/
public boolean isVisible();
/**
* Sets whether the menu item is enabled. Disabling a menu item will not
* allow it to be invoked via its shortcut. The menu item will still be
* visible.
*
* @param enabled If true then the item will be invokable; if false it is
* won't be invokable.
* @return This Item so additional setters can be called.
*/
public MenuItem setEnabled(boolean enabled);
/**
* Return the enabled state of the menu item.
*
* @return If true the item is enabled and hence invokable; else it is not.
*/
public boolean isEnabled();
/**
* Check whether this item has an associated sub-menu. I.e. it is a
* sub-menu of another menu.
*
* @return If true this item has a menu; else it is a
* normal item.
*/
public boolean hasSubMenu();
/**
* Get the sub-menu to be invoked when this item is selected, if it has
* one. See {@link #hasSubMenu()}.
*
* @return The associated menu if there is one, else null
*/
public SubMenu getSubMenu();
/**
* Set a custom listener for invocation of this menu item. In most
* situations, it is more efficient and easier to use
* {@link Activity#onOptionsItemSelected(MenuItem)} or
* {@link Activity#onContextItemSelected(MenuItem)}.
*
* @param menuItemClickListener The object to receive invokations.
* @return This Item so additional setters can be called.
* @see Activity#onOptionsItemSelected(MenuItem)
* @see Activity#onContextItemSelected(MenuItem)
*/
public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener);
/**
* Gets the extra information linked to this menu item. This extra
* information is set by the View that added this menu item to the
* menu.
*
* @see OnCreateContextMenuListener
* @return The extra information linked to the View that added this
* menu item to the menu. This can be null.
*/
public ContextMenuInfo getMenuInfo();
/**
* Sets how this item should display in the presence of an Action Bar.
* The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},
* {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should
* be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.
* SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,
* it should be shown with a text label.
*
* @param actionEnum How the item should display. One of
* {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or
* {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.
*
* @see android.app.ActionBar
* @see #setActionView(View)
*/
public void setShowAsAction(int actionEnum);
/**
* Sets how this item should display in the presence of an Action Bar.
* The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},
* {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should
* be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.
* SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,
* it should be shown with a text label.
*
* <p>Note: This method differs from {@link #setShowAsAction(int)} only in that it
* returns the current MenuItem instance for call chaining.
*
* @param actionEnum How the item should display. One of
* {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or
* {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.
*
* @see android.app.ActionBar
* @see #setActionView(View)
* @return This MenuItem instance for call chaining.
*/
public MenuItem setShowAsActionFlags(int actionEnum);
/**
* Set an action view for this menu item. An action view will be displayed in place
* of an automatically generated menu item element in the UI when this item is shown
* as an action within a parent.
* <p>
* <strong>Note:</strong> Setting an action view overrides the action provider
* set via {@link #setActionProvider(ActionProvider)}.
* </p>
*
* @param view View to use for presenting this item to the user.
* @return This Item so additional setters can be called.
*
* @see #setShowAsAction(int)
*/
public MenuItem setActionView(View view);
/**
* Set an action view for this menu item. An action view will be displayed in place
* of an automatically generated menu item element in the UI when this item is shown
* as an action within a parent.
* <p>
* <strong>Note:</strong> Setting an action view overrides the action provider
* set via {@link #setActionProvider(ActionProvider)}.
* </p>
*
* @param resId Layout resource to use for presenting this item to the user.
* @return This Item so additional setters can be called.
*
* @see #setShowAsAction(int)
*/
public MenuItem setActionView(int resId);
/**
* Returns the currently set action view for this menu item.
*
* @return This item's action view
*
* @see #setActionView(View)
* @see #setShowAsAction(int)
*/
public View getActionView();
/**
* Sets the {@link ActionProvider} responsible for creating an action view if
* the item is placed on the action bar. The provider also provides a default
* action invoked if the item is placed in the overflow menu.
* <p>
* <strong>Note:</strong> Setting an action provider overrides the action view
* set via {@link #setActionView(int)} or {@link #setActionView(View)}.
* </p>
*
* @param actionProvider The action provider.
* @return This Item so additional setters can be called.
*
* @see ActionProvider
*/
public MenuItem setActionProvider(ActionProvider actionProvider);
/**
* Gets the {@link ActionProvider}.
*
* @return The action provider.
*
* @see ActionProvider
* @see #setActionProvider(ActionProvider)
*/
public ActionProvider getActionProvider();
/**
* Expand the action view associated with this menu item.
* The menu item must have an action view set, as well as
* the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.
* If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)}
* it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)}
* method invoked. The listener may return false from this method to prevent expanding
* the action view.
*
* @return true if the action view was expanded, false otherwise.
*/
public boolean expandActionView();
/**
* Collapse the action view associated with this menu item.
* The menu item must have an action view set, as well as the showAsAction flag
* {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using
* {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its
* {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked.
* The listener may return false from this method to prevent collapsing the action view.
*
* @return true if the action view was collapsed, false otherwise.
*/
public boolean collapseActionView();
/**
* Returns true if this menu item's action view has been expanded.
*
* @return true if the item's action view is expanded, false otherwise.
*
* @see #expandActionView()
* @see #collapseActionView()
* @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
* @see OnActionExpandListener
*/
public boolean isActionViewExpanded();
/**
* Set an {@link OnActionExpandListener} on this menu item to be notified when
* the associated action view is expanded or collapsed. The menu item must
* be configured to expand or collapse its action view using the flag
* {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.
*
* @param listener Listener that will respond to expand/collapse events
* @return This menu item instance for call chaining
*/
public MenuItem setOnActionExpandListener(OnActionExpandListener listener);
} | zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/MenuItem.java | Java | asf20 | 23,294 |
/*
* Copyright (C) 2006 The Android Open Source Project
* 2011 Jake Wharton
*
* 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.view;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.InflateException;
import android.view.View;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.view.menu.MenuItemImpl;
/**
* This class is used to instantiate menu XML files into Menu objects.
* <p>
* For performance reasons, menu inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use MenuInflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource (R.
* <em>something</em> file.)
*/
public class MenuInflater {
private static final String LOG_TAG = "MenuInflater";
/** Menu tag name in XML. */
private static final String XML_MENU = "menu";
/** Group tag name in XML. */
private static final String XML_GROUP = "group";
/** Item tag name in XML. */
private static final String XML_ITEM = "item";
private static final int NO_ID = 0;
private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class};
private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE;
private final Object[] mActionViewConstructorArguments;
private final Object[] mActionProviderConstructorArguments;
private Context mContext;
/**
* Constructs a menu inflater.
*
* @see Activity#getMenuInflater()
*/
public MenuInflater(Context context) {
mContext = context;
mActionViewConstructorArguments = new Object[] {context};
mActionProviderConstructorArguments = mActionViewConstructorArguments;
}
/**
* Inflate a menu hierarchy from the specified XML resource. Throws
* {@link InflateException} if there is an error.
*
* @param menuRes Resource ID for an XML layout resource to load (e.g.,
* <code>R.menu.main_activity</code>)
* @param menu The Menu to inflate into. The items and submenus will be
* added to this Menu.
*/
public void inflate(int menuRes, Menu menu) {
XmlResourceParser parser = null;
try {
parser = mContext.getResources().getLayout(menuRes);
AttributeSet attrs = Xml.asAttributeSet(parser);
parseMenu(parser, attrs, menu);
} catch (XmlPullParserException e) {
throw new InflateException("Error inflating menu XML", e);
} catch (IOException e) {
throw new InflateException("Error inflating menu XML", e);
} finally {
if (parser != null) parser.close();
}
}
/**
* Called internally to fill the given menu. If a sub menu is seen, it will
* call this recursively.
*/
private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu)
throws XmlPullParserException, IOException {
MenuState menuState = new MenuState(menu);
int eventType = parser.getEventType();
String tagName;
boolean lookingForEndOfUnknownTag = false;
String unknownTagName = null;
// This loop will skip to the menu start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.getName();
if (tagName.equals(XML_MENU)) {
// Go to next tag
eventType = parser.next();
break;
}
throw new RuntimeException("Expecting menu, got " + tagName);
}
eventType = parser.next();
} while (eventType != XmlPullParser.END_DOCUMENT);
boolean reachedEndOfMenu = false;
while (!reachedEndOfMenu) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (lookingForEndOfUnknownTag) {
break;
}
tagName = parser.getName();
if (tagName.equals(XML_GROUP)) {
menuState.readGroup(attrs);
} else if (tagName.equals(XML_ITEM)) {
menuState.readItem(attrs);
} else if (tagName.equals(XML_MENU)) {
// A menu start tag denotes a submenu for an item
SubMenu subMenu = menuState.addSubMenuItem();
// Parse the submenu into returned SubMenu
parseMenu(parser, attrs, subMenu);
} else {
lookingForEndOfUnknownTag = true;
unknownTagName = tagName;
}
break;
case XmlPullParser.END_TAG:
tagName = parser.getName();
if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
lookingForEndOfUnknownTag = false;
unknownTagName = null;
} else if (tagName.equals(XML_GROUP)) {
menuState.resetGroup();
} else if (tagName.equals(XML_ITEM)) {
// Add the item if it hasn't been added (if the item was
// a submenu, it would have been added already)
if (!menuState.hasAddedItem()) {
if (menuState.itemActionProvider != null &&
menuState.itemActionProvider.hasSubMenu()) {
menuState.addSubMenuItem();
} else {
menuState.addItem();
}
}
} else if (tagName.equals(XML_MENU)) {
reachedEndOfMenu = true;
}
break;
case XmlPullParser.END_DOCUMENT:
throw new RuntimeException("Unexpected end of document");
}
eventType = parser.next();
}
}
private static class InflatedOnMenuItemClickListener
implements MenuItem.OnMenuItemClickListener {
private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class };
private Context mContext;
private Method mMethod;
public InflatedOnMenuItemClickListener(Context context, String methodName) {
mContext = context;
Class<?> c = context.getClass();
try {
mMethod = c.getMethod(methodName, PARAM_TYPES);
} catch (Exception e) {
InflateException ex = new InflateException(
"Couldn't resolve menu item onClick handler " + methodName +
" in class " + c.getName());
ex.initCause(e);
throw ex;
}
}
public boolean onMenuItemClick(MenuItem item) {
try {
if (mMethod.getReturnType() == Boolean.TYPE) {
return (Boolean) mMethod.invoke(mContext, item);
} else {
mMethod.invoke(mContext, item);
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* State for the current menu.
* <p>
* Groups can not be nested unless there is another menu (which will have
* its state class).
*/
private class MenuState {
private Menu menu;
/*
* Group state is set on items as they are added, allowing an item to
* override its group state. (As opposed to set on items at the group end tag.)
*/
private int groupId;
private int groupCategory;
private int groupOrder;
private int groupCheckable;
private boolean groupVisible;
private boolean groupEnabled;
private boolean itemAdded;
private int itemId;
private int itemCategoryOrder;
private CharSequence itemTitle;
private CharSequence itemTitleCondensed;
private int itemIconResId;
private char itemAlphabeticShortcut;
private char itemNumericShortcut;
/**
* Sync to attrs.xml enum:
* - 0: none
* - 1: all
* - 2: exclusive
*/
private int itemCheckable;
private boolean itemChecked;
private boolean itemVisible;
private boolean itemEnabled;
/**
* Sync to attrs.xml enum, values in MenuItem:
* - 0: never
* - 1: ifRoom
* - 2: always
* - -1: Safe sentinel for "no value".
*/
private int itemShowAsAction;
private int itemActionViewLayout;
private String itemActionViewClassName;
private String itemActionProviderClassName;
private String itemListenerMethodName;
private ActionProvider itemActionProvider;
private static final int defaultGroupId = NO_ID;
private static final int defaultItemId = NO_ID;
private static final int defaultItemCategory = 0;
private static final int defaultItemOrder = 0;
private static final int defaultItemCheckable = 0;
private static final boolean defaultItemChecked = false;
private static final boolean defaultItemVisible = true;
private static final boolean defaultItemEnabled = true;
public MenuState(final Menu menu) {
this.menu = menu;
resetGroup();
}
public void resetGroup() {
groupId = defaultGroupId;
groupCategory = defaultItemCategory;
groupOrder = defaultItemOrder;
groupCheckable = defaultItemCheckable;
groupVisible = defaultItemVisible;
groupEnabled = defaultItemEnabled;
}
/**
* Called when the parser is pointing to a group tag.
*/
public void readGroup(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuGroup);
groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId);
groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory);
groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder);
groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable);
groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible);
groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled);
a.recycle();
}
/**
* Called when the parser is pointing to an item tag.
*/
public void readItem(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuItem);
// Inherit attributes from the group as default value
itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId);
final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory);
final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder);
itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK);
itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title);
itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed);
itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0);
itemAlphabeticShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut));
itemNumericShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut));
if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) {
// Item has attribute checkable, use it
itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0;
} else {
// Item does not have attribute, use the group's (group can have one more state
// for checkable that represents the exclusive checkable)
itemCheckable = groupCheckable;
}
itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked);
itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible);
itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled);
TypedValue value = new TypedValue();
a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value);
itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1;
itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick);
itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0);
itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass);
itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass);
final boolean hasActionProvider = itemActionProviderClassName != null;
if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) {
itemActionProvider = newInstance(itemActionProviderClassName,
ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE,
mActionProviderConstructorArguments);
} else {
if (hasActionProvider) {
Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'."
+ " Action view already specified.");
}
itemActionProvider = null;
}
a.recycle();
itemAdded = false;
}
private char getShortcut(String shortcutString) {
if (shortcutString == null) {
return 0;
} else {
return shortcutString.charAt(0);
}
}
private void setItem(MenuItem item) {
item.setChecked(itemChecked)
.setVisible(itemVisible)
.setEnabled(itemEnabled)
.setCheckable(itemCheckable >= 1)
.setTitleCondensed(itemTitleCondensed)
.setIcon(itemIconResId)
.setAlphabeticShortcut(itemAlphabeticShortcut)
.setNumericShortcut(itemNumericShortcut);
if (itemShowAsAction >= 0) {
item.setShowAsAction(itemShowAsAction);
}
if (itemListenerMethodName != null) {
if (mContext.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
item.setOnMenuItemClickListener(
new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName));
}
if (itemCheckable >= 2) {
if (item instanceof MenuItemImpl) {
MenuItemImpl impl = (MenuItemImpl) item;
impl.setExclusiveCheckable(true);
} else {
menu.setGroupCheckable(groupId, true, true);
}
}
boolean actionViewSpecified = false;
if (itemActionViewClassName != null) {
View actionView = (View) newInstance(itemActionViewClassName,
ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments);
item.setActionView(actionView);
actionViewSpecified = true;
}
if (itemActionViewLayout > 0) {
if (!actionViewSpecified) {
item.setActionView(itemActionViewLayout);
actionViewSpecified = true;
} else {
Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'."
+ " Action view already specified.");
}
}
if (itemActionProvider != null) {
item.setActionProvider(itemActionProvider);
}
}
public void addItem() {
itemAdded = true;
setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle));
}
public SubMenu addSubMenuItem() {
itemAdded = true;
SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle);
setItem(subMenu.getItem());
return subMenu;
}
public boolean hasAddedItem() {
return itemAdded;
}
@SuppressWarnings("unchecked")
private <T> T newInstance(String className, Class<?>[] constructorSignature,
Object[] arguments) {
try {
Class<?> clazz = mContext.getClassLoader().loadClass(className);
Constructor<?> constructor = clazz.getConstructor(constructorSignature);
return (T) constructor.newInstance(arguments);
} catch (Exception e) {
Log.w(LOG_TAG, "Cannot instantiate class: " + className, e);
}
return null;
}
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/MenuInflater.java | Java | asf20 | 19,430 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
/**
* When a {@link View} implements this interface it will receive callbacks
* when expanded or collapsed as an action view alongside the optional,
* app-specified callbacks to {@link OnActionExpandListener}.
*
* <p>See {@link MenuItem} for more information about action views.
* See {@link android.app.ActionBar} for more information about the action bar.
*/
public interface CollapsibleActionView {
/**
* Called when this view is expanded as an action view.
* See {@link MenuItem#expandActionView()}.
*/
public void onActionViewExpanded();
/**
* Called when this view is collapsed as an action view.
* See {@link MenuItem#collapseActionView()}.
*/
public void onActionViewCollapsed();
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/CollapsibleActionView.java | Java | asf20 | 1,402 |
/*
* Copyright (C) 2007 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.view;
import android.graphics.drawable.Drawable;
import android.view.View;
/**
* Subclass of {@link Menu} for sub menus.
* <p>
* Sub menus do not support item icons, or nested sub menus.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface SubMenu extends Menu {
/**
* Sets the submenu header's title to the title given in <var>titleRes</var>
* resource identifier.
*
* @param titleRes The string resource identifier used for the title.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderTitle(int titleRes);
/**
* Sets the submenu header's title to the title given in <var>title</var>.
*
* @param title The character sequence used for the title.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderTitle(CharSequence title);
/**
* Sets the submenu header's icon to the icon given in <var>iconRes</var>
* resource id.
*
* @param iconRes The resource identifier used for the icon.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderIcon(int iconRes);
/**
* Sets the submenu header's icon to the icon given in <var>icon</var>
* {@link Drawable}.
*
* @param icon The {@link Drawable} used for the icon.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderIcon(Drawable icon);
/**
* Sets the header of the submenu to the {@link View} given in
* <var>view</var>. This replaces the header title and icon (and those
* replace this).
*
* @param view The {@link View} used for the header.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderView(View view);
/**
* Clears the header of the submenu.
*/
public void clearHeader();
/**
* Change the icon associated with this submenu's item in its parent menu.
*
* @see MenuItem#setIcon(int)
* @param iconRes The new icon (as a resource ID) to be displayed.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setIcon(int iconRes);
/**
* Change the icon associated with this submenu's item in its parent menu.
*
* @see MenuItem#setIcon(Drawable)
* @param icon The new icon (as a Drawable) to be displayed.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setIcon(Drawable icon);
/**
* Gets the {@link MenuItem} that represents this submenu in the parent
* menu. Use this for setting additional item attributes.
*
* @return The {@link MenuItem} that launches the submenu when invoked.
*/
public MenuItem getItem();
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/SubMenu.java | Java | asf20 | 3,646 |
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* 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.view;
import android.content.Context;
/**
* <p>Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.</p>
*
* <p>The only existing implementation of this abstract class is
* android.policy.PhoneWindow, which you should instantiate when needing a
* Window. Eventually that class will be refactored and a factory method added
* for creating Window instances without knowing about a particular
* implementation.</p>
*/
public abstract class Window extends android.view.Window {
public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR;
public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY;
public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY;
public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE;
public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS;
public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS;
/**
* Create a new instance for a context.
*
* @param context Context.
*/
private Window(Context context) {
super(context);
}
public interface Callback {
/**
* Called when a panel's menu item has been selected by the user.
*
* @param featureId The panel that the menu is in.
* @param item The menu item that was selected.
*
* @return boolean Return true to finish processing of selection, or
* false to perform the normal menu handling (calling its
* Runnable or sending a Message to its target Handler).
*/
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/Window.java | Java | asf20 | 2,778 |
/*
* 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.view;
import android.view.View;
/**
* Represents a contextual mode of the user interface. Action modes can be used for
* modal interactions with content and replace parts of the normal UI until finished.
* Examples of good action modes include selection modes, search, content editing, etc.
*/
public abstract class ActionMode {
private Object mTag;
/**
* 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);
/**
* Set the subtitle of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param subtitle Subtitle string to set
*
* @see #setSubtitle(int)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(CharSequence subtitle);
/**
* Set the subtitle 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 subtitle
*
* @see #setSubtitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(int resId);
/**
* Set a custom view for this action mode. The custom view will take the place of
* the title and subtitle. Useful for things like search boxes.
*
* @param view Custom view to use in place of the title/subtitle.
*
* @see #setTitle(CharSequence)
* @see #setSubtitle(CharSequence)
*/
public abstract void setCustomView(View view);
/**
* 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 menu of actions that this action mode presents.
* @return The action mode's menu.
*/
public abstract Menu getMenu();
/**
* Returns the current title of this action mode.
* @return Title text
*/
public abstract CharSequence getTitle();
/**
* Returns the current subtitle of this action mode.
* @return Subtitle text
*/
public abstract CharSequence getSubtitle();
/**
* Returns the current custom view for this action mode.
* @return The current custom view
*/
public abstract View getCustomView();
/**
* 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);
}
} | zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/ActionMode.java | Java | asf20 | 7,820 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.content.Context;
import android.view.View;
/**
* This class is a mediator for accomplishing a given task, for example sharing a file.
* It is responsible for creating a view that performs an action that accomplishes the task.
* This class also implements other functions such a performing a default action.
* <p>
* An ActionProvider can be optionally specified for a {@link MenuItem} and in such a
* case it will be responsible for creating the action view that appears in the
* {@link android.app.ActionBar} as a substitute for the menu item when the item is
* displayed as an action item. Also the provider is responsible for performing a
* default action if a menu item placed on the overflow menu of the ActionBar is
* selected and none of the menu item callbacks has handled the selection. For this
* case the provider can also optionally provide a sub-menu for accomplishing the
* task at hand.
* </p>
* <p>
* There are two ways for using an action provider for creating and handling of action views:
* <ul>
* <li>
* Setting the action provider on a {@link MenuItem} directly by calling
* {@link MenuItem#setActionProvider(ActionProvider)}.
* </li>
* <li>
* Declaring the action provider in the menu XML resource. For example:
* <pre>
* <code>
* <item android:id="@+id/my_menu_item"
* android:title="Title"
* android:icon="@drawable/my_menu_item_icon"
* android:showAsAction="ifRoom"
* android:actionProviderClass="foo.bar.SomeActionProvider" />
* </code>
* </pre>
* </li>
* </ul>
* </p>
*
* @see MenuItem#setActionProvider(ActionProvider)
* @see MenuItem#getActionProvider()
*/
public abstract class ActionProvider {
private SubUiVisibilityListener mSubUiVisibilityListener;
/**
* Creates a new instance.
*
* @param context Context for accessing resources.
*/
public ActionProvider(Context context) {
}
/**
* Factory method for creating new action views.
*
* @return A new action view.
*/
public abstract View onCreateActionView();
/**
* Performs an optional default action.
* <p>
* For the case of an action provider placed in a menu item not shown as an action this
* method is invoked if previous callbacks for processing menu selection has handled
* the event.
* </p>
* <p>
* A menu item selection is processed in the following order:
* <ul>
* <li>
* Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick
* MenuItem.OnMenuItemClickListener.onMenuItemClick}.
* </li>
* <li>
* Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem)
* Activity.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem)
* Fragment.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Launching the {@link android.content.Intent} set via
* {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)}
* </li>
* <li>
* Invoking this method.
* </li>
* </ul>
* </p>
* <p>
* The default implementation does not perform any action and returns false.
* </p>
*/
public boolean onPerformDefaultAction() {
return false;
}
/**
* Determines if this ActionProvider has a submenu associated with it.
*
* <p>Associated submenus will be shown when an action view is not. This
* provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)}
* after the call to {@link #onPerformDefaultAction()} and before a submenu is
* displayed to the user.
*
* @return true if the item backed by this provider should have an associated submenu
*/
public boolean hasSubMenu() {
return false;
}
/**
* Called to prepare an associated submenu for the menu item backed by this ActionProvider.
*
* <p>if {@link #hasSubMenu()} returns true, this method will be called when the
* menu item is selected to prepare the submenu for presentation to the user. Apps
* may use this to create or alter submenu content right before display.
*
* @param subMenu Submenu that will be displayed
*/
public void onPrepareSubMenu(SubMenu subMenu) {
}
/**
* Notify the system that the visibility of an action view's sub-UI such as
* an anchored popup has changed. This will affect how other system
* visibility notifications occur.
*
* @hide Pending future API approval
*/
public void subUiVisibilityChanged(boolean isVisible) {
if (mSubUiVisibilityListener != null) {
mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible);
}
}
/**
* @hide Internal use only
*/
public void setSubUiVisibilityListener(SubUiVisibilityListener listener) {
mSubUiVisibilityListener = listener;
}
/**
* @hide Internal use only
*/
public interface SubUiVisibilityListener {
public void onSubUiVisibilityChanged(boolean isVisible);
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/view/ActionProvider.java | Java | asf20 | 5,865 |
package com.actionbarsherlock;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.ActionBarSherlockCompat;
import com.actionbarsherlock.internal.ActionBarSherlockNative;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
/**
* <p>Helper for implementing the action bar design pattern across all versions
* of Android.</p>
*
* <p>This class will manage interaction with a custom action bar based on the
* Android 4.0 source code. The exposed API mirrors that of its native
* counterpart and you should refer to its documentation for instruction.</p>
*
* @author Jake Wharton <jakewharton@gmail.com>
*/
public abstract class ActionBarSherlock {
protected static final String TAG = "ActionBarSherlock";
protected static final boolean DEBUG = false;
private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class };
private static final HashMap<Implementation, Class<? extends ActionBarSherlock>> IMPLEMENTATIONS =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>();
static {
//Register our two built-in implementations
registerImplementation(ActionBarSherlockCompat.class);
registerImplementation(ActionBarSherlockNative.class);
}
/**
* <p>Denotes an implementation of ActionBarSherlock which provides an
* action bar-enhanced experience.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Implementation {
static final int DEFAULT_API = -1;
static final int DEFAULT_DPI = -1;
int api() default DEFAULT_API;
int dpi() default DEFAULT_DPI;
}
/** Activity interface for menu creation callback. */
public interface OnCreatePanelMenuListener {
public boolean onCreatePanelMenu(int featureId, Menu menu);
}
/** Activity interface for menu creation callback. */
public interface OnCreateOptionsMenuListener {
public boolean onCreateOptionsMenu(Menu menu);
}
/** Activity interface for menu item selection callback. */
public interface OnMenuItemSelectedListener {
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
/** Activity interface for menu item selection callback. */
public interface OnOptionsItemSelectedListener {
public boolean onOptionsItemSelected(MenuItem item);
}
/** Activity interface for menu preparation callback. */
public interface OnPreparePanelListener {
public boolean onPreparePanel(int featureId, View view, Menu menu);
}
/** Activity interface for menu preparation callback. */
public interface OnPrepareOptionsMenuListener {
public boolean onPrepareOptionsMenu(Menu menu);
}
/** Activity interface for action mode finished callback. */
public interface OnActionModeFinishedListener {
public void onActionModeFinished(ActionMode mode);
}
/** Activity interface for action mode started callback. */
public interface OnActionModeStartedListener {
public void onActionModeStarted(ActionMode mode);
}
/**
* If set, the logic in these classes will assume that an {@link Activity}
* is dispatching all of the required events to the class. This flag should
* only be used internally or if you are creating your own base activity
* modeled after one of the included types (e.g., {@code SherlockActivity}).
*/
public static final int FLAG_DELEGATE = 1;
/**
* Register an ActionBarSherlock implementation.
*
* @param implementationClass Target implementation class which extends
* {@link ActionBarSherlock}. This class must also be annotated with
* {@link Implementation}.
*/
public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) {
if (!implementationClass.isAnnotationPresent(Implementation.class)) {
throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
} else if (IMPLEMENTATIONS.containsValue(implementationClass)) {
if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered");
return;
}
Implementation impl = implementationClass.getAnnotation(Implementation.class);
if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
IMPLEMENTATIONS.put(impl, implementationClass);
}
/**
* Unregister an ActionBarSherlock implementation. <strong>This should be
* considered very volatile and you should only use it if you know what
* you are doing.</strong> You have been warned.
*
* @param implementationClass Target implementation class.
* @return Boolean indicating whether the class was removed.
*/
public static boolean unregisterImplementation(Class<? extends ActionBarSherlock> implementationClass) {
return IMPLEMENTATIONS.values().remove(implementationClass);
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Activity to wrap.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity) {
return wrap(activity, 0);
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Owning activity.
* @param flags Option flags to control behavior.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity, int flags) {
//Create a local implementation map we can modify
HashMap<Implementation, Class<? extends ActionBarSherlock>> impls =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS);
boolean hasQualfier;
/* DPI FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
//Only honor TVDPI as a specific qualifier
if (key.dpi() == DisplayMetrics.DENSITY_TV) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyDpi = keys.next().dpi();
if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
|| (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
keys.remove();
}
}
}
/* API FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
if (key.api() != Implementation.DEFAULT_API) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final int runtimeApi = Build.VERSION.SDK_INT;
int bestApi = 0;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyApi = keys.next().api();
if (keyApi > runtimeApi) {
keys.remove();
} else if (keyApi > bestApi) {
bestApi = keyApi;
}
}
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
if (keys.next().api() != bestApi) {
keys.remove();
}
}
}
if (impls.size() > 1) {
throw new IllegalStateException("More than one implementation matches configuration.");
}
if (impls.isEmpty()) {
throw new IllegalStateException("No implementations match configuration.");
}
Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
if (DEBUG) Log.i(TAG, "Using implementation: " + impl.getSimpleName());
try {
Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
return ctor.newInstance(activity, flags);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/** Activity which is displaying the action bar. Also used for context. */
protected final Activity mActivity;
/** Whether delegating actions for the activity or managing ourselves. */
protected final boolean mIsDelegate;
/** Reference to our custom menu inflater which supports action items. */
protected MenuInflater mMenuInflater;
protected ActionBarSherlock(Activity activity, int flags) {
if (DEBUG) Log.d(TAG, "[<ctor>] activity: " + activity + ", flags: " + flags);
mActivity = activity;
mIsDelegate = (flags & FLAG_DELEGATE) != 0;
}
/**
* Get the current action bar instance.
*
* @return Action bar instance.
*/
public abstract ActionBar getActionBar();
///////////////////////////////////////////////////////////////////////////
// Lifecycle and interaction callbacks when delegating
///////////////////////////////////////////////////////////////////////////
/**
* Notify action bar of a configuration change event. Should be dispatched
* after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* public void onConfigurationChanged(Configuration newConfig) {
* super.onConfigurationChanged(newConfig);
* mSherlock.dispatchConfigurationChanged(newConfig);
* }
* </pre></blockquote>
*
* @param newConfig The new device configuration.
*/
public void dispatchConfigurationChanged(Configuration newConfig) {}
/**
* Notify the action bar that the activity has finished its resuming. This
* should be dispatched after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostResume() {
* super.onPostResume();
* mSherlock.dispatchPostResume();
* }
* </pre></blockquote>
*/
public void dispatchPostResume() {}
/**
* Notify the action bar that the activity is pausing. This should be
* dispatched before the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPause() {
* mSherlock.dispatchPause();
* super.onPause();
* }
* </pre></blockquote>
*/
public void dispatchPause() {}
/**
* Notify the action bar that the activity is stopping. This should be
* called before the superclass implementation.
*
* <blockquote><p>
* @Override
* protected void onStop() {
* mSherlock.dispatchStop();
* super.onStop();
* }
* </p></blockquote>
*/
public void dispatchStop() {}
/**
* Indicate that the menu should be recreated by calling
* {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}.
*/
public abstract void dispatchInvalidateOptionsMenu();
/**
* Notify the action bar that it should display its overflow menu if it is
* appropriate for the device. The implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><p>
* @Override
* public void openOptionsMenu() {
* if (!mSherlock.dispatchOpenOptionsMenu()) {
* super.openOptionsMenu();
* }
* }
* </p></blockquote>
*
* @return {@code true} if the opening of the menu was handled internally.
*/
public boolean dispatchOpenOptionsMenu() {
return false;
}
/**
* Notify the action bar that it should close its overflow menu if it is
* appropriate for the device. This implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><pre>
* @Override
* public void closeOptionsMenu() {
* if (!mSherlock.dispatchCloseOptionsMenu()) {
* super.closeOptionsMenu();
* }
* }
* </pre></blockquote>
*
* @return {@code true} if the closing of the menu was handled internally.
*/
public boolean dispatchCloseOptionsMenu() {
return false;
}
/**
* Notify the class that the activity has finished its creation. This
* should be called after the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostCreate(Bundle savedInstanceState) {
* mSherlock.dispatchPostCreate(savedInstanceState);
* super.onPostCreate(savedInstanceState);
* }
* </pre></blockquote>
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle
* contains the data it most recently supplied in
* {@link Activity#}onSaveInstanceState(Bundle)}.
* <strong>Note: Otherwise it is null.</strong>
*/
public void dispatchPostCreate(Bundle savedInstanceState) {}
/**
* Notify the action bar that the title has changed and the action bar
* should be updated to reflect the change. This should be called before
* the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onTitleChanged(CharSequence title, int color) {
* mSherlock.dispatchTitleChanged(title, color);
* super.onTitleChanged(title, color);
* }
* </pre></blockquote>
*
* @param title New activity title.
* @param color New activity color.
*/
public void dispatchTitleChanged(CharSequence title, int color) {}
/**
* Notify the action bar the user has created a key event. This is used to
* toggle the display of the overflow action item with the menu key and to
* close the action mode or expanded action item with the back key.
*
* <blockquote><pre>
* @Override
* public boolean dispatchKeyEvent(KeyEvent event) {
* if (mSherlock.dispatchKeyEvent(event)) {
* return true;
* }
* return super.dispatchKeyEvent(event);
* }
* </pre></blockquote>
*
* @param event Description of the key event.
* @return {@code true} if the event was handled.
*/
public boolean dispatchKeyEvent(KeyEvent event) {
return false;
}
/**
* Notify the action bar that the Activity has triggered a menu creation
* which should happen on the conclusion of {@link Activity#onCreate}. This
* will be used to gain a reference to the native menu for native and
* overflow binding as well as to indicate when compatibility create should
* occur for the first time.
*
* @param menu Activity native menu.
* @return {@code true} since we always want to say that we have a native
*/
public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that the Activity has triggered a menu preparation
* which usually means that the user has requested the overflow menu via a
* hardware menu key. You should return the result of this method call and
* not call the superclass implementation.
*
* <blockquote><p>
* @Override
* public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
* return mSherlock.dispatchPrepareOptionsMenu(menu);
* }
* </p></blockquote>
*
* @param menu Activity native menu.
* @return {@code true} if menu display should proceed.
*/
public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that a native options menu item has been selected.
* The implementation should return the result of this method call.
*
* <blockquote><p>
* @Override
* public final boolean onOptionsItemSelected(android.view.MenuItem item) {
* return mSherlock.dispatchOptionsItemSelected(item);
* }
* </p></blockquote>
*
* @param item Options menu item.
* @return @{code true} if the selection was handled.
*/
public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item);
/**
* Notify the action bar that the overflow menu has been opened. The
* implementation should conditionally return {@code true} if this method
* returns {@code true}, otherwise return the result of the superclass
* method.
*
* <blockquote><p>
* @Override
* public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
* if (mSherlock.dispatchMenuOpened(featureId, menu)) {
* return true;
* }
* return super.onMenuOpened(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId Window feature which triggered the event.
* @param menu Activity native menu.
* @return {@code true} if the event was handled by this method.
*/
public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) {
return false;
}
/**
* Notify the action bar that the overflow menu has been closed. This
* method should be called before the superclass implementation.
*
* <blockquote><p>
* @Override
* public void onPanelClosed(int featureId, android.view.Menu menu) {
* mSherlock.dispatchPanelClosed(featureId, menu);
* super.onPanelClosed(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId
* @param menu
*/
public void dispatchPanelClosed(int featureId, android.view.Menu menu) {}
/**
* Notify the action bar that the activity has been destroyed. This method
* should be called before the superclass implementation.
*
* <blockquote><p>
* @Override
* public void onDestroy() {
* mSherlock.dispatchDestroy();
* super.onDestroy();
* }
* </p></blockquote>
*/
public void dispatchDestroy() {}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Internal method to trigger the menu creation process.
*
* @return {@code true} if menu creation should proceed.
*/
protected final boolean callbackCreateOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnCreatePanelMenuListener) {
OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity;
result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu);
} else if (mActivity instanceof OnCreateOptionsMenuListener) {
OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity;
result = listener.onCreateOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result);
return result;
}
/**
* Internal method to trigger the menu preparation process.
*
* @return {@code true} if menu preparation should proceed.
*/
protected final boolean callbackPrepareOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnPreparePanelListener) {
OnPreparePanelListener listener = (OnPreparePanelListener)mActivity;
result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu);
} else if (mActivity instanceof OnPrepareOptionsMenuListener) {
OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity;
result = listener.onPrepareOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result);
return result;
}
/**
* Internal method for dispatching options menu selection to the owning
* activity callback.
*
* @param item Selected options menu item.
* @return {@code true} if the item selection was handled in the callback.
*/
protected final boolean callbackOptionsItemSelected(MenuItem item) {
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed());
boolean result = false;
if (mActivity instanceof OnMenuItemSelectedListener) {
OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity;
result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item);
} else if (mActivity instanceof OnOptionsItemSelectedListener) {
OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity;
result = listener.onOptionsItemSelected(item);
}
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result);
return result;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Query for the availability of a certain feature.
*
* @param featureId The feature ID to check.
* @return {@code true} if feature is enabled, {@code false} otherwise.
*/
public abstract boolean hasFeature(int featureId);
/**
* Enable extended screen features. This must be called before
* {@code setContentView()}. May be called as many times as desired as long
* as it is before {@code setContentView()}. If not called, no extended
* features will be available. You can not turn off a feature once it is
* requested.
*
* @param featureId The desired features, defined as constants by Window.
* @return Returns true if the requested feature is supported and now
* enabled.
*/
public abstract boolean requestFeature(int featureId);
/**
* Set extra options that will influence the UI for this window.
*
* @param uiOptions Flags specifying extra options for this window.
*/
public abstract void setUiOptions(int uiOptions);
/**
* Set extra options that will influence the UI for this window. Only the
* bits filtered by mask will be modified.
*
* @param uiOptions Flags specifying extra options for this window.
* @param mask Flags specifying which options should be modified. Others
* will remain unchanged.
*/
public abstract void setUiOptions(int uiOptions, int mask);
/**
* Set the content of the activity inside the action bar.
*
* @param layoutResId Layout resource ID.
*/
public abstract void setContentView(int layoutResId);
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
*/
public void setContentView(View view) {
if (DEBUG) Log.d(TAG, "[setContentView] view: " + view);
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
* @param params Layout parameters to apply to the view.
*/
public abstract void setContentView(View view, ViewGroup.LayoutParams params);
/**
* Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
* to add an additional content view to the screen. Added after any
* existing ones on the screen -- existing views are NOT removed.
*
* @param view The desired content to display.
* @param params Layout parameters for the view.
*/
public abstract void addContentView(View view, ViewGroup.LayoutParams params);
/**
* Change the title associated with this activity.
*/
public abstract void setTitle(CharSequence title);
/**
* Change the title associated with this activity.
*/
public void setTitle(int resId) {
if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId);
setTitle(mActivity.getString(resId));
}
/**
* Sets the visibility of the progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarVisibility(boolean visible);
/**
* Sets the visibility of the indeterminate progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarIndeterminateVisibility(boolean visible);
/**
* Sets whether the horizontal progress bar in the title should be indeterminate (the circular
* is always indeterminate).
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param indeterminate Whether the horizontal progress bar should be indeterminate.
*/
public abstract void setProgressBarIndeterminate(boolean indeterminate);
/**
* Sets the progress for the progress bars in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param progress The progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive). If 10000 is given, the progress
* bar will be completely filled and will fade out.
*/
public abstract void setProgress(int progress);
/**
* Sets the secondary progress for the progress bar in the title. This
* progress is drawn between the primary progress (set via
* {@link #setProgress(int)} and the background. It can be ideal for media
* scenarios such as showing the buffering progress while the default
* progress shows the play progress.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive).
*/
public abstract void setSecondaryProgress(int secondaryProgress);
/**
* Get a menu inflater instance which supports the newer menu attributes.
*
* @return Menu inflater instance.
*/
public MenuInflater getMenuInflater() {
if (DEBUG) Log.d(TAG, "[getMenuInflater]");
// Make sure that action views can get an appropriate theme.
if (mMenuInflater == null) {
if (getActionBar() != null) {
mMenuInflater = new MenuInflater(getThemedContext());
} else {
mMenuInflater = new MenuInflater(mActivity);
}
}
return mMenuInflater;
}
protected abstract Context getThemedContext();
/**
* Start an action mode.
*
* @param callback Callback that will manage lifecycle events for this
* context mode.
* @return The ContextMode that was started, or null if it was canceled.
* @see ActionMode
*/
public abstract ActionMode startActionMode(ActionMode.Callback callback);
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/ActionBarSherlock.java | Java | asf20 | 30,369 |
/*
* 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();
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java | Java | asf20 | 6,312 |
/*
* 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));
}
} | zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java | Java | asf20 | 1,940 |
/*
* 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;
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java | Java | asf20 | 53,216 |
/*
* 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);
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java | Java | asf20 | 10,313 |
/*
* 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;
}
}
| zzxxasp-key | libprojects/abs/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java | Java | asf20 | 21,908 |