DO NOT MERGE: Merge commit 'b972321361fdd5d7cc5ee9d92b610c3aeaef6a8c' from oc-support-26.0-dev to stage-aosp-master. am: cc3da80ac4  -s ours
am: 3b9144a101  -s ours

Change-Id: Iebb53cecf53ac05745fc056f2ec6077d8fc03428
diff --git a/.gitignore b/.gitignore
index e57740b..abfef7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,3 +14,5 @@
 *.iml
 **/out
 buildSrc/build
+lifecycle/common/build
+jacoco.exec
\ No newline at end of file
diff --git a/annotations/src/android/support/annotation/MainThread.java b/annotations/src/android/support/annotation/MainThread.java
index 5478751..2f50306 100644
--- a/annotations/src/android/support/annotation/MainThread.java
+++ b/annotations/src/android/support/annotation/MainThread.java
@@ -34,9 +34,17 @@
  *  @MainThread
  *  public void deliverResult(D data) { ... }
  * </code></pre>
+ *
+ * <p class="note"><b>Note:</b> Ordinarily, an app's main thread is also the UI
+ * thread. However, However, under special circumstances, an app's main thread
+ * might not be its UI thread; for more information, see
+ * <a href="/studio/write/annotations.html#thread-annotations">Thread
+ * annotations</a>.
+ *
+ * @see android.support.annotation.UiThread
  */
 @Documented
 @Retention(CLASS)
 @Target({METHOD,CONSTRUCTOR,TYPE})
 public @interface MainThread {
-}
\ No newline at end of file
+}
diff --git a/annotations/src/android/support/annotation/UiThread.java b/annotations/src/android/support/annotation/UiThread.java
index ef81986..0a9a0c1 100644
--- a/annotations/src/android/support/annotation/UiThread.java
+++ b/annotations/src/android/support/annotation/UiThread.java
@@ -35,9 +35,17 @@
  *
  *  public abstract void setText(@NonNull String text) { ... }
  * </code></pre>
+ *
+ * <p class="note"><b>Note:</b> Ordinarily, an app's UI thread is also the main
+ * thread. However, However, under special circumstances, an app's UI thread
+ * might not be its main thread; for more information, see
+ * <a href="/studio/write/annotations.html#thread-annotations">Thread
+ * annotations</a>.
+ *
+ * @see android.support.annotation.MainThread
  */
 @Documented
 @Retention(CLASS)
 @Target({METHOD,CONSTRUCTOR,TYPE})
 public @interface UiThread {
-}
\ No newline at end of file
+}
diff --git a/api/25.4.0.ignore b/api/25.4.0.ignore
index e63593a..97d6ff8 100644
--- a/api/25.4.0.ignore
+++ b/api/25.4.0.ignore
@@ -6,3 +6,4 @@
 24c3865
 a684458
 7c9f9f7
+18b5692
\ No newline at end of file
diff --git a/api/26.0.0-SNAPSHOT.txt b/api/26.0.0-SNAPSHOT.txt
index 4d70979..fe0c575 100644
--- a/api/26.0.0-SNAPSHOT.txt
+++ b/api/26.0.0-SNAPSHOT.txt
@@ -50,6 +50,9 @@
     ctor public FlingAnimation(K, android.support.animation.FloatPropertyCompat<K>);
     method public float getFriction();
     method public android.support.animation.FlingAnimation setFriction(float);
+    method public android.support.animation.FlingAnimation setMaxValue(float);
+    method public android.support.animation.FlingAnimation setMinValue(float);
+    method public android.support.animation.FlingAnimation setStartVelocity(float);
   }
 
   public abstract class FloatPropertyCompat<T> {
@@ -378,6 +381,9 @@
     ctor public AppBarLayout(android.content.Context);
     ctor public AppBarLayout(android.content.Context, android.util.AttributeSet);
     method public void addOnOffsetChangedListener(android.support.design.widget.AppBarLayout.OnOffsetChangedListener);
+    method protected android.support.design.widget.AppBarLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.design.widget.AppBarLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.design.widget.AppBarLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public deprecated float getTargetElevation();
     method public final int getTotalScrollRange();
     method public void removeOnOffsetChangedListener(android.support.design.widget.AppBarLayout.OnOffsetChangedListener);
@@ -510,6 +516,9 @@
     method public boolean getSkipCollapsed();
     method public final int getState();
     method public boolean isHideable();
+    method public void onNestedPreScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int[]);
+    method public boolean onStartNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int);
+    method public void onStopNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View);
     method public void setBottomSheetCallback(android.support.design.widget.BottomSheetBehavior.BottomSheetCallback);
     method public void setHideable(boolean);
     method public final void setPeekHeight(int);
@@ -550,6 +559,9 @@
     ctor public CollapsingToolbarLayout(android.content.Context);
     ctor public CollapsingToolbarLayout(android.content.Context, android.util.AttributeSet);
     ctor public CollapsingToolbarLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.design.widget.CollapsingToolbarLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.widget.FrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.widget.FrameLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public int getCollapsedTitleGravity();
     method public android.graphics.Typeface getCollapsedTitleTypeface();
     method public android.graphics.drawable.Drawable getContentScrim();
@@ -615,6 +627,9 @@
     ctor public CoordinatorLayout(android.content.Context, android.util.AttributeSet, int);
     method public void dispatchDependentViewsChanged(android.view.View);
     method public boolean doViewsOverlap(android.view.View, android.view.View);
+    method protected android.support.design.widget.CoordinatorLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.design.widget.CoordinatorLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.design.widget.CoordinatorLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public java.util.List<android.view.View> getDependencies(android.view.View);
     method public java.util.List<android.view.View> getDependents(android.view.View);
     method public android.graphics.drawable.Drawable getStatusBarBackground();
@@ -708,6 +723,7 @@
     method public boolean getUseCompatPadding();
     method public void hide();
     method public void hide(android.support.design.widget.FloatingActionButton.OnVisibilityChangedListener);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
     method public void setCompatElevation(float);
     method public void setRippleColor(int);
     method public void setSize(int);
@@ -847,6 +863,7 @@
     method public void addTab(android.support.design.widget.TabLayout.Tab, boolean);
     method public void addTab(android.support.design.widget.TabLayout.Tab, int, boolean);
     method public void clearOnTabSelectedListeners();
+    method public android.widget.FrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
     method public int getSelectedTabPosition();
     method public android.support.design.widget.TabLayout.Tab getTabAt(int);
     method public int getTabCount();
@@ -1027,6 +1044,8 @@
   public class ExifInterface {
     ctor public ExifInterface(java.lang.String) throws java.io.IOException;
     ctor public ExifInterface(java.io.InputStream) throws java.io.IOException;
+    method public void flipHorizontally();
+    method public void flipVertically();
     method public double getAltitude(double);
     method public java.lang.String getAttribute(java.lang.String);
     method public double getAttributeDouble(java.lang.String, double);
@@ -1039,8 +1058,12 @@
     method public long[] getThumbnailRange();
     method public boolean hasThumbnail();
     method public boolean isThumbnailCompressed();
+    method public void resetOrientation();
+    method public void rotate(int);
     method public void saveAttributes() throws java.io.IOException;
+    method public void setAltitude(double);
     method public void setAttribute(java.lang.String, java.lang.String);
+    method public void setGpsInfo(android.location.Location);
     method public void setLatLong(double, double);
     field public static final int ORIENTATION_FLIP_HORIZONTAL = 2; // 0x2
     field public static final int ORIENTATION_FLIP_VERTICAL = 4; // 0x4
@@ -1193,115 +1216,6 @@
 
 package android.support.media.tv {
 
-  public abstract class BasePreviewProgram extends android.support.media.tv.BaseProgram {
-    method public java.lang.String getAuthor();
-    method public int getAvailability();
-    method public java.lang.String getContentId();
-    method public int getDurationMillis();
-    method public android.content.Intent getIntent() throws java.net.URISyntaxException;
-    method public android.net.Uri getIntentUri();
-    method public long getInteractionCount();
-    method public int getInteractionType();
-    method public java.lang.String getInternalProviderId();
-    method public int getItemCount();
-    method public int getLastPlaybackPositionMillis();
-    method public android.net.Uri getLogoUri();
-    method public java.lang.String getOfferPrice();
-    method public int getPosterArtAspectRatio();
-    method public android.net.Uri getPreviewVideoUri();
-    method public java.lang.String getReleaseDate();
-    method public java.lang.String getStartingPrice();
-    method public int getThumbnailAspectRatio();
-    method public int getType();
-    method public boolean isBrowsable();
-    method public boolean isLive();
-    method public boolean isTransient();
-  }
-
-  public static abstract class BasePreviewProgram.Builder<T extends android.support.media.tv.BasePreviewProgram.Builder> extends android.support.media.tv.BaseProgram.Builder {
-    ctor public BasePreviewProgram.Builder();
-    ctor public BasePreviewProgram.Builder(android.support.media.tv.BasePreviewProgram);
-    method public T setAuthor(java.lang.String);
-    method public T setAvailability(int);
-    method public T setContentId(java.lang.String);
-    method public T setDurationMillis(int);
-    method public T setIntent(android.content.Intent);
-    method public T setIntentUri(android.net.Uri);
-    method public T setInteractionCount(long);
-    method public T setInteractionType(int);
-    method public T setInternalProviderId(java.lang.String);
-    method public T setItemCount(int);
-    method public T setLastPlaybackPositionMillis(int);
-    method public T setLive(boolean);
-    method public T setLogoUri(android.net.Uri);
-    method public T setOfferPrice(java.lang.String);
-    method public T setPosterArtAspectRatio(int);
-    method public T setPreviewVideoUri(android.net.Uri);
-    method public T setReleaseDate(java.lang.String);
-    method public T setReleaseDate(java.util.Date);
-    method public T setStartingPrice(java.lang.String);
-    method public T setThumbnailAspectRatio(int);
-    method public T setTransient(boolean);
-    method public T setType(int);
-  }
-
-  public abstract class BaseProgram {
-    method public java.lang.String[] getAudioLanguages();
-    method public java.lang.String[] getCanonicalGenres();
-    method public android.media.tv.TvContentRating[] getContentRatings();
-    method public java.lang.String getDescription();
-    method public java.lang.String getEpisodeNumber();
-    method public java.lang.String getEpisodeTitle();
-    method public long getId();
-    method public byte[] getInternalProviderDataByteArray();
-    method public java.lang.Long getInternalProviderFlag1();
-    method public java.lang.Long getInternalProviderFlag2();
-    method public java.lang.Long getInternalProviderFlag3();
-    method public java.lang.Long getInternalProviderFlag4();
-    method public java.lang.String getLongDescription();
-    method public android.net.Uri getPosterArtUri();
-    method public java.lang.String getReviewRating();
-    method public int getReviewRatingStyle();
-    method public java.lang.String getSeasonNumber();
-    method public java.lang.String getSeasonTitle();
-    method public android.net.Uri getThumbnailUri();
-    method public java.lang.String getTitle();
-    method public int getVideoHeight();
-    method public int getVideoWidth();
-    method public boolean isSearchable();
-    method public android.content.ContentValues toContentValues();
-  }
-
-  public static abstract class BaseProgram.Builder<T extends android.support.media.tv.BaseProgram.Builder> {
-    ctor public BaseProgram.Builder();
-    ctor public BaseProgram.Builder(android.support.media.tv.BaseProgram);
-    method public T setAudioLanguages(java.lang.String[]);
-    method public T setCanonicalGenres(java.lang.String[]);
-    method public T setContentRatings(android.media.tv.TvContentRating[]);
-    method public T setDescription(java.lang.String);
-    method public T setEpisodeNumber(int);
-    method public T setEpisodeNumber(java.lang.String, int);
-    method public T setEpisodeTitle(java.lang.String);
-    method public T setId(long);
-    method public T setInternalProviderData(byte[]);
-    method public T setInternalProviderFlag1(long);
-    method public T setInternalProviderFlag2(long);
-    method public T setInternalProviderFlag3(long);
-    method public T setInternalProviderFlag4(long);
-    method public T setLongDescription(java.lang.String);
-    method public T setPosterArtUri(android.net.Uri);
-    method public T setReviewRating(java.lang.String);
-    method public T setReviewRatingStyle(int);
-    method public T setSearchable(boolean);
-    method public T setSeasonNumber(int);
-    method public T setSeasonNumber(java.lang.String, int);
-    method public T setSeasonTitle(java.lang.String);
-    method public T setThumbnailUri(android.net.Uri);
-    method public T setTitle(java.lang.String);
-    method public T setVideoHeight(int);
-    method public T setVideoWidth(int);
-  }
-
   public final class Channel {
     method public static android.support.media.tv.Channel fromCursor(android.database.Cursor);
     method public int getAppLinkColor();
@@ -1375,13 +1289,16 @@
     method public static boolean storeChannelLogo(android.content.Context, long, android.graphics.Bitmap);
   }
 
-  public final class PreviewProgram extends android.support.media.tv.BasePreviewProgram {
+  public final class PreviewProgram {
+    method public boolean equals(java.lang.Object);
     method public static android.support.media.tv.PreviewProgram fromCursor(android.database.Cursor);
     method public long getChannelId();
     method public int getWeight();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
   }
 
-  public static final class PreviewProgram.Builder extends android.support.media.tv.BasePreviewProgram.Builder {
+  public static final class PreviewProgram.Builder {
     ctor public PreviewProgram.Builder();
     ctor public PreviewProgram.Builder(android.support.media.tv.PreviewProgram);
     method public android.support.media.tv.PreviewProgram build();
@@ -1389,17 +1306,21 @@
     method public android.support.media.tv.PreviewProgram.Builder setWeight(int);
   }
 
-  public final class Program extends android.support.media.tv.BaseProgram implements java.lang.Comparable {
+  public final class Program implements java.lang.Comparable {
     method public int compareTo(android.support.media.tv.Program);
+    method public boolean equals(java.lang.Object);
     method public static android.support.media.tv.Program fromCursor(android.database.Cursor);
     method public java.lang.String[] getBroadcastGenres();
     method public long getChannelId();
     method public long getEndTimeUtcMillis();
     method public long getStartTimeUtcMillis();
+    method public int hashCode();
     method public boolean isRecordingProhibited();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
   }
 
-  public static class Program.Builder extends android.support.media.tv.BaseProgram.Builder {
+  public static class Program.Builder {
     ctor public Program.Builder();
     ctor public Program.Builder(android.support.media.tv.Program);
     method public android.support.media.tv.Program build();
@@ -1431,6 +1352,7 @@
     method public static boolean isChannelUriForPassthroughInput(android.net.Uri);
     method public static boolean isChannelUriForTunerInput(android.net.Uri);
     method public static boolean isProgramUri(android.net.Uri);
+    method public static boolean isRecordedProgramUri(android.net.Uri);
     method public static void requestChannelBrowsable(android.content.Context, long);
     field public static final java.lang.String ACTION_INITIALIZE_PROGRAMS = "android.media.tv.action.INITIALIZE_PROGRAMS";
     field public static final java.lang.String ACTION_PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT = "android.media.tv.action.PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT";
@@ -1800,13 +1722,16 @@
     field public static final int WATCH_NEXT_TYPE_WATCHLIST = 3; // 0x3
   }
 
-  public final class WatchNextProgram extends android.support.media.tv.BasePreviewProgram {
+  public final class WatchNextProgram {
+    method public boolean equals(java.lang.Object);
     method public static android.support.media.tv.WatchNextProgram fromCursor(android.database.Cursor);
     method public long getLastEngagementTimeUtcMillis();
     method public int getWatchNextType();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
   }
 
-  public static final class WatchNextProgram.Builder extends android.support.media.tv.BasePreviewProgram.Builder {
+  public static final class WatchNextProgram.Builder {
     ctor public WatchNextProgram.Builder();
     ctor public WatchNextProgram.Builder(android.support.media.tv.WatchNextProgram);
     method public android.support.media.tv.WatchNextProgram build();
@@ -1822,6 +1747,8 @@
     ctor public PercentFrameLayout(android.content.Context);
     ctor public PercentFrameLayout(android.content.Context, android.util.AttributeSet);
     ctor public PercentFrameLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.percent.PercentFrameLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.percent.PercentFrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
   }
 
   public static deprecated class PercentFrameLayout.LayoutParams extends android.widget.FrameLayout.LayoutParams implements android.support.percent.PercentLayoutHelper.PercentLayoutParams {
@@ -1870,6 +1797,8 @@
     ctor public PercentRelativeLayout(android.content.Context);
     ctor public PercentRelativeLayout(android.content.Context, android.util.AttributeSet);
     ctor public PercentRelativeLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.percent.PercentRelativeLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.percent.PercentRelativeLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
   }
 
   public static deprecated class PercentRelativeLayout.LayoutParams extends android.widget.RelativeLayout.LayoutParams implements android.support.percent.PercentLayoutHelper.PercentLayoutParams {
@@ -1886,6 +1815,7 @@
 
   public class EmojiCompat {
     method public static android.support.text.emoji.EmojiCompat get();
+    method public java.lang.String getAssetSignature();
     method public int getLoadState();
     method public static boolean handleDeleteSurroundingText(android.view.inputmethod.InputConnection, android.text.Editable, int, int, boolean);
     method public static boolean handleOnKeyDown(android.text.Editable, int, android.view.KeyEvent);
@@ -1901,17 +1831,16 @@
     field public static final java.lang.String EDITOR_INFO_METAVERSION_KEY = "android.support.text.emoji.emojiCompat_metadataVersion";
     field public static final java.lang.String EDITOR_INFO_REPLACE_ALL_KEY = "android.support.text.emoji.emojiCompat_replaceAll";
     field public static final int LOAD_STATE_FAILED = 2; // 0x2
-    field public static final deprecated int LOAD_STATE_FAILURE = 2; // 0x2
     field public static final int LOAD_STATE_LOADING = 0; // 0x0
     field public static final int LOAD_STATE_SUCCEEDED = 1; // 0x1
-    field public static final deprecated int LOAD_STATE_SUCCESS = 1; // 0x1
     field public static final int REPLACE_STRATEGY_ALL = 1; // 0x1
     field public static final int REPLACE_STRATEGY_DEFAULT = 0; // 0x0
     field public static final int REPLACE_STRATEGY_NON_EXISTENT = 2; // 0x2
   }
 
   public static abstract class EmojiCompat.Config {
-    ctor protected EmojiCompat.Config(android.support.text.emoji.EmojiCompat.MetadataLoader);
+    ctor protected EmojiCompat.Config(android.support.text.emoji.EmojiCompat.MetadataRepoLoader);
+    method protected final android.support.text.emoji.EmojiCompat.MetadataRepoLoader getMetadataRepoLoader();
     method public android.support.text.emoji.EmojiCompat.Config registerInitCallback(android.support.text.emoji.EmojiCompat.InitCallback);
     method public android.support.text.emoji.EmojiCompat.Config setEmojiSpanIndicatorColor(int);
     method public android.support.text.emoji.EmojiCompat.Config setEmojiSpanIndicatorEnabled(boolean);
@@ -1925,14 +1854,14 @@
     method public void onInitialized();
   }
 
-  public static abstract class EmojiCompat.LoaderCallback {
-    ctor public EmojiCompat.LoaderCallback();
-    method public abstract void onFailed(java.lang.Throwable);
-    method public abstract void onLoaded(android.support.text.emoji.MetadataRepo);
+  public static abstract interface EmojiCompat.MetadataRepoLoader {
+    method public abstract void load(android.support.text.emoji.EmojiCompat.MetadataRepoLoaderCallback);
   }
 
-  public static abstract interface EmojiCompat.MetadataLoader {
-    method public abstract void load(android.support.text.emoji.EmojiCompat.LoaderCallback);
+  public static abstract class EmojiCompat.MetadataRepoLoaderCallback {
+    ctor public EmojiCompat.MetadataRepoLoaderCallback();
+    method public abstract void onFailed(java.lang.Throwable);
+    method public abstract void onLoaded(android.support.text.emoji.MetadataRepo);
   }
 
   public abstract class EmojiSpan extends android.text.style.ReplacementSpan {
@@ -1941,6 +1870,18 @@
 
   public class FontRequestEmojiCompatConfig extends android.support.text.emoji.EmojiCompat.Config {
     ctor public FontRequestEmojiCompatConfig(android.content.Context, android.support.v4.provider.FontRequest);
+    method public android.support.text.emoji.FontRequestEmojiCompatConfig setHandler(android.os.Handler);
+    method public android.support.text.emoji.FontRequestEmojiCompatConfig setRetryPolicy(android.support.text.emoji.FontRequestEmojiCompatConfig.RetryPolicy);
+  }
+
+  public static class FontRequestEmojiCompatConfig.ExponentialBackoffRetryPolicy extends android.support.text.emoji.FontRequestEmojiCompatConfig.RetryPolicy {
+    ctor public FontRequestEmojiCompatConfig.ExponentialBackoffRetryPolicy(long);
+    method public long getRetryDelay();
+  }
+
+  public static abstract class FontRequestEmojiCompatConfig.RetryPolicy {
+    ctor public FontRequestEmojiCompatConfig.RetryPolicy();
+    method public abstract long getRetryDelay();
   }
 
   public final class MetadataRepo {
@@ -2005,6 +1946,16 @@
     method public void setMaxEmojiCount(int);
   }
 
+  public class EmojiExtractTextLayout extends android.widget.LinearLayout {
+    ctor public EmojiExtractTextLayout(android.content.Context);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getEmojiReplaceStrategy();
+    method public void onUpdateExtractingViews(android.inputmethodservice.InputMethodService, android.view.inputmethod.EditorInfo);
+    method public void setEmojiReplaceStrategy(int);
+  }
+
   public class EmojiTextView extends android.widget.TextView {
     ctor public EmojiTextView(android.content.Context);
     ctor public EmojiTextView(android.content.Context, android.util.AttributeSet);
@@ -2244,14 +2195,27 @@
   public class TransitionSet extends android.support.transition.Transition {
     ctor public TransitionSet();
     ctor public TransitionSet(android.content.Context, android.util.AttributeSet);
+    method public android.support.transition.TransitionSet addListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.TransitionSet addTarget(android.view.View);
+    method public android.support.transition.TransitionSet addTarget(int);
+    method public android.support.transition.TransitionSet addTarget(java.lang.String);
+    method public android.support.transition.TransitionSet addTarget(java.lang.Class);
     method public android.support.transition.TransitionSet addTransition(android.support.transition.Transition);
     method public void captureEndValues(android.support.transition.TransitionValues);
     method public void captureStartValues(android.support.transition.TransitionValues);
     method public int getOrdering();
     method public android.support.transition.Transition getTransitionAt(int);
     method public int getTransitionCount();
+    method public android.support.transition.TransitionSet removeListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.TransitionSet removeTarget(int);
+    method public android.support.transition.TransitionSet removeTarget(android.view.View);
+    method public android.support.transition.TransitionSet removeTarget(java.lang.Class);
+    method public android.support.transition.TransitionSet removeTarget(java.lang.String);
     method public android.support.transition.TransitionSet removeTransition(android.support.transition.Transition);
+    method public android.support.transition.TransitionSet setDuration(long);
+    method public android.support.transition.TransitionSet setInterpolator(android.animation.TimeInterpolator);
     method public android.support.transition.TransitionSet setOrdering(int);
+    method public android.support.transition.TransitionSet setStartDelay(long);
     field public static final int ORDERING_SEQUENTIAL = 1; // 0x1
     field public static final int ORDERING_TOGETHER = 0; // 0x0
   }
@@ -2326,6 +2290,7 @@
     ctor public FragmentTabHost(android.content.Context, android.util.AttributeSet);
     method public void addTab(android.widget.TabHost.TabSpec, java.lang.Class<?>, android.os.Bundle);
     method public void onTabChanged(java.lang.String);
+    method public deprecated void setup();
     method public void setup(android.content.Context, android.app.FragmentManager);
     method public void setup(android.content.Context, android.app.FragmentManager, int);
   }
@@ -3085,6 +3050,10 @@
     method public long getSupportedActions();
     method public boolean hasValidMedia();
     method public boolean isMediaPlaying();
+    method protected void pausePlayback();
+    method protected void skipToNext();
+    method protected void skipToPrevious();
+    method protected void startPlayback(int);
   }
 
   public abstract class OnboardingFragment extends android.app.Fragment {
@@ -3249,6 +3218,7 @@
 
   public class PlaybackFragmentGlueHost extends android.support.v17.leanback.media.PlaybackGlueHost implements android.support.v17.leanback.widget.PlaybackSeekUi {
     ctor public PlaybackFragmentGlueHost(android.support.v17.leanback.app.PlaybackFragment);
+    method public void fadeOut();
     method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
   }
 
@@ -3345,6 +3315,7 @@
 
   public class PlaybackSupportFragmentGlueHost extends android.support.v17.leanback.media.PlaybackGlueHost implements android.support.v17.leanback.widget.PlaybackSeekUi {
     ctor public PlaybackSupportFragmentGlueHost(android.support.v17.leanback.app.PlaybackSupportFragment);
+    method public void fadeOut();
     method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
   }
 
@@ -4005,6 +3976,9 @@
     ctor public BaseCardView(android.content.Context);
     ctor public BaseCardView(android.content.Context, android.util.AttributeSet);
     ctor public BaseCardView(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.v17.leanback.widget.BaseCardView.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v17.leanback.widget.BaseCardView.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v17.leanback.widget.BaseCardView.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public int getCardType();
     method public deprecated int getExtraVisibility();
     method public int getInfoVisibility();
@@ -6018,6 +5992,8 @@
     method public android.support.v4.app.FragmentManager getSupportFragmentManager();
     method public android.support.v4.app.LoaderManager getSupportLoaderManager();
     method public void onAttachFragment(android.support.v4.app.Fragment);
+    method public void onMultiWindowModeChanged(boolean);
+    method public void onPictureInPictureModeChanged(boolean);
     method protected void onResumeFragments();
     method public java.lang.Object onRetainCustomNonConfigurationInstance();
     method public final java.lang.Object onRetainNonConfigurationInstance();
@@ -6184,6 +6160,7 @@
     ctor public FragmentTabHost(android.content.Context, android.util.AttributeSet);
     method public void addTab(android.widget.TabHost.TabSpec, java.lang.Class<?>, android.os.Bundle);
     method public void onTabChanged(java.lang.String);
+    method public deprecated void setup();
     method public void setup(android.content.Context, android.support.v4.app.FragmentManager);
     method public void setup(android.content.Context, android.support.v4.app.FragmentManager, int);
   }
@@ -6262,9 +6239,12 @@
   public abstract class JobIntentService extends android.app.Service {
     ctor public JobIntentService();
     method public static void enqueueWork(android.content.Context, java.lang.Class, int, android.content.Intent);
+    method public static void enqueueWork(android.content.Context, android.content.ComponentName, int, android.content.Intent);
+    method public boolean isStopped();
     method public android.os.IBinder onBind(android.content.Intent);
     method protected abstract void onHandleWork(android.content.Intent);
     method public boolean onStopCurrentWork();
+    method public void setInterruptIfStopped(boolean);
   }
 
   public class ListFragment extends android.support.v4.app.Fragment {
@@ -6316,7 +6296,6 @@
     method public static int getActionCount(android.app.Notification);
     method public static int getBadgeIconType(android.app.Notification);
     method public static java.lang.String getCategory(android.app.Notification);
-    method public static deprecated java.lang.String getChannel(android.app.Notification);
     method public static java.lang.String getChannelId(android.app.Notification);
     method public static android.os.Bundle getExtras(android.app.Notification);
     method public static java.lang.String getGroup(android.app.Notification);
@@ -6324,7 +6303,6 @@
     method public static boolean getLocalOnly(android.app.Notification);
     method public static java.lang.String getShortcutId(android.app.Notification);
     method public static java.lang.String getSortKey(android.app.Notification);
-    method public static deprecated long getTimeout(android.app.Notification);
     method public static long getTimeoutAfter(android.app.Notification);
     method public static boolean isGroupSummary(android.app.Notification);
     field public static final int BADGE_ICON_LARGE = 2; // 0x2
@@ -6481,7 +6459,6 @@
     method public android.support.v4.app.NotificationCompat.Builder setAutoCancel(boolean);
     method public android.support.v4.app.NotificationCompat.Builder setBadgeIconType(int);
     method public android.support.v4.app.NotificationCompat.Builder setCategory(java.lang.String);
-    method public deprecated android.support.v4.app.NotificationCompat.Builder setChannel(java.lang.String);
     method public android.support.v4.app.NotificationCompat.Builder setChannelId(java.lang.String);
     method public android.support.v4.app.NotificationCompat.Builder setColor(int);
     method public android.support.v4.app.NotificationCompat.Builder setColorized(boolean);
@@ -6521,7 +6498,6 @@
     method public android.support.v4.app.NotificationCompat.Builder setSubText(java.lang.CharSequence);
     method public android.support.v4.app.NotificationCompat.Builder setTicker(java.lang.CharSequence);
     method public android.support.v4.app.NotificationCompat.Builder setTicker(java.lang.CharSequence, android.widget.RemoteViews);
-    method public deprecated android.support.v4.app.NotificationCompat.Builder setTimeout(long);
     method public android.support.v4.app.NotificationCompat.Builder setTimeoutAfter(long);
     method public android.support.v4.app.NotificationCompat.Builder setUsesChronometer(boolean);
     method public android.support.v4.app.NotificationCompat.Builder setVibrate(long[]);
@@ -6561,6 +6537,10 @@
     method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation.Builder setReplyAction(android.app.PendingIntent, android.support.v4.app.RemoteInput);
   }
 
+  public static class NotificationCompat.DecoratedCustomViewStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.DecoratedCustomViewStyle();
+  }
+
   public static abstract interface NotificationCompat.Extender {
     method public abstract android.support.v4.app.NotificationCompat.Builder extend(android.support.v4.app.NotificationCompat.Builder);
   }
@@ -7163,6 +7143,7 @@
     method public void setCircular(boolean);
     method public void setColorFilter(android.graphics.ColorFilter);
     method public void setCornerRadius(float);
+    method public void setDither(boolean);
     method public void setGravity(int);
     method public void setMipMap(boolean);
     method public void setTargetDensity(android.graphics.Canvas);
@@ -7536,6 +7517,27 @@
 
 }
 
+package android.support.v4.media.app {
+
+  public class NotificationCompat {
+  }
+
+  public static class NotificationCompat.DecoratedMediaCustomViewStyle extends android.support.v4.media.app.NotificationCompat.MediaStyle {
+    ctor public NotificationCompat.DecoratedMediaCustomViewStyle();
+  }
+
+  public static class NotificationCompat.MediaStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.MediaStyle();
+    ctor public NotificationCompat.MediaStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public static android.support.v4.media.session.MediaSessionCompat.Token getMediaSession(android.app.Notification);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setCancelButtonIntent(android.app.PendingIntent);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setMediaSession(android.support.v4.media.session.MediaSessionCompat.Token);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setShowActionsInCompactView(int...);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setShowCancelButton(boolean);
+  }
+
+}
+
 package android.support.v4.media.session {
 
   public class MediaButtonReceiver extends android.content.BroadcastReceiver {
@@ -7625,6 +7627,7 @@
     method public abstract void sendCustomAction(java.lang.String, android.os.Bundle);
     method public abstract void setCaptioningEnabled(boolean);
     method public abstract void setRating(android.support.v4.media.RatingCompat);
+    method public abstract void setRating(android.support.v4.media.RatingCompat, android.os.Bundle);
     method public abstract void setRepeatMode(int);
     method public abstract void setShuffleMode(int);
     method public abstract deprecated void setShuffleModeEnabled(boolean);
@@ -7632,6 +7635,7 @@
     method public abstract void skipToPrevious();
     method public abstract void skipToQueueItem(long);
     method public abstract void stop();
+    field public static final java.lang.String EXTRA_LEGACY_STREAM_TYPE = "android.media.session.extra.LEGACY_STREAM_TYPE";
   }
 
   public class MediaSessionCompat {
@@ -7665,12 +7669,12 @@
     method public void setSessionActivity(android.app.PendingIntent);
     method public void setShuffleMode(int);
     method public deprecated void setShuffleModeEnabled(boolean);
-    field public static final java.lang.String ACTION_ARGUMENT_MEDIA_ATTRIBUTE = "android.support.v4.media.session.action.ARGUMENT_MEDIA_ATTRIBUTE";
-    field public static final java.lang.String ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE = "android.support.v4.media.session.action.ARGUMENT_MEDIA_ATTRIBUTE_VALUE";
     field public static final java.lang.String ACTION_FLAG_AS_INAPPROPRIATE = "android.support.v4.media.session.action.FLAG_AS_INAPPROPRIATE";
     field public static final java.lang.String ACTION_FOLLOW = "android.support.v4.media.session.action.FOLLOW";
     field public static final java.lang.String ACTION_SKIP_AD = "android.support.v4.media.session.action.SKIP_AD";
     field public static final java.lang.String ACTION_UNFOLLOW = "android.support.v4.media.session.action.UNFOLLOW";
+    field public static final java.lang.String ARGUMENT_MEDIA_ATTRIBUTE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE";
+    field public static final java.lang.String ARGUMENT_MEDIA_ATTRIBUTE_VALUE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE_VALUE";
     field public static final int FLAG_HANDLES_MEDIA_BUTTONS = 1; // 0x1
     field public static final int FLAG_HANDLES_QUEUE_COMMANDS = 4; // 0x4
     field public static final int FLAG_HANDLES_TRANSPORT_CONTROLS = 2; // 0x2
@@ -7702,6 +7706,7 @@
     method public void onSeekTo(long);
     method public void onSetCaptioningEnabled(boolean);
     method public void onSetRating(android.support.v4.media.RatingCompat);
+    method public void onSetRating(android.support.v4.media.RatingCompat, android.os.Bundle);
     method public void onSetRepeatMode(int);
     method public void onSetShuffleMode(int);
     method public deprecated void onSetShuffleModeEnabled(boolean);
@@ -8273,6 +8278,10 @@
     method public void trimToSize(int);
   }
 
+  public class ObjectsCompat {
+    method public static boolean equals(java.lang.Object, java.lang.Object);
+  }
+
   public class Pair<F, S> {
     ctor public Pair(F, S);
     method public static <A, B> android.support.v4.util.Pair<A, B> create(A, B);
@@ -8349,14 +8358,6 @@
 
 }
 
-package android.support.v4.utils {
-
-  public class ObjectUtils {
-    method public static boolean objectEquals(java.lang.Object, java.lang.Object);
-  }
-
-}
-
 package android.support.v4.view {
 
   public abstract class AbsSavedState implements android.os.Parcelable {
@@ -8701,6 +8702,7 @@
     ctor public PagerTabStrip(android.content.Context, android.util.AttributeSet);
     method public boolean getDrawFullUnderline();
     method public int getTabIndicatorColor();
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
     method public void setDrawFullUnderline(boolean);
     method public void setTabIndicatorColor(int);
     method public void setTabIndicatorColorResource(int);
@@ -8833,6 +8835,7 @@
     method public static deprecated float getY(android.view.View);
     method public static float getZ(android.view.View);
     method public static boolean hasAccessibilityDelegate(android.view.View);
+    method public static boolean hasExplicitFocusable(android.view.View);
     method public static boolean hasNestedScrollingParent(android.view.View);
     method public static boolean hasNestedScrollingParent(android.view.View, int);
     method public static boolean hasOnClickListeners(android.view.View);
@@ -9449,6 +9452,7 @@
 
   public class AccessibilityRecordCompat {
     ctor public deprecated AccessibilityRecordCompat(java.lang.Object);
+    method public deprecated boolean equals(java.lang.Object);
     method public deprecated int getAddedCount();
     method public deprecated java.lang.CharSequence getBeforeText();
     method public deprecated java.lang.CharSequence getClassName();
@@ -9469,6 +9473,7 @@
     method public deprecated java.util.List<java.lang.CharSequence> getText();
     method public deprecated int getToIndex();
     method public deprecated int getWindowId();
+    method public deprecated int hashCode();
     method public deprecated boolean isChecked();
     method public deprecated boolean isEnabled();
     method public deprecated boolean isFullScreen();
@@ -9585,6 +9590,42 @@
     field public static final float RELATIVE_UNSPECIFIED = 0.0f;
   }
 
+  public class CircularProgressDrawable extends android.graphics.drawable.Drawable {
+    ctor public CircularProgressDrawable(android.content.Context);
+    method public void draw(android.graphics.Canvas);
+    method public boolean getArrowEnabled();
+    method public float getArrowHeight();
+    method public float getArrowScale();
+    method public float getArrowWidth();
+    method public int getBackgroundColor();
+    method public float getCenterRadius();
+    method public int[] getColorSchemeColors();
+    method public float getEndTrim();
+    method public int getOpacity();
+    method public float getProgressRotation();
+    method public float getStartTrim();
+    method public android.graphics.Paint.Cap getStrokeCap();
+    method public float getStrokeWidth();
+    method public boolean isRunning();
+    method public void setAlpha(int);
+    method public void setArrowDimensions(float, float);
+    method public void setArrowEnabled(boolean);
+    method public void setArrowScale(float);
+    method public void setBackgroundColor(int);
+    method public void setCenterRadius(float);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setColorSchemeColors(int...);
+    method public void setProgressRotation(float);
+    method public void setStartEndTrim(float, float);
+    method public void setStrokeCap(android.graphics.Paint.Cap);
+    method public void setStrokeWidth(float);
+    method public void setStyle(int);
+    method public void start();
+    method public void stop();
+    field public static final int DEFAULT = 1; // 0x1
+    field public static final int LARGE = 0; // 0x0
+  }
+
   public final class CompoundButtonCompat {
     method public static android.graphics.drawable.Drawable getButtonDrawable(android.widget.CompoundButton);
     method public static android.content.res.ColorStateList getButtonTintList(android.widget.CompoundButton);
@@ -10318,6 +10359,7 @@
     method public deprecated void setSupportProgressBarIndeterminateVisibility(boolean);
     method public deprecated void setSupportProgressBarVisibility(boolean);
     method public android.support.v7.view.ActionMode startSupportActionMode(android.support.v7.view.ActionMode.Callback);
+    method public void supportInvalidateOptionsMenu();
     method public void supportNavigateUpTo(android.content.Intent);
     method public boolean supportRequestWindowFeature(int);
     method public boolean supportShouldUpRecreateTask(android.content.Intent);
@@ -10463,30 +10505,30 @@
     method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
   }
 
-  public class NotificationCompat extends android.support.v4.app.NotificationCompat {
-    ctor public NotificationCompat();
-    method public static android.support.v4.media.session.MediaSessionCompat.Token getMediaSession(android.app.Notification);
+  public deprecated class NotificationCompat extends android.support.v4.app.NotificationCompat {
+    ctor public deprecated NotificationCompat();
+    method public static deprecated android.support.v4.media.session.MediaSessionCompat.Token getMediaSession(android.app.Notification);
   }
 
-  public static class NotificationCompat.Builder extends android.support.v4.app.NotificationCompat.Builder {
-    ctor public NotificationCompat.Builder(android.content.Context);
+  public static deprecated class NotificationCompat.Builder extends android.support.v4.app.NotificationCompat.Builder {
+    ctor public deprecated NotificationCompat.Builder(android.content.Context);
   }
 
-  public static class NotificationCompat.DecoratedCustomViewStyle extends android.support.v4.app.NotificationCompat.Style {
-    ctor public NotificationCompat.DecoratedCustomViewStyle();
+  public static deprecated class NotificationCompat.DecoratedCustomViewStyle extends android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle {
+    ctor public deprecated NotificationCompat.DecoratedCustomViewStyle();
   }
 
-  public static class NotificationCompat.DecoratedMediaCustomViewStyle extends android.support.v7.app.NotificationCompat.MediaStyle {
-    ctor public NotificationCompat.DecoratedMediaCustomViewStyle();
+  public static deprecated class NotificationCompat.DecoratedMediaCustomViewStyle extends android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle {
+    ctor public deprecated NotificationCompat.DecoratedMediaCustomViewStyle();
   }
 
-  public static class NotificationCompat.MediaStyle extends android.support.v4.app.NotificationCompat.Style {
-    ctor public NotificationCompat.MediaStyle();
-    ctor public NotificationCompat.MediaStyle(android.support.v4.app.NotificationCompat.Builder);
-    method public android.support.v7.app.NotificationCompat.MediaStyle setCancelButtonIntent(android.app.PendingIntent);
-    method public android.support.v7.app.NotificationCompat.MediaStyle setMediaSession(android.support.v4.media.session.MediaSessionCompat.Token);
-    method public android.support.v7.app.NotificationCompat.MediaStyle setShowActionsInCompactView(int...);
-    method public android.support.v7.app.NotificationCompat.MediaStyle setShowCancelButton(boolean);
+  public static deprecated class NotificationCompat.MediaStyle extends android.support.v4.media.app.NotificationCompat.MediaStyle {
+    ctor public deprecated NotificationCompat.MediaStyle();
+    ctor public deprecated NotificationCompat.MediaStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setCancelButtonIntent(android.app.PendingIntent);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setMediaSession(android.support.v4.media.session.MediaSessionCompat.Token);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setShowActionsInCompactView(int...);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setShowCancelButton(boolean);
   }
 
 }
@@ -11595,6 +11637,9 @@
     ctor public ActionMenuView(android.content.Context);
     ctor public ActionMenuView(android.content.Context, android.util.AttributeSet);
     method public void dismissPopupMenus();
+    method protected android.support.v7.widget.ActionMenuView.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.ActionMenuView.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.ActionMenuView.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public android.view.Menu getMenu();
     method public android.graphics.drawable.Drawable getOverflowIcon();
     method public int getPopupTheme();
@@ -11628,13 +11673,17 @@
     ctor public AppCompatAutoCompleteTextView(android.content.Context);
     ctor public AppCompatAutoCompleteTextView(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatAutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class AppCompatButton extends android.widget.Button implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatButton(android.content.Context);
     ctor public AppCompatButton(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatButton(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
     method public void setSupportAllCaps(boolean);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class AppCompatCheckBox extends android.widget.CheckBox implements android.support.v4.widget.TintableCompoundButton {
@@ -11647,30 +11696,37 @@
     ctor public AppCompatCheckedTextView(android.content.Context);
     ctor public AppCompatCheckedTextView(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatCheckedTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class AppCompatEditText extends android.widget.EditText implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatEditText(android.content.Context);
     ctor public AppCompatEditText(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatEditText(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class AppCompatImageButton extends android.widget.ImageButton implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatImageButton(android.content.Context);
     ctor public AppCompatImageButton(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatImageButton(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
   }
 
   public class AppCompatImageView extends android.widget.ImageView implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatImageView(android.content.Context);
     ctor public AppCompatImageView(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatImageView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
   }
 
   public class AppCompatMultiAutoCompleteTextView extends android.widget.MultiAutoCompleteTextView implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatMultiAutoCompleteTextView(android.content.Context);
     ctor public AppCompatMultiAutoCompleteTextView(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatMultiAutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class AppCompatRadioButton extends android.widget.RadioButton implements android.support.v4.widget.TintableCompoundButton {
@@ -11698,12 +11754,15 @@
     ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int);
     ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int, int);
     ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int, int, android.content.res.Resources.Theme);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
   }
 
   public class AppCompatTextView extends android.widget.TextView implements android.support.v4.view.TintableBackgroundView {
     ctor public AppCompatTextView(android.content.Context);
     ctor public AppCompatTextView(android.content.Context, android.util.AttributeSet);
     ctor public AppCompatTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
   }
 
   public class CardView extends android.widget.FrameLayout {
@@ -11754,6 +11813,9 @@
     ctor public GridLayout(android.content.Context, android.util.AttributeSet, int);
     ctor public GridLayout(android.content.Context, android.util.AttributeSet);
     ctor public GridLayout(android.content.Context);
+    method protected android.support.v7.widget.GridLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.GridLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.GridLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public int getAlignmentMode();
     method public int getColumnCount();
     method public int getOrientation();
@@ -11855,6 +11917,9 @@
     ctor public LinearLayoutCompat(android.content.Context);
     ctor public LinearLayoutCompat(android.content.Context, android.util.AttributeSet);
     ctor public LinearLayoutCompat(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.v7.widget.LinearLayoutCompat.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.LinearLayoutCompat.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.LinearLayoutCompat.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public int getBaselineAlignedChildIndex();
     method public android.graphics.drawable.Drawable getDividerDrawable();
     method public int getDividerPadding();
@@ -12057,6 +12122,7 @@
   public class PagerSnapHelper extends android.support.v7.widget.SnapHelper {
     ctor public PagerSnapHelper();
     method public int[] calculateDistanceToFinalSnap(android.support.v7.widget.RecyclerView.LayoutManager, android.view.View);
+    method protected android.support.v7.widget.LinearSmoothScroller createSnapScroller(android.support.v7.widget.RecyclerView.LayoutManager);
     method public android.view.View findSnapView(android.support.v7.widget.RecyclerView.LayoutManager);
     method public int findTargetSnapPosition(android.support.v7.widget.RecyclerView.LayoutManager, int, int);
   }
@@ -12701,7 +12767,8 @@
     method public void attachToRecyclerView(android.support.v7.widget.RecyclerView) throws java.lang.IllegalStateException;
     method public abstract int[] calculateDistanceToFinalSnap(android.support.v7.widget.RecyclerView.LayoutManager, android.view.View);
     method public int[] calculateScrollDistance(int, int);
-    method protected android.support.v7.widget.LinearSmoothScroller createSnapScroller(android.support.v7.widget.RecyclerView.LayoutManager);
+    method protected android.support.v7.widget.RecyclerView.SmoothScroller createScroller(android.support.v7.widget.RecyclerView.LayoutManager);
+    method protected deprecated android.support.v7.widget.LinearSmoothScroller createSnapScroller(android.support.v7.widget.RecyclerView.LayoutManager);
     method public abstract android.view.View findSnapView(android.support.v7.widget.RecyclerView.LayoutManager);
     method public abstract int findTargetSnapPosition(android.support.v7.widget.RecyclerView.LayoutManager, int, int);
     method public boolean onFling(int, int);
@@ -12801,6 +12868,9 @@
     ctor public Toolbar(android.content.Context, android.util.AttributeSet, int);
     method public void collapseActionView();
     method public void dismissPopupMenus();
+    method protected android.support.v7.widget.Toolbar.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.Toolbar.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.Toolbar.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
     method public int getContentInsetEnd();
     method public int getContentInsetEndWithActions();
     method public int getContentInsetLeft();
@@ -12982,6 +13052,7 @@
     ctor public BoxInsetLayout(android.content.Context);
     ctor public BoxInsetLayout(android.content.Context, android.util.AttributeSet);
     ctor public BoxInsetLayout(android.content.Context, android.util.AttributeSet, int);
+    method public android.support.wear.widget.BoxInsetLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
     method protected void onLayout(boolean, int, int, int, int);
   }
 
@@ -13003,12 +13074,56 @@
     field public int boxedEdges;
   }
 
+  public class CircularProgressLayout extends android.widget.FrameLayout {
+    ctor public CircularProgressLayout(android.content.Context);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getBackgroundColor();
+    method public int[] getColorSchemeColors();
+    method public android.support.wear.widget.CircularProgressLayout.OnTimerFinishedListener getOnTimerFinishedListener();
+    method public android.support.v4.widget.CircularProgressDrawable getProgressDrawable();
+    method public float getStartingRotation();
+    method public float getStrokeWidth();
+    method public long getTotalTime();
+    method public boolean isIndeterminate();
+    method public boolean isTimerRunning();
+    method public void setColorSchemeColors(int...);
+    method public void setIndeterminate(boolean);
+    method public void setOnTimerFinishedListener(android.support.wear.widget.CircularProgressLayout.OnTimerFinishedListener);
+    method public void setStartingRotation(float);
+    method public void setStrokeWidth(float);
+    method public void setTotalTime(long);
+    method public void startTimer();
+    method public void stopTimer();
+  }
+
+  public static abstract interface CircularProgressLayout.OnTimerFinishedListener {
+    method public abstract void onTimerFinished(android.support.wear.widget.CircularProgressLayout);
+  }
+
   public class CurvingLayoutCallback extends android.support.wear.widget.WearableLinearLayoutManager.LayoutCallback {
     ctor public CurvingLayoutCallback(android.content.Context);
     method public void adjustAnchorOffsetXY(android.view.View, float[]);
     method public void onLayoutFinished(android.view.View, android.support.v7.widget.RecyclerView);
   }
 
+  public class RoundedDrawable extends android.graphics.drawable.Drawable {
+    ctor public RoundedDrawable();
+    method public void draw(android.graphics.Canvas);
+    method public int getBackgroundColor();
+    method public android.graphics.drawable.Drawable getDrawable();
+    method public int getOpacity();
+    method public int getRadius();
+    method public boolean isClipEnabled();
+    method public void setAlpha(int);
+    method public void setBackgroundColor(int);
+    method public void setClipEnabled(boolean);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setDrawable(android.graphics.drawable.Drawable);
+    method public void setRadius(int);
+  }
+
   public class SwipeDismissFrameLayout extends android.widget.FrameLayout {
     ctor public SwipeDismissFrameLayout(android.content.Context);
     ctor public SwipeDismissFrameLayout(android.content.Context, android.util.AttributeSet);
diff --git a/api/26.0.0.txt b/api/26.0.0.txt
new file mode 100644
index 0000000..fe0c575
--- /dev/null
+++ b/api/26.0.0.txt
@@ -0,0 +1,13266 @@
+package android.support.animation {
+
+  public abstract class DynamicAnimation<T extends android.support.animation.DynamicAnimation<T>> {
+    method public T addEndListener(android.support.animation.DynamicAnimation.OnAnimationEndListener);
+    method public T addUpdateListener(android.support.animation.DynamicAnimation.OnAnimationUpdateListener);
+    method public void cancel();
+    method public float getMinimumVisibleChange();
+    method public boolean isRunning();
+    method public void removeEndListener(android.support.animation.DynamicAnimation.OnAnimationEndListener);
+    method public void removeUpdateListener(android.support.animation.DynamicAnimation.OnAnimationUpdateListener);
+    method public T setMaxValue(float);
+    method public T setMinValue(float);
+    method public T setMinimumVisibleChange(float);
+    method public T setStartValue(float);
+    method public T setStartVelocity(float);
+    method public void start();
+    field public static final android.support.animation.DynamicAnimation.ViewProperty ALPHA;
+    field public static final float MIN_VISIBLE_CHANGE_ALPHA = 0.00390625f;
+    field public static final float MIN_VISIBLE_CHANGE_PIXELS = 1.0f;
+    field public static final float MIN_VISIBLE_CHANGE_ROTATION_DEGREES = 0.1f;
+    field public static final float MIN_VISIBLE_CHANGE_SCALE = 0.002f;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty ROTATION;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty ROTATION_X;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty ROTATION_Y;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty SCALE_X;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty SCALE_Y;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty SCROLL_X;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty SCROLL_Y;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty TRANSLATION_X;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty TRANSLATION_Y;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty TRANSLATION_Z;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty X;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty Y;
+    field public static final android.support.animation.DynamicAnimation.ViewProperty Z;
+  }
+
+  public static abstract interface DynamicAnimation.OnAnimationEndListener {
+    method public abstract void onAnimationEnd(android.support.animation.DynamicAnimation, boolean, float, float);
+  }
+
+  public static abstract interface DynamicAnimation.OnAnimationUpdateListener {
+    method public abstract void onAnimationUpdate(android.support.animation.DynamicAnimation, float, float);
+  }
+
+  public static abstract class DynamicAnimation.ViewProperty extends android.support.animation.FloatPropertyCompat {
+  }
+
+  public final class FlingAnimation extends android.support.animation.DynamicAnimation {
+    ctor public FlingAnimation(android.support.animation.FloatValueHolder);
+    ctor public FlingAnimation(K, android.support.animation.FloatPropertyCompat<K>);
+    method public float getFriction();
+    method public android.support.animation.FlingAnimation setFriction(float);
+    method public android.support.animation.FlingAnimation setMaxValue(float);
+    method public android.support.animation.FlingAnimation setMinValue(float);
+    method public android.support.animation.FlingAnimation setStartVelocity(float);
+  }
+
+  public abstract class FloatPropertyCompat<T> {
+    ctor public FloatPropertyCompat(java.lang.String);
+    method public static <T> android.support.animation.FloatPropertyCompat<T> createFloatPropertyCompat(android.util.FloatProperty<T>);
+    method public abstract float getValue(T);
+    method public abstract void setValue(T, float);
+  }
+
+  public final class FloatValueHolder {
+    ctor public FloatValueHolder();
+    ctor public FloatValueHolder(float);
+    method public float getValue();
+    method public void setValue(float);
+  }
+
+  public final class SpringAnimation extends android.support.animation.DynamicAnimation {
+    ctor public SpringAnimation(android.support.animation.FloatValueHolder);
+    ctor public SpringAnimation(K, android.support.animation.FloatPropertyCompat<K>);
+    ctor public SpringAnimation(K, android.support.animation.FloatPropertyCompat<K>, float);
+    method public void animateToFinalPosition(float);
+    method public boolean canSkipToEnd();
+    method public android.support.animation.SpringForce getSpring();
+    method public android.support.animation.SpringAnimation setSpring(android.support.animation.SpringForce);
+    method public void skipToEnd();
+  }
+
+  public final class SpringForce {
+    ctor public SpringForce();
+    ctor public SpringForce(float);
+    method public float getDampingRatio();
+    method public float getFinalPosition();
+    method public float getStiffness();
+    method public android.support.animation.SpringForce setDampingRatio(float);
+    method public android.support.animation.SpringForce setFinalPosition(float);
+    method public android.support.animation.SpringForce setStiffness(float);
+    field public static final float DAMPING_RATIO_HIGH_BOUNCY = 0.2f;
+    field public static final float DAMPING_RATIO_LOW_BOUNCY = 0.75f;
+    field public static final float DAMPING_RATIO_MEDIUM_BOUNCY = 0.5f;
+    field public static final float DAMPING_RATIO_NO_BOUNCY = 1.0f;
+    field public static final float STIFFNESS_HIGH = 10000.0f;
+    field public static final float STIFFNESS_LOW = 200.0f;
+    field public static final float STIFFNESS_MEDIUM = 1500.0f;
+    field public static final float STIFFNESS_VERY_LOW = 50.0f;
+  }
+
+}
+
+package android.support.app.recommendation {
+
+  public final class ContentRecommendation {
+    method public java.lang.String getBackgroundImageUri();
+    method public int getBadgeImageResourceId();
+    method public int getColor();
+    method public android.graphics.Bitmap getContentImage();
+    method public android.support.app.recommendation.ContentRecommendation.IntentData getContentIntent();
+    method public java.lang.String[] getContentTypes();
+    method public android.support.app.recommendation.ContentRecommendation.IntentData getDismissIntent();
+    method public java.lang.String[] getGenres();
+    method public java.lang.String getGroup();
+    method public java.lang.String getIdTag();
+    method public java.lang.String getMaturityRating();
+    method public android.app.Notification getNotificationObject(android.content.Context);
+    method public java.lang.String getPricingType();
+    method public java.lang.String getPricingValue();
+    method public java.lang.String getPrimaryContentType();
+    method public int getProgressMax();
+    method public int getProgressValue();
+    method public long getRunningTime();
+    method public java.lang.String getSortKey();
+    method public java.lang.String getSourceName();
+    method public int getStatus();
+    method public java.lang.String getText();
+    method public java.lang.String getTitle();
+    method public boolean hasProgressInfo();
+    method public boolean isAutoDismiss();
+    method public void setAutoDismiss(boolean);
+    method public void setGroup(java.lang.String);
+    method public void setProgress(int, int);
+    method public void setSortKey(java.lang.String);
+    method public void setStatus(int);
+    field public static final java.lang.String CONTENT_MATURITY_ALL = "android.contentMaturity.all";
+    field public static final java.lang.String CONTENT_MATURITY_HIGH = "android.contentMaturity.high";
+    field public static final java.lang.String CONTENT_MATURITY_LOW = "android.contentMaturity.low";
+    field public static final java.lang.String CONTENT_MATURITY_MEDIUM = "android.contentMaturity.medium";
+    field public static final java.lang.String CONTENT_PRICING_FREE = "android.contentPrice.free";
+    field public static final java.lang.String CONTENT_PRICING_PREORDER = "android.contentPrice.preorder";
+    field public static final java.lang.String CONTENT_PRICING_PURCHASE = "android.contentPrice.purchase";
+    field public static final java.lang.String CONTENT_PRICING_RENTAL = "android.contentPrice.rental";
+    field public static final java.lang.String CONTENT_PRICING_SUBSCRIPTION = "android.contentPrice.subscription";
+    field public static final int CONTENT_STATUS_AVAILABLE = 2; // 0x2
+    field public static final int CONTENT_STATUS_PENDING = 1; // 0x1
+    field public static final int CONTENT_STATUS_READY = 0; // 0x0
+    field public static final int CONTENT_STATUS_UNAVAILABLE = 3; // 0x3
+    field public static final java.lang.String CONTENT_TYPE_APP = "android.contentType.app";
+    field public static final java.lang.String CONTENT_TYPE_BOOK = "android.contentType.book";
+    field public static final java.lang.String CONTENT_TYPE_COMIC = "android.contentType.comic";
+    field public static final java.lang.String CONTENT_TYPE_GAME = "android.contentType.game";
+    field public static final java.lang.String CONTENT_TYPE_MAGAZINE = "android.contentType.magazine";
+    field public static final java.lang.String CONTENT_TYPE_MOVIE = "android.contentType.movie";
+    field public static final java.lang.String CONTENT_TYPE_MUSIC = "android.contentType.music";
+    field public static final java.lang.String CONTENT_TYPE_NEWS = "android.contentType.news";
+    field public static final java.lang.String CONTENT_TYPE_PODCAST = "android.contentType.podcast";
+    field public static final java.lang.String CONTENT_TYPE_RADIO = "android.contentType.radio";
+    field public static final java.lang.String CONTENT_TYPE_SERIAL = "android.contentType.serial";
+    field public static final java.lang.String CONTENT_TYPE_SPORTS = "android.contentType.sports";
+    field public static final java.lang.String CONTENT_TYPE_TRAILER = "android.contentType.trailer";
+    field public static final java.lang.String CONTENT_TYPE_VIDEO = "android.contentType.video";
+    field public static final java.lang.String CONTENT_TYPE_WEBSITE = "android.contentType.website";
+    field public static final int INTENT_TYPE_ACTIVITY = 1; // 0x1
+    field public static final int INTENT_TYPE_BROADCAST = 2; // 0x2
+    field public static final int INTENT_TYPE_SERVICE = 3; // 0x3
+  }
+
+  public static final class ContentRecommendation.Builder {
+    ctor public ContentRecommendation.Builder();
+    method public android.support.app.recommendation.ContentRecommendation build();
+    method public android.support.app.recommendation.ContentRecommendation.Builder setAutoDismiss(boolean);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setBackgroundImageUri(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setBadgeIcon(int);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setColor(int);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setContentImage(android.graphics.Bitmap);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setContentIntentData(int, android.content.Intent, int, android.os.Bundle);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setContentTypes(java.lang.String[]);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setDismissIntentData(int, android.content.Intent, int, android.os.Bundle);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setGenres(java.lang.String[]);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setGroup(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setIdTag(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setMaturityRating(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setPricingInformation(java.lang.String, java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setProgress(int, int);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setRunningTime(long);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setSortKey(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setSourceName(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setStatus(int);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setText(java.lang.String);
+    method public android.support.app.recommendation.ContentRecommendation.Builder setTitle(java.lang.String);
+  }
+
+  public static abstract class ContentRecommendation.ContentMaturity implements java.lang.annotation.Annotation {
+  }
+
+  public static abstract class ContentRecommendation.ContentPricing implements java.lang.annotation.Annotation {
+  }
+
+  public static abstract class ContentRecommendation.ContentStatus implements java.lang.annotation.Annotation {
+  }
+
+  public static abstract class ContentRecommendation.ContentType implements java.lang.annotation.Annotation {
+  }
+
+  public static class ContentRecommendation.IntentData {
+    ctor public ContentRecommendation.IntentData();
+  }
+
+  public static abstract class ContentRecommendation.IntentType implements java.lang.annotation.Annotation {
+  }
+
+  public final class RecommendationExtender implements android.app.Notification.Extender {
+    ctor public RecommendationExtender();
+    ctor public RecommendationExtender(android.app.Notification);
+    method public android.app.Notification.Builder extend(android.app.Notification.Builder);
+    method public java.lang.String[] getContentTypes();
+    method public java.lang.String[] getGenres();
+    method public java.lang.String getMaturityRating();
+    method public java.lang.String getPricingType();
+    method public java.lang.String getPricingValue();
+    method public java.lang.String getPrimaryContentType();
+    method public long getRunningTime();
+    method public int getStatus();
+    method public android.support.app.recommendation.RecommendationExtender setContentTypes(java.lang.String[]);
+    method public android.support.app.recommendation.RecommendationExtender setGenres(java.lang.String[]);
+    method public android.support.app.recommendation.RecommendationExtender setMaturityRating(java.lang.String);
+    method public android.support.app.recommendation.RecommendationExtender setPricingInformation(java.lang.String, java.lang.String);
+    method public android.support.app.recommendation.RecommendationExtender setRunningTime(long);
+    method public android.support.app.recommendation.RecommendationExtender setStatus(int);
+  }
+
+}
+
+package android.support.customtabs {
+
+  public class CustomTabsCallback {
+    ctor public CustomTabsCallback();
+    method public void extraCallback(java.lang.String, android.os.Bundle);
+    method public void onMessageChannelReady(android.os.Bundle);
+    method public void onNavigationEvent(int, android.os.Bundle);
+    method public void onPostMessage(java.lang.String, android.os.Bundle);
+    field public static final int NAVIGATION_ABORTED = 4; // 0x4
+    field public static final int NAVIGATION_FAILED = 3; // 0x3
+    field public static final int NAVIGATION_FINISHED = 2; // 0x2
+    field public static final int NAVIGATION_STARTED = 1; // 0x1
+    field public static final int TAB_HIDDEN = 6; // 0x6
+    field public static final int TAB_SHOWN = 5; // 0x5
+  }
+
+  public class CustomTabsClient {
+    method public static boolean bindCustomTabsService(android.content.Context, java.lang.String, android.support.customtabs.CustomTabsServiceConnection);
+    method public static boolean connectAndInitialize(android.content.Context, java.lang.String);
+    method public android.os.Bundle extraCommand(java.lang.String, android.os.Bundle);
+    method public static java.lang.String getPackageName(android.content.Context, java.util.List<java.lang.String>);
+    method public static java.lang.String getPackageName(android.content.Context, java.util.List<java.lang.String>, boolean);
+    method public android.support.customtabs.CustomTabsSession newSession(android.support.customtabs.CustomTabsCallback);
+    method public boolean warmup(long);
+  }
+
+  public final class CustomTabsIntent {
+    method public static int getMaxToolbarItems();
+    method public void launchUrl(android.content.Context, android.net.Uri);
+    method public static android.content.Intent setAlwaysUseBrowserUI(android.content.Intent);
+    method public static boolean shouldAlwaysUseBrowserUI(android.content.Intent);
+    field public static final java.lang.String EXTRA_ACTION_BUTTON_BUNDLE = "android.support.customtabs.extra.ACTION_BUTTON_BUNDLE";
+    field public static final java.lang.String EXTRA_CLOSE_BUTTON_ICON = "android.support.customtabs.extra.CLOSE_BUTTON_ICON";
+    field public static final java.lang.String EXTRA_DEFAULT_SHARE_MENU_ITEM = "android.support.customtabs.extra.SHARE_MENU_ITEM";
+    field public static final java.lang.String EXTRA_ENABLE_INSTANT_APPS = "android.support.customtabs.extra.EXTRA_ENABLE_INSTANT_APPS";
+    field public static final java.lang.String EXTRA_ENABLE_URLBAR_HIDING = "android.support.customtabs.extra.ENABLE_URLBAR_HIDING";
+    field public static final java.lang.String EXTRA_EXIT_ANIMATION_BUNDLE = "android.support.customtabs.extra.EXIT_ANIMATION_BUNDLE";
+    field public static final java.lang.String EXTRA_MENU_ITEMS = "android.support.customtabs.extra.MENU_ITEMS";
+    field public static final java.lang.String EXTRA_REMOTEVIEWS = "android.support.customtabs.extra.EXTRA_REMOTEVIEWS";
+    field public static final java.lang.String EXTRA_REMOTEVIEWS_CLICKED_ID = "android.support.customtabs.extra.EXTRA_REMOTEVIEWS_CLICKED_ID";
+    field public static final java.lang.String EXTRA_REMOTEVIEWS_PENDINGINTENT = "android.support.customtabs.extra.EXTRA_REMOTEVIEWS_PENDINGINTENT";
+    field public static final java.lang.String EXTRA_REMOTEVIEWS_VIEW_IDS = "android.support.customtabs.extra.EXTRA_REMOTEVIEWS_VIEW_IDS";
+    field public static final java.lang.String EXTRA_SECONDARY_TOOLBAR_COLOR = "android.support.customtabs.extra.SECONDARY_TOOLBAR_COLOR";
+    field public static final java.lang.String EXTRA_SESSION = "android.support.customtabs.extra.SESSION";
+    field public static final java.lang.String EXTRA_TINT_ACTION_BUTTON = "android.support.customtabs.extra.TINT_ACTION_BUTTON";
+    field public static final java.lang.String EXTRA_TITLE_VISIBILITY_STATE = "android.support.customtabs.extra.TITLE_VISIBILITY";
+    field public static final java.lang.String EXTRA_TOOLBAR_COLOR = "android.support.customtabs.extra.TOOLBAR_COLOR";
+    field public static final java.lang.String EXTRA_TOOLBAR_ITEMS = "android.support.customtabs.extra.TOOLBAR_ITEMS";
+    field public static final java.lang.String KEY_DESCRIPTION = "android.support.customtabs.customaction.DESCRIPTION";
+    field public static final java.lang.String KEY_ICON = "android.support.customtabs.customaction.ICON";
+    field public static final java.lang.String KEY_ID = "android.support.customtabs.customaction.ID";
+    field public static final java.lang.String KEY_MENU_ITEM_TITLE = "android.support.customtabs.customaction.MENU_ITEM_TITLE";
+    field public static final java.lang.String KEY_PENDING_INTENT = "android.support.customtabs.customaction.PENDING_INTENT";
+    field public static final int NO_TITLE = 0; // 0x0
+    field public static final int SHOW_PAGE_TITLE = 1; // 0x1
+    field public static final int TOOLBAR_ACTION_BUTTON_ID = 0; // 0x0
+    field public final android.content.Intent intent;
+    field public final android.os.Bundle startAnimationBundle;
+  }
+
+  public static final class CustomTabsIntent.Builder {
+    ctor public CustomTabsIntent.Builder();
+    ctor public CustomTabsIntent.Builder(android.support.customtabs.CustomTabsSession);
+    method public android.support.customtabs.CustomTabsIntent.Builder addDefaultShareMenuItem();
+    method public android.support.customtabs.CustomTabsIntent.Builder addMenuItem(java.lang.String, android.app.PendingIntent);
+    method public deprecated android.support.customtabs.CustomTabsIntent.Builder addToolbarItem(int, android.graphics.Bitmap, java.lang.String, android.app.PendingIntent) throws java.lang.IllegalStateException;
+    method public android.support.customtabs.CustomTabsIntent build();
+    method public android.support.customtabs.CustomTabsIntent.Builder enableUrlBarHiding();
+    method public android.support.customtabs.CustomTabsIntent.Builder setActionButton(android.graphics.Bitmap, java.lang.String, android.app.PendingIntent, boolean);
+    method public android.support.customtabs.CustomTabsIntent.Builder setActionButton(android.graphics.Bitmap, java.lang.String, android.app.PendingIntent);
+    method public android.support.customtabs.CustomTabsIntent.Builder setCloseButtonIcon(android.graphics.Bitmap);
+    method public android.support.customtabs.CustomTabsIntent.Builder setExitAnimations(android.content.Context, int, int);
+    method public android.support.customtabs.CustomTabsIntent.Builder setInstantAppsEnabled(boolean);
+    method public android.support.customtabs.CustomTabsIntent.Builder setSecondaryToolbarColor(int);
+    method public android.support.customtabs.CustomTabsIntent.Builder setSecondaryToolbarViews(android.widget.RemoteViews, int[], android.app.PendingIntent);
+    method public android.support.customtabs.CustomTabsIntent.Builder setShowTitle(boolean);
+    method public android.support.customtabs.CustomTabsIntent.Builder setStartAnimations(android.content.Context, int, int);
+    method public android.support.customtabs.CustomTabsIntent.Builder setToolbarColor(int);
+  }
+
+  public abstract class CustomTabsService extends android.app.Service {
+    ctor public CustomTabsService();
+    method protected boolean cleanUpSession(android.support.customtabs.CustomTabsSessionToken);
+    method protected abstract android.os.Bundle extraCommand(java.lang.String, android.os.Bundle);
+    method protected abstract boolean mayLaunchUrl(android.support.customtabs.CustomTabsSessionToken, android.net.Uri, android.os.Bundle, java.util.List<android.os.Bundle>);
+    method protected abstract boolean newSession(android.support.customtabs.CustomTabsSessionToken);
+    method public android.os.IBinder onBind(android.content.Intent);
+    method protected abstract int postMessage(android.support.customtabs.CustomTabsSessionToken, java.lang.String, android.os.Bundle);
+    method protected abstract boolean requestPostMessageChannel(android.support.customtabs.CustomTabsSessionToken, android.net.Uri);
+    method protected abstract boolean updateVisuals(android.support.customtabs.CustomTabsSessionToken, android.os.Bundle);
+    method protected abstract boolean warmup(long);
+    field public static final java.lang.String ACTION_CUSTOM_TABS_CONNECTION = "android.support.customtabs.action.CustomTabsService";
+    field public static final java.lang.String KEY_URL = "android.support.customtabs.otherurls.URL";
+    field public static final int RESULT_FAILURE_DISALLOWED = -1; // 0xffffffff
+    field public static final int RESULT_FAILURE_MESSAGING_ERROR = -3; // 0xfffffffd
+    field public static final int RESULT_FAILURE_REMOTE_ERROR = -2; // 0xfffffffe
+    field public static final int RESULT_SUCCESS = 0; // 0x0
+  }
+
+  public static abstract class CustomTabsService.Result implements java.lang.annotation.Annotation {
+  }
+
+  public abstract class CustomTabsServiceConnection implements android.content.ServiceConnection {
+    ctor public CustomTabsServiceConnection();
+    method public abstract void onCustomTabsServiceConnected(android.content.ComponentName, android.support.customtabs.CustomTabsClient);
+    method public final void onServiceConnected(android.content.ComponentName, android.os.IBinder);
+  }
+
+  public final class CustomTabsSession {
+    method public boolean mayLaunchUrl(android.net.Uri, android.os.Bundle, java.util.List<android.os.Bundle>);
+    method public int postMessage(java.lang.String, android.os.Bundle);
+    method public boolean requestPostMessageChannel(android.net.Uri);
+    method public boolean setActionButton(android.graphics.Bitmap, java.lang.String);
+    method public boolean setSecondaryToolbarViews(android.widget.RemoteViews, int[], android.app.PendingIntent);
+    method public deprecated boolean setToolbarItem(int, android.graphics.Bitmap, java.lang.String);
+  }
+
+  public class CustomTabsSessionToken {
+    method public android.support.customtabs.CustomTabsCallback getCallback();
+    method public static android.support.customtabs.CustomTabsSessionToken getSessionTokenFromIntent(android.content.Intent);
+    method public boolean isAssociatedWith(android.support.customtabs.CustomTabsSession);
+  }
+
+  public class PostMessageService extends android.app.Service {
+    ctor public PostMessageService();
+    method public android.os.IBinder onBind(android.content.Intent);
+  }
+
+  public abstract class PostMessageServiceConnection implements android.content.ServiceConnection {
+    ctor public PostMessageServiceConnection(android.support.customtabs.CustomTabsSessionToken);
+    method public boolean bindSessionToPostMessageService(android.content.Context, java.lang.String);
+    method public final boolean notifyMessageChannelReady(android.os.Bundle);
+    method public void onPostMessageServiceConnected();
+    method public void onPostMessageServiceDisconnected();
+    method public final void onServiceConnected(android.content.ComponentName, android.os.IBinder);
+    method public final void onServiceDisconnected(android.content.ComponentName);
+    method public final boolean postMessage(java.lang.String, android.os.Bundle);
+    method public void unbindFromContext(android.content.Context);
+  }
+
+}
+
+package android.support.design.widget {
+
+  public class AppBarLayout extends android.widget.LinearLayout {
+    ctor public AppBarLayout(android.content.Context);
+    ctor public AppBarLayout(android.content.Context, android.util.AttributeSet);
+    method public void addOnOffsetChangedListener(android.support.design.widget.AppBarLayout.OnOffsetChangedListener);
+    method protected android.support.design.widget.AppBarLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.design.widget.AppBarLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.design.widget.AppBarLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public deprecated float getTargetElevation();
+    method public final int getTotalScrollRange();
+    method public void removeOnOffsetChangedListener(android.support.design.widget.AppBarLayout.OnOffsetChangedListener);
+    method public void setExpanded(boolean);
+    method public void setExpanded(boolean, boolean);
+    method public deprecated void setTargetElevation(float);
+  }
+
+  public static class AppBarLayout.Behavior extends android.support.design.widget.HeaderBehavior {
+    ctor public AppBarLayout.Behavior();
+    ctor public AppBarLayout.Behavior(android.content.Context, android.util.AttributeSet);
+    method public boolean onLayoutChild(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, int);
+    method public boolean onMeasureChild(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, int, int, int, int);
+    method public void onNestedPreScroll(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, android.view.View, int, int, int[], int);
+    method public void onNestedScroll(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, android.view.View, int, int, int, int, int);
+    method public void onRestoreInstanceState(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, android.os.Parcelable);
+    method public android.os.Parcelable onSaveInstanceState(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout);
+    method public boolean onStartNestedScroll(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, android.view.View, android.view.View, int, int);
+    method public void onStopNestedScroll(android.support.design.widget.CoordinatorLayout, android.support.design.widget.AppBarLayout, android.view.View, int);
+    method public void setDragCallback(android.support.design.widget.AppBarLayout.Behavior.DragCallback);
+  }
+
+  public static abstract class AppBarLayout.Behavior.DragCallback {
+    ctor public AppBarLayout.Behavior.DragCallback();
+    method public abstract boolean canDrag(android.support.design.widget.AppBarLayout);
+  }
+
+  protected static class AppBarLayout.Behavior.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public AppBarLayout.Behavior.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public AppBarLayout.Behavior.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.design.widget.AppBarLayout.Behavior.SavedState> CREATOR;
+  }
+
+  public static class AppBarLayout.LayoutParams extends android.widget.LinearLayout.LayoutParams {
+    ctor public AppBarLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public AppBarLayout.LayoutParams(int, int);
+    ctor public AppBarLayout.LayoutParams(int, int, float);
+    ctor public AppBarLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public AppBarLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public AppBarLayout.LayoutParams(android.widget.LinearLayout.LayoutParams);
+    ctor public AppBarLayout.LayoutParams(android.support.design.widget.AppBarLayout.LayoutParams);
+    method public int getScrollFlags();
+    method public android.view.animation.Interpolator getScrollInterpolator();
+    method public void setScrollFlags(int);
+    method public void setScrollInterpolator(android.view.animation.Interpolator);
+    field public static final int SCROLL_FLAG_ENTER_ALWAYS = 4; // 0x4
+    field public static final int SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = 8; // 0x8
+    field public static final int SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = 2; // 0x2
+    field public static final int SCROLL_FLAG_SCROLL = 1; // 0x1
+    field public static final int SCROLL_FLAG_SNAP = 16; // 0x10
+  }
+
+  public static abstract interface AppBarLayout.OnOffsetChangedListener {
+    method public abstract void onOffsetChanged(android.support.design.widget.AppBarLayout, int);
+  }
+
+  public static class AppBarLayout.ScrollingViewBehavior extends android.support.design.widget.HeaderScrollingViewBehavior {
+    ctor public AppBarLayout.ScrollingViewBehavior();
+    ctor public AppBarLayout.ScrollingViewBehavior(android.content.Context, android.util.AttributeSet);
+    method public boolean layoutDependsOn(android.support.design.widget.CoordinatorLayout, android.view.View, android.view.View);
+    method public boolean onDependentViewChanged(android.support.design.widget.CoordinatorLayout, android.view.View, android.view.View);
+    method public boolean onRequestChildRectangleOnScreen(android.support.design.widget.CoordinatorLayout, android.view.View, android.graphics.Rect, boolean);
+  }
+
+  public abstract class BaseTransientBottomBar<B extends android.support.design.widget.BaseTransientBottomBar<B>> {
+    ctor protected BaseTransientBottomBar(android.view.ViewGroup, android.view.View, android.support.design.widget.BaseTransientBottomBar.ContentViewCallback);
+    method public B addCallback(android.support.design.widget.BaseTransientBottomBar.BaseCallback<B>);
+    method public void dismiss();
+    method public android.content.Context getContext();
+    method public int getDuration();
+    method public android.view.View getView();
+    method public boolean isShown();
+    method public boolean isShownOrQueued();
+    method public B removeCallback(android.support.design.widget.BaseTransientBottomBar.BaseCallback<B>);
+    method public B setDuration(int);
+    method public void show();
+    field public static final int LENGTH_INDEFINITE = -2; // 0xfffffffe
+    field public static final int LENGTH_LONG = 0; // 0x0
+    field public static final int LENGTH_SHORT = -1; // 0xffffffff
+  }
+
+  public static abstract class BaseTransientBottomBar.BaseCallback<B> {
+    ctor public BaseTransientBottomBar.BaseCallback();
+    method public void onDismissed(B, int);
+    method public void onShown(B);
+    field public static final int DISMISS_EVENT_ACTION = 1; // 0x1
+    field public static final int DISMISS_EVENT_CONSECUTIVE = 4; // 0x4
+    field public static final int DISMISS_EVENT_MANUAL = 3; // 0x3
+    field public static final int DISMISS_EVENT_SWIPE = 0; // 0x0
+    field public static final int DISMISS_EVENT_TIMEOUT = 2; // 0x2
+  }
+
+  public static abstract interface BaseTransientBottomBar.ContentViewCallback {
+    method public abstract void animateContentIn(int, int);
+    method public abstract void animateContentOut(int, int);
+  }
+
+  public class BottomNavigationView extends android.widget.FrameLayout {
+    ctor public BottomNavigationView(android.content.Context);
+    ctor public BottomNavigationView(android.content.Context, android.util.AttributeSet);
+    ctor public BottomNavigationView(android.content.Context, android.util.AttributeSet, int);
+    method public int getItemBackgroundResource();
+    method public android.content.res.ColorStateList getItemIconTintList();
+    method public android.content.res.ColorStateList getItemTextColor();
+    method public int getMaxItemCount();
+    method public android.view.Menu getMenu();
+    method public int getSelectedItemId();
+    method public void inflateMenu(int);
+    method public void setItemBackgroundResource(int);
+    method public void setItemIconTintList(android.content.res.ColorStateList);
+    method public void setItemTextColor(android.content.res.ColorStateList);
+    method public void setOnNavigationItemReselectedListener(android.support.design.widget.BottomNavigationView.OnNavigationItemReselectedListener);
+    method public void setOnNavigationItemSelectedListener(android.support.design.widget.BottomNavigationView.OnNavigationItemSelectedListener);
+    method public void setSelectedItemId(int);
+  }
+
+  public static abstract interface BottomNavigationView.OnNavigationItemReselectedListener {
+    method public abstract void onNavigationItemReselected(android.view.MenuItem);
+  }
+
+  public static abstract interface BottomNavigationView.OnNavigationItemSelectedListener {
+    method public abstract boolean onNavigationItemSelected(android.view.MenuItem);
+  }
+
+  public class BottomSheetBehavior<V extends android.view.View> extends android.support.design.widget.CoordinatorLayout.Behavior {
+    ctor public BottomSheetBehavior();
+    ctor public BottomSheetBehavior(android.content.Context, android.util.AttributeSet);
+    method public static <V extends android.view.View> android.support.design.widget.BottomSheetBehavior<V> from(V);
+    method public final int getPeekHeight();
+    method public boolean getSkipCollapsed();
+    method public final int getState();
+    method public boolean isHideable();
+    method public void onNestedPreScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int[]);
+    method public boolean onStartNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int);
+    method public void onStopNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View);
+    method public void setBottomSheetCallback(android.support.design.widget.BottomSheetBehavior.BottomSheetCallback);
+    method public void setHideable(boolean);
+    method public final void setPeekHeight(int);
+    method public void setSkipCollapsed(boolean);
+    method public final void setState(int);
+    field public static final int PEEK_HEIGHT_AUTO = -1; // 0xffffffff
+    field public static final int STATE_COLLAPSED = 4; // 0x4
+    field public static final int STATE_DRAGGING = 1; // 0x1
+    field public static final int STATE_EXPANDED = 3; // 0x3
+    field public static final int STATE_HIDDEN = 5; // 0x5
+    field public static final int STATE_SETTLING = 2; // 0x2
+  }
+
+  public static abstract class BottomSheetBehavior.BottomSheetCallback {
+    ctor public BottomSheetBehavior.BottomSheetCallback();
+    method public abstract void onSlide(android.view.View, float);
+    method public abstract void onStateChanged(android.view.View, int);
+  }
+
+  protected static class BottomSheetBehavior.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public BottomSheetBehavior.SavedState(android.os.Parcel);
+    ctor public BottomSheetBehavior.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public BottomSheetBehavior.SavedState(android.os.Parcelable, int);
+    field public static final android.os.Parcelable.Creator<android.support.design.widget.BottomSheetBehavior.SavedState> CREATOR;
+  }
+
+  public class BottomSheetDialog extends android.support.v7.app.AppCompatDialog {
+    ctor public BottomSheetDialog(android.content.Context);
+    ctor public BottomSheetDialog(android.content.Context, int);
+    ctor protected BottomSheetDialog(android.content.Context, boolean, android.content.DialogInterface.OnCancelListener);
+  }
+
+  public class BottomSheetDialogFragment extends android.support.v7.app.AppCompatDialogFragment {
+    ctor public BottomSheetDialogFragment();
+  }
+
+  public class CollapsingToolbarLayout extends android.widget.FrameLayout {
+    ctor public CollapsingToolbarLayout(android.content.Context);
+    ctor public CollapsingToolbarLayout(android.content.Context, android.util.AttributeSet);
+    ctor public CollapsingToolbarLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.design.widget.CollapsingToolbarLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.widget.FrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.widget.FrameLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getCollapsedTitleGravity();
+    method public android.graphics.Typeface getCollapsedTitleTypeface();
+    method public android.graphics.drawable.Drawable getContentScrim();
+    method public int getExpandedTitleGravity();
+    method public int getExpandedTitleMarginBottom();
+    method public int getExpandedTitleMarginEnd();
+    method public int getExpandedTitleMarginStart();
+    method public int getExpandedTitleMarginTop();
+    method public android.graphics.Typeface getExpandedTitleTypeface();
+    method public long getScrimAnimationDuration();
+    method public int getScrimVisibleHeightTrigger();
+    method public android.graphics.drawable.Drawable getStatusBarScrim();
+    method public java.lang.CharSequence getTitle();
+    method public boolean isTitleEnabled();
+    method public void setCollapsedTitleGravity(int);
+    method public void setCollapsedTitleTextAppearance(int);
+    method public void setCollapsedTitleTextColor(int);
+    method public void setCollapsedTitleTextColor(android.content.res.ColorStateList);
+    method public void setCollapsedTitleTypeface(android.graphics.Typeface);
+    method public void setContentScrim(android.graphics.drawable.Drawable);
+    method public void setContentScrimColor(int);
+    method public void setContentScrimResource(int);
+    method public void setExpandedTitleColor(int);
+    method public void setExpandedTitleGravity(int);
+    method public void setExpandedTitleMargin(int, int, int, int);
+    method public void setExpandedTitleMarginBottom(int);
+    method public void setExpandedTitleMarginEnd(int);
+    method public void setExpandedTitleMarginStart(int);
+    method public void setExpandedTitleMarginTop(int);
+    method public void setExpandedTitleTextAppearance(int);
+    method public void setExpandedTitleTextColor(android.content.res.ColorStateList);
+    method public void setExpandedTitleTypeface(android.graphics.Typeface);
+    method public void setScrimAnimationDuration(long);
+    method public void setScrimVisibleHeightTrigger(int);
+    method public void setScrimsShown(boolean);
+    method public void setScrimsShown(boolean, boolean);
+    method public void setStatusBarScrim(android.graphics.drawable.Drawable);
+    method public void setStatusBarScrimColor(int);
+    method public void setStatusBarScrimResource(int);
+    method public void setTitle(java.lang.CharSequence);
+    method public void setTitleEnabled(boolean);
+  }
+
+  public static class CollapsingToolbarLayout.LayoutParams extends android.widget.FrameLayout.LayoutParams {
+    ctor public CollapsingToolbarLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public CollapsingToolbarLayout.LayoutParams(int, int);
+    ctor public CollapsingToolbarLayout.LayoutParams(int, int, int);
+    ctor public CollapsingToolbarLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public CollapsingToolbarLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public CollapsingToolbarLayout.LayoutParams(android.widget.FrameLayout.LayoutParams);
+    method public int getCollapseMode();
+    method public float getParallaxMultiplier();
+    method public void setCollapseMode(int);
+    method public void setParallaxMultiplier(float);
+    field public static final int COLLAPSE_MODE_OFF = 0; // 0x0
+    field public static final int COLLAPSE_MODE_PARALLAX = 2; // 0x2
+    field public static final int COLLAPSE_MODE_PIN = 1; // 0x1
+  }
+
+  public class CoordinatorLayout extends android.view.ViewGroup implements android.support.v4.view.NestedScrollingParent2 {
+    ctor public CoordinatorLayout(android.content.Context);
+    ctor public CoordinatorLayout(android.content.Context, android.util.AttributeSet);
+    ctor public CoordinatorLayout(android.content.Context, android.util.AttributeSet, int);
+    method public void dispatchDependentViewsChanged(android.view.View);
+    method public boolean doViewsOverlap(android.view.View, android.view.View);
+    method protected android.support.design.widget.CoordinatorLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.design.widget.CoordinatorLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.design.widget.CoordinatorLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public java.util.List<android.view.View> getDependencies(android.view.View);
+    method public java.util.List<android.view.View> getDependents(android.view.View);
+    method public android.graphics.drawable.Drawable getStatusBarBackground();
+    method public boolean isPointInChildBounds(android.view.View, int, int);
+    method public void onAttachedToWindow();
+    method public void onDetachedFromWindow();
+    method public void onDraw(android.graphics.Canvas);
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void onLayoutChild(android.view.View, int);
+    method public void onMeasureChild(android.view.View, int, int, int, int);
+    method public void onNestedPreScroll(android.view.View, int, int, int[], int);
+    method public void onNestedScroll(android.view.View, int, int, int, int, int);
+    method public void onNestedScrollAccepted(android.view.View, android.view.View, int, int);
+    method public boolean onStartNestedScroll(android.view.View, android.view.View, int, int);
+    method public void onStopNestedScroll(android.view.View, int);
+    method public void setStatusBarBackground(android.graphics.drawable.Drawable);
+    method public void setStatusBarBackgroundColor(int);
+    method public void setStatusBarBackgroundResource(int);
+  }
+
+  public static abstract class CoordinatorLayout.Behavior<V extends android.view.View> {
+    ctor public CoordinatorLayout.Behavior();
+    ctor public CoordinatorLayout.Behavior(android.content.Context, android.util.AttributeSet);
+    method public boolean blocksInteractionBelow(android.support.design.widget.CoordinatorLayout, V);
+    method public boolean getInsetDodgeRect(android.support.design.widget.CoordinatorLayout, V, android.graphics.Rect);
+    method public int getScrimColor(android.support.design.widget.CoordinatorLayout, V);
+    method public float getScrimOpacity(android.support.design.widget.CoordinatorLayout, V);
+    method public static java.lang.Object getTag(android.view.View);
+    method public boolean layoutDependsOn(android.support.design.widget.CoordinatorLayout, V, android.view.View);
+    method public android.support.v4.view.WindowInsetsCompat onApplyWindowInsets(android.support.design.widget.CoordinatorLayout, V, android.support.v4.view.WindowInsetsCompat);
+    method public void onAttachedToLayoutParams(android.support.design.widget.CoordinatorLayout.LayoutParams);
+    method public boolean onDependentViewChanged(android.support.design.widget.CoordinatorLayout, V, android.view.View);
+    method public void onDependentViewRemoved(android.support.design.widget.CoordinatorLayout, V, android.view.View);
+    method public void onDetachedFromLayoutParams();
+    method public boolean onInterceptTouchEvent(android.support.design.widget.CoordinatorLayout, V, android.view.MotionEvent);
+    method public boolean onLayoutChild(android.support.design.widget.CoordinatorLayout, V, int);
+    method public boolean onMeasureChild(android.support.design.widget.CoordinatorLayout, V, int, int, int, int);
+    method public boolean onNestedFling(android.support.design.widget.CoordinatorLayout, V, android.view.View, float, float, boolean);
+    method public boolean onNestedPreFling(android.support.design.widget.CoordinatorLayout, V, android.view.View, float, float);
+    method public deprecated void onNestedPreScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int[]);
+    method public void onNestedPreScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int[], int);
+    method public deprecated void onNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int, int);
+    method public void onNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int, int, int);
+    method public deprecated void onNestedScrollAccepted(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int);
+    method public void onNestedScrollAccepted(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int, int);
+    method public boolean onRequestChildRectangleOnScreen(android.support.design.widget.CoordinatorLayout, V, android.graphics.Rect, boolean);
+    method public void onRestoreInstanceState(android.support.design.widget.CoordinatorLayout, V, android.os.Parcelable);
+    method public android.os.Parcelable onSaveInstanceState(android.support.design.widget.CoordinatorLayout, V);
+    method public deprecated boolean onStartNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int);
+    method public boolean onStartNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, android.view.View, int, int);
+    method public deprecated void onStopNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View);
+    method public void onStopNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int);
+    method public boolean onTouchEvent(android.support.design.widget.CoordinatorLayout, V, android.view.MotionEvent);
+    method public static void setTag(android.view.View, java.lang.Object);
+  }
+
+  public static abstract class CoordinatorLayout.DefaultBehavior implements java.lang.annotation.Annotation {
+  }
+
+  public static class CoordinatorLayout.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public CoordinatorLayout.LayoutParams(int, int);
+    ctor public CoordinatorLayout.LayoutParams(android.support.design.widget.CoordinatorLayout.LayoutParams);
+    ctor public CoordinatorLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public CoordinatorLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getAnchorId();
+    method public android.support.design.widget.CoordinatorLayout.Behavior getBehavior();
+    method public void setAnchorId(int);
+    method public void setBehavior(android.support.design.widget.CoordinatorLayout.Behavior);
+    field public int anchorGravity;
+    field public int dodgeInsetEdges;
+    field public int gravity;
+    field public int insetEdge;
+    field public int keyline;
+  }
+
+  protected static class CoordinatorLayout.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public CoordinatorLayout.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public CoordinatorLayout.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.design.widget.CoordinatorLayout.SavedState> CREATOR;
+  }
+
+  public class FloatingActionButton extends android.support.design.widget.VisibilityAwareImageButton {
+    ctor public FloatingActionButton(android.content.Context);
+    ctor public FloatingActionButton(android.content.Context, android.util.AttributeSet);
+    ctor public FloatingActionButton(android.content.Context, android.util.AttributeSet, int);
+    method public float getCompatElevation();
+    method public android.graphics.drawable.Drawable getContentBackground();
+    method public boolean getContentRect(android.graphics.Rect);
+    method public int getRippleColor();
+    method public int getSize();
+    method public boolean getUseCompatPadding();
+    method public void hide();
+    method public void hide(android.support.design.widget.FloatingActionButton.OnVisibilityChangedListener);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setCompatElevation(float);
+    method public void setRippleColor(int);
+    method public void setSize(int);
+    method public void setUseCompatPadding(boolean);
+    method public void show();
+    method public void show(android.support.design.widget.FloatingActionButton.OnVisibilityChangedListener);
+    field public static final int SIZE_AUTO = -1; // 0xffffffff
+    field public static final int SIZE_MINI = 1; // 0x1
+    field public static final int SIZE_NORMAL = 0; // 0x0
+  }
+
+  public static class FloatingActionButton.Behavior extends android.support.design.widget.CoordinatorLayout.Behavior {
+    ctor public FloatingActionButton.Behavior();
+    ctor public FloatingActionButton.Behavior(android.content.Context, android.util.AttributeSet);
+    method public boolean getInsetDodgeRect(android.support.design.widget.CoordinatorLayout, android.support.design.widget.FloatingActionButton, android.graphics.Rect);
+    method public boolean isAutoHideEnabled();
+    method public boolean onDependentViewChanged(android.support.design.widget.CoordinatorLayout, android.support.design.widget.FloatingActionButton, android.view.View);
+    method public boolean onLayoutChild(android.support.design.widget.CoordinatorLayout, android.support.design.widget.FloatingActionButton, int);
+    method public void setAutoHideEnabled(boolean);
+  }
+
+  public static abstract class FloatingActionButton.OnVisibilityChangedListener {
+    ctor public FloatingActionButton.OnVisibilityChangedListener();
+    method public void onHidden(android.support.design.widget.FloatingActionButton);
+    method public void onShown(android.support.design.widget.FloatingActionButton);
+  }
+
+   abstract class HeaderBehavior<V extends android.view.View> extends android.support.design.widget.ViewOffsetBehavior {
+    ctor public HeaderBehavior();
+    ctor public HeaderBehavior(android.content.Context, android.util.AttributeSet);
+  }
+
+   abstract class HeaderScrollingViewBehavior extends android.support.design.widget.ViewOffsetBehavior {
+    ctor public HeaderScrollingViewBehavior();
+    ctor public HeaderScrollingViewBehavior(android.content.Context, android.util.AttributeSet);
+    method public final int getOverlayTop();
+    method protected void layoutChild(android.support.design.widget.CoordinatorLayout, android.view.View, int);
+    method public boolean onMeasureChild(android.support.design.widget.CoordinatorLayout, android.view.View, int, int, int, int);
+    method public final void setOverlayTop(int);
+  }
+
+  public class NavigationView extends android.widget.FrameLayout {
+    ctor public NavigationView(android.content.Context);
+    ctor public NavigationView(android.content.Context, android.util.AttributeSet);
+    ctor public NavigationView(android.content.Context, android.util.AttributeSet, int);
+    method public void addHeaderView(android.view.View);
+    method public int getHeaderCount();
+    method public android.view.View getHeaderView(int);
+    method public android.graphics.drawable.Drawable getItemBackground();
+    method public android.content.res.ColorStateList getItemIconTintList();
+    method public android.content.res.ColorStateList getItemTextColor();
+    method public android.view.Menu getMenu();
+    method public android.view.View inflateHeaderView(int);
+    method public void inflateMenu(int);
+    method public void removeHeaderView(android.view.View);
+    method public void setCheckedItem(int);
+    method public void setItemBackground(android.graphics.drawable.Drawable);
+    method public void setItemBackgroundResource(int);
+    method public void setItemIconTintList(android.content.res.ColorStateList);
+    method public void setItemTextAppearance(int);
+    method public void setItemTextColor(android.content.res.ColorStateList);
+    method public void setNavigationItemSelectedListener(android.support.design.widget.NavigationView.OnNavigationItemSelectedListener);
+  }
+
+  public static abstract interface NavigationView.OnNavigationItemSelectedListener {
+    method public abstract boolean onNavigationItemSelected(android.view.MenuItem);
+  }
+
+  public static class NavigationView.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public NavigationView.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public NavigationView.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.design.widget.NavigationView.SavedState> CREATOR;
+    field public android.os.Bundle menuState;
+  }
+
+  public final class Snackbar extends android.support.design.widget.BaseTransientBottomBar {
+    method public static android.support.design.widget.Snackbar make(android.view.View, java.lang.CharSequence, int);
+    method public static android.support.design.widget.Snackbar make(android.view.View, int, int);
+    method public android.support.design.widget.Snackbar setAction(int, android.view.View.OnClickListener);
+    method public android.support.design.widget.Snackbar setAction(java.lang.CharSequence, android.view.View.OnClickListener);
+    method public android.support.design.widget.Snackbar setActionTextColor(android.content.res.ColorStateList);
+    method public android.support.design.widget.Snackbar setActionTextColor(int);
+    method public deprecated android.support.design.widget.Snackbar setCallback(android.support.design.widget.Snackbar.Callback);
+    method public android.support.design.widget.Snackbar setText(java.lang.CharSequence);
+    method public android.support.design.widget.Snackbar setText(int);
+    field public static final int LENGTH_INDEFINITE = -2; // 0xfffffffe
+    field public static final int LENGTH_LONG = 0; // 0x0
+    field public static final int LENGTH_SHORT = -1; // 0xffffffff
+  }
+
+  public static class Snackbar.Callback extends android.support.design.widget.BaseTransientBottomBar.BaseCallback {
+    ctor public Snackbar.Callback();
+    method public void onDismissed(android.support.design.widget.Snackbar, int);
+    method public void onShown(android.support.design.widget.Snackbar);
+    field public static final int DISMISS_EVENT_ACTION = 1; // 0x1
+    field public static final int DISMISS_EVENT_CONSECUTIVE = 4; // 0x4
+    field public static final int DISMISS_EVENT_MANUAL = 3; // 0x3
+    field public static final int DISMISS_EVENT_SWIPE = 0; // 0x0
+    field public static final int DISMISS_EVENT_TIMEOUT = 2; // 0x2
+  }
+
+  public class SwipeDismissBehavior<V extends android.view.View> extends android.support.design.widget.CoordinatorLayout.Behavior {
+    ctor public SwipeDismissBehavior();
+    method public boolean canSwipeDismissView(android.view.View);
+    method public int getDragState();
+    method public void setDragDismissDistance(float);
+    method public void setEndAlphaSwipeDistance(float);
+    method public void setListener(android.support.design.widget.SwipeDismissBehavior.OnDismissListener);
+    method public void setSensitivity(float);
+    method public void setStartAlphaSwipeDistance(float);
+    method public void setSwipeDirection(int);
+    field public static final int STATE_DRAGGING = 1; // 0x1
+    field public static final int STATE_IDLE = 0; // 0x0
+    field public static final int STATE_SETTLING = 2; // 0x2
+    field public static final int SWIPE_DIRECTION_ANY = 2; // 0x2
+    field public static final int SWIPE_DIRECTION_END_TO_START = 1; // 0x1
+    field public static final int SWIPE_DIRECTION_START_TO_END = 0; // 0x0
+  }
+
+  public static abstract interface SwipeDismissBehavior.OnDismissListener {
+    method public abstract void onDismiss(android.view.View);
+    method public abstract void onDragStateChanged(int);
+  }
+
+  public final class TabItem extends android.view.View {
+    ctor public TabItem(android.content.Context);
+    ctor public TabItem(android.content.Context, android.util.AttributeSet);
+  }
+
+  public class TabLayout extends android.widget.HorizontalScrollView {
+    ctor public TabLayout(android.content.Context);
+    ctor public TabLayout(android.content.Context, android.util.AttributeSet);
+    ctor public TabLayout(android.content.Context, android.util.AttributeSet, int);
+    method public void addOnTabSelectedListener(android.support.design.widget.TabLayout.OnTabSelectedListener);
+    method public void addTab(android.support.design.widget.TabLayout.Tab);
+    method public void addTab(android.support.design.widget.TabLayout.Tab, int);
+    method public void addTab(android.support.design.widget.TabLayout.Tab, boolean);
+    method public void addTab(android.support.design.widget.TabLayout.Tab, int, boolean);
+    method public void clearOnTabSelectedListeners();
+    method public android.widget.FrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method public int getSelectedTabPosition();
+    method public android.support.design.widget.TabLayout.Tab getTabAt(int);
+    method public int getTabCount();
+    method public int getTabGravity();
+    method public int getTabMode();
+    method public android.content.res.ColorStateList getTabTextColors();
+    method public android.support.design.widget.TabLayout.Tab newTab();
+    method public void removeAllTabs();
+    method public void removeOnTabSelectedListener(android.support.design.widget.TabLayout.OnTabSelectedListener);
+    method public void removeTab(android.support.design.widget.TabLayout.Tab);
+    method public void removeTabAt(int);
+    method public deprecated void setOnTabSelectedListener(android.support.design.widget.TabLayout.OnTabSelectedListener);
+    method public void setScrollPosition(int, float, boolean);
+    method public void setSelectedTabIndicatorColor(int);
+    method public void setSelectedTabIndicatorHeight(int);
+    method public void setTabGravity(int);
+    method public void setTabMode(int);
+    method public void setTabTextColors(android.content.res.ColorStateList);
+    method public void setTabTextColors(int, int);
+    method public deprecated void setTabsFromPagerAdapter(android.support.v4.view.PagerAdapter);
+    method public void setupWithViewPager(android.support.v4.view.ViewPager);
+    method public void setupWithViewPager(android.support.v4.view.ViewPager, boolean);
+    field public static final int GRAVITY_CENTER = 1; // 0x1
+    field public static final int GRAVITY_FILL = 0; // 0x0
+    field public static final int MODE_FIXED = 1; // 0x1
+    field public static final int MODE_SCROLLABLE = 0; // 0x0
+  }
+
+  public static abstract interface TabLayout.OnTabSelectedListener {
+    method public abstract void onTabReselected(android.support.design.widget.TabLayout.Tab);
+    method public abstract void onTabSelected(android.support.design.widget.TabLayout.Tab);
+    method public abstract void onTabUnselected(android.support.design.widget.TabLayout.Tab);
+  }
+
+  public static final class TabLayout.Tab {
+    method public java.lang.CharSequence getContentDescription();
+    method public android.view.View getCustomView();
+    method public android.graphics.drawable.Drawable getIcon();
+    method public int getPosition();
+    method public java.lang.Object getTag();
+    method public java.lang.CharSequence getText();
+    method public boolean isSelected();
+    method public void select();
+    method public android.support.design.widget.TabLayout.Tab setContentDescription(int);
+    method public android.support.design.widget.TabLayout.Tab setContentDescription(java.lang.CharSequence);
+    method public android.support.design.widget.TabLayout.Tab setCustomView(android.view.View);
+    method public android.support.design.widget.TabLayout.Tab setCustomView(int);
+    method public android.support.design.widget.TabLayout.Tab setIcon(android.graphics.drawable.Drawable);
+    method public android.support.design.widget.TabLayout.Tab setIcon(int);
+    method public android.support.design.widget.TabLayout.Tab setTag(java.lang.Object);
+    method public android.support.design.widget.TabLayout.Tab setText(java.lang.CharSequence);
+    method public android.support.design.widget.TabLayout.Tab setText(int);
+    field public static final int INVALID_POSITION = -1; // 0xffffffff
+  }
+
+  public static class TabLayout.TabLayoutOnPageChangeListener implements android.support.v4.view.ViewPager.OnPageChangeListener {
+    ctor public TabLayout.TabLayoutOnPageChangeListener(android.support.design.widget.TabLayout);
+    method public void onPageScrollStateChanged(int);
+    method public void onPageScrolled(int, float, int);
+    method public void onPageSelected(int);
+  }
+
+  public static class TabLayout.ViewPagerOnTabSelectedListener implements android.support.design.widget.TabLayout.OnTabSelectedListener {
+    ctor public TabLayout.ViewPagerOnTabSelectedListener(android.support.v4.view.ViewPager);
+    method public void onTabReselected(android.support.design.widget.TabLayout.Tab);
+    method public void onTabSelected(android.support.design.widget.TabLayout.Tab);
+    method public void onTabUnselected(android.support.design.widget.TabLayout.Tab);
+  }
+
+  public class TextInputEditText extends android.support.v7.widget.AppCompatEditText {
+    ctor public TextInputEditText(android.content.Context);
+    ctor public TextInputEditText(android.content.Context, android.util.AttributeSet);
+    ctor public TextInputEditText(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class TextInputLayout extends android.widget.LinearLayout {
+    ctor public TextInputLayout(android.content.Context);
+    ctor public TextInputLayout(android.content.Context, android.util.AttributeSet);
+    ctor public TextInputLayout(android.content.Context, android.util.AttributeSet, int);
+    method public int getCounterMaxLength();
+    method public android.widget.EditText getEditText();
+    method public java.lang.CharSequence getError();
+    method public java.lang.CharSequence getHint();
+    method public java.lang.CharSequence getPasswordVisibilityToggleContentDescription();
+    method public android.graphics.drawable.Drawable getPasswordVisibilityToggleDrawable();
+    method public android.graphics.Typeface getTypeface();
+    method public boolean isCounterEnabled();
+    method public boolean isErrorEnabled();
+    method public boolean isHintAnimationEnabled();
+    method public boolean isHintEnabled();
+    method public boolean isPasswordVisibilityToggleEnabled();
+    method public android.os.Parcelable onSaveInstanceState();
+    method public void setCounterEnabled(boolean);
+    method public void setCounterMaxLength(int);
+    method public void setError(java.lang.CharSequence);
+    method public void setErrorEnabled(boolean);
+    method public void setErrorTextAppearance(int);
+    method public void setHint(java.lang.CharSequence);
+    method public void setHintAnimationEnabled(boolean);
+    method public void setHintEnabled(boolean);
+    method public void setHintTextAppearance(int);
+    method public void setPasswordVisibilityToggleContentDescription(int);
+    method public void setPasswordVisibilityToggleContentDescription(java.lang.CharSequence);
+    method public void setPasswordVisibilityToggleDrawable(int);
+    method public void setPasswordVisibilityToggleDrawable(android.graphics.drawable.Drawable);
+    method public void setPasswordVisibilityToggleEnabled(boolean);
+    method public void setPasswordVisibilityToggleTintList(android.content.res.ColorStateList);
+    method public void setPasswordVisibilityToggleTintMode(android.graphics.PorterDuff.Mode);
+    method public void setTypeface(android.graphics.Typeface);
+  }
+
+   class ViewOffsetBehavior<V extends android.view.View> extends android.support.design.widget.CoordinatorLayout.Behavior {
+    ctor public ViewOffsetBehavior();
+    ctor public ViewOffsetBehavior(android.content.Context, android.util.AttributeSet);
+    method public int getLeftAndRightOffset();
+    method public int getTopAndBottomOffset();
+    method protected void layoutChild(android.support.design.widget.CoordinatorLayout, V, int);
+    method public boolean setLeftAndRightOffset(int);
+    method public boolean setTopAndBottomOffset(int);
+  }
+
+   class VisibilityAwareImageButton extends android.widget.ImageButton {
+    ctor public VisibilityAwareImageButton(android.content.Context);
+    ctor public VisibilityAwareImageButton(android.content.Context, android.util.AttributeSet);
+    ctor public VisibilityAwareImageButton(android.content.Context, android.util.AttributeSet, int);
+  }
+
+}
+
+package android.support.graphics.drawable {
+
+  public abstract interface Animatable2Compat {
+    method public abstract void clearAnimationCallbacks();
+    method public abstract void registerAnimationCallback(android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+    method public abstract boolean unregisterAnimationCallback(android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+  }
+
+  public static abstract class Animatable2Compat.AnimationCallback {
+    ctor public Animatable2Compat.AnimationCallback();
+    method public void onAnimationEnd(android.graphics.drawable.Drawable);
+    method public void onAnimationStart(android.graphics.drawable.Drawable);
+  }
+
+  public class AnimatedVectorDrawableCompat extends android.support.graphics.drawable.VectorDrawableCommon implements android.support.graphics.drawable.Animatable2Compat {
+    method public void clearAnimationCallbacks();
+    method public static void clearAnimationCallbacks(android.graphics.drawable.Drawable);
+    method public static android.support.graphics.drawable.AnimatedVectorDrawableCompat create(android.content.Context, int);
+    method public static android.support.graphics.drawable.AnimatedVectorDrawableCompat createFromXmlInner(android.content.Context, android.content.res.Resources, org.xmlpull.v1.XmlPullParser, android.util.AttributeSet, android.content.res.Resources.Theme) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method public void draw(android.graphics.Canvas);
+    method public int getOpacity();
+    method public boolean isRunning();
+    method public void registerAnimationCallback(android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+    method public static void registerAnimationCallback(android.graphics.drawable.Drawable, android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+    method public void setAlpha(int);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void start();
+    method public void stop();
+    method public boolean unregisterAnimationCallback(android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+    method public static boolean unregisterAnimationCallback(android.graphics.drawable.Drawable, android.support.graphics.drawable.Animatable2Compat.AnimationCallback);
+  }
+
+   abstract class VectorDrawableCommon extends android.graphics.drawable.Drawable {
+  }
+
+  public class VectorDrawableCompat extends android.support.graphics.drawable.VectorDrawableCommon {
+    method public static android.support.graphics.drawable.VectorDrawableCompat create(android.content.res.Resources, int, android.content.res.Resources.Theme);
+    method public static android.support.graphics.drawable.VectorDrawableCompat createFromXmlInner(android.content.res.Resources, org.xmlpull.v1.XmlPullParser, android.util.AttributeSet, android.content.res.Resources.Theme) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method public void draw(android.graphics.Canvas);
+    method public int getOpacity();
+    method public void setAlpha(int);
+    method public void setColorFilter(android.graphics.ColorFilter);
+  }
+
+}
+
+package android.support.media {
+
+  public class ExifInterface {
+    ctor public ExifInterface(java.lang.String) throws java.io.IOException;
+    ctor public ExifInterface(java.io.InputStream) throws java.io.IOException;
+    method public void flipHorizontally();
+    method public void flipVertically();
+    method public double getAltitude(double);
+    method public java.lang.String getAttribute(java.lang.String);
+    method public double getAttributeDouble(java.lang.String, double);
+    method public int getAttributeInt(java.lang.String, int);
+    method public deprecated boolean getLatLong(float[]);
+    method public double[] getLatLong();
+    method public byte[] getThumbnail();
+    method public android.graphics.Bitmap getThumbnailBitmap();
+    method public byte[] getThumbnailBytes();
+    method public long[] getThumbnailRange();
+    method public boolean hasThumbnail();
+    method public boolean isThumbnailCompressed();
+    method public void resetOrientation();
+    method public void rotate(int);
+    method public void saveAttributes() throws java.io.IOException;
+    method public void setAltitude(double);
+    method public void setAttribute(java.lang.String, java.lang.String);
+    method public void setGpsInfo(android.location.Location);
+    method public void setLatLong(double, double);
+    field public static final int ORIENTATION_FLIP_HORIZONTAL = 2; // 0x2
+    field public static final int ORIENTATION_FLIP_VERTICAL = 4; // 0x4
+    field public static final int ORIENTATION_NORMAL = 1; // 0x1
+    field public static final int ORIENTATION_ROTATE_180 = 3; // 0x3
+    field public static final int ORIENTATION_ROTATE_270 = 8; // 0x8
+    field public static final int ORIENTATION_ROTATE_90 = 6; // 0x6
+    field public static final int ORIENTATION_TRANSPOSE = 5; // 0x5
+    field public static final int ORIENTATION_TRANSVERSE = 7; // 0x7
+    field public static final int ORIENTATION_UNDEFINED = 0; // 0x0
+    field public static final java.lang.String TAG_APERTURE_VALUE = "ApertureValue";
+    field public static final java.lang.String TAG_ARTIST = "Artist";
+    field public static final java.lang.String TAG_BITS_PER_SAMPLE = "BitsPerSample";
+    field public static final java.lang.String TAG_BRIGHTNESS_VALUE = "BrightnessValue";
+    field public static final java.lang.String TAG_CFA_PATTERN = "CFAPattern";
+    field public static final java.lang.String TAG_COLOR_SPACE = "ColorSpace";
+    field public static final java.lang.String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration";
+    field public static final java.lang.String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel";
+    field public static final java.lang.String TAG_COMPRESSION = "Compression";
+    field public static final java.lang.String TAG_CONTRAST = "Contrast";
+    field public static final java.lang.String TAG_COPYRIGHT = "Copyright";
+    field public static final java.lang.String TAG_CUSTOM_RENDERED = "CustomRendered";
+    field public static final java.lang.String TAG_DATETIME = "DateTime";
+    field public static final java.lang.String TAG_DATETIME_DIGITIZED = "DateTimeDigitized";
+    field public static final java.lang.String TAG_DATETIME_ORIGINAL = "DateTimeOriginal";
+    field public static final java.lang.String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize";
+    field public static final java.lang.String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription";
+    field public static final java.lang.String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio";
+    field public static final java.lang.String TAG_DNG_VERSION = "DNGVersion";
+    field public static final java.lang.String TAG_EXIF_VERSION = "ExifVersion";
+    field public static final java.lang.String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue";
+    field public static final java.lang.String TAG_EXPOSURE_INDEX = "ExposureIndex";
+    field public static final java.lang.String TAG_EXPOSURE_MODE = "ExposureMode";
+    field public static final java.lang.String TAG_EXPOSURE_PROGRAM = "ExposureProgram";
+    field public static final java.lang.String TAG_EXPOSURE_TIME = "ExposureTime";
+    field public static final java.lang.String TAG_FILE_SOURCE = "FileSource";
+    field public static final java.lang.String TAG_FLASH = "Flash";
+    field public static final java.lang.String TAG_FLASHPIX_VERSION = "FlashpixVersion";
+    field public static final java.lang.String TAG_FLASH_ENERGY = "FlashEnergy";
+    field public static final java.lang.String TAG_FOCAL_LENGTH = "FocalLength";
+    field public static final java.lang.String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm";
+    field public static final java.lang.String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit";
+    field public static final java.lang.String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution";
+    field public static final java.lang.String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution";
+    field public static final java.lang.String TAG_F_NUMBER = "FNumber";
+    field public static final java.lang.String TAG_GAIN_CONTROL = "GainControl";
+    field public static final java.lang.String TAG_GPS_ALTITUDE = "GPSAltitude";
+    field public static final java.lang.String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef";
+    field public static final java.lang.String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation";
+    field public static final java.lang.String TAG_GPS_DATESTAMP = "GPSDateStamp";
+    field public static final java.lang.String TAG_GPS_DEST_BEARING = "GPSDestBearing";
+    field public static final java.lang.String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef";
+    field public static final java.lang.String TAG_GPS_DEST_DISTANCE = "GPSDestDistance";
+    field public static final java.lang.String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef";
+    field public static final java.lang.String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude";
+    field public static final java.lang.String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef";
+    field public static final java.lang.String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude";
+    field public static final java.lang.String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef";
+    field public static final java.lang.String TAG_GPS_DIFFERENTIAL = "GPSDifferential";
+    field public static final java.lang.String TAG_GPS_DOP = "GPSDOP";
+    field public static final java.lang.String TAG_GPS_IMG_DIRECTION = "GPSImgDirection";
+    field public static final java.lang.String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef";
+    field public static final java.lang.String TAG_GPS_LATITUDE = "GPSLatitude";
+    field public static final java.lang.String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
+    field public static final java.lang.String TAG_GPS_LONGITUDE = "GPSLongitude";
+    field public static final java.lang.String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
+    field public static final java.lang.String TAG_GPS_MAP_DATUM = "GPSMapDatum";
+    field public static final java.lang.String TAG_GPS_MEASURE_MODE = "GPSMeasureMode";
+    field public static final java.lang.String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";
+    field public static final java.lang.String TAG_GPS_SATELLITES = "GPSSatellites";
+    field public static final java.lang.String TAG_GPS_SPEED = "GPSSpeed";
+    field public static final java.lang.String TAG_GPS_SPEED_REF = "GPSSpeedRef";
+    field public static final java.lang.String TAG_GPS_STATUS = "GPSStatus";
+    field public static final java.lang.String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
+    field public static final java.lang.String TAG_GPS_TRACK = "GPSTrack";
+    field public static final java.lang.String TAG_GPS_TRACK_REF = "GPSTrackRef";
+    field public static final java.lang.String TAG_GPS_VERSION_ID = "GPSVersionID";
+    field public static final java.lang.String TAG_IMAGE_DESCRIPTION = "ImageDescription";
+    field public static final java.lang.String TAG_IMAGE_LENGTH = "ImageLength";
+    field public static final java.lang.String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID";
+    field public static final java.lang.String TAG_IMAGE_WIDTH = "ImageWidth";
+    field public static final java.lang.String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex";
+    field public static final java.lang.String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings";
+    field public static final java.lang.String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat";
+    field public static final java.lang.String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength";
+    field public static final java.lang.String TAG_LIGHT_SOURCE = "LightSource";
+    field public static final java.lang.String TAG_MAKE = "Make";
+    field public static final java.lang.String TAG_MAKER_NOTE = "MakerNote";
+    field public static final java.lang.String TAG_MAX_APERTURE_VALUE = "MaxApertureValue";
+    field public static final java.lang.String TAG_METERING_MODE = "MeteringMode";
+    field public static final java.lang.String TAG_MODEL = "Model";
+    field public static final java.lang.String TAG_NEW_SUBFILE_TYPE = "NewSubfileType";
+    field public static final java.lang.String TAG_OECF = "OECF";
+    field public static final java.lang.String TAG_ORF_ASPECT_FRAME = "AspectFrame";
+    field public static final java.lang.String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength";
+    field public static final java.lang.String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart";
+    field public static final java.lang.String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage";
+    field public static final java.lang.String TAG_ORIENTATION = "Orientation";
+    field public static final java.lang.String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation";
+    field public static final java.lang.String TAG_PIXEL_X_DIMENSION = "PixelXDimension";
+    field public static final java.lang.String TAG_PIXEL_Y_DIMENSION = "PixelYDimension";
+    field public static final java.lang.String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration";
+    field public static final java.lang.String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities";
+    field public static final java.lang.String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite";
+    field public static final java.lang.String TAG_RELATED_SOUND_FILE = "RelatedSoundFile";
+    field public static final java.lang.String TAG_RESOLUTION_UNIT = "ResolutionUnit";
+    field public static final java.lang.String TAG_ROWS_PER_STRIP = "RowsPerStrip";
+    field public static final java.lang.String TAG_RW2_ISO = "ISO";
+    field public static final java.lang.String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw";
+    field public static final java.lang.String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder";
+    field public static final java.lang.String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder";
+    field public static final java.lang.String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder";
+    field public static final java.lang.String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder";
+    field public static final java.lang.String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel";
+    field public static final java.lang.String TAG_SATURATION = "Saturation";
+    field public static final java.lang.String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType";
+    field public static final java.lang.String TAG_SCENE_TYPE = "SceneType";
+    field public static final java.lang.String TAG_SENSING_METHOD = "SensingMethod";
+    field public static final java.lang.String TAG_SHARPNESS = "Sharpness";
+    field public static final java.lang.String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue";
+    field public static final java.lang.String TAG_SOFTWARE = "Software";
+    field public static final java.lang.String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse";
+    field public static final java.lang.String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity";
+    field public static final java.lang.String TAG_STRIP_BYTE_COUNTS = "StripByteCounts";
+    field public static final java.lang.String TAG_STRIP_OFFSETS = "StripOffsets";
+    field public static final java.lang.String TAG_SUBFILE_TYPE = "SubfileType";
+    field public static final java.lang.String TAG_SUBJECT_AREA = "SubjectArea";
+    field public static final java.lang.String TAG_SUBJECT_DISTANCE = "SubjectDistance";
+    field public static final java.lang.String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange";
+    field public static final java.lang.String TAG_SUBJECT_LOCATION = "SubjectLocation";
+    field public static final java.lang.String TAG_SUBSEC_TIME = "SubSecTime";
+    field public static final java.lang.String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized";
+    field public static final java.lang.String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal";
+    field public static final java.lang.String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength";
+    field public static final java.lang.String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth";
+    field public static final java.lang.String TAG_TRANSFER_FUNCTION = "TransferFunction";
+    field public static final java.lang.String TAG_USER_COMMENT = "UserComment";
+    field public static final java.lang.String TAG_WHITE_BALANCE = "WhiteBalance";
+    field public static final java.lang.String TAG_WHITE_POINT = "WhitePoint";
+    field public static final java.lang.String TAG_X_RESOLUTION = "XResolution";
+    field public static final java.lang.String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients";
+    field public static final java.lang.String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning";
+    field public static final java.lang.String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling";
+    field public static final java.lang.String TAG_Y_RESOLUTION = "YResolution";
+    field public static final int WHITEBALANCE_AUTO = 0; // 0x0
+    field public static final int WHITEBALANCE_MANUAL = 1; // 0x1
+  }
+
+}
+
+package android.support.media.tv {
+
+  public final class Channel {
+    method public static android.support.media.tv.Channel fromCursor(android.database.Cursor);
+    method public int getAppLinkColor();
+    method public android.net.Uri getAppLinkIconUri();
+    method public android.content.Intent getAppLinkIntent() throws java.net.URISyntaxException;
+    method public android.net.Uri getAppLinkIntentUri();
+    method public android.net.Uri getAppLinkPosterArtUri();
+    method public java.lang.String getAppLinkText();
+    method public java.lang.String getDescription();
+    method public java.lang.String getDisplayName();
+    method public java.lang.String getDisplayNumber();
+    method public long getId();
+    method public java.lang.String getInputId();
+    method public byte[] getInternalProviderDataByteArray();
+    method public java.lang.Long getInternalProviderFlag1();
+    method public java.lang.Long getInternalProviderFlag2();
+    method public java.lang.Long getInternalProviderFlag3();
+    method public java.lang.Long getInternalProviderFlag4();
+    method public java.lang.String getInternalProviderId();
+    method public java.lang.String getNetworkAffiliation();
+    method public int getOriginalNetworkId();
+    method public java.lang.String getPackageName();
+    method public int getServiceId();
+    method public java.lang.String getServiceType();
+    method public int getTransportStreamId();
+    method public java.lang.String getType();
+    method public java.lang.String getVideoFormat();
+    method public boolean isBrowsable();
+    method public boolean isLocked();
+    method public boolean isSearchable();
+    method public boolean isTransient();
+    method public android.content.ContentValues toContentValues();
+  }
+
+  public static final class Channel.Builder {
+    ctor public Channel.Builder();
+    ctor public Channel.Builder(android.support.media.tv.Channel);
+    method public android.support.media.tv.Channel build();
+    method public android.support.media.tv.Channel.Builder setAppLinkColor(int);
+    method public android.support.media.tv.Channel.Builder setAppLinkIconUri(android.net.Uri);
+    method public android.support.media.tv.Channel.Builder setAppLinkIntent(android.content.Intent);
+    method public android.support.media.tv.Channel.Builder setAppLinkIntentUri(android.net.Uri);
+    method public android.support.media.tv.Channel.Builder setAppLinkPosterArtUri(android.net.Uri);
+    method public android.support.media.tv.Channel.Builder setAppLinkText(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setDescription(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setDisplayName(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setDisplayNumber(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setInputId(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setInternalProviderData(byte[]);
+    method public android.support.media.tv.Channel.Builder setInternalProviderData(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setInternalProviderFlag1(long);
+    method public android.support.media.tv.Channel.Builder setInternalProviderFlag2(long);
+    method public android.support.media.tv.Channel.Builder setInternalProviderFlag3(long);
+    method public android.support.media.tv.Channel.Builder setInternalProviderFlag4(long);
+    method public android.support.media.tv.Channel.Builder setInternalProviderId(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setNetworkAffiliation(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setOriginalNetworkId(int);
+    method public android.support.media.tv.Channel.Builder setSearchable(boolean);
+    method public android.support.media.tv.Channel.Builder setServiceId(int);
+    method public android.support.media.tv.Channel.Builder setServiceType(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setTransient(boolean);
+    method public android.support.media.tv.Channel.Builder setTransportStreamId(int);
+    method public android.support.media.tv.Channel.Builder setType(java.lang.String);
+    method public android.support.media.tv.Channel.Builder setVideoFormat(java.lang.String);
+  }
+
+  public class ChannelLogoUtils {
+    ctor public ChannelLogoUtils();
+    method public static android.graphics.Bitmap loadChannelLogo(android.content.Context, long);
+    method public static boolean storeChannelLogo(android.content.Context, long, android.net.Uri);
+    method public static boolean storeChannelLogo(android.content.Context, long, android.graphics.Bitmap);
+  }
+
+  public final class PreviewProgram {
+    method public boolean equals(java.lang.Object);
+    method public static android.support.media.tv.PreviewProgram fromCursor(android.database.Cursor);
+    method public long getChannelId();
+    method public int getWeight();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
+  }
+
+  public static final class PreviewProgram.Builder {
+    ctor public PreviewProgram.Builder();
+    ctor public PreviewProgram.Builder(android.support.media.tv.PreviewProgram);
+    method public android.support.media.tv.PreviewProgram build();
+    method public android.support.media.tv.PreviewProgram.Builder setChannelId(long);
+    method public android.support.media.tv.PreviewProgram.Builder setWeight(int);
+  }
+
+  public final class Program implements java.lang.Comparable {
+    method public int compareTo(android.support.media.tv.Program);
+    method public boolean equals(java.lang.Object);
+    method public static android.support.media.tv.Program fromCursor(android.database.Cursor);
+    method public java.lang.String[] getBroadcastGenres();
+    method public long getChannelId();
+    method public long getEndTimeUtcMillis();
+    method public long getStartTimeUtcMillis();
+    method public int hashCode();
+    method public boolean isRecordingProhibited();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
+  }
+
+  public static class Program.Builder {
+    ctor public Program.Builder();
+    ctor public Program.Builder(android.support.media.tv.Program);
+    method public android.support.media.tv.Program build();
+    method public android.support.media.tv.Program.Builder setBroadcastGenres(java.lang.String[]);
+    method public android.support.media.tv.Program.Builder setChannelId(long);
+    method public android.support.media.tv.Program.Builder setEndTimeUtcMillis(long);
+    method public android.support.media.tv.Program.Builder setRecordingProhibited(boolean);
+    method public android.support.media.tv.Program.Builder setStartTimeUtcMillis(long);
+  }
+
+  public final class TvContractCompat {
+    method public static android.net.Uri buildChannelLogoUri(long);
+    method public static android.net.Uri buildChannelLogoUri(android.net.Uri);
+    method public static android.net.Uri buildChannelUri(long);
+    method public static android.net.Uri buildChannelUriForPassthroughInput(java.lang.String);
+    method public static android.net.Uri buildChannelsUriForInput(java.lang.String);
+    method public static java.lang.String buildInputId(android.content.ComponentName);
+    method public static android.net.Uri buildPreviewProgramUri(long);
+    method public static android.net.Uri buildPreviewProgramsUriForChannel(long);
+    method public static android.net.Uri buildPreviewProgramsUriForChannel(android.net.Uri);
+    method public static android.net.Uri buildProgramUri(long);
+    method public static android.net.Uri buildProgramsUriForChannel(long);
+    method public static android.net.Uri buildProgramsUriForChannel(android.net.Uri);
+    method public static android.net.Uri buildProgramsUriForChannel(long, long, long);
+    method public static android.net.Uri buildProgramsUriForChannel(android.net.Uri, long, long);
+    method public static android.net.Uri buildRecordedProgramUri(long);
+    method public static android.net.Uri buildWatchNextProgramUri(long);
+    method public static boolean isChannelUri(android.net.Uri);
+    method public static boolean isChannelUriForPassthroughInput(android.net.Uri);
+    method public static boolean isChannelUriForTunerInput(android.net.Uri);
+    method public static boolean isProgramUri(android.net.Uri);
+    method public static boolean isRecordedProgramUri(android.net.Uri);
+    method public static void requestChannelBrowsable(android.content.Context, long);
+    field public static final java.lang.String ACTION_INITIALIZE_PROGRAMS = "android.media.tv.action.INITIALIZE_PROGRAMS";
+    field public static final java.lang.String ACTION_PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT = "android.media.tv.action.PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT";
+    field public static final java.lang.String ACTION_PREVIEW_PROGRAM_BROWSABLE_DISABLED = "android.media.tv.action.PREVIEW_PROGRAM_BROWSABLE_DISABLED";
+    field public static final java.lang.String ACTION_REQUEST_CHANNEL_BROWSABLE = "android.media.tv.action.REQUEST_CHANNEL_BROWSABLE";
+    field public static final java.lang.String ACTION_WATCH_NEXT_PROGRAM_BROWSABLE_DISABLED = "android.media.tv.action.WATCH_NEXT_PROGRAM_BROWSABLE_DISABLED";
+    field public static final java.lang.String AUTHORITY = "android.media.tv";
+    field public static final java.lang.String EXTRA_CHANNEL_ID = "android.media.tv.extra.CHANNEL_ID";
+    field public static final java.lang.String EXTRA_PREVIEW_PROGRAM_ID = "android.media.tv.extra.PREVIEW_PROGRAM_ID";
+    field public static final java.lang.String EXTRA_WATCH_NEXT_PROGRAM_ID = "android.media.tv.extra.WATCH_NEXT_PROGRAM_ID";
+  }
+
+  public static abstract interface TvContractCompat.BaseTvColumns {
+    field public static final java.lang.String COLUMN_PACKAGE_NAME = "package_name";
+  }
+
+  public static final class TvContractCompat.Channels implements android.support.media.tv.TvContractCompat.BaseTvColumns {
+    method public static java.lang.String getVideoResolution(java.lang.String);
+    field public static final java.lang.String COLUMN_APP_LINK_COLOR = "app_link_color";
+    field public static final java.lang.String COLUMN_APP_LINK_ICON_URI = "app_link_icon_uri";
+    field public static final java.lang.String COLUMN_APP_LINK_INTENT_URI = "app_link_intent_uri";
+    field public static final java.lang.String COLUMN_APP_LINK_POSTER_ART_URI = "app_link_poster_art_uri";
+    field public static final java.lang.String COLUMN_APP_LINK_TEXT = "app_link_text";
+    field public static final java.lang.String COLUMN_BROWSABLE = "browsable";
+    field public static final java.lang.String COLUMN_DESCRIPTION = "description";
+    field public static final java.lang.String COLUMN_DISPLAY_NAME = "display_name";
+    field public static final java.lang.String COLUMN_DISPLAY_NUMBER = "display_number";
+    field public static final java.lang.String COLUMN_INPUT_ID = "input_id";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG1 = "internal_provider_flag1";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG2 = "internal_provider_flag2";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG3 = "internal_provider_flag3";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG4 = "internal_provider_flag4";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_ID = "internal_provider_id";
+    field public static final java.lang.String COLUMN_LOCKED = "locked";
+    field public static final java.lang.String COLUMN_NETWORK_AFFILIATION = "network_affiliation";
+    field public static final java.lang.String COLUMN_ORIGINAL_NETWORK_ID = "original_network_id";
+    field public static final java.lang.String COLUMN_SEARCHABLE = "searchable";
+    field public static final java.lang.String COLUMN_SERVICE_ID = "service_id";
+    field public static final java.lang.String COLUMN_SERVICE_TYPE = "service_type";
+    field public static final java.lang.String COLUMN_TRANSIENT = "transient";
+    field public static final java.lang.String COLUMN_TRANSPORT_STREAM_ID = "transport_stream_id";
+    field public static final java.lang.String COLUMN_TYPE = "type";
+    field public static final java.lang.String COLUMN_VERSION_NUMBER = "version_number";
+    field public static final java.lang.String COLUMN_VIDEO_FORMAT = "video_format";
+    field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/channel";
+    field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/channel";
+    field public static final android.net.Uri CONTENT_URI;
+    field public static final java.lang.String SERVICE_TYPE_AUDIO = "SERVICE_TYPE_AUDIO";
+    field public static final java.lang.String SERVICE_TYPE_AUDIO_VIDEO = "SERVICE_TYPE_AUDIO_VIDEO";
+    field public static final java.lang.String SERVICE_TYPE_OTHER = "SERVICE_TYPE_OTHER";
+    field public static final java.lang.String TYPE_1SEG = "TYPE_1SEG";
+    field public static final java.lang.String TYPE_ATSC_C = "TYPE_ATSC_C";
+    field public static final java.lang.String TYPE_ATSC_M_H = "TYPE_ATSC_M_H";
+    field public static final java.lang.String TYPE_ATSC_T = "TYPE_ATSC_T";
+    field public static final java.lang.String TYPE_CMMB = "TYPE_CMMB";
+    field public static final java.lang.String TYPE_DTMB = "TYPE_DTMB";
+    field public static final java.lang.String TYPE_DVB_C = "TYPE_DVB_C";
+    field public static final java.lang.String TYPE_DVB_C2 = "TYPE_DVB_C2";
+    field public static final java.lang.String TYPE_DVB_H = "TYPE_DVB_H";
+    field public static final java.lang.String TYPE_DVB_S = "TYPE_DVB_S";
+    field public static final java.lang.String TYPE_DVB_S2 = "TYPE_DVB_S2";
+    field public static final java.lang.String TYPE_DVB_SH = "TYPE_DVB_SH";
+    field public static final java.lang.String TYPE_DVB_T = "TYPE_DVB_T";
+    field public static final java.lang.String TYPE_DVB_T2 = "TYPE_DVB_T2";
+    field public static final java.lang.String TYPE_ISDB_C = "TYPE_ISDB_C";
+    field public static final java.lang.String TYPE_ISDB_S = "TYPE_ISDB_S";
+    field public static final java.lang.String TYPE_ISDB_T = "TYPE_ISDB_T";
+    field public static final java.lang.String TYPE_ISDB_TB = "TYPE_ISDB_TB";
+    field public static final java.lang.String TYPE_NTSC = "TYPE_NTSC";
+    field public static final java.lang.String TYPE_OTHER = "TYPE_OTHER";
+    field public static final java.lang.String TYPE_PAL = "TYPE_PAL";
+    field public static final java.lang.String TYPE_PREVIEW = "TYPE_PREVIEW";
+    field public static final java.lang.String TYPE_SECAM = "TYPE_SECAM";
+    field public static final java.lang.String TYPE_S_DMB = "TYPE_S_DMB";
+    field public static final java.lang.String TYPE_T_DMB = "TYPE_T_DMB";
+    field public static final java.lang.String VIDEO_FORMAT_1080I = "VIDEO_FORMAT_1080I";
+    field public static final java.lang.String VIDEO_FORMAT_1080P = "VIDEO_FORMAT_1080P";
+    field public static final java.lang.String VIDEO_FORMAT_2160P = "VIDEO_FORMAT_2160P";
+    field public static final java.lang.String VIDEO_FORMAT_240P = "VIDEO_FORMAT_240P";
+    field public static final java.lang.String VIDEO_FORMAT_360P = "VIDEO_FORMAT_360P";
+    field public static final java.lang.String VIDEO_FORMAT_4320P = "VIDEO_FORMAT_4320P";
+    field public static final java.lang.String VIDEO_FORMAT_480I = "VIDEO_FORMAT_480I";
+    field public static final java.lang.String VIDEO_FORMAT_480P = "VIDEO_FORMAT_480P";
+    field public static final java.lang.String VIDEO_FORMAT_576I = "VIDEO_FORMAT_576I";
+    field public static final java.lang.String VIDEO_FORMAT_576P = "VIDEO_FORMAT_576P";
+    field public static final java.lang.String VIDEO_FORMAT_720P = "VIDEO_FORMAT_720P";
+    field public static final java.lang.String VIDEO_RESOLUTION_ED = "VIDEO_RESOLUTION_ED";
+    field public static final java.lang.String VIDEO_RESOLUTION_FHD = "VIDEO_RESOLUTION_FHD";
+    field public static final java.lang.String VIDEO_RESOLUTION_HD = "VIDEO_RESOLUTION_HD";
+    field public static final java.lang.String VIDEO_RESOLUTION_SD = "VIDEO_RESOLUTION_SD";
+    field public static final java.lang.String VIDEO_RESOLUTION_UHD = "VIDEO_RESOLUTION_UHD";
+  }
+
+  public static final class TvContractCompat.Channels.Logo {
+    field public static final java.lang.String CONTENT_DIRECTORY = "logo";
+  }
+
+  public static final class TvContractCompat.PreviewPrograms implements android.support.media.tv.TvContractCompat.BaseTvColumns {
+    field public static final int ASPECT_RATIO_16_9 = 0; // 0x0
+    field public static final int ASPECT_RATIO_1_1 = 3; // 0x3
+    field public static final int ASPECT_RATIO_2_3 = 4; // 0x4
+    field public static final int ASPECT_RATIO_3_2 = 1; // 0x1
+    field public static final int ASPECT_RATIO_4_3 = 2; // 0x2
+    field public static final int AVAILABILITY_AVAILABLE = 0; // 0x0
+    field public static final int AVAILABILITY_FREE_WITH_SUBSCRIPTION = 1; // 0x1
+    field public static final int AVAILABILITY_PAID_CONTENT = 2; // 0x2
+    field public static final java.lang.String COLUMN_AUDIO_LANGUAGE = "audio_language";
+    field public static final java.lang.String COLUMN_AUTHOR = "author";
+    field public static final java.lang.String COLUMN_AVAILABILITY = "availability";
+    field public static final java.lang.String COLUMN_BROWSABLE = "browsable";
+    field public static final java.lang.String COLUMN_CANONICAL_GENRE = "canonical_genre";
+    field public static final java.lang.String COLUMN_CHANNEL_ID = "channel_id";
+    field public static final java.lang.String COLUMN_CONTENT_ID = "content_id";
+    field public static final java.lang.String COLUMN_CONTENT_RATING = "content_rating";
+    field public static final java.lang.String COLUMN_DURATION_MILLIS = "duration_millis";
+    field public static final java.lang.String COLUMN_EPISODE_DISPLAY_NUMBER = "episode_display_number";
+    field public static final java.lang.String COLUMN_EPISODE_TITLE = "episode_title";
+    field public static final java.lang.String COLUMN_INTENT_URI = "intent_uri";
+    field public static final java.lang.String COLUMN_INTERACTION_COUNT = "interaction_count";
+    field public static final java.lang.String COLUMN_INTERACTION_TYPE = "interaction_type";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG1 = "internal_provider_flag1";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG2 = "internal_provider_flag2";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG3 = "internal_provider_flag3";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG4 = "internal_provider_flag4";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_ID = "internal_provider_id";
+    field public static final java.lang.String COLUMN_ITEM_COUNT = "item_count";
+    field public static final java.lang.String COLUMN_LAST_PLAYBACK_POSITION_MILLIS = "last_playback_position_millis";
+    field public static final java.lang.String COLUMN_LIVE = "live";
+    field public static final java.lang.String COLUMN_LOGO_URI = "logo_uri";
+    field public static final java.lang.String COLUMN_LONG_DESCRIPTION = "long_description";
+    field public static final java.lang.String COLUMN_OFFER_PRICE = "offer_price";
+    field public static final java.lang.String COLUMN_POSTER_ART_ASPECT_RATIO = "poster_art_aspect_ratio";
+    field public static final java.lang.String COLUMN_POSTER_ART_URI = "poster_art_uri";
+    field public static final java.lang.String COLUMN_PREVIEW_VIDEO_URI = "preview_video_uri";
+    field public static final java.lang.String COLUMN_RELEASE_DATE = "release_date";
+    field public static final java.lang.String COLUMN_REVIEW_RATING = "review_rating";
+    field public static final java.lang.String COLUMN_REVIEW_RATING_STYLE = "review_rating_style";
+    field public static final java.lang.String COLUMN_SEARCHABLE = "searchable";
+    field public static final java.lang.String COLUMN_SEASON_DISPLAY_NUMBER = "season_display_number";
+    field public static final java.lang.String COLUMN_SEASON_TITLE = "season_title";
+    field public static final java.lang.String COLUMN_SHORT_DESCRIPTION = "short_description";
+    field public static final java.lang.String COLUMN_STARTING_PRICE = "starting_price";
+    field public static final java.lang.String COLUMN_THUMBNAIL_ASPECT_RATIO = "poster_thumbnail_aspect_ratio";
+    field public static final java.lang.String COLUMN_THUMBNAIL_URI = "thumbnail_uri";
+    field public static final java.lang.String COLUMN_TITLE = "title";
+    field public static final java.lang.String COLUMN_TRANSIENT = "transient";
+    field public static final java.lang.String COLUMN_TYPE = "type";
+    field public static final java.lang.String COLUMN_VERSION_NUMBER = "version_number";
+    field public static final java.lang.String COLUMN_VIDEO_HEIGHT = "video_height";
+    field public static final java.lang.String COLUMN_VIDEO_WIDTH = "video_width";
+    field public static final java.lang.String COLUMN_WEIGHT = "weight";
+    field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/preview_program";
+    field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/preview_program";
+    field public static final android.net.Uri CONTENT_URI;
+    field public static final int INTERACTION_TYPE_FANS = 3; // 0x3
+    field public static final int INTERACTION_TYPE_FOLLOWERS = 2; // 0x2
+    field public static final int INTERACTION_TYPE_LIKES = 4; // 0x4
+    field public static final int INTERACTION_TYPE_LISTENS = 1; // 0x1
+    field public static final int INTERACTION_TYPE_THUMBS = 5; // 0x5
+    field public static final int INTERACTION_TYPE_VIEWERS = 6; // 0x6
+    field public static final int INTERACTION_TYPE_VIEWS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_PERCENTAGE = 2; // 0x2
+    field public static final int REVIEW_RATING_STYLE_STARS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_THUMBS_UP_DOWN = 1; // 0x1
+    field public static final int TYPE_ALBUM = 8; // 0x8
+    field public static final int TYPE_ARTIST = 9; // 0x9
+    field public static final int TYPE_CHANNEL = 6; // 0x6
+    field public static final int TYPE_CLIP = 4; // 0x4
+    field public static final int TYPE_EVENT = 5; // 0x5
+    field public static final int TYPE_MOVIE = 0; // 0x0
+    field public static final int TYPE_PLAYLIST = 10; // 0xa
+    field public static final int TYPE_STATION = 11; // 0xb
+    field public static final int TYPE_TRACK = 7; // 0x7
+    field public static final int TYPE_TV_EPISODE = 3; // 0x3
+    field public static final int TYPE_TV_SEASON = 2; // 0x2
+    field public static final int TYPE_TV_SERIES = 1; // 0x1
+  }
+
+  public static final class TvContractCompat.Programs implements android.support.media.tv.TvContractCompat.BaseTvColumns {
+    field public static final java.lang.String COLUMN_AUDIO_LANGUAGE = "audio_language";
+    field public static final java.lang.String COLUMN_BROADCAST_GENRE = "broadcast_genre";
+    field public static final java.lang.String COLUMN_CANONICAL_GENRE = "canonical_genre";
+    field public static final java.lang.String COLUMN_CHANNEL_ID = "channel_id";
+    field public static final java.lang.String COLUMN_CONTENT_RATING = "content_rating";
+    field public static final java.lang.String COLUMN_END_TIME_UTC_MILLIS = "end_time_utc_millis";
+    field public static final java.lang.String COLUMN_EPISODE_DISPLAY_NUMBER = "episode_display_number";
+    field public static final deprecated java.lang.String COLUMN_EPISODE_NUMBER = "episode_number";
+    field public static final java.lang.String COLUMN_EPISODE_TITLE = "episode_title";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG1 = "internal_provider_flag1";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG2 = "internal_provider_flag2";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG3 = "internal_provider_flag3";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG4 = "internal_provider_flag4";
+    field public static final java.lang.String COLUMN_LONG_DESCRIPTION = "long_description";
+    field public static final java.lang.String COLUMN_POSTER_ART_URI = "poster_art_uri";
+    field public static final java.lang.String COLUMN_RECORDING_PROHIBITED = "recording_prohibited";
+    field public static final java.lang.String COLUMN_REVIEW_RATING = "review_rating";
+    field public static final java.lang.String COLUMN_REVIEW_RATING_STYLE = "review_rating_style";
+    field public static final java.lang.String COLUMN_SEARCHABLE = "searchable";
+    field public static final java.lang.String COLUMN_SEASON_DISPLAY_NUMBER = "season_display_number";
+    field public static final deprecated java.lang.String COLUMN_SEASON_NUMBER = "season_number";
+    field public static final java.lang.String COLUMN_SEASON_TITLE = "season_title";
+    field public static final java.lang.String COLUMN_SHORT_DESCRIPTION = "short_description";
+    field public static final java.lang.String COLUMN_START_TIME_UTC_MILLIS = "start_time_utc_millis";
+    field public static final java.lang.String COLUMN_THUMBNAIL_URI = "thumbnail_uri";
+    field public static final java.lang.String COLUMN_TITLE = "title";
+    field public static final java.lang.String COLUMN_VERSION_NUMBER = "version_number";
+    field public static final java.lang.String COLUMN_VIDEO_HEIGHT = "video_height";
+    field public static final java.lang.String COLUMN_VIDEO_WIDTH = "video_width";
+    field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/program";
+    field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/program";
+    field public static final android.net.Uri CONTENT_URI;
+    field public static final int REVIEW_RATING_STYLE_PERCENTAGE = 2; // 0x2
+    field public static final int REVIEW_RATING_STYLE_STARS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_THUMBS_UP_DOWN = 1; // 0x1
+  }
+
+  public static final class TvContractCompat.Programs.Genres {
+    method public static java.lang.String[] decode(java.lang.String);
+    method public static java.lang.String encode(java.lang.String...);
+    method public static boolean isCanonical(java.lang.String);
+    field public static final java.lang.String ANIMAL_WILDLIFE = "ANIMAL_WILDLIFE";
+    field public static final java.lang.String ARTS = "ARTS";
+    field public static final java.lang.String COMEDY = "COMEDY";
+    field public static final java.lang.String DRAMA = "DRAMA";
+    field public static final java.lang.String EDUCATION = "EDUCATION";
+    field public static final java.lang.String ENTERTAINMENT = "ENTERTAINMENT";
+    field public static final java.lang.String FAMILY_KIDS = "FAMILY_KIDS";
+    field public static final java.lang.String GAMING = "GAMING";
+    field public static final java.lang.String LIFE_STYLE = "LIFE_STYLE";
+    field public static final java.lang.String MOVIES = "MOVIES";
+    field public static final java.lang.String MUSIC = "MUSIC";
+    field public static final java.lang.String NEWS = "NEWS";
+    field public static final java.lang.String PREMIER = "PREMIER";
+    field public static final java.lang.String SHOPPING = "SHOPPING";
+    field public static final java.lang.String SPORTS = "SPORTS";
+    field public static final java.lang.String TECH_SCIENCE = "TECH_SCIENCE";
+    field public static final java.lang.String TRAVEL = "TRAVEL";
+  }
+
+  public static final class TvContractCompat.RecordedPrograms implements android.support.media.tv.TvContractCompat.BaseTvColumns {
+    field public static final java.lang.String COLUMN_AUDIO_LANGUAGE = "audio_language";
+    field public static final java.lang.String COLUMN_BROADCAST_GENRE = "broadcast_genre";
+    field public static final java.lang.String COLUMN_CANONICAL_GENRE = "canonical_genre";
+    field public static final java.lang.String COLUMN_CHANNEL_ID = "channel_id";
+    field public static final java.lang.String COLUMN_CONTENT_RATING = "content_rating";
+    field public static final java.lang.String COLUMN_END_TIME_UTC_MILLIS = "end_time_utc_millis";
+    field public static final java.lang.String COLUMN_EPISODE_DISPLAY_NUMBER = "episode_display_number";
+    field public static final java.lang.String COLUMN_EPISODE_TITLE = "episode_title";
+    field public static final java.lang.String COLUMN_INPUT_ID = "input_id";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG1 = "internal_provider_flag1";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG2 = "internal_provider_flag2";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG3 = "internal_provider_flag3";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG4 = "internal_provider_flag4";
+    field public static final java.lang.String COLUMN_LONG_DESCRIPTION = "long_description";
+    field public static final java.lang.String COLUMN_POSTER_ART_URI = "poster_art_uri";
+    field public static final java.lang.String COLUMN_RECORDING_DATA_BYTES = "recording_data_bytes";
+    field public static final java.lang.String COLUMN_RECORDING_DATA_URI = "recording_data_uri";
+    field public static final java.lang.String COLUMN_RECORDING_DURATION_MILLIS = "recording_duration_millis";
+    field public static final java.lang.String COLUMN_RECORDING_EXPIRE_TIME_UTC_MILLIS = "recording_expire_time_utc_millis";
+    field public static final java.lang.String COLUMN_REVIEW_RATING = "review_rating";
+    field public static final java.lang.String COLUMN_REVIEW_RATING_STYLE = "review_rating_style";
+    field public static final java.lang.String COLUMN_SEARCHABLE = "searchable";
+    field public static final java.lang.String COLUMN_SEASON_DISPLAY_NUMBER = "season_display_number";
+    field public static final java.lang.String COLUMN_SEASON_TITLE = "season_title";
+    field public static final java.lang.String COLUMN_SHORT_DESCRIPTION = "short_description";
+    field public static final java.lang.String COLUMN_START_TIME_UTC_MILLIS = "start_time_utc_millis";
+    field public static final java.lang.String COLUMN_THUMBNAIL_URI = "thumbnail_uri";
+    field public static final java.lang.String COLUMN_TITLE = "title";
+    field public static final java.lang.String COLUMN_VERSION_NUMBER = "version_number";
+    field public static final java.lang.String COLUMN_VIDEO_HEIGHT = "video_height";
+    field public static final java.lang.String COLUMN_VIDEO_WIDTH = "video_width";
+    field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/recorded_program";
+    field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/recorded_program";
+    field public static final android.net.Uri CONTENT_URI;
+    field public static final int REVIEW_RATING_STYLE_PERCENTAGE = 2; // 0x2
+    field public static final int REVIEW_RATING_STYLE_STARS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_THUMBS_UP_DOWN = 1; // 0x1
+  }
+
+  public static final class TvContractCompat.WatchNextPrograms implements android.support.media.tv.TvContractCompat.BaseTvColumns {
+    field public static final int ASPECT_RATIO_16_9 = 0; // 0x0
+    field public static final int ASPECT_RATIO_1_1 = 3; // 0x3
+    field public static final int ASPECT_RATIO_2_3 = 4; // 0x4
+    field public static final int ASPECT_RATIO_3_2 = 1; // 0x1
+    field public static final int ASPECT_RATIO_4_3 = 2; // 0x2
+    field public static final int AVAILABILITY_AVAILABLE = 0; // 0x0
+    field public static final int AVAILABILITY_FREE_WITH_SUBSCRIPTION = 1; // 0x1
+    field public static final int AVAILABILITY_PAID_CONTENT = 2; // 0x2
+    field public static final java.lang.String COLUMN_AUDIO_LANGUAGE = "audio_language";
+    field public static final java.lang.String COLUMN_AUTHOR = "author";
+    field public static final java.lang.String COLUMN_AVAILABILITY = "availability";
+    field public static final java.lang.String COLUMN_BROWSABLE = "browsable";
+    field public static final java.lang.String COLUMN_CANONICAL_GENRE = "canonical_genre";
+    field public static final java.lang.String COLUMN_CONTENT_ID = "content_id";
+    field public static final java.lang.String COLUMN_CONTENT_RATING = "content_rating";
+    field public static final java.lang.String COLUMN_DURATION_MILLIS = "duration_millis";
+    field public static final java.lang.String COLUMN_EPISODE_DISPLAY_NUMBER = "episode_display_number";
+    field public static final java.lang.String COLUMN_EPISODE_TITLE = "episode_title";
+    field public static final java.lang.String COLUMN_INTENT_URI = "intent_uri";
+    field public static final java.lang.String COLUMN_INTERACTION_COUNT = "interaction_count";
+    field public static final java.lang.String COLUMN_INTERACTION_TYPE = "interaction_type";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG1 = "internal_provider_flag1";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG2 = "internal_provider_flag2";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG3 = "internal_provider_flag3";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_FLAG4 = "internal_provider_flag4";
+    field public static final java.lang.String COLUMN_INTERNAL_PROVIDER_ID = "internal_provider_id";
+    field public static final java.lang.String COLUMN_ITEM_COUNT = "item_count";
+    field public static final java.lang.String COLUMN_LAST_ENGAGEMENT_TIME_UTC_MILLIS = "last_engagement_time_utc_millis";
+    field public static final java.lang.String COLUMN_LAST_PLAYBACK_POSITION_MILLIS = "last_playback_position_millis";
+    field public static final java.lang.String COLUMN_LIVE = "live";
+    field public static final java.lang.String COLUMN_LOGO_URI = "logo_uri";
+    field public static final java.lang.String COLUMN_LONG_DESCRIPTION = "long_description";
+    field public static final java.lang.String COLUMN_OFFER_PRICE = "offer_price";
+    field public static final java.lang.String COLUMN_POSTER_ART_ASPECT_RATIO = "poster_art_aspect_ratio";
+    field public static final java.lang.String COLUMN_POSTER_ART_URI = "poster_art_uri";
+    field public static final java.lang.String COLUMN_PREVIEW_VIDEO_URI = "preview_video_uri";
+    field public static final java.lang.String COLUMN_RELEASE_DATE = "release_date";
+    field public static final java.lang.String COLUMN_REVIEW_RATING = "review_rating";
+    field public static final java.lang.String COLUMN_REVIEW_RATING_STYLE = "review_rating_style";
+    field public static final java.lang.String COLUMN_SEARCHABLE = "searchable";
+    field public static final java.lang.String COLUMN_SEASON_DISPLAY_NUMBER = "season_display_number";
+    field public static final java.lang.String COLUMN_SEASON_TITLE = "season_title";
+    field public static final java.lang.String COLUMN_SHORT_DESCRIPTION = "short_description";
+    field public static final java.lang.String COLUMN_STARTING_PRICE = "starting_price";
+    field public static final java.lang.String COLUMN_THUMBNAIL_ASPECT_RATIO = "poster_thumbnail_aspect_ratio";
+    field public static final java.lang.String COLUMN_THUMBNAIL_URI = "thumbnail_uri";
+    field public static final java.lang.String COLUMN_TITLE = "title";
+    field public static final java.lang.String COLUMN_TRANSIENT = "transient";
+    field public static final java.lang.String COLUMN_TYPE = "type";
+    field public static final java.lang.String COLUMN_VERSION_NUMBER = "version_number";
+    field public static final java.lang.String COLUMN_VIDEO_HEIGHT = "video_height";
+    field public static final java.lang.String COLUMN_VIDEO_WIDTH = "video_width";
+    field public static final java.lang.String COLUMN_WATCH_NEXT_TYPE = "watch_next_type";
+    field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/watch_next_program";
+    field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/watch_next_program";
+    field public static final android.net.Uri CONTENT_URI;
+    field public static final int INTERACTION_TYPE_FANS = 3; // 0x3
+    field public static final int INTERACTION_TYPE_FOLLOWERS = 2; // 0x2
+    field public static final int INTERACTION_TYPE_LIKES = 4; // 0x4
+    field public static final int INTERACTION_TYPE_LISTENS = 1; // 0x1
+    field public static final int INTERACTION_TYPE_THUMBS = 5; // 0x5
+    field public static final int INTERACTION_TYPE_VIEWERS = 6; // 0x6
+    field public static final int INTERACTION_TYPE_VIEWS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_PERCENTAGE = 2; // 0x2
+    field public static final int REVIEW_RATING_STYLE_STARS = 0; // 0x0
+    field public static final int REVIEW_RATING_STYLE_THUMBS_UP_DOWN = 1; // 0x1
+    field public static final int TYPE_ALBUM = 8; // 0x8
+    field public static final int TYPE_ARTIST = 9; // 0x9
+    field public static final int TYPE_CHANNEL = 6; // 0x6
+    field public static final int TYPE_CLIP = 4; // 0x4
+    field public static final int TYPE_EVENT = 5; // 0x5
+    field public static final int TYPE_MOVIE = 0; // 0x0
+    field public static final int TYPE_PLAYLIST = 10; // 0xa
+    field public static final int TYPE_STATION = 11; // 0xb
+    field public static final int TYPE_TRACK = 7; // 0x7
+    field public static final int TYPE_TV_EPISODE = 3; // 0x3
+    field public static final int TYPE_TV_SEASON = 2; // 0x2
+    field public static final int TYPE_TV_SERIES = 1; // 0x1
+    field public static final int WATCH_NEXT_TYPE_CONTINUE = 0; // 0x0
+    field public static final int WATCH_NEXT_TYPE_NEW = 2; // 0x2
+    field public static final int WATCH_NEXT_TYPE_NEXT = 1; // 0x1
+    field public static final int WATCH_NEXT_TYPE_WATCHLIST = 3; // 0x3
+  }
+
+  public final class WatchNextProgram {
+    method public boolean equals(java.lang.Object);
+    method public static android.support.media.tv.WatchNextProgram fromCursor(android.database.Cursor);
+    method public long getLastEngagementTimeUtcMillis();
+    method public int getWatchNextType();
+    method public android.content.ContentValues toContentValues();
+    method public java.lang.String toString();
+  }
+
+  public static final class WatchNextProgram.Builder {
+    ctor public WatchNextProgram.Builder();
+    ctor public WatchNextProgram.Builder(android.support.media.tv.WatchNextProgram);
+    method public android.support.media.tv.WatchNextProgram build();
+    method public android.support.media.tv.WatchNextProgram.Builder setLastEngagementTimeUtcMillis(long);
+    method public android.support.media.tv.WatchNextProgram.Builder setWatchNextType(int);
+  }
+
+}
+
+package android.support.percent {
+
+  public deprecated class PercentFrameLayout extends android.widget.FrameLayout {
+    ctor public PercentFrameLayout(android.content.Context);
+    ctor public PercentFrameLayout(android.content.Context, android.util.AttributeSet);
+    ctor public PercentFrameLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.percent.PercentFrameLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.percent.PercentFrameLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+  }
+
+  public static deprecated class PercentFrameLayout.LayoutParams extends android.widget.FrameLayout.LayoutParams implements android.support.percent.PercentLayoutHelper.PercentLayoutParams {
+    ctor public PercentFrameLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public PercentFrameLayout.LayoutParams(int, int);
+    ctor public PercentFrameLayout.LayoutParams(int, int, int);
+    ctor public PercentFrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public PercentFrameLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public PercentFrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams);
+    ctor public PercentFrameLayout.LayoutParams(android.support.percent.PercentFrameLayout.LayoutParams);
+    method public android.support.percent.PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo();
+  }
+
+  public deprecated class PercentLayoutHelper {
+    ctor public PercentLayoutHelper(android.view.ViewGroup);
+    method public void adjustChildren(int, int);
+    method public static void fetchWidthAndHeight(android.view.ViewGroup.LayoutParams, android.content.res.TypedArray, int, int);
+    method public static android.support.percent.PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo(android.content.Context, android.util.AttributeSet);
+    method public boolean handleMeasuredStateTooSmall();
+    method public void restoreOriginalParams();
+  }
+
+  public static deprecated class PercentLayoutHelper.PercentLayoutInfo {
+    ctor public PercentLayoutHelper.PercentLayoutInfo();
+    method public void fillLayoutParams(android.view.ViewGroup.LayoutParams, int, int);
+    method public deprecated void fillMarginLayoutParams(android.view.ViewGroup.MarginLayoutParams, int, int);
+    method public void fillMarginLayoutParams(android.view.View, android.view.ViewGroup.MarginLayoutParams, int, int);
+    method public void restoreLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public void restoreMarginLayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    field public float aspectRatio;
+    field public float bottomMarginPercent;
+    field public float endMarginPercent;
+    field public float heightPercent;
+    field public float leftMarginPercent;
+    field public float rightMarginPercent;
+    field public float startMarginPercent;
+    field public float topMarginPercent;
+    field public float widthPercent;
+  }
+
+  public static abstract deprecated interface PercentLayoutHelper.PercentLayoutParams {
+    method public abstract android.support.percent.PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo();
+  }
+
+  public deprecated class PercentRelativeLayout extends android.widget.RelativeLayout {
+    ctor public PercentRelativeLayout(android.content.Context);
+    ctor public PercentRelativeLayout(android.content.Context, android.util.AttributeSet);
+    ctor public PercentRelativeLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.percent.PercentRelativeLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.percent.PercentRelativeLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+  }
+
+  public static deprecated class PercentRelativeLayout.LayoutParams extends android.widget.RelativeLayout.LayoutParams implements android.support.percent.PercentLayoutHelper.PercentLayoutParams {
+    ctor public PercentRelativeLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public PercentRelativeLayout.LayoutParams(int, int);
+    ctor public PercentRelativeLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public PercentRelativeLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    method public android.support.percent.PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo();
+  }
+
+}
+
+package android.support.text.emoji {
+
+  public class EmojiCompat {
+    method public static android.support.text.emoji.EmojiCompat get();
+    method public java.lang.String getAssetSignature();
+    method public int getLoadState();
+    method public static boolean handleDeleteSurroundingText(android.view.inputmethod.InputConnection, android.text.Editable, int, int, boolean);
+    method public static boolean handleOnKeyDown(android.text.Editable, int, android.view.KeyEvent);
+    method public boolean hasEmojiGlyph(java.lang.CharSequence);
+    method public boolean hasEmojiGlyph(java.lang.CharSequence, int);
+    method public static android.support.text.emoji.EmojiCompat init(android.support.text.emoji.EmojiCompat.Config);
+    method public java.lang.CharSequence process(java.lang.CharSequence);
+    method public java.lang.CharSequence process(java.lang.CharSequence, int, int);
+    method public java.lang.CharSequence process(java.lang.CharSequence, int, int, int);
+    method public java.lang.CharSequence process(java.lang.CharSequence, int, int, int, int);
+    method public void registerInitCallback(android.support.text.emoji.EmojiCompat.InitCallback);
+    method public void unregisterInitCallback(android.support.text.emoji.EmojiCompat.InitCallback);
+    field public static final java.lang.String EDITOR_INFO_METAVERSION_KEY = "android.support.text.emoji.emojiCompat_metadataVersion";
+    field public static final java.lang.String EDITOR_INFO_REPLACE_ALL_KEY = "android.support.text.emoji.emojiCompat_replaceAll";
+    field public static final int LOAD_STATE_FAILED = 2; // 0x2
+    field public static final int LOAD_STATE_LOADING = 0; // 0x0
+    field public static final int LOAD_STATE_SUCCEEDED = 1; // 0x1
+    field public static final int REPLACE_STRATEGY_ALL = 1; // 0x1
+    field public static final int REPLACE_STRATEGY_DEFAULT = 0; // 0x0
+    field public static final int REPLACE_STRATEGY_NON_EXISTENT = 2; // 0x2
+  }
+
+  public static abstract class EmojiCompat.Config {
+    ctor protected EmojiCompat.Config(android.support.text.emoji.EmojiCompat.MetadataRepoLoader);
+    method protected final android.support.text.emoji.EmojiCompat.MetadataRepoLoader getMetadataRepoLoader();
+    method public android.support.text.emoji.EmojiCompat.Config registerInitCallback(android.support.text.emoji.EmojiCompat.InitCallback);
+    method public android.support.text.emoji.EmojiCompat.Config setEmojiSpanIndicatorColor(int);
+    method public android.support.text.emoji.EmojiCompat.Config setEmojiSpanIndicatorEnabled(boolean);
+    method public android.support.text.emoji.EmojiCompat.Config setReplaceAll(boolean);
+    method public android.support.text.emoji.EmojiCompat.Config unregisterInitCallback(android.support.text.emoji.EmojiCompat.InitCallback);
+  }
+
+  public static abstract class EmojiCompat.InitCallback {
+    ctor public EmojiCompat.InitCallback();
+    method public void onFailed(java.lang.Throwable);
+    method public void onInitialized();
+  }
+
+  public static abstract interface EmojiCompat.MetadataRepoLoader {
+    method public abstract void load(android.support.text.emoji.EmojiCompat.MetadataRepoLoaderCallback);
+  }
+
+  public static abstract class EmojiCompat.MetadataRepoLoaderCallback {
+    ctor public EmojiCompat.MetadataRepoLoaderCallback();
+    method public abstract void onFailed(java.lang.Throwable);
+    method public abstract void onLoaded(android.support.text.emoji.MetadataRepo);
+  }
+
+  public abstract class EmojiSpan extends android.text.style.ReplacementSpan {
+    method public int getSize(android.graphics.Paint, java.lang.CharSequence, int, int, android.graphics.Paint.FontMetricsInt);
+  }
+
+  public class FontRequestEmojiCompatConfig extends android.support.text.emoji.EmojiCompat.Config {
+    ctor public FontRequestEmojiCompatConfig(android.content.Context, android.support.v4.provider.FontRequest);
+    method public android.support.text.emoji.FontRequestEmojiCompatConfig setHandler(android.os.Handler);
+    method public android.support.text.emoji.FontRequestEmojiCompatConfig setRetryPolicy(android.support.text.emoji.FontRequestEmojiCompatConfig.RetryPolicy);
+  }
+
+  public static class FontRequestEmojiCompatConfig.ExponentialBackoffRetryPolicy extends android.support.text.emoji.FontRequestEmojiCompatConfig.RetryPolicy {
+    ctor public FontRequestEmojiCompatConfig.ExponentialBackoffRetryPolicy(long);
+    method public long getRetryDelay();
+  }
+
+  public static abstract class FontRequestEmojiCompatConfig.RetryPolicy {
+    ctor public FontRequestEmojiCompatConfig.RetryPolicy();
+    method public abstract long getRetryDelay();
+  }
+
+  public final class MetadataRepo {
+    method public static android.support.text.emoji.MetadataRepo create(android.graphics.Typeface, java.io.InputStream) throws java.io.IOException;
+    method public static android.support.text.emoji.MetadataRepo create(android.graphics.Typeface, java.nio.ByteBuffer) throws java.io.IOException;
+    method public static android.support.text.emoji.MetadataRepo create(android.content.res.AssetManager, java.lang.String) throws java.io.IOException;
+  }
+
+}
+
+package android.support.text.emoji.bundled {
+
+  public class BundledEmojiCompatConfig extends android.support.text.emoji.EmojiCompat.Config {
+    ctor public BundledEmojiCompatConfig(android.content.Context);
+  }
+
+}
+
+package android.support.text.emoji.widget {
+
+  public class EmojiAppCompatButton extends android.support.v7.widget.AppCompatButton {
+    ctor public EmojiAppCompatButton(android.content.Context);
+    ctor public EmojiAppCompatButton(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiAppCompatButton(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class EmojiAppCompatEditText extends android.support.v7.widget.AppCompatEditText {
+    ctor public EmojiAppCompatEditText(android.content.Context);
+    ctor public EmojiAppCompatEditText(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiAppCompatEditText(android.content.Context, android.util.AttributeSet, int);
+    method public int getMaxEmojiCount();
+    method public void setMaxEmojiCount(int);
+  }
+
+  public class EmojiAppCompatTextView extends android.support.v7.widget.AppCompatTextView {
+    ctor public EmojiAppCompatTextView(android.content.Context);
+    ctor public EmojiAppCompatTextView(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiAppCompatTextView(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class EmojiButton extends android.widget.Button {
+    ctor public EmojiButton(android.content.Context);
+    ctor public EmojiButton(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiButton(android.content.Context, android.util.AttributeSet, int);
+    ctor public EmojiButton(android.content.Context, android.util.AttributeSet, int, int);
+  }
+
+  public class EmojiEditText extends android.widget.EditText {
+    ctor public EmojiEditText(android.content.Context);
+    ctor public EmojiEditText(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiEditText(android.content.Context, android.util.AttributeSet, int);
+    ctor public EmojiEditText(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getMaxEmojiCount();
+    method public void setMaxEmojiCount(int);
+  }
+
+  public final class EmojiEditTextHelper {
+    ctor public EmojiEditTextHelper(android.widget.EditText);
+    method public android.text.method.KeyListener getKeyListener(android.text.method.KeyListener);
+    method public int getMaxEmojiCount();
+    method public android.view.inputmethod.InputConnection onCreateInputConnection(android.view.inputmethod.InputConnection, android.view.inputmethod.EditorInfo);
+    method public void setMaxEmojiCount(int);
+  }
+
+  public class EmojiExtractTextLayout extends android.widget.LinearLayout {
+    ctor public EmojiExtractTextLayout(android.content.Context);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public EmojiExtractTextLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getEmojiReplaceStrategy();
+    method public void onUpdateExtractingViews(android.inputmethodservice.InputMethodService, android.view.inputmethod.EditorInfo);
+    method public void setEmojiReplaceStrategy(int);
+  }
+
+  public class EmojiTextView extends android.widget.TextView {
+    ctor public EmojiTextView(android.content.Context);
+    ctor public EmojiTextView(android.content.Context, android.util.AttributeSet);
+    ctor public EmojiTextView(android.content.Context, android.util.AttributeSet, int);
+    ctor public EmojiTextView(android.content.Context, android.util.AttributeSet, int, int);
+  }
+
+  public final class EmojiTextViewHelper {
+    ctor public EmojiTextViewHelper(android.widget.TextView);
+    method public android.text.InputFilter[] getFilters(android.text.InputFilter[]);
+    method public void setAllCaps(boolean);
+    method public void updateTransformationMethod();
+    method public android.text.method.TransformationMethod wrapTransformationMethod(android.text.method.TransformationMethod);
+  }
+
+}
+
+package android.support.transition {
+
+  public class ArcMotion extends android.support.transition.PathMotion {
+    ctor public ArcMotion();
+    ctor public ArcMotion(android.content.Context, android.util.AttributeSet);
+    method public float getMaximumAngle();
+    method public float getMinimumHorizontalAngle();
+    method public float getMinimumVerticalAngle();
+    method public android.graphics.Path getPath(float, float, float, float);
+    method public void setMaximumAngle(float);
+    method public void setMinimumHorizontalAngle(float);
+    method public void setMinimumVerticalAngle(float);
+  }
+
+  public class AutoTransition extends android.support.transition.TransitionSet {
+    ctor public AutoTransition();
+    ctor public AutoTransition(android.content.Context, android.util.AttributeSet);
+  }
+
+  public class ChangeBounds extends android.support.transition.Transition {
+    ctor public ChangeBounds();
+    ctor public ChangeBounds(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+    method public boolean getResizeClip();
+    method public void setResizeClip(boolean);
+  }
+
+  public class ChangeClipBounds extends android.support.transition.Transition {
+    ctor public ChangeClipBounds();
+    ctor public ChangeClipBounds(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+  }
+
+  public class ChangeImageTransform extends android.support.transition.Transition {
+    ctor public ChangeImageTransform();
+    ctor public ChangeImageTransform(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+  }
+
+  public class ChangeScroll extends android.support.transition.Transition {
+    ctor public ChangeScroll();
+    ctor public ChangeScroll(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+  }
+
+  public class ChangeTransform extends android.support.transition.Transition {
+    ctor public ChangeTransform();
+    ctor public ChangeTransform(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+    method public boolean getReparent();
+    method public boolean getReparentWithOverlay();
+    method public void setReparent(boolean);
+    method public void setReparentWithOverlay(boolean);
+  }
+
+  public class CircularPropagation extends android.support.transition.VisibilityPropagation {
+    ctor public CircularPropagation();
+    method public long getStartDelay(android.view.ViewGroup, android.support.transition.Transition, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public void setPropagationSpeed(float);
+  }
+
+  public class Explode extends android.support.transition.Visibility {
+    ctor public Explode();
+    ctor public Explode(android.content.Context, android.util.AttributeSet);
+  }
+
+  public class Fade extends android.support.transition.Visibility {
+    ctor public Fade(int);
+    ctor public Fade();
+    ctor public Fade(android.content.Context, android.util.AttributeSet);
+    field public static final int IN = 1; // 0x1
+    field public static final int OUT = 2; // 0x2
+  }
+
+  public abstract class PathMotion {
+    ctor public PathMotion();
+    ctor public PathMotion(android.content.Context, android.util.AttributeSet);
+    method public abstract android.graphics.Path getPath(float, float, float, float);
+  }
+
+  public class PatternPathMotion extends android.support.transition.PathMotion {
+    ctor public PatternPathMotion();
+    ctor public PatternPathMotion(android.content.Context, android.util.AttributeSet);
+    ctor public PatternPathMotion(android.graphics.Path);
+    method public android.graphics.Path getPath(float, float, float, float);
+    method public android.graphics.Path getPatternPath();
+    method public void setPatternPath(android.graphics.Path);
+  }
+
+  public class Scene {
+    ctor public Scene(android.view.ViewGroup);
+    ctor public Scene(android.view.ViewGroup, android.view.View);
+    method public void enter();
+    method public void exit();
+    method public static android.support.transition.Scene getSceneForLayout(android.view.ViewGroup, int, android.content.Context);
+    method public android.view.ViewGroup getSceneRoot();
+    method public void setEnterAction(java.lang.Runnable);
+    method public void setExitAction(java.lang.Runnable);
+  }
+
+  public class SidePropagation extends android.support.transition.VisibilityPropagation {
+    ctor public SidePropagation();
+    method public long getStartDelay(android.view.ViewGroup, android.support.transition.Transition, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public void setPropagationSpeed(float);
+    method public void setSide(int);
+  }
+
+  public class Slide extends android.support.transition.Visibility {
+    ctor public Slide();
+    ctor public Slide(int);
+    ctor public Slide(android.content.Context, android.util.AttributeSet);
+    method public int getSlideEdge();
+    method public void setSlideEdge(int);
+  }
+
+  public abstract class Transition {
+    ctor public Transition();
+    ctor public Transition(android.content.Context, android.util.AttributeSet);
+    method public android.support.transition.Transition addListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.Transition addTarget(android.view.View);
+    method public android.support.transition.Transition addTarget(int);
+    method public android.support.transition.Transition addTarget(java.lang.String);
+    method public android.support.transition.Transition addTarget(java.lang.Class);
+    method public abstract void captureEndValues(android.support.transition.TransitionValues);
+    method public abstract void captureStartValues(android.support.transition.TransitionValues);
+    method public android.support.transition.Transition clone();
+    method public android.animation.Animator createAnimator(android.view.ViewGroup, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public android.support.transition.Transition excludeChildren(android.view.View, boolean);
+    method public android.support.transition.Transition excludeChildren(int, boolean);
+    method public android.support.transition.Transition excludeChildren(java.lang.Class, boolean);
+    method public android.support.transition.Transition excludeTarget(android.view.View, boolean);
+    method public android.support.transition.Transition excludeTarget(int, boolean);
+    method public android.support.transition.Transition excludeTarget(java.lang.String, boolean);
+    method public android.support.transition.Transition excludeTarget(java.lang.Class, boolean);
+    method public long getDuration();
+    method public android.graphics.Rect getEpicenter();
+    method public android.support.transition.Transition.EpicenterCallback getEpicenterCallback();
+    method public android.animation.TimeInterpolator getInterpolator();
+    method public java.lang.String getName();
+    method public android.support.transition.PathMotion getPathMotion();
+    method public android.support.transition.TransitionPropagation getPropagation();
+    method public long getStartDelay();
+    method public java.util.List<java.lang.Integer> getTargetIds();
+    method public java.util.List<java.lang.String> getTargetNames();
+    method public java.util.List<java.lang.Class> getTargetTypes();
+    method public java.util.List<android.view.View> getTargets();
+    method public java.lang.String[] getTransitionProperties();
+    method public android.support.transition.TransitionValues getTransitionValues(android.view.View, boolean);
+    method public boolean isTransitionRequired(android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public android.support.transition.Transition removeListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.Transition removeTarget(android.view.View);
+    method public android.support.transition.Transition removeTarget(int);
+    method public android.support.transition.Transition removeTarget(java.lang.String);
+    method public android.support.transition.Transition removeTarget(java.lang.Class);
+    method public android.support.transition.Transition setDuration(long);
+    method public void setEpicenterCallback(android.support.transition.Transition.EpicenterCallback);
+    method public android.support.transition.Transition setInterpolator(android.animation.TimeInterpolator);
+    method public void setMatchOrder(int...);
+    method public void setPathMotion(android.support.transition.PathMotion);
+    method public void setPropagation(android.support.transition.TransitionPropagation);
+    method public android.support.transition.Transition setStartDelay(long);
+    field public static final int MATCH_ID = 3; // 0x3
+    field public static final int MATCH_INSTANCE = 1; // 0x1
+    field public static final int MATCH_ITEM_ID = 4; // 0x4
+    field public static final int MATCH_NAME = 2; // 0x2
+  }
+
+  public static abstract class Transition.EpicenterCallback {
+    ctor public Transition.EpicenterCallback();
+    method public abstract android.graphics.Rect onGetEpicenter(android.support.transition.Transition);
+  }
+
+  public static abstract interface Transition.TransitionListener {
+    method public abstract void onTransitionCancel(android.support.transition.Transition);
+    method public abstract void onTransitionEnd(android.support.transition.Transition);
+    method public abstract void onTransitionPause(android.support.transition.Transition);
+    method public abstract void onTransitionResume(android.support.transition.Transition);
+    method public abstract void onTransitionStart(android.support.transition.Transition);
+  }
+
+  public class TransitionInflater {
+    method public static android.support.transition.TransitionInflater from(android.content.Context);
+    method public android.support.transition.Transition inflateTransition(int);
+    method public android.support.transition.TransitionManager inflateTransitionManager(int, android.view.ViewGroup);
+  }
+
+  public class TransitionListenerAdapter implements android.support.transition.Transition.TransitionListener {
+    ctor public TransitionListenerAdapter();
+    method public void onTransitionCancel(android.support.transition.Transition);
+    method public void onTransitionEnd(android.support.transition.Transition);
+    method public void onTransitionPause(android.support.transition.Transition);
+    method public void onTransitionResume(android.support.transition.Transition);
+    method public void onTransitionStart(android.support.transition.Transition);
+  }
+
+  public class TransitionManager {
+    ctor public TransitionManager();
+    method public static void beginDelayedTransition(android.view.ViewGroup);
+    method public static void beginDelayedTransition(android.view.ViewGroup, android.support.transition.Transition);
+    method public static void endTransitions(android.view.ViewGroup);
+    method public static void go(android.support.transition.Scene);
+    method public static void go(android.support.transition.Scene, android.support.transition.Transition);
+    method public void setTransition(android.support.transition.Scene, android.support.transition.Transition);
+    method public void setTransition(android.support.transition.Scene, android.support.transition.Scene, android.support.transition.Transition);
+    method public void transitionTo(android.support.transition.Scene);
+  }
+
+  public abstract class TransitionPropagation {
+    ctor public TransitionPropagation();
+    method public abstract void captureValues(android.support.transition.TransitionValues);
+    method public abstract java.lang.String[] getPropagationProperties();
+    method public abstract long getStartDelay(android.view.ViewGroup, android.support.transition.Transition, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+  }
+
+  public class TransitionSet extends android.support.transition.Transition {
+    ctor public TransitionSet();
+    ctor public TransitionSet(android.content.Context, android.util.AttributeSet);
+    method public android.support.transition.TransitionSet addListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.TransitionSet addTarget(android.view.View);
+    method public android.support.transition.TransitionSet addTarget(int);
+    method public android.support.transition.TransitionSet addTarget(java.lang.String);
+    method public android.support.transition.TransitionSet addTarget(java.lang.Class);
+    method public android.support.transition.TransitionSet addTransition(android.support.transition.Transition);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+    method public int getOrdering();
+    method public android.support.transition.Transition getTransitionAt(int);
+    method public int getTransitionCount();
+    method public android.support.transition.TransitionSet removeListener(android.support.transition.Transition.TransitionListener);
+    method public android.support.transition.TransitionSet removeTarget(int);
+    method public android.support.transition.TransitionSet removeTarget(android.view.View);
+    method public android.support.transition.TransitionSet removeTarget(java.lang.Class);
+    method public android.support.transition.TransitionSet removeTarget(java.lang.String);
+    method public android.support.transition.TransitionSet removeTransition(android.support.transition.Transition);
+    method public android.support.transition.TransitionSet setDuration(long);
+    method public android.support.transition.TransitionSet setInterpolator(android.animation.TimeInterpolator);
+    method public android.support.transition.TransitionSet setOrdering(int);
+    method public android.support.transition.TransitionSet setStartDelay(long);
+    field public static final int ORDERING_SEQUENTIAL = 1; // 0x1
+    field public static final int ORDERING_TOGETHER = 0; // 0x0
+  }
+
+  public class TransitionValues {
+    ctor public TransitionValues();
+    field public final java.util.Map<java.lang.String, java.lang.Object> values;
+    field public android.view.View view;
+  }
+
+  public abstract class Visibility extends android.support.transition.Transition {
+    ctor public Visibility();
+    ctor public Visibility(android.content.Context, android.util.AttributeSet);
+    method public void captureEndValues(android.support.transition.TransitionValues);
+    method public void captureStartValues(android.support.transition.TransitionValues);
+    method public int getMode();
+    method public boolean isVisible(android.support.transition.TransitionValues);
+    method public android.animation.Animator onAppear(android.view.ViewGroup, android.support.transition.TransitionValues, int, android.support.transition.TransitionValues, int);
+    method public android.animation.Animator onAppear(android.view.ViewGroup, android.view.View, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public android.animation.Animator onDisappear(android.view.ViewGroup, android.support.transition.TransitionValues, int, android.support.transition.TransitionValues, int);
+    method public android.animation.Animator onDisappear(android.view.ViewGroup, android.view.View, android.support.transition.TransitionValues, android.support.transition.TransitionValues);
+    method public void setMode(int);
+    field public static final int MODE_IN = 1; // 0x1
+    field public static final int MODE_OUT = 2; // 0x2
+  }
+
+  public abstract class VisibilityPropagation extends android.support.transition.TransitionPropagation {
+    ctor public VisibilityPropagation();
+    method public void captureValues(android.support.transition.TransitionValues);
+    method public java.lang.String[] getPropagationProperties();
+    method public int getViewVisibility(android.support.transition.TransitionValues);
+    method public int getViewX(android.support.transition.TransitionValues);
+    method public int getViewY(android.support.transition.TransitionValues);
+  }
+
+}
+
+package android.support.v13.app {
+
+  public class ActivityCompat extends android.support.v4.app.ActivityCompat {
+    ctor protected ActivityCompat();
+    method public static android.support.v13.view.DragAndDropPermissionsCompat requestDragAndDropPermissions(android.app.Activity, android.view.DragEvent);
+  }
+
+  public class FragmentCompat {
+    ctor public FragmentCompat();
+    method public static void requestPermissions(android.app.Fragment, java.lang.String[], int);
+    method public static deprecated void setMenuVisibility(android.app.Fragment, boolean);
+    method public static void setUserVisibleHint(android.app.Fragment, boolean);
+    method public static boolean shouldShowRequestPermissionRationale(android.app.Fragment, java.lang.String);
+  }
+
+  public static abstract interface FragmentCompat.OnRequestPermissionsResultCallback {
+    method public abstract void onRequestPermissionsResult(int, java.lang.String[], int[]);
+  }
+
+  public abstract class FragmentPagerAdapter extends android.support.v4.view.PagerAdapter {
+    ctor public FragmentPagerAdapter(android.app.FragmentManager);
+    method public abstract android.app.Fragment getItem(int);
+    method public long getItemId(int);
+    method public boolean isViewFromObject(android.view.View, java.lang.Object);
+  }
+
+  public abstract class FragmentStatePagerAdapter extends android.support.v4.view.PagerAdapter {
+    ctor public FragmentStatePagerAdapter(android.app.FragmentManager);
+    method public abstract android.app.Fragment getItem(int);
+    method public boolean isViewFromObject(android.view.View, java.lang.Object);
+  }
+
+  public class FragmentTabHost extends android.widget.TabHost implements android.widget.TabHost.OnTabChangeListener {
+    ctor public FragmentTabHost(android.content.Context);
+    ctor public FragmentTabHost(android.content.Context, android.util.AttributeSet);
+    method public void addTab(android.widget.TabHost.TabSpec, java.lang.Class<?>, android.os.Bundle);
+    method public void onTabChanged(java.lang.String);
+    method public deprecated void setup();
+    method public void setup(android.content.Context, android.app.FragmentManager);
+    method public void setup(android.content.Context, android.app.FragmentManager, int);
+  }
+
+}
+
+package android.support.v13.view {
+
+  public final class DragAndDropPermissionsCompat {
+    method public void release();
+  }
+
+  public class DragStartHelper {
+    ctor public DragStartHelper(android.view.View, android.support.v13.view.DragStartHelper.OnDragStartListener);
+    method public void attach();
+    method public void detach();
+    method public void getTouchPosition(android.graphics.Point);
+    method public boolean onLongClick(android.view.View);
+    method public boolean onTouch(android.view.View, android.view.MotionEvent);
+  }
+
+  public static abstract interface DragStartHelper.OnDragStartListener {
+    method public abstract boolean onDragStart(android.view.View, android.support.v13.view.DragStartHelper);
+  }
+
+  public deprecated class ViewCompat extends android.support.v4.view.ViewCompat {
+  }
+
+}
+
+package android.support.v13.view.inputmethod {
+
+  public final class EditorInfoCompat {
+    ctor public EditorInfoCompat();
+    method public static java.lang.String[] getContentMimeTypes(android.view.inputmethod.EditorInfo);
+    method public static void setContentMimeTypes(android.view.inputmethod.EditorInfo, java.lang.String[]);
+    field public static final int IME_FLAG_FORCE_ASCII = -2147483648; // 0x80000000
+    field public static final int IME_FLAG_NO_PERSONALIZED_LEARNING = 16777216; // 0x1000000
+  }
+
+  public final class InputConnectionCompat {
+    ctor public InputConnectionCompat();
+    method public static boolean commitContent(android.view.inputmethod.InputConnection, android.view.inputmethod.EditorInfo, android.support.v13.view.inputmethod.InputContentInfoCompat, int, android.os.Bundle);
+    method public static android.view.inputmethod.InputConnection createWrapper(android.view.inputmethod.InputConnection, android.view.inputmethod.EditorInfo, android.support.v13.view.inputmethod.InputConnectionCompat.OnCommitContentListener);
+    field public static int INPUT_CONTENT_GRANT_READ_URI_PERMISSION;
+  }
+
+  public static abstract interface InputConnectionCompat.OnCommitContentListener {
+    method public abstract boolean onCommitContent(android.support.v13.view.inputmethod.InputContentInfoCompat, int, android.os.Bundle);
+  }
+
+  public final class InputContentInfoCompat {
+    ctor public InputContentInfoCompat(android.net.Uri, android.content.ClipDescription, android.net.Uri);
+    method public android.net.Uri getContentUri();
+    method public android.content.ClipDescription getDescription();
+    method public android.net.Uri getLinkUri();
+    method public void releasePermission();
+    method public void requestPermission();
+    method public java.lang.Object unwrap();
+    method public static android.support.v13.view.inputmethod.InputContentInfoCompat wrap(java.lang.Object);
+  }
+
+}
+
+package android.support.v14.preference {
+
+  public class EditTextPreferenceDialogFragment extends android.support.v14.preference.PreferenceDialogFragment {
+    ctor public EditTextPreferenceDialogFragment();
+    method public static android.support.v14.preference.EditTextPreferenceDialogFragment newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public class ListPreferenceDialogFragment extends android.support.v14.preference.PreferenceDialogFragment {
+    ctor public ListPreferenceDialogFragment();
+    method public static android.support.v14.preference.ListPreferenceDialogFragment newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public class MultiSelectListPreference extends android.support.v7.preference.DialogPreference {
+    ctor public MultiSelectListPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public MultiSelectListPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public MultiSelectListPreference(android.content.Context, android.util.AttributeSet);
+    ctor public MultiSelectListPreference(android.content.Context);
+    method public int findIndexOfValue(java.lang.String);
+    method public java.lang.CharSequence[] getEntries();
+    method public java.lang.CharSequence[] getEntryValues();
+    method protected boolean[] getSelectedItems();
+    method public java.util.Set<java.lang.String> getValues();
+    method public void setEntries(java.lang.CharSequence[]);
+    method public void setEntries(int);
+    method public void setEntryValues(java.lang.CharSequence[]);
+    method public void setEntryValues(int);
+    method public void setValues(java.util.Set<java.lang.String>);
+  }
+
+  public class MultiSelectListPreferenceDialogFragment extends android.support.v14.preference.PreferenceDialogFragment {
+    ctor public MultiSelectListPreferenceDialogFragment();
+    method public static android.support.v14.preference.MultiSelectListPreferenceDialogFragment newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public abstract class PreferenceDialogFragment extends android.app.DialogFragment implements android.content.DialogInterface.OnClickListener {
+    ctor public PreferenceDialogFragment();
+    method public android.support.v7.preference.DialogPreference getPreference();
+    method protected void onBindDialogView(android.view.View);
+    method public void onClick(android.content.DialogInterface, int);
+    method protected android.view.View onCreateDialogView(android.content.Context);
+    method public abstract void onDialogClosed(boolean);
+    method protected void onPrepareDialogBuilder(android.app.AlertDialog.Builder);
+    field protected static final java.lang.String ARG_KEY = "key";
+  }
+
+  public abstract class PreferenceFragment extends android.app.Fragment implements android.support.v7.preference.DialogPreference.TargetFragment android.support.v7.preference.PreferenceManager.OnDisplayPreferenceDialogListener android.support.v7.preference.PreferenceManager.OnNavigateToScreenListener android.support.v7.preference.PreferenceManager.OnPreferenceTreeClickListener {
+    ctor public PreferenceFragment();
+    method public void addPreferencesFromResource(int);
+    method public android.support.v7.preference.Preference findPreference(java.lang.CharSequence);
+    method public final android.support.v7.widget.RecyclerView getListView();
+    method public android.support.v7.preference.PreferenceManager getPreferenceManager();
+    method public android.support.v7.preference.PreferenceScreen getPreferenceScreen();
+    method protected android.support.v7.widget.RecyclerView.Adapter onCreateAdapter(android.support.v7.preference.PreferenceScreen);
+    method public android.support.v7.widget.RecyclerView.LayoutManager onCreateLayoutManager();
+    method public abstract void onCreatePreferences(android.os.Bundle, java.lang.String);
+    method public android.support.v7.widget.RecyclerView onCreateRecyclerView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void onDisplayPreferenceDialog(android.support.v7.preference.Preference);
+    method public void onNavigateToScreen(android.support.v7.preference.PreferenceScreen);
+    method public boolean onPreferenceTreeClick(android.support.v7.preference.Preference);
+    method public void scrollToPreference(java.lang.String);
+    method public void scrollToPreference(android.support.v7.preference.Preference);
+    method public void setDivider(android.graphics.drawable.Drawable);
+    method public void setDividerHeight(int);
+    method public void setPreferenceScreen(android.support.v7.preference.PreferenceScreen);
+    method public void setPreferencesFromResource(int, java.lang.String);
+    field public static final java.lang.String ARG_PREFERENCE_ROOT = "android.support.v7.preference.PreferenceFragmentCompat.PREFERENCE_ROOT";
+  }
+
+  public static abstract interface PreferenceFragment.OnPreferenceDisplayDialogCallback {
+    method public abstract boolean onPreferenceDisplayDialog(android.support.v14.preference.PreferenceFragment, android.support.v7.preference.Preference);
+  }
+
+  public static abstract interface PreferenceFragment.OnPreferenceStartFragmentCallback {
+    method public abstract boolean onPreferenceStartFragment(android.support.v14.preference.PreferenceFragment, android.support.v7.preference.Preference);
+  }
+
+  public static abstract interface PreferenceFragment.OnPreferenceStartScreenCallback {
+    method public abstract boolean onPreferenceStartScreen(android.support.v14.preference.PreferenceFragment, android.support.v7.preference.PreferenceScreen);
+  }
+
+  public class SwitchPreference extends android.support.v7.preference.TwoStatePreference {
+    ctor public SwitchPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public SwitchPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public SwitchPreference(android.content.Context, android.util.AttributeSet);
+    ctor public SwitchPreference(android.content.Context);
+    method public java.lang.CharSequence getSwitchTextOff();
+    method public java.lang.CharSequence getSwitchTextOn();
+    method public void setSwitchTextOff(java.lang.CharSequence);
+    method public void setSwitchTextOff(int);
+    method public void setSwitchTextOn(java.lang.CharSequence);
+    method public void setSwitchTextOn(int);
+  }
+
+}
+
+package android.support.v17.leanback.app {
+
+  public final class BackgroundManager {
+    method public void attach(android.view.Window);
+    method public void attachToView(android.view.View);
+    method public void clearDrawable();
+    method public final int getColor();
+    method public deprecated android.graphics.drawable.Drawable getDefaultDimLayer();
+    method public deprecated android.graphics.drawable.Drawable getDimLayer();
+    method public android.graphics.drawable.Drawable getDrawable();
+    method public static android.support.v17.leanback.app.BackgroundManager getInstance(android.app.Activity);
+    method public boolean isAttached();
+    method public boolean isAutoReleaseOnStop();
+    method public void release();
+    method public void setAutoReleaseOnStop(boolean);
+    method public void setBitmap(android.graphics.Bitmap);
+    method public void setColor(int);
+    method public deprecated void setDimLayer(android.graphics.drawable.Drawable);
+    method public void setDrawable(android.graphics.drawable.Drawable);
+    method public void setThemeDrawableResourceId(int);
+  }
+
+  public class BaseFragment extends android.support.v17.leanback.app.BrandedFragment {
+    method protected java.lang.Object createEntranceTransition();
+    method public final android.support.v17.leanback.app.ProgressBarManager getProgressBarManager();
+    method protected void onEntranceTransitionEnd();
+    method protected void onEntranceTransitionPrepare();
+    method protected void onEntranceTransitionStart();
+    method public void prepareEntranceTransition();
+    method protected void runEntranceTransition(java.lang.Object);
+    method public void startEntranceTransition();
+  }
+
+   abstract class BaseRowFragment extends android.app.Fragment {
+    method public final android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public final android.support.v17.leanback.widget.ItemBridgeAdapter getBridgeAdapter();
+    method public final android.support.v17.leanback.widget.PresenterSelector getPresenterSelector();
+    method public int getSelectedPosition();
+    method public final android.support.v17.leanback.widget.VerticalGridView getVerticalGridView();
+    method public void onTransitionEnd();
+    method public boolean onTransitionPrepare();
+    method public void onTransitionStart();
+    method public final void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setAlignment(int);
+    method public final void setPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+  }
+
+   abstract class BaseRowSupportFragment extends android.support.v4.app.Fragment {
+    method public final android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public final android.support.v17.leanback.widget.ItemBridgeAdapter getBridgeAdapter();
+    method public final android.support.v17.leanback.widget.PresenterSelector getPresenterSelector();
+    method public int getSelectedPosition();
+    method public final android.support.v17.leanback.widget.VerticalGridView getVerticalGridView();
+    method public void onTransitionEnd();
+    method public boolean onTransitionPrepare();
+    method public void onTransitionStart();
+    method public final void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setAlignment(int);
+    method public final void setPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+  }
+
+  public class BaseSupportFragment extends android.support.v17.leanback.app.BrandedSupportFragment {
+    method protected java.lang.Object createEntranceTransition();
+    method public final android.support.v17.leanback.app.ProgressBarManager getProgressBarManager();
+    method protected void onEntranceTransitionEnd();
+    method protected void onEntranceTransitionPrepare();
+    method protected void onEntranceTransitionStart();
+    method public void prepareEntranceTransition();
+    method protected void runEntranceTransition(java.lang.Object);
+    method public void startEntranceTransition();
+  }
+
+  public class BrandedFragment extends android.app.Fragment {
+    ctor public BrandedFragment();
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public int getSearchAffordanceColor();
+    method public android.support.v17.leanback.widget.SearchOrbView.Colors getSearchAffordanceColors();
+    method public java.lang.CharSequence getTitle();
+    method public android.view.View getTitleView();
+    method public android.support.v17.leanback.widget.TitleViewAdapter getTitleViewAdapter();
+    method public void installTitleView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public final boolean isShowingTitle();
+    method public android.view.View onInflateTitleView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnSearchClickedListener(android.view.View.OnClickListener);
+    method public void setSearchAffordanceColor(int);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setTitle(java.lang.CharSequence);
+    method public void setTitleView(android.view.View);
+    method public void showTitle(boolean);
+    method public void showTitle(int);
+  }
+
+  public class BrandedSupportFragment extends android.support.v4.app.Fragment {
+    ctor public BrandedSupportFragment();
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public int getSearchAffordanceColor();
+    method public android.support.v17.leanback.widget.SearchOrbView.Colors getSearchAffordanceColors();
+    method public java.lang.CharSequence getTitle();
+    method public android.view.View getTitleView();
+    method public android.support.v17.leanback.widget.TitleViewAdapter getTitleViewAdapter();
+    method public void installTitleView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public final boolean isShowingTitle();
+    method public android.view.View onInflateTitleView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnSearchClickedListener(android.view.View.OnClickListener);
+    method public void setSearchAffordanceColor(int);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setTitle(java.lang.CharSequence);
+    method public void setTitleView(android.view.View);
+    method public void showTitle(boolean);
+    method public void showTitle(int);
+  }
+
+  public class BrowseFragment extends android.support.v17.leanback.app.BaseFragment {
+    ctor public BrowseFragment();
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String, int);
+    method public void enableMainFragmentScaling(boolean);
+    method public deprecated void enableRowScaling(boolean);
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public int getBrandColor();
+    method public android.support.v17.leanback.app.HeadersFragment getHeadersFragment();
+    method public int getHeadersState();
+    method public android.app.Fragment getMainFragment();
+    method public final android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapterRegistry getMainFragmentRegistry();
+    method public android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.OnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public android.support.v17.leanback.app.RowsFragment getRowsFragment();
+    method public int getSelectedPosition();
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder getSelectedRowViewHolder();
+    method public final boolean isHeadersTransitionOnBackEnabled();
+    method public boolean isInHeadersTransition();
+    method public boolean isShowingHeaders();
+    method public android.support.v17.leanback.app.HeadersFragment onCreateHeadersFragment();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setBrandColor(int);
+    method public void setBrowseTransitionListener(android.support.v17.leanback.app.BrowseFragment.BrowseTransitionListener);
+    method public void setHeaderPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public void setHeadersState(int);
+    method public final void setHeadersTransitionOnBackEnabled(boolean);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+    method public void startHeadersTransition(boolean);
+    field public static final int HEADERS_DISABLED = 3; // 0x3
+    field public static final int HEADERS_ENABLED = 1; // 0x1
+    field public static final int HEADERS_HIDDEN = 2; // 0x2
+  }
+
+  public static class BrowseFragment.BrowseTransitionListener {
+    ctor public BrowseFragment.BrowseTransitionListener();
+    method public void onHeadersTransitionStart(boolean);
+    method public void onHeadersTransitionStop(boolean);
+  }
+
+  public static abstract class BrowseFragment.FragmentFactory<T extends android.app.Fragment> {
+    ctor public BrowseFragment.FragmentFactory();
+    method public abstract T createFragment(java.lang.Object);
+  }
+
+  public static abstract interface BrowseFragment.FragmentHost {
+    method public abstract void notifyDataReady(android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapter);
+    method public abstract void notifyViewCreated(android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapter);
+    method public abstract void showTitleView(boolean);
+  }
+
+  public static class BrowseFragment.ListRowFragmentFactory extends android.support.v17.leanback.app.BrowseFragment.FragmentFactory {
+    ctor public BrowseFragment.ListRowFragmentFactory();
+    method public android.support.v17.leanback.app.RowsFragment createFragment(java.lang.Object);
+  }
+
+  public static class BrowseFragment.MainFragmentAdapter<T extends android.app.Fragment> {
+    ctor public BrowseFragment.MainFragmentAdapter(T);
+    method public final T getFragment();
+    method public final android.support.v17.leanback.app.BrowseFragment.FragmentHost getFragmentHost();
+    method public boolean isScalingEnabled();
+    method public boolean isScrolling();
+    method public void onTransitionEnd();
+    method public boolean onTransitionPrepare();
+    method public void onTransitionStart();
+    method public void setAlignment(int);
+    method public void setEntranceTransitionState(boolean);
+    method public void setExpand(boolean);
+    method public void setScalingEnabled(boolean);
+  }
+
+  public static abstract interface BrowseFragment.MainFragmentAdapterProvider {
+    method public abstract android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapter getMainFragmentAdapter();
+  }
+
+  public static final class BrowseFragment.MainFragmentAdapterRegistry {
+    ctor public BrowseFragment.MainFragmentAdapterRegistry();
+    method public android.app.Fragment createFragment(java.lang.Object);
+    method public void registerFragment(java.lang.Class, android.support.v17.leanback.app.BrowseFragment.FragmentFactory);
+  }
+
+  public static class BrowseFragment.MainFragmentRowsAdapter<T extends android.app.Fragment> {
+    ctor public BrowseFragment.MainFragmentRowsAdapter(T);
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder findRowViewHolderByPosition(int);
+    method public final T getFragment();
+    method public int getSelectedPosition();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+    method public void setSelectedPosition(int, boolean);
+  }
+
+  public static abstract interface BrowseFragment.MainFragmentRowsAdapterProvider {
+    method public abstract android.support.v17.leanback.app.BrowseFragment.MainFragmentRowsAdapter getMainFragmentRowsAdapter();
+  }
+
+  public class BrowseSupportFragment extends android.support.v17.leanback.app.BaseSupportFragment {
+    ctor public BrowseSupportFragment();
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String, int);
+    method public void enableMainFragmentScaling(boolean);
+    method public deprecated void enableRowScaling(boolean);
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public int getBrandColor();
+    method public int getHeadersState();
+    method public android.support.v17.leanback.app.HeadersSupportFragment getHeadersSupportFragment();
+    method public android.support.v4.app.Fragment getMainFragment();
+    method public final android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapterRegistry getMainFragmentRegistry();
+    method public android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.OnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public android.support.v17.leanback.app.RowsSupportFragment getRowsSupportFragment();
+    method public int getSelectedPosition();
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder getSelectedRowViewHolder();
+    method public final boolean isHeadersTransitionOnBackEnabled();
+    method public boolean isInHeadersTransition();
+    method public boolean isShowingHeaders();
+    method public android.support.v17.leanback.app.HeadersSupportFragment onCreateHeadersSupportFragment();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setBrandColor(int);
+    method public void setBrowseTransitionListener(android.support.v17.leanback.app.BrowseSupportFragment.BrowseTransitionListener);
+    method public void setHeaderPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public void setHeadersState(int);
+    method public final void setHeadersTransitionOnBackEnabled(boolean);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+    method public void startHeadersTransition(boolean);
+    field public static final int HEADERS_DISABLED = 3; // 0x3
+    field public static final int HEADERS_ENABLED = 1; // 0x1
+    field public static final int HEADERS_HIDDEN = 2; // 0x2
+  }
+
+  public static class BrowseSupportFragment.BrowseTransitionListener {
+    ctor public BrowseSupportFragment.BrowseTransitionListener();
+    method public void onHeadersTransitionStart(boolean);
+    method public void onHeadersTransitionStop(boolean);
+  }
+
+  public static abstract class BrowseSupportFragment.FragmentFactory<T extends android.support.v4.app.Fragment> {
+    ctor public BrowseSupportFragment.FragmentFactory();
+    method public abstract T createFragment(java.lang.Object);
+  }
+
+  public static abstract interface BrowseSupportFragment.FragmentHost {
+    method public abstract void notifyDataReady(android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapter);
+    method public abstract void notifyViewCreated(android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapter);
+    method public abstract void showTitleView(boolean);
+  }
+
+  public static class BrowseSupportFragment.ListRowFragmentFactory extends android.support.v17.leanback.app.BrowseSupportFragment.FragmentFactory {
+    ctor public BrowseSupportFragment.ListRowFragmentFactory();
+    method public android.support.v17.leanback.app.RowsSupportFragment createFragment(java.lang.Object);
+  }
+
+  public static class BrowseSupportFragment.MainFragmentAdapter<T extends android.support.v4.app.Fragment> {
+    ctor public BrowseSupportFragment.MainFragmentAdapter(T);
+    method public final T getFragment();
+    method public final android.support.v17.leanback.app.BrowseSupportFragment.FragmentHost getFragmentHost();
+    method public boolean isScalingEnabled();
+    method public boolean isScrolling();
+    method public void onTransitionEnd();
+    method public boolean onTransitionPrepare();
+    method public void onTransitionStart();
+    method public void setAlignment(int);
+    method public void setEntranceTransitionState(boolean);
+    method public void setExpand(boolean);
+    method public void setScalingEnabled(boolean);
+  }
+
+  public static abstract interface BrowseSupportFragment.MainFragmentAdapterProvider {
+    method public abstract android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapter getMainFragmentAdapter();
+  }
+
+  public static final class BrowseSupportFragment.MainFragmentAdapterRegistry {
+    ctor public BrowseSupportFragment.MainFragmentAdapterRegistry();
+    method public android.support.v4.app.Fragment createFragment(java.lang.Object);
+    method public void registerFragment(java.lang.Class, android.support.v17.leanback.app.BrowseSupportFragment.FragmentFactory);
+  }
+
+  public static class BrowseSupportFragment.MainFragmentRowsAdapter<T extends android.support.v4.app.Fragment> {
+    ctor public BrowseSupportFragment.MainFragmentRowsAdapter(T);
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder findRowViewHolderByPosition(int);
+    method public final T getFragment();
+    method public int getSelectedPosition();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+    method public void setSelectedPosition(int, boolean);
+  }
+
+  public static abstract interface BrowseSupportFragment.MainFragmentRowsAdapterProvider {
+    method public abstract android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentRowsAdapter getMainFragmentRowsAdapter();
+  }
+
+  public class DetailsFragment extends android.support.v17.leanback.app.BaseFragment {
+    ctor public DetailsFragment();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public android.support.v17.leanback.widget.BaseOnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.DetailsParallax getParallax();
+    method public android.support.v17.leanback.app.RowsFragment getRowsFragment();
+    method protected deprecated android.view.View inflateTitle(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method protected void onSetDetailsOverviewRowStatus(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter, android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int, int, int);
+    method protected void onSetRowStatus(android.support.v17.leanback.widget.RowPresenter, android.support.v17.leanback.widget.RowPresenter.ViewHolder, int, int, int);
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method protected void setupDetailsOverviewRowPresenter(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter);
+    method protected void setupPresenter(android.support.v17.leanback.widget.Presenter);
+  }
+
+  public class DetailsFragmentBackgroundController {
+    ctor public DetailsFragmentBackgroundController(android.support.v17.leanback.app.DetailsFragment);
+    method public boolean canNavigateToVideoFragment();
+    method public void enableParallax();
+    method public void enableParallax(android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.support.v17.leanback.widget.ParallaxTarget.PropertyValuesHolderTarget);
+    method public final android.app.Fragment findOrCreateVideoFragment();
+    method public final android.graphics.drawable.Drawable getBottomDrawable();
+    method public final android.graphics.Bitmap getCoverBitmap();
+    method public final android.graphics.drawable.Drawable getCoverDrawable();
+    method public final int getParallaxDrawableMaxOffset();
+    method public final android.support.v17.leanback.media.PlaybackGlue getPlaybackGlue();
+    method public final int getSolidColor();
+    method public android.support.v17.leanback.media.PlaybackGlueHost onCreateGlueHost();
+    method public android.app.Fragment onCreateVideoFragment();
+    method public final void setCoverBitmap(android.graphics.Bitmap);
+    method public final void setParallaxDrawableMaxOffset(int);
+    method public final void setSolidColor(int);
+    method public void setupVideoPlayback(android.support.v17.leanback.media.PlaybackGlue);
+    method public final void switchToRows();
+    method public final void switchToVideo();
+  }
+
+  public class DetailsSupportFragment extends android.support.v17.leanback.app.BaseSupportFragment {
+    ctor public DetailsSupportFragment();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public android.support.v17.leanback.widget.BaseOnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.DetailsParallax getParallax();
+    method public android.support.v17.leanback.app.RowsSupportFragment getRowsSupportFragment();
+    method protected deprecated android.view.View inflateTitle(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method protected void onSetDetailsOverviewRowStatus(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter, android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int, int, int);
+    method protected void onSetRowStatus(android.support.v17.leanback.widget.RowPresenter, android.support.v17.leanback.widget.RowPresenter.ViewHolder, int, int, int);
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method protected void setupDetailsOverviewRowPresenter(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter);
+    method protected void setupPresenter(android.support.v17.leanback.widget.Presenter);
+  }
+
+  public class DetailsSupportFragmentBackgroundController {
+    ctor public DetailsSupportFragmentBackgroundController(android.support.v17.leanback.app.DetailsSupportFragment);
+    method public boolean canNavigateToVideoSupportFragment();
+    method public void enableParallax();
+    method public void enableParallax(android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.support.v17.leanback.widget.ParallaxTarget.PropertyValuesHolderTarget);
+    method public final android.support.v4.app.Fragment findOrCreateVideoSupportFragment();
+    method public final android.graphics.drawable.Drawable getBottomDrawable();
+    method public final android.graphics.Bitmap getCoverBitmap();
+    method public final android.graphics.drawable.Drawable getCoverDrawable();
+    method public final int getParallaxDrawableMaxOffset();
+    method public final android.support.v17.leanback.media.PlaybackGlue getPlaybackGlue();
+    method public final int getSolidColor();
+    method public android.support.v17.leanback.media.PlaybackGlueHost onCreateGlueHost();
+    method public android.support.v4.app.Fragment onCreateVideoSupportFragment();
+    method public final void setCoverBitmap(android.graphics.Bitmap);
+    method public final void setParallaxDrawableMaxOffset(int);
+    method public final void setSolidColor(int);
+    method public void setupVideoPlayback(android.support.v17.leanback.media.PlaybackGlue);
+    method public final void switchToRows();
+    method public final void switchToVideo();
+  }
+
+  public class ErrorFragment extends android.support.v17.leanback.app.BrandedFragment {
+    ctor public ErrorFragment();
+    method public android.graphics.drawable.Drawable getBackgroundDrawable();
+    method public android.view.View.OnClickListener getButtonClickListener();
+    method public java.lang.String getButtonText();
+    method public android.graphics.drawable.Drawable getImageDrawable();
+    method public java.lang.CharSequence getMessage();
+    method public boolean isBackgroundTranslucent();
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setButtonClickListener(android.view.View.OnClickListener);
+    method public void setButtonText(java.lang.String);
+    method public void setDefaultBackground(boolean);
+    method public void setImageDrawable(android.graphics.drawable.Drawable);
+    method public void setMessage(java.lang.CharSequence);
+  }
+
+  public class ErrorSupportFragment extends android.support.v17.leanback.app.BrandedSupportFragment {
+    ctor public ErrorSupportFragment();
+    method public android.graphics.drawable.Drawable getBackgroundDrawable();
+    method public android.view.View.OnClickListener getButtonClickListener();
+    method public java.lang.String getButtonText();
+    method public android.graphics.drawable.Drawable getImageDrawable();
+    method public java.lang.CharSequence getMessage();
+    method public boolean isBackgroundTranslucent();
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setButtonClickListener(android.view.View.OnClickListener);
+    method public void setButtonText(java.lang.String);
+    method public void setDefaultBackground(boolean);
+    method public void setImageDrawable(android.graphics.drawable.Drawable);
+    method public void setMessage(java.lang.CharSequence);
+  }
+
+  public class GuidedStepFragment extends android.app.Fragment {
+    ctor public GuidedStepFragment();
+    method public static int add(android.app.FragmentManager, android.support.v17.leanback.app.GuidedStepFragment);
+    method public static int add(android.app.FragmentManager, android.support.v17.leanback.app.GuidedStepFragment, int);
+    method public static int addAsRoot(android.app.Activity, android.support.v17.leanback.app.GuidedStepFragment, int);
+    method public void collapseAction(boolean);
+    method public void collapseSubActions();
+    method public void expandAction(android.support.v17.leanback.widget.GuidedAction, boolean);
+    method public void expandSubActions(android.support.v17.leanback.widget.GuidedAction);
+    method public android.support.v17.leanback.widget.GuidedAction findActionById(long);
+    method public int findActionPositionById(long);
+    method public android.support.v17.leanback.widget.GuidedAction findButtonActionById(long);
+    method public int findButtonActionPositionById(long);
+    method public void finishGuidedStepFragments();
+    method public android.view.View getActionItemView(int);
+    method public java.util.List<android.support.v17.leanback.widget.GuidedAction> getActions();
+    method public android.view.View getButtonActionItemView(int);
+    method public java.util.List<android.support.v17.leanback.widget.GuidedAction> getButtonActions();
+    method public static android.support.v17.leanback.app.GuidedStepFragment getCurrentGuidedStepFragment(android.app.FragmentManager);
+    method public android.support.v17.leanback.widget.GuidanceStylist getGuidanceStylist();
+    method public android.support.v17.leanback.widget.GuidedActionsStylist getGuidedActionsStylist();
+    method public android.support.v17.leanback.widget.GuidedActionsStylist getGuidedButtonActionsStylist();
+    method public int getSelectedActionPosition();
+    method public int getSelectedButtonActionPosition();
+    method public int getUiStyle();
+    method public boolean isExpanded();
+    method public boolean isFocusOutEndAllowed();
+    method public boolean isFocusOutStartAllowed();
+    method public boolean isSubActionsExpanded();
+    method public void notifyActionChanged(int);
+    method public void notifyButtonActionChanged(int);
+    method protected void onAddSharedElementTransition(android.app.FragmentTransaction, android.support.v17.leanback.app.GuidedStepFragment);
+    method public void onCreateActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>, android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist onCreateActionsStylist();
+    method public android.view.View onCreateBackgroundView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void onCreateButtonActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>, android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist onCreateButtonActionsStylist();
+    method public android.support.v17.leanback.widget.GuidanceStylist.Guidance onCreateGuidance(android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidanceStylist onCreateGuidanceStylist();
+    method public void onGuidedActionClicked(android.support.v17.leanback.widget.GuidedAction);
+    method public void onGuidedActionEditCanceled(android.support.v17.leanback.widget.GuidedAction);
+    method public deprecated void onGuidedActionEdited(android.support.v17.leanback.widget.GuidedAction);
+    method public long onGuidedActionEditedAndProceed(android.support.v17.leanback.widget.GuidedAction);
+    method public void onGuidedActionFocused(android.support.v17.leanback.widget.GuidedAction);
+    method protected void onProvideFragmentTransitions();
+    method public int onProvideTheme();
+    method public boolean onSubGuidedActionClicked(android.support.v17.leanback.widget.GuidedAction);
+    method public void openInEditMode(android.support.v17.leanback.widget.GuidedAction);
+    method public void popBackStackToGuidedStepFragment(java.lang.Class, int);
+    method public void setActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public void setButtonActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public void setSelectedActionPosition(int);
+    method public void setSelectedButtonActionPosition(int);
+    method public void setUiStyle(int);
+    field public static final java.lang.String EXTRA_UI_STYLE = "uiStyle";
+    field public static final int UI_STYLE_ACTIVITY_ROOT = 2; // 0x2
+    field public static final deprecated int UI_STYLE_DEFAULT = 0; // 0x0
+    field public static final int UI_STYLE_ENTRANCE = 1; // 0x1
+    field public static final int UI_STYLE_REPLACE = 0; // 0x0
+  }
+
+  public class GuidedStepSupportFragment extends android.support.v4.app.Fragment {
+    ctor public GuidedStepSupportFragment();
+    method public static int add(android.support.v4.app.FragmentManager, android.support.v17.leanback.app.GuidedStepSupportFragment);
+    method public static int add(android.support.v4.app.FragmentManager, android.support.v17.leanback.app.GuidedStepSupportFragment, int);
+    method public static int addAsRoot(android.support.v4.app.FragmentActivity, android.support.v17.leanback.app.GuidedStepSupportFragment, int);
+    method public void collapseAction(boolean);
+    method public void collapseSubActions();
+    method public void expandAction(android.support.v17.leanback.widget.GuidedAction, boolean);
+    method public void expandSubActions(android.support.v17.leanback.widget.GuidedAction);
+    method public android.support.v17.leanback.widget.GuidedAction findActionById(long);
+    method public int findActionPositionById(long);
+    method public android.support.v17.leanback.widget.GuidedAction findButtonActionById(long);
+    method public int findButtonActionPositionById(long);
+    method public void finishGuidedStepSupportFragments();
+    method public android.view.View getActionItemView(int);
+    method public java.util.List<android.support.v17.leanback.widget.GuidedAction> getActions();
+    method public android.view.View getButtonActionItemView(int);
+    method public java.util.List<android.support.v17.leanback.widget.GuidedAction> getButtonActions();
+    method public static android.support.v17.leanback.app.GuidedStepSupportFragment getCurrentGuidedStepSupportFragment(android.support.v4.app.FragmentManager);
+    method public android.support.v17.leanback.widget.GuidanceStylist getGuidanceStylist();
+    method public android.support.v17.leanback.widget.GuidedActionsStylist getGuidedActionsStylist();
+    method public android.support.v17.leanback.widget.GuidedActionsStylist getGuidedButtonActionsStylist();
+    method public int getSelectedActionPosition();
+    method public int getSelectedButtonActionPosition();
+    method public int getUiStyle();
+    method public boolean isExpanded();
+    method public boolean isFocusOutEndAllowed();
+    method public boolean isFocusOutStartAllowed();
+    method public boolean isSubActionsExpanded();
+    method public void notifyActionChanged(int);
+    method public void notifyButtonActionChanged(int);
+    method protected void onAddSharedElementTransition(android.support.v4.app.FragmentTransaction, android.support.v17.leanback.app.GuidedStepSupportFragment);
+    method public void onCreateActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>, android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist onCreateActionsStylist();
+    method public android.view.View onCreateBackgroundView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void onCreateButtonActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>, android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist onCreateButtonActionsStylist();
+    method public android.support.v17.leanback.widget.GuidanceStylist.Guidance onCreateGuidance(android.os.Bundle);
+    method public android.support.v17.leanback.widget.GuidanceStylist onCreateGuidanceStylist();
+    method public void onGuidedActionClicked(android.support.v17.leanback.widget.GuidedAction);
+    method public void onGuidedActionEditCanceled(android.support.v17.leanback.widget.GuidedAction);
+    method public deprecated void onGuidedActionEdited(android.support.v17.leanback.widget.GuidedAction);
+    method public long onGuidedActionEditedAndProceed(android.support.v17.leanback.widget.GuidedAction);
+    method public void onGuidedActionFocused(android.support.v17.leanback.widget.GuidedAction);
+    method protected void onProvideFragmentTransitions();
+    method public int onProvideTheme();
+    method public boolean onSubGuidedActionClicked(android.support.v17.leanback.widget.GuidedAction);
+    method public void openInEditMode(android.support.v17.leanback.widget.GuidedAction);
+    method public void popBackStackToGuidedStepSupportFragment(java.lang.Class, int);
+    method public void setActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public void setButtonActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public void setSelectedActionPosition(int);
+    method public void setSelectedButtonActionPosition(int);
+    method public void setUiStyle(int);
+    field public static final java.lang.String EXTRA_UI_STYLE = "uiStyle";
+    field public static final int UI_STYLE_ACTIVITY_ROOT = 2; // 0x2
+    field public static final deprecated int UI_STYLE_DEFAULT = 0; // 0x0
+    field public static final int UI_STYLE_ENTRANCE = 1; // 0x1
+    field public static final int UI_STYLE_REPLACE = 0; // 0x0
+  }
+
+  public class HeadersFragment extends android.support.v17.leanback.app.BaseRowFragment {
+    ctor public HeadersFragment();
+    method public boolean isScrolling();
+    method public void setOnHeaderClickedListener(android.support.v17.leanback.app.HeadersFragment.OnHeaderClickedListener);
+    method public void setOnHeaderViewSelectedListener(android.support.v17.leanback.app.HeadersFragment.OnHeaderViewSelectedListener);
+  }
+
+  public static abstract interface HeadersFragment.OnHeaderClickedListener {
+    method public abstract void onHeaderClicked(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder, android.support.v17.leanback.widget.Row);
+  }
+
+  public static abstract interface HeadersFragment.OnHeaderViewSelectedListener {
+    method public abstract void onHeaderSelected(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder, android.support.v17.leanback.widget.Row);
+  }
+
+  public class HeadersSupportFragment extends android.support.v17.leanback.app.BaseRowSupportFragment {
+    ctor public HeadersSupportFragment();
+    method public boolean isScrolling();
+    method public void setOnHeaderClickedListener(android.support.v17.leanback.app.HeadersSupportFragment.OnHeaderClickedListener);
+    method public void setOnHeaderViewSelectedListener(android.support.v17.leanback.app.HeadersSupportFragment.OnHeaderViewSelectedListener);
+  }
+
+  public static abstract interface HeadersSupportFragment.OnHeaderClickedListener {
+    method public abstract void onHeaderClicked(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder, android.support.v17.leanback.widget.Row);
+  }
+
+  public static abstract interface HeadersSupportFragment.OnHeaderViewSelectedListener {
+    method public abstract void onHeaderSelected(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder, android.support.v17.leanback.widget.Row);
+  }
+
+  public abstract deprecated class MediaControllerGlue extends android.support.v17.leanback.app.PlaybackControlGlue {
+    ctor public MediaControllerGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlayFragment, int[]);
+    ctor public MediaControllerGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlayFragment, int[], int[]);
+    method public void attachToMediaController(android.support.v4.media.session.MediaControllerCompat);
+    method public void detach();
+    method public int getCurrentPosition();
+    method public int getCurrentSpeedId();
+    method public android.graphics.drawable.Drawable getMediaArt();
+    method public final android.support.v4.media.session.MediaControllerCompat getMediaController();
+    method public int getMediaDuration();
+    method public java.lang.CharSequence getMediaSubtitle();
+    method public java.lang.CharSequence getMediaTitle();
+    method public long getSupportedActions();
+    method public boolean hasValidMedia();
+    method public boolean isMediaPlaying();
+    method protected void pausePlayback();
+    method protected void skipToNext();
+    method protected void skipToPrevious();
+    method protected void startPlayback(int);
+  }
+
+  public abstract class OnboardingFragment extends android.app.Fragment {
+    ctor public OnboardingFragment();
+    method public final int getArrowBackgroundColor();
+    method public final int getArrowColor();
+    method protected final int getCurrentPageIndex();
+    method public final int getDescriptionViewTextColor();
+    method public final int getDotBackgroundColor();
+    method public final int getIconResourceId();
+    method public final int getLogoResourceId();
+    method protected abstract int getPageCount();
+    method protected abstract java.lang.CharSequence getPageDescription(int);
+    method protected abstract java.lang.CharSequence getPageTitle(int);
+    method public final java.lang.CharSequence getStartButtonText();
+    method public final int getTitleViewTextColor();
+    method protected final boolean isLogoAnimationFinished();
+    method protected void moveToNextPage();
+    method protected void moveToPreviousPage();
+    method protected abstract android.view.View onCreateBackgroundView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected abstract android.view.View onCreateContentView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected android.animation.Animator onCreateDescriptionAnimator();
+    method protected android.animation.Animator onCreateEnterAnimation();
+    method protected abstract android.view.View onCreateForegroundView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected android.animation.Animator onCreateLogoAnimation();
+    method protected android.animation.Animator onCreateTitleAnimator();
+    method protected void onFinishFragment();
+    method protected void onLogoAnimationFinished();
+    method protected void onPageChanged(int, int);
+    method public int onProvideTheme();
+    method public void setArrowBackgroundColor(int);
+    method public void setArrowColor(int);
+    method public void setDescriptionViewTextColor(int);
+    method public void setDotBackgroundColor(int);
+    method public final void setIconResouceId(int);
+    method public final void setLogoResourceId(int);
+    method public void setStartButtonText(java.lang.CharSequence);
+    method public void setTitleViewTextColor(int);
+    method protected final void startEnterAnimation(boolean);
+  }
+
+  public abstract class OnboardingSupportFragment extends android.support.v4.app.Fragment {
+    ctor public OnboardingSupportFragment();
+    method public final int getArrowBackgroundColor();
+    method public final int getArrowColor();
+    method protected final int getCurrentPageIndex();
+    method public final int getDescriptionViewTextColor();
+    method public final int getDotBackgroundColor();
+    method public final int getIconResourceId();
+    method public final int getLogoResourceId();
+    method protected abstract int getPageCount();
+    method protected abstract java.lang.CharSequence getPageDescription(int);
+    method protected abstract java.lang.CharSequence getPageTitle(int);
+    method public final java.lang.CharSequence getStartButtonText();
+    method public final int getTitleViewTextColor();
+    method protected final boolean isLogoAnimationFinished();
+    method protected void moveToNextPage();
+    method protected void moveToPreviousPage();
+    method protected abstract android.view.View onCreateBackgroundView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected abstract android.view.View onCreateContentView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected android.animation.Animator onCreateDescriptionAnimator();
+    method protected android.animation.Animator onCreateEnterAnimation();
+    method protected abstract android.view.View onCreateForegroundView(android.view.LayoutInflater, android.view.ViewGroup);
+    method protected android.animation.Animator onCreateLogoAnimation();
+    method protected android.animation.Animator onCreateTitleAnimator();
+    method protected void onFinishFragment();
+    method protected void onLogoAnimationFinished();
+    method protected void onPageChanged(int, int);
+    method public int onProvideTheme();
+    method public void setArrowBackgroundColor(int);
+    method public void setArrowColor(int);
+    method public void setDescriptionViewTextColor(int);
+    method public void setDotBackgroundColor(int);
+    method public final void setIconResouceId(int);
+    method public final void setLogoResourceId(int);
+    method public void setStartButtonText(java.lang.CharSequence);
+    method public void setTitleViewTextColor(int);
+    method protected final void startEnterAnimation(boolean);
+  }
+
+  public abstract deprecated class PlaybackControlGlue extends android.support.v17.leanback.media.PlaybackControlGlue {
+    ctor public PlaybackControlGlue(android.content.Context, int[]);
+    ctor public PlaybackControlGlue(android.content.Context, int[], int[]);
+    ctor public PlaybackControlGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlayFragment, int[]);
+    ctor public PlaybackControlGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlayFragment, int[], int[]);
+    method public android.support.v17.leanback.widget.PlaybackControlsRowPresenter createControlsRowAndPresenter();
+    method protected android.support.v17.leanback.widget.SparseArrayObjectAdapter createPrimaryActionsAdapter(android.support.v17.leanback.widget.PresenterSelector);
+    method public android.support.v17.leanback.app.PlaybackOverlayFragment getFragment();
+    method public deprecated android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public final void next();
+    method protected void onRowChanged(android.support.v17.leanback.widget.PlaybackControlsRow);
+    method public final void pause();
+    method protected deprecated void pausePlayback();
+    method public final void play(int);
+    method public final void previous();
+    method public deprecated void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method protected deprecated void skipToNext();
+    method protected deprecated void skipToPrevious();
+    method protected deprecated void startPlayback(int);
+  }
+
+  public static abstract deprecated interface PlaybackControlGlue.InputEventHandler {
+    method public abstract boolean handleInputEvent(android.view.InputEvent);
+  }
+
+  public abstract deprecated class PlaybackControlSupportGlue extends android.support.v17.leanback.app.PlaybackControlGlue {
+    ctor public PlaybackControlSupportGlue(android.content.Context, int[]);
+    ctor public PlaybackControlSupportGlue(android.content.Context, int[], int[]);
+    ctor public PlaybackControlSupportGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlaySupportFragment, int[]);
+    ctor public PlaybackControlSupportGlue(android.content.Context, android.support.v17.leanback.app.PlaybackOverlaySupportFragment, int[], int[]);
+    field public static final int ACTION_CUSTOM_LEFT_FIRST = 1; // 0x1
+    field public static final int ACTION_CUSTOM_RIGHT_FIRST = 4096; // 0x1000
+    field public static final int ACTION_FAST_FORWARD = 128; // 0x80
+    field public static final int ACTION_PLAY_PAUSE = 64; // 0x40
+    field public static final int ACTION_REWIND = 32; // 0x20
+    field public static final int ACTION_SKIP_TO_NEXT = 256; // 0x100
+    field public static final int ACTION_SKIP_TO_PREVIOUS = 16; // 0x10
+    field public static final int PLAYBACK_SPEED_FAST_L0 = 10; // 0xa
+    field public static final int PLAYBACK_SPEED_FAST_L1 = 11; // 0xb
+    field public static final int PLAYBACK_SPEED_FAST_L2 = 12; // 0xc
+    field public static final int PLAYBACK_SPEED_FAST_L3 = 13; // 0xd
+    field public static final int PLAYBACK_SPEED_FAST_L4 = 14; // 0xe
+    field public static final int PLAYBACK_SPEED_INVALID = -1; // 0xffffffff
+    field public static final int PLAYBACK_SPEED_NORMAL = 1; // 0x1
+    field public static final int PLAYBACK_SPEED_PAUSED = 0; // 0x0
+  }
+
+  public class PlaybackFragment extends android.app.Fragment {
+    ctor public PlaybackFragment();
+    method public deprecated void fadeOut();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public int getBackgroundType();
+    method public android.support.v17.leanback.app.ProgressBarManager getProgressBarManager();
+    method public void hideControlsOverlay(boolean);
+    method public boolean isControlsOverlayAutoHideEnabled();
+    method public boolean isControlsOverlayVisible();
+    method public deprecated boolean isFadingEnabled();
+    method public void notifyPlaybackRowChanged();
+    method protected void onBufferingStateChanged(boolean);
+    method protected void onError(int, java.lang.CharSequence);
+    method protected void onVideoSizeChanged(int, int);
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setBackgroundType(int);
+    method public void setControlsOverlayAutoHideEnabled(boolean);
+    method public deprecated void setFadingEnabled(boolean);
+    method public void setHostCallback(android.support.v17.leanback.media.PlaybackGlueHost.HostCallback);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public final void setOnKeyInterceptListener(android.view.View.OnKeyListener);
+    method public void setOnPlaybackItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setPlaybackRow(android.support.v17.leanback.widget.Row);
+    method public void setPlaybackRowPresenter(android.support.v17.leanback.widget.PlaybackRowPresenter);
+    method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method public void showControlsOverlay(boolean);
+    method public void tickle();
+    field public static final int BG_DARK = 1; // 0x1
+    field public static final int BG_LIGHT = 2; // 0x2
+    field public static final int BG_NONE = 0; // 0x0
+  }
+
+  public class PlaybackFragmentGlueHost extends android.support.v17.leanback.media.PlaybackGlueHost implements android.support.v17.leanback.widget.PlaybackSeekUi {
+    ctor public PlaybackFragmentGlueHost(android.support.v17.leanback.app.PlaybackFragment);
+    method public void fadeOut();
+    method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+  }
+
+  public deprecated class PlaybackOverlayFragment extends android.support.v17.leanback.app.DetailsFragment {
+    ctor public PlaybackOverlayFragment();
+    method public void fadeOut();
+    method public int getBackgroundType();
+    method public final android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler getEventHandler();
+    method public android.support.v17.leanback.app.PlaybackOverlayFragment.OnFadeCompleteListener getFadeCompleteListener();
+    method public final deprecated android.support.v17.leanback.app.PlaybackOverlayFragment.InputEventHandler getInputEventHandler();
+    method public boolean isFadingEnabled();
+    method public void setBackgroundType(int);
+    method public final void setEventHandler(android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler);
+    method public void setFadeCompleteListener(android.support.v17.leanback.app.PlaybackOverlayFragment.OnFadeCompleteListener);
+    method public void setFadingEnabled(boolean);
+    method public final deprecated void setInputEventHandler(android.support.v17.leanback.app.PlaybackOverlayFragment.InputEventHandler);
+    method public void tickle();
+    field public static final int BG_DARK = 1; // 0x1
+    field public static final int BG_LIGHT = 2; // 0x2
+    field public static final int BG_NONE = 0; // 0x0
+  }
+
+  public static abstract deprecated interface PlaybackOverlayFragment.InputEventHandler implements android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler {
+  }
+
+  public static class PlaybackOverlayFragment.OnFadeCompleteListener {
+    ctor public PlaybackOverlayFragment.OnFadeCompleteListener();
+    method public void onFadeInComplete();
+    method public void onFadeOutComplete();
+  }
+
+  public deprecated class PlaybackOverlaySupportFragment extends android.support.v17.leanback.app.DetailsSupportFragment {
+    ctor public PlaybackOverlaySupportFragment();
+    method public void fadeOut();
+    method public int getBackgroundType();
+    method public final android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler getEventHandler();
+    method public android.support.v17.leanback.app.PlaybackOverlaySupportFragment.OnFadeCompleteListener getFadeCompleteListener();
+    method public final deprecated android.support.v17.leanback.app.PlaybackOverlaySupportFragment.InputEventHandler getInputEventHandler();
+    method public boolean isFadingEnabled();
+    method public void setBackgroundType(int);
+    method public final void setEventHandler(android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler);
+    method public void setFadeCompleteListener(android.support.v17.leanback.app.PlaybackOverlaySupportFragment.OnFadeCompleteListener);
+    method public void setFadingEnabled(boolean);
+    method public final deprecated void setInputEventHandler(android.support.v17.leanback.app.PlaybackOverlaySupportFragment.InputEventHandler);
+    method public void tickle();
+    field public static final int BG_DARK = 1; // 0x1
+    field public static final int BG_LIGHT = 2; // 0x2
+    field public static final int BG_NONE = 0; // 0x0
+  }
+
+  public static abstract deprecated interface PlaybackOverlaySupportFragment.InputEventHandler implements android.support.v17.leanback.app.PlaybackControlGlue.InputEventHandler {
+  }
+
+  public static class PlaybackOverlaySupportFragment.OnFadeCompleteListener {
+    ctor public PlaybackOverlaySupportFragment.OnFadeCompleteListener();
+    method public void onFadeInComplete();
+    method public void onFadeOutComplete();
+  }
+
+  public class PlaybackSupportFragment extends android.support.v4.app.Fragment {
+    ctor public PlaybackSupportFragment();
+    method public deprecated void fadeOut();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public int getBackgroundType();
+    method public android.support.v17.leanback.app.ProgressBarManager getProgressBarManager();
+    method public void hideControlsOverlay(boolean);
+    method public boolean isControlsOverlayAutoHideEnabled();
+    method public boolean isControlsOverlayVisible();
+    method public deprecated boolean isFadingEnabled();
+    method public void notifyPlaybackRowChanged();
+    method protected void onBufferingStateChanged(boolean);
+    method protected void onError(int, java.lang.CharSequence);
+    method protected void onVideoSizeChanged(int, int);
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setBackgroundType(int);
+    method public void setControlsOverlayAutoHideEnabled(boolean);
+    method public deprecated void setFadingEnabled(boolean);
+    method public void setHostCallback(android.support.v17.leanback.media.PlaybackGlueHost.HostCallback);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public final void setOnKeyInterceptListener(android.view.View.OnKeyListener);
+    method public void setOnPlaybackItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setPlaybackRow(android.support.v17.leanback.widget.Row);
+    method public void setPlaybackRowPresenter(android.support.v17.leanback.widget.PlaybackRowPresenter);
+    method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, boolean);
+    method public void showControlsOverlay(boolean);
+    method public void tickle();
+    field public static final int BG_DARK = 1; // 0x1
+    field public static final int BG_LIGHT = 2; // 0x2
+    field public static final int BG_NONE = 0; // 0x0
+  }
+
+  public class PlaybackSupportFragmentGlueHost extends android.support.v17.leanback.media.PlaybackGlueHost implements android.support.v17.leanback.widget.PlaybackSeekUi {
+    ctor public PlaybackSupportFragmentGlueHost(android.support.v17.leanback.app.PlaybackSupportFragment);
+    method public void fadeOut();
+    method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+  }
+
+  public final class ProgressBarManager {
+    ctor public ProgressBarManager();
+    method public void disableProgressBar();
+    method public void enableProgressBar();
+    method public long getInitialDelay();
+    method public void hide();
+    method public void setInitialDelay(long);
+    method public void setProgressBarView(android.view.View);
+    method public void setRootView(android.view.ViewGroup);
+    method public void show();
+  }
+
+  public class RowsFragment extends android.support.v17.leanback.app.BaseRowFragment implements android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapterProvider android.support.v17.leanback.app.BrowseFragment.MainFragmentRowsAdapterProvider {
+    ctor public RowsFragment();
+    method public deprecated void enableRowScaling(boolean);
+    method protected android.support.v17.leanback.widget.VerticalGridView findGridViewFromRoot(android.view.View);
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder findRowViewHolderByPosition(int);
+    method public android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapter getMainFragmentAdapter();
+    method public android.support.v17.leanback.app.BrowseFragment.MainFragmentRowsAdapter getMainFragmentRowsAdapter();
+    method public android.support.v17.leanback.widget.BaseOnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.BaseOnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder getRowViewHolder(int);
+    method public boolean isScrolling();
+    method public void setEntranceTransitionState(boolean);
+    method public void setExpand(boolean);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+  }
+
+  public static class RowsFragment.MainFragmentAdapter extends android.support.v17.leanback.app.BrowseFragment.MainFragmentAdapter {
+    ctor public RowsFragment.MainFragmentAdapter(android.support.v17.leanback.app.RowsFragment);
+  }
+
+  public static class RowsFragment.MainFragmentRowsAdapter extends android.support.v17.leanback.app.BrowseFragment.MainFragmentRowsAdapter {
+    ctor public RowsFragment.MainFragmentRowsAdapter(android.support.v17.leanback.app.RowsFragment);
+  }
+
+  public class RowsSupportFragment extends android.support.v17.leanback.app.BaseRowSupportFragment implements android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapterProvider android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentRowsAdapterProvider {
+    ctor public RowsSupportFragment();
+    method public deprecated void enableRowScaling(boolean);
+    method protected android.support.v17.leanback.widget.VerticalGridView findGridViewFromRoot(android.view.View);
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder findRowViewHolderByPosition(int);
+    method public android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapter getMainFragmentAdapter();
+    method public android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentRowsAdapter getMainFragmentRowsAdapter();
+    method public android.support.v17.leanback.widget.BaseOnItemViewClickedListener getOnItemViewClickedListener();
+    method public android.support.v17.leanback.widget.BaseOnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public android.support.v17.leanback.widget.RowPresenter.ViewHolder getRowViewHolder(int);
+    method public boolean isScrolling();
+    method public void setEntranceTransitionState(boolean);
+    method public void setExpand(boolean);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public void setSelectedPosition(int, boolean, android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+  }
+
+  public static class RowsSupportFragment.MainFragmentAdapter extends android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentAdapter {
+    ctor public RowsSupportFragment.MainFragmentAdapter(android.support.v17.leanback.app.RowsSupportFragment);
+  }
+
+  public static class RowsSupportFragment.MainFragmentRowsAdapter extends android.support.v17.leanback.app.BrowseSupportFragment.MainFragmentRowsAdapter {
+    ctor public RowsSupportFragment.MainFragmentRowsAdapter(android.support.v17.leanback.app.RowsSupportFragment);
+  }
+
+  public class SearchFragment extends android.app.Fragment {
+    ctor public SearchFragment();
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String);
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String, java.lang.String);
+    method public void displayCompletions(java.util.List<java.lang.String>);
+    method public void displayCompletions(android.view.inputmethod.CompletionInfo[]);
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public android.content.Intent getRecognizerIntent();
+    method public android.support.v17.leanback.app.RowsFragment getRowsFragment();
+    method public java.lang.String getTitle();
+    method public static android.support.v17.leanback.app.SearchFragment newInstance(java.lang.String);
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchAffordanceColorsInListening(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchQuery(java.lang.String, boolean);
+    method public void setSearchQuery(android.content.Intent, boolean);
+    method public void setSearchResultProvider(android.support.v17.leanback.app.SearchFragment.SearchResultProvider);
+    method public void setSpeechRecognitionCallback(android.support.v17.leanback.widget.SpeechRecognitionCallback);
+    method public void setTitle(java.lang.String);
+    method public void startRecognition();
+  }
+
+  public static abstract interface SearchFragment.SearchResultProvider {
+    method public abstract android.support.v17.leanback.widget.ObjectAdapter getResultsAdapter();
+    method public abstract boolean onQueryTextChange(java.lang.String);
+    method public abstract boolean onQueryTextSubmit(java.lang.String);
+  }
+
+  public class SearchSupportFragment extends android.support.v4.app.Fragment {
+    ctor public SearchSupportFragment();
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String);
+    method public static android.os.Bundle createArgs(android.os.Bundle, java.lang.String, java.lang.String);
+    method public void displayCompletions(java.util.List<java.lang.String>);
+    method public void displayCompletions(android.view.inputmethod.CompletionInfo[]);
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public android.content.Intent getRecognizerIntent();
+    method public android.support.v17.leanback.app.RowsSupportFragment getRowsSupportFragment();
+    method public java.lang.String getTitle();
+    method public static android.support.v17.leanback.app.SearchSupportFragment newInstance(java.lang.String);
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchAffordanceColorsInListening(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchQuery(java.lang.String, boolean);
+    method public void setSearchQuery(android.content.Intent, boolean);
+    method public void setSearchResultProvider(android.support.v17.leanback.app.SearchSupportFragment.SearchResultProvider);
+    method public void setSpeechRecognitionCallback(android.support.v17.leanback.widget.SpeechRecognitionCallback);
+    method public void setTitle(java.lang.String);
+    method public void startRecognition();
+  }
+
+  public static abstract interface SearchSupportFragment.SearchResultProvider {
+    method public abstract android.support.v17.leanback.widget.ObjectAdapter getResultsAdapter();
+    method public abstract boolean onQueryTextChange(java.lang.String);
+    method public abstract boolean onQueryTextSubmit(java.lang.String);
+  }
+
+  public class VerticalGridFragment extends android.support.v17.leanback.app.BaseFragment {
+    ctor public VerticalGridFragment();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public android.support.v17.leanback.widget.VerticalGridPresenter getGridPresenter();
+    method public android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setGridPresenter(android.support.v17.leanback.widget.VerticalGridPresenter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+  }
+
+  public class VerticalGridSupportFragment extends android.support.v17.leanback.app.BaseSupportFragment {
+    ctor public VerticalGridSupportFragment();
+    method public android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public android.support.v17.leanback.widget.VerticalGridPresenter getGridPresenter();
+    method public android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setGridPresenter(android.support.v17.leanback.widget.VerticalGridPresenter);
+    method public void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public void setSelectedPosition(int);
+  }
+
+  public class VideoFragment extends android.support.v17.leanback.app.PlaybackFragment {
+    ctor public VideoFragment();
+    method public android.view.SurfaceView getSurfaceView();
+    method public void setSurfaceHolderCallback(android.view.SurfaceHolder.Callback);
+  }
+
+  public class VideoFragmentGlueHost extends android.support.v17.leanback.app.PlaybackFragmentGlueHost implements android.support.v17.leanback.media.SurfaceHolderGlueHost {
+    ctor public VideoFragmentGlueHost(android.support.v17.leanback.app.VideoFragment);
+    method public void setSurfaceHolderCallback(android.view.SurfaceHolder.Callback);
+  }
+
+  public class VideoSupportFragment extends android.support.v17.leanback.app.PlaybackSupportFragment {
+    ctor public VideoSupportFragment();
+    method public android.view.SurfaceView getSurfaceView();
+    method public void setSurfaceHolderCallback(android.view.SurfaceHolder.Callback);
+  }
+
+  public class VideoSupportFragmentGlueHost extends android.support.v17.leanback.app.PlaybackSupportFragmentGlueHost implements android.support.v17.leanback.media.SurfaceHolderGlueHost {
+    ctor public VideoSupportFragmentGlueHost(android.support.v17.leanback.app.VideoSupportFragment);
+    method public void setSurfaceHolderCallback(android.view.SurfaceHolder.Callback);
+  }
+
+}
+
+package android.support.v17.leanback.database {
+
+  public abstract class CursorMapper {
+    ctor public CursorMapper();
+    method protected abstract java.lang.Object bind(android.database.Cursor);
+    method protected abstract void bindColumns(android.database.Cursor);
+    method public java.lang.Object convert(android.database.Cursor);
+  }
+
+}
+
+package android.support.v17.leanback.graphics {
+
+  public class BoundsRule {
+    ctor public BoundsRule();
+    ctor public BoundsRule(android.support.v17.leanback.graphics.BoundsRule);
+    method public void calculateBounds(android.graphics.Rect, android.graphics.Rect);
+    field public android.support.v17.leanback.graphics.BoundsRule.ValueRule bottom;
+    field public android.support.v17.leanback.graphics.BoundsRule.ValueRule left;
+    field public android.support.v17.leanback.graphics.BoundsRule.ValueRule right;
+    field public android.support.v17.leanback.graphics.BoundsRule.ValueRule top;
+  }
+
+  public static final class BoundsRule.ValueRule {
+    method public static android.support.v17.leanback.graphics.BoundsRule.ValueRule absoluteValue(int);
+    method public int getAbsoluteValue();
+    method public float getFraction();
+    method public static android.support.v17.leanback.graphics.BoundsRule.ValueRule inheritFromParent(float);
+    method public static android.support.v17.leanback.graphics.BoundsRule.ValueRule inheritFromParentWithOffset(float, int);
+    method public void setAbsoluteValue(int);
+    method public void setFraction(float);
+  }
+
+  public final class ColorFilterCache {
+    method public static android.support.v17.leanback.graphics.ColorFilterCache getColorFilterCache(int);
+    method public android.graphics.ColorFilter getFilterForLevel(float);
+  }
+
+  public final class ColorFilterDimmer {
+    method public void applyFilterToView(android.view.View);
+    method public static android.support.v17.leanback.graphics.ColorFilterDimmer create(android.support.v17.leanback.graphics.ColorFilterCache, float, float);
+    method public static android.support.v17.leanback.graphics.ColorFilterDimmer createDefault(android.content.Context);
+    method public android.graphics.ColorFilter getColorFilter();
+    method public android.graphics.Paint getPaint();
+    method public void setActiveLevel(float);
+  }
+
+  public final class ColorOverlayDimmer {
+    method public int applyToColor(int);
+    method public static android.support.v17.leanback.graphics.ColorOverlayDimmer createColorOverlayDimmer(int, float, float);
+    method public static android.support.v17.leanback.graphics.ColorOverlayDimmer createDefault(android.content.Context);
+    method public void drawColorOverlay(android.graphics.Canvas, android.view.View, boolean);
+    method public int getAlpha();
+    method public float getAlphaFloat();
+    method public android.graphics.Paint getPaint();
+    method public boolean needsDraw();
+    method public void setActiveLevel(float);
+  }
+
+  public class CompositeDrawable extends android.graphics.drawable.Drawable implements android.graphics.drawable.Drawable.Callback {
+    ctor public CompositeDrawable();
+    method public void addChildDrawable(android.graphics.drawable.Drawable);
+    method public void draw(android.graphics.Canvas);
+    method public android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable getChildAt(int);
+    method public int getChildCount();
+    method public android.graphics.drawable.Drawable getDrawable(int);
+    method public int getOpacity();
+    method public void invalidateDrawable(android.graphics.drawable.Drawable);
+    method public void removeChild(int);
+    method public void removeDrawable(android.graphics.drawable.Drawable);
+    method public void scheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable, long);
+    method public void setAlpha(int);
+    method public void setChildDrawableAt(int, android.graphics.drawable.Drawable);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void unscheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable);
+  }
+
+  public static final class CompositeDrawable.ChildDrawable {
+    ctor public CompositeDrawable.ChildDrawable(android.graphics.drawable.Drawable, android.support.v17.leanback.graphics.CompositeDrawable);
+    method public android.support.v17.leanback.graphics.BoundsRule getBoundsRule();
+    method public android.graphics.drawable.Drawable getDrawable();
+    method public void recomputeBounds();
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Integer> BOTTOM_ABSOLUTE;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Float> BOTTOM_FRACTION;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Integer> LEFT_ABSOLUTE;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Float> LEFT_FRACTION;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Integer> RIGHT_ABSOLUTE;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Float> RIGHT_FRACTION;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Integer> TOP_ABSOLUTE;
+    field public static final android.util.Property<android.support.v17.leanback.graphics.CompositeDrawable.ChildDrawable, java.lang.Float> TOP_FRACTION;
+  }
+
+  public class FitWidthBitmapDrawable extends android.graphics.drawable.Drawable {
+    ctor public FitWidthBitmapDrawable();
+    method public void draw(android.graphics.Canvas);
+    method public android.graphics.Bitmap getBitmap();
+    method public int getOpacity();
+    method public android.graphics.Rect getSource();
+    method public int getVerticalOffset();
+    method public void setAlpha(int);
+    method public void setBitmap(android.graphics.Bitmap);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setSource(android.graphics.Rect);
+    method public void setVerticalOffset(int);
+    field public static final android.util.Property<android.support.v17.leanback.graphics.FitWidthBitmapDrawable, java.lang.Integer> PROPERTY_VERTICAL_OFFSET;
+  }
+
+}
+
+package android.support.v17.leanback.media {
+
+  public abstract class MediaControllerGlue extends android.support.v17.leanback.media.PlaybackControlGlue {
+    ctor public MediaControllerGlue(android.content.Context, int[], int[]);
+    method public void attachToMediaController(android.support.v4.media.session.MediaControllerCompat);
+    method public void detach();
+    method public int getCurrentPosition();
+    method public int getCurrentSpeedId();
+    method public android.graphics.drawable.Drawable getMediaArt();
+    method public final android.support.v4.media.session.MediaControllerCompat getMediaController();
+    method public int getMediaDuration();
+    method public java.lang.CharSequence getMediaSubtitle();
+    method public java.lang.CharSequence getMediaTitle();
+    method public long getSupportedActions();
+    method public boolean hasValidMedia();
+    method public boolean isMediaPlaying();
+  }
+
+  public class MediaPlayerAdapter extends android.support.v17.leanback.media.PlayerAdapter {
+    ctor public MediaPlayerAdapter(android.content.Context);
+    method protected boolean onError(int, int);
+    method protected boolean onInfo(int, int);
+    method protected void onSeekComplete();
+    method public void pause();
+    method public void play();
+    method public void release();
+    method public void reset();
+    method public boolean setDataSource(android.net.Uri);
+  }
+
+  public class PlaybackBannerControlGlue<T extends android.support.v17.leanback.media.PlayerAdapter> extends android.support.v17.leanback.media.PlaybackBaseControlGlue {
+    ctor public PlaybackBannerControlGlue(android.content.Context, int[], T);
+    ctor public PlaybackBannerControlGlue(android.content.Context, int[], int[], T);
+    method public int[] getFastForwardSpeeds();
+    method public int[] getRewindSpeeds();
+    method public long getSupportedActions();
+    method public void onActionClicked(android.support.v17.leanback.widget.Action);
+    method protected android.support.v17.leanback.widget.PlaybackRowPresenter onCreateRowPresenter();
+    method public boolean onKey(android.view.View, int, android.view.KeyEvent);
+    field public static final int ACTION_CUSTOM_LEFT_FIRST = 1; // 0x1
+    field public static final int ACTION_CUSTOM_RIGHT_FIRST = 4096; // 0x1000
+    field public static final int ACTION_FAST_FORWARD = 128; // 0x80
+    field public static final int ACTION_PLAY_PAUSE = 64; // 0x40
+    field public static final int ACTION_REWIND = 32; // 0x20
+    field public static final int ACTION_SKIP_TO_NEXT = 256; // 0x100
+    field public static final int ACTION_SKIP_TO_PREVIOUS = 16; // 0x10
+    field public static final int PLAYBACK_SPEED_FAST_L0 = 10; // 0xa
+    field public static final int PLAYBACK_SPEED_FAST_L1 = 11; // 0xb
+    field public static final int PLAYBACK_SPEED_FAST_L2 = 12; // 0xc
+    field public static final int PLAYBACK_SPEED_FAST_L3 = 13; // 0xd
+    field public static final int PLAYBACK_SPEED_FAST_L4 = 14; // 0xe
+    field public static final int PLAYBACK_SPEED_INVALID = -1; // 0xffffffff
+    field public static final int PLAYBACK_SPEED_NORMAL = 1; // 0x1
+    field public static final int PLAYBACK_SPEED_PAUSED = 0; // 0x0
+  }
+
+  public abstract class PlaybackBaseControlGlue<T extends android.support.v17.leanback.media.PlayerAdapter> extends android.support.v17.leanback.media.PlaybackGlue implements android.support.v17.leanback.widget.OnActionClickedListener android.view.View.OnKeyListener {
+    ctor public PlaybackBaseControlGlue(android.content.Context, T);
+    method public android.graphics.drawable.Drawable getArt();
+    method public final long getBufferedPosition();
+    method public android.support.v17.leanback.widget.PlaybackControlsRow getControlsRow();
+    method public long getCurrentPosition();
+    method public final long getDuration();
+    method public android.support.v17.leanback.widget.PlaybackRowPresenter getPlaybackRowPresenter();
+    method public final T getPlayerAdapter();
+    method public java.lang.CharSequence getSubtitle();
+    method public java.lang.CharSequence getTitle();
+    method public boolean isControlsOverlayAutoHideEnabled();
+    method public final boolean isPlaying();
+    method public final boolean isPrepared();
+    method protected static void notifyItemChanged(android.support.v17.leanback.widget.ArrayObjectAdapter, java.lang.Object);
+    method public abstract void onActionClicked(android.support.v17.leanback.widget.Action);
+    method protected void onCreatePrimaryActions(android.support.v17.leanback.widget.ArrayObjectAdapter);
+    method protected abstract android.support.v17.leanback.widget.PlaybackRowPresenter onCreateRowPresenter();
+    method protected void onCreateSecondaryActions(android.support.v17.leanback.widget.ArrayObjectAdapter);
+    method public abstract boolean onKey(android.view.View, int, android.view.KeyEvent);
+    method protected void onPlayCompleted();
+    method protected void onPlayStateChanged();
+    method protected void onPreparedStateChanged();
+    method public final void seekTo(long);
+    method public void setArt(android.graphics.drawable.Drawable);
+    method public void setControlsOverlayAutoHideEnabled(boolean);
+    method public void setControlsRow(android.support.v17.leanback.widget.PlaybackControlsRow);
+    method public void setPlaybackRowPresenter(android.support.v17.leanback.widget.PlaybackRowPresenter);
+    method public void setSubtitle(java.lang.CharSequence);
+    method public void setTitle(java.lang.CharSequence);
+  }
+
+  public abstract class PlaybackControlGlue extends android.support.v17.leanback.media.PlaybackGlue implements android.support.v17.leanback.widget.OnActionClickedListener android.view.View.OnKeyListener {
+    ctor public PlaybackControlGlue(android.content.Context, int[]);
+    ctor public PlaybackControlGlue(android.content.Context, int[], int[]);
+    method public void enableProgressUpdating(boolean);
+    method public android.support.v17.leanback.widget.PlaybackControlsRow getControlsRow();
+    method public deprecated android.support.v17.leanback.widget.PlaybackControlsRowPresenter getControlsRowPresenter();
+    method public abstract int getCurrentPosition();
+    method public abstract int getCurrentSpeedId();
+    method public int[] getFastForwardSpeeds();
+    method public abstract android.graphics.drawable.Drawable getMediaArt();
+    method public abstract int getMediaDuration();
+    method public abstract java.lang.CharSequence getMediaSubtitle();
+    method public abstract java.lang.CharSequence getMediaTitle();
+    method public android.support.v17.leanback.widget.PlaybackRowPresenter getPlaybackRowPresenter();
+    method public int[] getRewindSpeeds();
+    method public abstract long getSupportedActions();
+    method public int getUpdatePeriod();
+    method public abstract boolean hasValidMedia();
+    method public boolean isFadingEnabled();
+    method public abstract boolean isMediaPlaying();
+    method public void onActionClicked(android.support.v17.leanback.widget.Action);
+    method protected void onCreateControlsRowAndPresenter();
+    method protected void onCreatePrimaryActions(android.support.v17.leanback.widget.SparseArrayObjectAdapter);
+    method protected void onCreateSecondaryActions(android.support.v17.leanback.widget.ArrayObjectAdapter);
+    method public boolean onKey(android.view.View, int, android.view.KeyEvent);
+    method protected void onMetadataChanged();
+    method protected void onStateChanged();
+    method public void play(int);
+    method public final void play();
+    method public void setControlsRow(android.support.v17.leanback.widget.PlaybackControlsRow);
+    method public deprecated void setControlsRowPresenter(android.support.v17.leanback.widget.PlaybackControlsRowPresenter);
+    method public void setFadingEnabled(boolean);
+    method public void setPlaybackRowPresenter(android.support.v17.leanback.widget.PlaybackRowPresenter);
+    method public void updateProgress();
+    field public static final int ACTION_CUSTOM_LEFT_FIRST = 1; // 0x1
+    field public static final int ACTION_CUSTOM_RIGHT_FIRST = 4096; // 0x1000
+    field public static final int ACTION_FAST_FORWARD = 128; // 0x80
+    field public static final int ACTION_PLAY_PAUSE = 64; // 0x40
+    field public static final int ACTION_REWIND = 32; // 0x20
+    field public static final int ACTION_SKIP_TO_NEXT = 256; // 0x100
+    field public static final int ACTION_SKIP_TO_PREVIOUS = 16; // 0x10
+    field public static final int PLAYBACK_SPEED_FAST_L0 = 10; // 0xa
+    field public static final int PLAYBACK_SPEED_FAST_L1 = 11; // 0xb
+    field public static final int PLAYBACK_SPEED_FAST_L2 = 12; // 0xc
+    field public static final int PLAYBACK_SPEED_FAST_L3 = 13; // 0xd
+    field public static final int PLAYBACK_SPEED_FAST_L4 = 14; // 0xe
+    field public static final int PLAYBACK_SPEED_INVALID = -1; // 0xffffffff
+    field public static final int PLAYBACK_SPEED_NORMAL = 1; // 0x1
+    field public static final int PLAYBACK_SPEED_PAUSED = 0; // 0x0
+  }
+
+  public abstract class PlaybackGlue {
+    ctor public PlaybackGlue(android.content.Context);
+    method public void addPlayerCallback(android.support.v17.leanback.media.PlaybackGlue.PlayerCallback);
+    method public android.content.Context getContext();
+    method public android.support.v17.leanback.media.PlaybackGlueHost getHost();
+    method protected java.util.List<android.support.v17.leanback.media.PlaybackGlue.PlayerCallback> getPlayerCallbacks();
+    method public boolean isPlaying();
+    method public boolean isPrepared();
+    method public deprecated boolean isReadyForPlayback();
+    method public void next();
+    method protected void onAttachedToHost(android.support.v17.leanback.media.PlaybackGlueHost);
+    method protected void onDetachedFromHost();
+    method protected void onHostPause();
+    method protected void onHostResume();
+    method protected void onHostStart();
+    method protected void onHostStop();
+    method public void pause();
+    method public void play();
+    method public void previous();
+    method public void removePlayerCallback(android.support.v17.leanback.media.PlaybackGlue.PlayerCallback);
+    method public final void setHost(android.support.v17.leanback.media.PlaybackGlueHost);
+    method public deprecated void setPlayerCallback(android.support.v17.leanback.media.PlaybackGlue.PlayerCallback);
+  }
+
+  public static abstract class PlaybackGlue.PlayerCallback {
+    ctor public PlaybackGlue.PlayerCallback();
+    method public void onPlayCompleted(android.support.v17.leanback.media.PlaybackGlue);
+    method public void onPlayStateChanged(android.support.v17.leanback.media.PlaybackGlue);
+    method public void onPreparedStateChanged(android.support.v17.leanback.media.PlaybackGlue);
+    method public deprecated void onReadyForPlayback();
+  }
+
+  public abstract class PlaybackGlueHost {
+    ctor public PlaybackGlueHost();
+    method public deprecated void fadeOut();
+    method public android.support.v17.leanback.media.PlaybackGlueHost.PlayerCallback getPlayerCallback();
+    method public void hideControlsOverlay(boolean);
+    method public boolean isControlsOverlayAutoHideEnabled();
+    method public boolean isControlsOverlayVisible();
+    method public void notifyPlaybackRowChanged();
+    method public void setControlsOverlayAutoHideEnabled(boolean);
+    method public deprecated void setFadingEnabled(boolean);
+    method public void setHostCallback(android.support.v17.leanback.media.PlaybackGlueHost.HostCallback);
+    method public void setOnActionClickedListener(android.support.v17.leanback.widget.OnActionClickedListener);
+    method public void setOnKeyInterceptListener(android.view.View.OnKeyListener);
+    method public void setPlaybackRow(android.support.v17.leanback.widget.Row);
+    method public void setPlaybackRowPresenter(android.support.v17.leanback.widget.PlaybackRowPresenter);
+    method public void showControlsOverlay(boolean);
+  }
+
+  public static abstract class PlaybackGlueHost.HostCallback {
+    ctor public PlaybackGlueHost.HostCallback();
+    method public void onHostDestroy();
+    method public void onHostPause();
+    method public void onHostResume();
+    method public void onHostStart();
+    method public void onHostStop();
+  }
+
+  public static class PlaybackGlueHost.PlayerCallback {
+    ctor public PlaybackGlueHost.PlayerCallback();
+    method public void onBufferingStateChanged(boolean);
+    method public void onError(int, java.lang.CharSequence);
+    method public void onVideoSizeChanged(int, int);
+  }
+
+  public class PlaybackTransportControlGlue<T extends android.support.v17.leanback.media.PlayerAdapter> extends android.support.v17.leanback.media.PlaybackBaseControlGlue {
+    ctor public PlaybackTransportControlGlue(android.content.Context, T);
+    method public final android.support.v17.leanback.widget.PlaybackSeekDataProvider getSeekProvider();
+    method public final boolean isSeekEnabled();
+    method public void onActionClicked(android.support.v17.leanback.widget.Action);
+    method protected android.support.v17.leanback.widget.PlaybackRowPresenter onCreateRowPresenter();
+    method public boolean onKey(android.view.View, int, android.view.KeyEvent);
+    method public final void setSeekEnabled(boolean);
+    method public final void setSeekProvider(android.support.v17.leanback.widget.PlaybackSeekDataProvider);
+  }
+
+  public abstract class PlayerAdapter {
+    ctor public PlayerAdapter();
+    method public long getBufferedPosition();
+    method public final android.support.v17.leanback.media.PlayerAdapter.Callback getCallback();
+    method public long getCurrentPosition();
+    method public long getDuration();
+    method public boolean isPlaying();
+    method public boolean isPrepared();
+    method public void onAttachedToHost(android.support.v17.leanback.media.PlaybackGlueHost);
+    method public void onDetachedFromHost();
+    method public abstract void pause();
+    method public abstract void play();
+    method public void seekTo(long);
+    method public final void setCallback(android.support.v17.leanback.media.PlayerAdapter.Callback);
+    method public void setProgressUpdatingEnabled(boolean);
+  }
+
+  public static class PlayerAdapter.Callback {
+    ctor public PlayerAdapter.Callback();
+    method public void onBufferedPositionChanged(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onBufferingStateChanged(android.support.v17.leanback.media.PlayerAdapter, boolean);
+    method public void onCurrentPositionChanged(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onDurationChanged(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onError(android.support.v17.leanback.media.PlayerAdapter, int, java.lang.String);
+    method public void onPlayCompleted(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onPlayStateChanged(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onPreparedStateChanged(android.support.v17.leanback.media.PlayerAdapter);
+    method public void onVideoSizeChanged(android.support.v17.leanback.media.PlayerAdapter, int, int);
+  }
+
+  public abstract interface SurfaceHolderGlueHost {
+    method public abstract void setSurfaceHolderCallback(android.view.SurfaceHolder.Callback);
+  }
+
+}
+
+package android.support.v17.leanback.system {
+
+  public class Settings {
+    method public boolean getBoolean(java.lang.String);
+    method public static android.support.v17.leanback.system.Settings getInstance(android.content.Context);
+    method public void setBoolean(java.lang.String, boolean);
+    field public static final java.lang.String PREFER_STATIC_SHADOWS = "PREFER_STATIC_SHADOWS";
+  }
+
+}
+
+package android.support.v17.leanback.widget {
+
+  public abstract class AbstractDetailsDescriptionPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public AbstractDetailsDescriptionPresenter();
+    method protected abstract void onBindDescription(android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter.ViewHolder, java.lang.Object);
+    method public final void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public final android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+  }
+
+  public static class AbstractDetailsDescriptionPresenter.ViewHolder extends android.support.v17.leanback.widget.Presenter.ViewHolder {
+    ctor public AbstractDetailsDescriptionPresenter.ViewHolder(android.view.View);
+    method public android.widget.TextView getBody();
+    method public android.widget.TextView getSubtitle();
+    method public android.widget.TextView getTitle();
+  }
+
+  public abstract class AbstractMediaItemPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public AbstractMediaItemPresenter();
+    ctor public AbstractMediaItemPresenter(int);
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method public android.support.v17.leanback.widget.Presenter getActionPresenter();
+    method protected int getMediaPlayState(java.lang.Object);
+    method public int getThemeId();
+    method public boolean hasMediaRowSeparator();
+    method protected abstract void onBindMediaDetails(android.support.v17.leanback.widget.AbstractMediaItemPresenter.ViewHolder, java.lang.Object);
+    method public void onBindMediaPlayState(android.support.v17.leanback.widget.AbstractMediaItemPresenter.ViewHolder);
+    method protected void onBindRowActions(android.support.v17.leanback.widget.AbstractMediaItemPresenter.ViewHolder);
+    method protected void onUnbindMediaDetails(android.support.v17.leanback.widget.AbstractMediaItemPresenter.ViewHolder);
+    method public void onUnbindMediaPlayState(android.support.v17.leanback.widget.AbstractMediaItemPresenter.ViewHolder);
+    method public void setActionPresenter(android.support.v17.leanback.widget.Presenter);
+    method public void setBackgroundColor(int);
+    method public void setHasMediaRowSeparator(boolean);
+    method public void setThemeId(int);
+    field public static final int PLAY_STATE_INITIAL = 0; // 0x0
+    field public static final int PLAY_STATE_PAUSED = 1; // 0x1
+    field public static final int PLAY_STATE_PLAYING = 2; // 0x2
+  }
+
+  public static class AbstractMediaItemPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public AbstractMediaItemPresenter.ViewHolder(android.view.View);
+    method public android.view.ViewGroup getMediaItemActionsContainer();
+    method public android.view.View getMediaItemDetailsView();
+    method public android.widget.TextView getMediaItemDurationView();
+    method public android.widget.TextView getMediaItemNameView();
+    method public android.widget.TextView getMediaItemNumberView();
+    method public android.widget.ViewFlipper getMediaItemNumberViewFlipper();
+    method public android.view.View getMediaItemPausedView();
+    method public android.view.View getMediaItemPlayingView();
+    method public android.support.v17.leanback.widget.MultiActionsProvider.MultiAction[] getMediaItemRowActions();
+    method public android.view.View getMediaItemRowSeparator();
+    method public android.view.View getSelectorView();
+    method public void notifyActionChanged(android.support.v17.leanback.widget.MultiActionsProvider.MultiAction);
+    method public void notifyDetailsChanged();
+    method public void notifyPlayStateChanged();
+    method public void onBindRowActions();
+    method public void setSelectedMediaItemNumberView(int);
+  }
+
+  public abstract class AbstractMediaListHeaderPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public AbstractMediaListHeaderPresenter(android.content.Context, int);
+    ctor public AbstractMediaListHeaderPresenter();
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method protected abstract void onBindMediaListHeaderViewHolder(android.support.v17.leanback.widget.AbstractMediaListHeaderPresenter.ViewHolder, java.lang.Object);
+    method public void setBackgroundColor(int);
+  }
+
+  public static class AbstractMediaListHeaderPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public AbstractMediaListHeaderPresenter.ViewHolder(android.view.View);
+    method public android.widget.TextView getHeaderView();
+  }
+
+  public class Action {
+    ctor public Action(long);
+    ctor public Action(long, java.lang.CharSequence);
+    ctor public Action(long, java.lang.CharSequence, java.lang.CharSequence);
+    ctor public Action(long, java.lang.CharSequence, java.lang.CharSequence, android.graphics.drawable.Drawable);
+    method public final void addKeyCode(int);
+    method public final android.graphics.drawable.Drawable getIcon();
+    method public final long getId();
+    method public final java.lang.CharSequence getLabel1();
+    method public final java.lang.CharSequence getLabel2();
+    method public final void removeKeyCode(int);
+    method public final boolean respondsToKeyCode(int);
+    method public final void setIcon(android.graphics.drawable.Drawable);
+    method public final void setId(long);
+    method public final void setLabel1(java.lang.CharSequence);
+    method public final void setLabel2(java.lang.CharSequence);
+    field public static final long NO_ID = -1L; // 0xffffffffffffffffL
+  }
+
+  public class ArrayObjectAdapter extends android.support.v17.leanback.widget.ObjectAdapter {
+    ctor public ArrayObjectAdapter(android.support.v17.leanback.widget.PresenterSelector);
+    ctor public ArrayObjectAdapter(android.support.v17.leanback.widget.Presenter);
+    ctor public ArrayObjectAdapter();
+    method public void add(java.lang.Object);
+    method public void add(int, java.lang.Object);
+    method public void addAll(int, java.util.Collection);
+    method public void clear();
+    method public java.lang.Object get(int);
+    method public int indexOf(java.lang.Object);
+    method public void notifyArrayItemRangeChanged(int, int);
+    method public boolean remove(java.lang.Object);
+    method public int removeItems(int, int);
+    method public void replace(int, java.lang.Object);
+    method public int size();
+    method public <E> java.util.List<E> unmodifiableList();
+  }
+
+  public class BaseCardView extends android.widget.FrameLayout {
+    ctor public BaseCardView(android.content.Context);
+    ctor public BaseCardView(android.content.Context, android.util.AttributeSet);
+    ctor public BaseCardView(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.v17.leanback.widget.BaseCardView.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v17.leanback.widget.BaseCardView.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v17.leanback.widget.BaseCardView.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getCardType();
+    method public deprecated int getExtraVisibility();
+    method public int getInfoVisibility();
+    method public boolean isSelectedAnimationDelayed();
+    method public void setCardType(int);
+    method public deprecated void setExtraVisibility(int);
+    method public void setInfoVisibility(int);
+    method public void setSelectedAnimationDelayed(boolean);
+    field public static final int CARD_REGION_VISIBLE_ACTIVATED = 1; // 0x1
+    field public static final int CARD_REGION_VISIBLE_ALWAYS = 0; // 0x0
+    field public static final int CARD_REGION_VISIBLE_SELECTED = 2; // 0x2
+    field public static final int CARD_TYPE_INFO_OVER = 1; // 0x1
+    field public static final int CARD_TYPE_INFO_UNDER = 2; // 0x2
+    field public static final int CARD_TYPE_INFO_UNDER_WITH_EXTRA = 3; // 0x3
+    field public static final int CARD_TYPE_MAIN_ONLY = 0; // 0x0
+  }
+
+  public static class BaseCardView.LayoutParams extends android.widget.FrameLayout.LayoutParams {
+    ctor public BaseCardView.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public BaseCardView.LayoutParams(int, int);
+    ctor public BaseCardView.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public BaseCardView.LayoutParams(android.support.v17.leanback.widget.BaseCardView.LayoutParams);
+    field public static final int VIEW_TYPE_EXTRA = 2; // 0x2
+    field public static final int VIEW_TYPE_INFO = 1; // 0x1
+    field public static final int VIEW_TYPE_MAIN = 0; // 0x0
+    field public int viewType;
+  }
+
+  public abstract class BaseGridView extends android.support.v7.widget.RecyclerView {
+    method public void addOnChildViewHolderSelectedListener(android.support.v17.leanback.widget.OnChildViewHolderSelectedListener);
+    method public void animateIn();
+    method public void animateOut();
+    method public int getChildDrawingOrder(int, int);
+    method public deprecated int getHorizontalMargin();
+    method public int getHorizontalSpacing();
+    method public int getInitialPrefetchItemCount();
+    method public int getItemAlignmentOffset();
+    method public float getItemAlignmentOffsetPercent();
+    method public int getItemAlignmentViewId();
+    method public android.support.v17.leanback.widget.BaseGridView.OnUnhandledKeyListener getOnUnhandledKeyListener();
+    method public final int getSaveChildrenLimitNumber();
+    method public final int getSaveChildrenPolicy();
+    method public int getSelectedPosition();
+    method public deprecated int getVerticalMargin();
+    method public int getVerticalSpacing();
+    method public void getViewSelectedOffsets(android.view.View, int[]);
+    method public int getWindowAlignment();
+    method public int getWindowAlignmentOffset();
+    method public float getWindowAlignmentOffsetPercent();
+    method public boolean hasPreviousViewInSameRow(int);
+    method public boolean isChildLayoutAnimated();
+    method public boolean isFocusDrawingOrderEnabled();
+    method public final boolean isFocusSearchDisabled();
+    method public boolean isItemAlignmentOffsetWithPadding();
+    method public boolean isScrollEnabled();
+    method public boolean isWindowAlignmentPreferKeyLineOverHighEdge();
+    method public boolean isWindowAlignmentPreferKeyLineOverLowEdge();
+    method public boolean onRequestFocusInDescendants(int, android.graphics.Rect);
+    method public void removeOnChildViewHolderSelectedListener(android.support.v17.leanback.widget.OnChildViewHolderSelectedListener);
+    method public void setAnimateChildLayout(boolean);
+    method public void setChildrenVisibility(int);
+    method public void setFocusDrawingOrderEnabled(boolean);
+    method public final void setFocusSearchDisabled(boolean);
+    method public void setGravity(int);
+    method public void setHasOverlappingRendering(boolean);
+    method public deprecated void setHorizontalMargin(int);
+    method public void setHorizontalSpacing(int);
+    method public void setInitialPrefetchItemCount(int);
+    method public void setItemAlignmentOffset(int);
+    method public void setItemAlignmentOffsetPercent(float);
+    method public void setItemAlignmentOffsetWithPadding(boolean);
+    method public void setItemAlignmentViewId(int);
+    method public deprecated void setItemMargin(int);
+    method public void setItemSpacing(int);
+    method public void setLayoutEnabled(boolean);
+    method public void setOnChildLaidOutListener(android.support.v17.leanback.widget.OnChildLaidOutListener);
+    method public void setOnChildSelectedListener(android.support.v17.leanback.widget.OnChildSelectedListener);
+    method public void setOnChildViewHolderSelectedListener(android.support.v17.leanback.widget.OnChildViewHolderSelectedListener);
+    method public void setOnKeyInterceptListener(android.support.v17.leanback.widget.BaseGridView.OnKeyInterceptListener);
+    method public void setOnMotionInterceptListener(android.support.v17.leanback.widget.BaseGridView.OnMotionInterceptListener);
+    method public void setOnTouchInterceptListener(android.support.v17.leanback.widget.BaseGridView.OnTouchInterceptListener);
+    method public void setOnUnhandledKeyListener(android.support.v17.leanback.widget.BaseGridView.OnUnhandledKeyListener);
+    method public void setPruneChild(boolean);
+    method public final void setSaveChildrenLimitNumber(int);
+    method public final void setSaveChildrenPolicy(int);
+    method public void setScrollEnabled(boolean);
+    method public void setSelectedPosition(int);
+    method public void setSelectedPosition(int, int);
+    method public void setSelectedPosition(int, android.support.v17.leanback.widget.ViewHolderTask);
+    method public void setSelectedPositionSmooth(int);
+    method public void setSelectedPositionSmooth(int, android.support.v17.leanback.widget.ViewHolderTask);
+    method public deprecated void setVerticalMargin(int);
+    method public void setVerticalSpacing(int);
+    method public void setWindowAlignment(int);
+    method public void setWindowAlignmentOffset(int);
+    method public void setWindowAlignmentOffsetPercent(float);
+    method public void setWindowAlignmentPreferKeyLineOverHighEdge(boolean);
+    method public void setWindowAlignmentPreferKeyLineOverLowEdge(boolean);
+    field public static final float ITEM_ALIGN_OFFSET_PERCENT_DISABLED = -1.0f;
+    field public static final int SAVE_ALL_CHILD = 3; // 0x3
+    field public static final int SAVE_LIMITED_CHILD = 2; // 0x2
+    field public static final int SAVE_NO_CHILD = 0; // 0x0
+    field public static final int SAVE_ON_SCREEN_CHILD = 1; // 0x1
+    field public static final int WINDOW_ALIGN_BOTH_EDGE = 3; // 0x3
+    field public static final int WINDOW_ALIGN_HIGH_EDGE = 2; // 0x2
+    field public static final int WINDOW_ALIGN_LOW_EDGE = 1; // 0x1
+    field public static final int WINDOW_ALIGN_NO_EDGE = 0; // 0x0
+    field public static final float WINDOW_ALIGN_OFFSET_PERCENT_DISABLED = -1.0f;
+  }
+
+  public static abstract interface BaseGridView.OnKeyInterceptListener {
+    method public abstract boolean onInterceptKeyEvent(android.view.KeyEvent);
+  }
+
+  public static abstract interface BaseGridView.OnMotionInterceptListener {
+    method public abstract boolean onInterceptMotionEvent(android.view.MotionEvent);
+  }
+
+  public static abstract interface BaseGridView.OnTouchInterceptListener {
+    method public abstract boolean onInterceptTouchEvent(android.view.MotionEvent);
+  }
+
+  public static abstract interface BaseGridView.OnUnhandledKeyListener {
+    method public abstract boolean onUnhandledKey(android.view.KeyEvent);
+  }
+
+  public abstract interface BaseOnItemViewClickedListener<T> {
+    method public abstract void onItemClicked(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object, android.support.v17.leanback.widget.RowPresenter.ViewHolder, T);
+  }
+
+  public abstract interface BaseOnItemViewSelectedListener<T> {
+    method public abstract void onItemSelected(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object, android.support.v17.leanback.widget.RowPresenter.ViewHolder, T);
+  }
+
+  public class BrowseFrameLayout extends android.widget.FrameLayout {
+    ctor public BrowseFrameLayout(android.content.Context);
+    ctor public BrowseFrameLayout(android.content.Context, android.util.AttributeSet);
+    ctor public BrowseFrameLayout(android.content.Context, android.util.AttributeSet, int);
+    method public android.support.v17.leanback.widget.BrowseFrameLayout.OnChildFocusListener getOnChildFocusListener();
+    method public android.support.v17.leanback.widget.BrowseFrameLayout.OnFocusSearchListener getOnFocusSearchListener();
+    method public void setOnChildFocusListener(android.support.v17.leanback.widget.BrowseFrameLayout.OnChildFocusListener);
+    method public void setOnDispatchKeyListener(android.view.View.OnKeyListener);
+    method public void setOnFocusSearchListener(android.support.v17.leanback.widget.BrowseFrameLayout.OnFocusSearchListener);
+  }
+
+  public static abstract interface BrowseFrameLayout.OnChildFocusListener {
+    method public abstract void onRequestChildFocus(android.view.View, android.view.View);
+    method public abstract boolean onRequestFocusInDescendants(int, android.graphics.Rect);
+  }
+
+  public static abstract interface BrowseFrameLayout.OnFocusSearchListener {
+    method public abstract android.view.View onFocusSearch(android.view.View, int);
+  }
+
+  public final class ClassPresenterSelector extends android.support.v17.leanback.widget.PresenterSelector {
+    ctor public ClassPresenterSelector();
+    method public android.support.v17.leanback.widget.ClassPresenterSelector addClassPresenter(java.lang.Class<?>, android.support.v17.leanback.widget.Presenter);
+    method public android.support.v17.leanback.widget.ClassPresenterSelector addClassPresenterSelector(java.lang.Class<?>, android.support.v17.leanback.widget.PresenterSelector);
+    method public android.support.v17.leanback.widget.Presenter getPresenter(java.lang.Object);
+  }
+
+  public class ControlButtonPresenterSelector extends android.support.v17.leanback.widget.PresenterSelector {
+    ctor public ControlButtonPresenterSelector();
+    method public android.support.v17.leanback.widget.Presenter getPresenter(java.lang.Object);
+    method public android.support.v17.leanback.widget.Presenter getPrimaryPresenter();
+    method public android.support.v17.leanback.widget.Presenter getSecondaryPresenter();
+  }
+
+  public class CursorObjectAdapter extends android.support.v17.leanback.widget.ObjectAdapter {
+    ctor public CursorObjectAdapter(android.support.v17.leanback.widget.PresenterSelector);
+    ctor public CursorObjectAdapter(android.support.v17.leanback.widget.Presenter);
+    ctor public CursorObjectAdapter();
+    method public void changeCursor(android.database.Cursor);
+    method public void close();
+    method public java.lang.Object get(int);
+    method public final android.database.Cursor getCursor();
+    method public final android.support.v17.leanback.database.CursorMapper getMapper();
+    method protected final void invalidateCache(int);
+    method protected final void invalidateCache(int, int);
+    method public boolean isClosed();
+    method protected void onCursorChanged();
+    method protected void onMapperChanged();
+    method public final void setMapper(android.support.v17.leanback.database.CursorMapper);
+    method public int size();
+    method public android.database.Cursor swapCursor(android.database.Cursor);
+  }
+
+  public class DetailsOverviewLogoPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public DetailsOverviewLogoPresenter();
+    method public boolean isBoundToImage(android.support.v17.leanback.widget.DetailsOverviewLogoPresenter.ViewHolder, android.support.v17.leanback.widget.DetailsOverviewRow);
+    method public void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public android.view.View onCreateView(android.view.ViewGroup);
+    method public android.support.v17.leanback.widget.Presenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void setContext(android.support.v17.leanback.widget.DetailsOverviewLogoPresenter.ViewHolder, android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter);
+  }
+
+  public static class DetailsOverviewLogoPresenter.ViewHolder extends android.support.v17.leanback.widget.Presenter.ViewHolder {
+    ctor public DetailsOverviewLogoPresenter.ViewHolder(android.view.View);
+    method public android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter getParentPresenter();
+    method public android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder getParentViewHolder();
+    method public boolean isSizeFromDrawableIntrinsic();
+    method public void setSizeFromDrawableIntrinsic(boolean);
+    field protected android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter mParentPresenter;
+    field protected android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder mParentViewHolder;
+  }
+
+  public class DetailsOverviewRow extends android.support.v17.leanback.widget.Row {
+    ctor public DetailsOverviewRow(java.lang.Object);
+    method public final deprecated void addAction(android.support.v17.leanback.widget.Action);
+    method public final deprecated void addAction(int, android.support.v17.leanback.widget.Action);
+    method public android.support.v17.leanback.widget.Action getActionForKeyCode(int);
+    method public final deprecated java.util.List<android.support.v17.leanback.widget.Action> getActions();
+    method public final android.support.v17.leanback.widget.ObjectAdapter getActionsAdapter();
+    method public final android.graphics.drawable.Drawable getImageDrawable();
+    method public final java.lang.Object getItem();
+    method public boolean isImageScaleUpAllowed();
+    method public final deprecated boolean removeAction(android.support.v17.leanback.widget.Action);
+    method public final void setActionsAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public final void setImageBitmap(android.content.Context, android.graphics.Bitmap);
+    method public final void setImageDrawable(android.graphics.drawable.Drawable);
+    method public void setImageScaleUpAllowed(boolean);
+    method public final void setItem(java.lang.Object);
+  }
+
+  public static class DetailsOverviewRow.Listener {
+    ctor public DetailsOverviewRow.Listener();
+    method public void onActionsAdapterChanged(android.support.v17.leanback.widget.DetailsOverviewRow);
+    method public void onImageDrawableChanged(android.support.v17.leanback.widget.DetailsOverviewRow);
+    method public void onItemChanged(android.support.v17.leanback.widget.DetailsOverviewRow);
+  }
+
+  public deprecated class DetailsOverviewRowPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public DetailsOverviewRowPresenter(android.support.v17.leanback.widget.Presenter);
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method public int getBackgroundColor();
+    method public android.support.v17.leanback.widget.OnActionClickedListener getOnActionClickedListener();
+    method public boolean isStyleLarge();
+    method public final boolean isUsingDefaultSelectEffect();
+    method public void setBackgroundColor(int);
+    method public void setOnActionClickedListener(android.support.v17.leanback.widget.OnActionClickedListener);
+    method public final void setSharedElementEnterTransition(android.app.Activity, java.lang.String, long);
+    method public final void setSharedElementEnterTransition(android.app.Activity, java.lang.String);
+    method public void setStyleLarge(boolean);
+  }
+
+  public final class DetailsOverviewRowPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public DetailsOverviewRowPresenter.ViewHolder(android.view.View, android.support.v17.leanback.widget.Presenter);
+    field public final android.support.v17.leanback.widget.Presenter.ViewHolder mDetailsDescriptionViewHolder;
+  }
+
+  public class DetailsParallax extends android.support.v17.leanback.widget.RecyclerViewParallax {
+    ctor public DetailsParallax();
+    method public android.support.v17.leanback.widget.Parallax.IntProperty getOverviewRowBottom();
+    method public android.support.v17.leanback.widget.Parallax.IntProperty getOverviewRowTop();
+  }
+
+  public class DividerPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public DividerPresenter();
+    method public void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public android.support.v17.leanback.widget.Presenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+  }
+
+  public class DividerRow extends android.support.v17.leanback.widget.Row {
+    ctor public DividerRow();
+    method public final boolean isRenderedAsRowView();
+  }
+
+  public abstract interface FacetProvider {
+    method public abstract java.lang.Object getFacet(java.lang.Class<?>);
+  }
+
+  public abstract interface FacetProviderAdapter {
+    method public abstract android.support.v17.leanback.widget.FacetProvider getFacetProvider(int);
+  }
+
+  public abstract interface FocusHighlight {
+    field public static final int ZOOM_FACTOR_LARGE = 3; // 0x3
+    field public static final int ZOOM_FACTOR_MEDIUM = 2; // 0x2
+    field public static final int ZOOM_FACTOR_NONE = 0; // 0x0
+    field public static final int ZOOM_FACTOR_SMALL = 1; // 0x1
+    field public static final int ZOOM_FACTOR_XSMALL = 4; // 0x4
+  }
+
+  public class FocusHighlightHelper {
+    ctor public FocusHighlightHelper();
+    method public static void setupBrowseItemFocusHighlight(android.support.v17.leanback.widget.ItemBridgeAdapter, int, boolean);
+    method public static deprecated void setupHeaderItemFocusHighlight(android.support.v17.leanback.widget.VerticalGridView);
+    method public static deprecated void setupHeaderItemFocusHighlight(android.support.v17.leanback.widget.VerticalGridView, boolean);
+    method public static void setupHeaderItemFocusHighlight(android.support.v17.leanback.widget.ItemBridgeAdapter);
+    method public static void setupHeaderItemFocusHighlight(android.support.v17.leanback.widget.ItemBridgeAdapter, boolean);
+  }
+
+  public abstract interface FragmentAnimationProvider {
+    method public abstract void onImeAppearing(java.util.List<android.animation.Animator>);
+    method public abstract void onImeDisappearing(java.util.List<android.animation.Animator>);
+  }
+
+  public class FullWidthDetailsOverviewRowPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public FullWidthDetailsOverviewRowPresenter(android.support.v17.leanback.widget.Presenter);
+    ctor public FullWidthDetailsOverviewRowPresenter(android.support.v17.leanback.widget.Presenter, android.support.v17.leanback.widget.DetailsOverviewLogoPresenter);
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method public final int getActionsBackgroundColor();
+    method public final int getAlignmentMode();
+    method public final int getBackgroundColor();
+    method public final int getInitialState();
+    method protected int getLayoutResourceId();
+    method public android.support.v17.leanback.widget.OnActionClickedListener getOnActionClickedListener();
+    method public final boolean isParticipatingEntranceTransition();
+    method public final boolean isUsingDefaultSelectEffect();
+    method public final void notifyOnBindLogo(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder);
+    method protected void onLayoutLogo(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int, boolean);
+    method protected void onLayoutOverviewFrame(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int, boolean);
+    method protected void onStateChanged(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int);
+    method public final void setActionsBackgroundColor(int);
+    method public final void setAlignmentMode(int);
+    method public final void setBackgroundColor(int);
+    method public final void setInitialState(int);
+    method public final void setListener(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.Listener);
+    method public void setOnActionClickedListener(android.support.v17.leanback.widget.OnActionClickedListener);
+    method public final void setParticipatingEntranceTransition(boolean);
+    method public final void setState(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder, int);
+    field public static final int ALIGN_MODE_MIDDLE = 1; // 0x1
+    field public static final int ALIGN_MODE_START = 0; // 0x0
+    field public static final int STATE_FULL = 1; // 0x1
+    field public static final int STATE_HALF = 0; // 0x0
+    field public static final int STATE_SMALL = 2; // 0x2
+    field protected int mInitialState;
+  }
+
+  public static abstract class FullWidthDetailsOverviewRowPresenter.Listener {
+    ctor public FullWidthDetailsOverviewRowPresenter.Listener();
+    method public void onBindLogo(android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.ViewHolder);
+  }
+
+  public class FullWidthDetailsOverviewRowPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public FullWidthDetailsOverviewRowPresenter.ViewHolder(android.view.View, android.support.v17.leanback.widget.Presenter, android.support.v17.leanback.widget.DetailsOverviewLogoPresenter);
+    method protected android.support.v17.leanback.widget.DetailsOverviewRow.Listener createRowListener();
+    method public final android.view.ViewGroup getActionsRow();
+    method public final android.view.ViewGroup getDetailsDescriptionFrame();
+    method public final android.support.v17.leanback.widget.Presenter.ViewHolder getDetailsDescriptionViewHolder();
+    method public final android.support.v17.leanback.widget.DetailsOverviewLogoPresenter.ViewHolder getLogoViewHolder();
+    method public final android.view.ViewGroup getOverviewView();
+    method public final int getState();
+    field protected final android.support.v17.leanback.widget.DetailsOverviewRow.Listener mRowListener;
+  }
+
+  public class FullWidthDetailsOverviewRowPresenter.ViewHolder.DetailsOverviewRowListener extends android.support.v17.leanback.widget.DetailsOverviewRow.Listener {
+    ctor public FullWidthDetailsOverviewRowPresenter.ViewHolder.DetailsOverviewRowListener();
+  }
+
+  public class FullWidthDetailsOverviewSharedElementHelper extends android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter.Listener {
+    ctor public FullWidthDetailsOverviewSharedElementHelper();
+    method public boolean getAutoStartSharedElementTransition();
+    method public void setAutoStartSharedElementTransition(boolean);
+    method public void setSharedElementEnterTransition(android.app.Activity, java.lang.String);
+    method public void setSharedElementEnterTransition(android.app.Activity, java.lang.String, long);
+    method public void startPostponedEnterTransition();
+  }
+
+  public class GuidanceStylist implements android.support.v17.leanback.widget.FragmentAnimationProvider {
+    ctor public GuidanceStylist();
+    method public android.widget.TextView getBreadcrumbView();
+    method public android.widget.TextView getDescriptionView();
+    method public android.widget.ImageView getIconView();
+    method public android.widget.TextView getTitleView();
+    method public android.view.View onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.support.v17.leanback.widget.GuidanceStylist.Guidance);
+    method public void onDestroyView();
+    method public void onImeAppearing(java.util.List<android.animation.Animator>);
+    method public void onImeDisappearing(java.util.List<android.animation.Animator>);
+    method public int onProvideLayoutId();
+  }
+
+  public static class GuidanceStylist.Guidance {
+    ctor public GuidanceStylist.Guidance(java.lang.String, java.lang.String, java.lang.String, android.graphics.drawable.Drawable);
+    method public java.lang.String getBreadcrumb();
+    method public java.lang.String getDescription();
+    method public android.graphics.drawable.Drawable getIconDrawable();
+    method public java.lang.String getTitle();
+  }
+
+  public class GuidedAction extends android.support.v17.leanback.widget.Action {
+    ctor protected GuidedAction();
+    method public int getCheckSetId();
+    method public java.lang.CharSequence getDescription();
+    method public int getDescriptionEditInputType();
+    method public int getDescriptionInputType();
+    method public java.lang.CharSequence getEditDescription();
+    method public int getEditInputType();
+    method public java.lang.CharSequence getEditTitle();
+    method public int getInputType();
+    method public android.content.Intent getIntent();
+    method public java.util.List<android.support.v17.leanback.widget.GuidedAction> getSubActions();
+    method public java.lang.CharSequence getTitle();
+    method public boolean hasEditableActivatorView();
+    method public boolean hasMultilineDescription();
+    method public boolean hasNext();
+    method public boolean hasSubActions();
+    method public boolean hasTextEditable();
+    method public boolean infoOnly();
+    method public final boolean isAutoSaveRestoreEnabled();
+    method public boolean isChecked();
+    method public boolean isDescriptionEditable();
+    method public boolean isEditTitleUsed();
+    method public boolean isEditable();
+    method public boolean isEnabled();
+    method public boolean isFocusable();
+    method public void onRestoreInstanceState(android.os.Bundle, java.lang.String);
+    method public void onSaveInstanceState(android.os.Bundle, java.lang.String);
+    method public void setChecked(boolean);
+    method public void setDescription(java.lang.CharSequence);
+    method public void setEditDescription(java.lang.CharSequence);
+    method public void setEditTitle(java.lang.CharSequence);
+    method public void setEnabled(boolean);
+    method public void setFocusable(boolean);
+    method public void setIntent(android.content.Intent);
+    method public void setSubActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public void setTitle(java.lang.CharSequence);
+    field public static final long ACTION_ID_CANCEL = -5L; // 0xfffffffffffffffbL
+    field public static final long ACTION_ID_CONTINUE = -7L; // 0xfffffffffffffff9L
+    field public static final long ACTION_ID_CURRENT = -3L; // 0xfffffffffffffffdL
+    field public static final long ACTION_ID_FINISH = -6L; // 0xfffffffffffffffaL
+    field public static final long ACTION_ID_NEXT = -2L; // 0xfffffffffffffffeL
+    field public static final long ACTION_ID_NO = -9L; // 0xfffffffffffffff7L
+    field public static final long ACTION_ID_OK = -4L; // 0xfffffffffffffffcL
+    field public static final long ACTION_ID_YES = -8L; // 0xfffffffffffffff8L
+    field public static final int CHECKBOX_CHECK_SET_ID = -1; // 0xffffffff
+    field public static final int DEFAULT_CHECK_SET_ID = 1; // 0x1
+    field public static final int NO_CHECK_SET = 0; // 0x0
+  }
+
+  public static class GuidedAction.Builder extends android.support.v17.leanback.widget.GuidedAction.BuilderBase {
+    ctor public deprecated GuidedAction.Builder();
+    ctor public GuidedAction.Builder(android.content.Context);
+    method public android.support.v17.leanback.widget.GuidedAction build();
+  }
+
+  public static abstract class GuidedAction.BuilderBase<B extends android.support.v17.leanback.widget.GuidedAction.BuilderBase> {
+    ctor public GuidedAction.BuilderBase(android.content.Context);
+    method protected final void applyValues(android.support.v17.leanback.widget.GuidedAction);
+    method public B autoSaveRestoreEnabled(boolean);
+    method public B checkSetId(int);
+    method public B checked(boolean);
+    method public B clickAction(long);
+    method public B description(java.lang.CharSequence);
+    method public B description(int);
+    method public B descriptionEditInputType(int);
+    method public B descriptionEditable(boolean);
+    method public B descriptionInputType(int);
+    method public B editDescription(java.lang.CharSequence);
+    method public B editDescription(int);
+    method public B editInputType(int);
+    method public B editTitle(java.lang.CharSequence);
+    method public B editTitle(int);
+    method public B editable(boolean);
+    method public B enabled(boolean);
+    method public B focusable(boolean);
+    method public android.content.Context getContext();
+    method public B hasEditableActivatorView(boolean);
+    method public B hasNext(boolean);
+    method public B icon(android.graphics.drawable.Drawable);
+    method public B icon(int);
+    method public deprecated B iconResourceId(int, android.content.Context);
+    method public B id(long);
+    method public B infoOnly(boolean);
+    method public B inputType(int);
+    method public B intent(android.content.Intent);
+    method public B multilineDescription(boolean);
+    method public B subActions(java.util.List<android.support.v17.leanback.widget.GuidedAction>);
+    method public B title(java.lang.CharSequence);
+    method public B title(int);
+  }
+
+  public class GuidedActionEditText extends android.widget.EditText implements android.support.v17.leanback.widget.ImeKeyMonitor {
+    ctor public GuidedActionEditText(android.content.Context);
+    ctor public GuidedActionEditText(android.content.Context, android.util.AttributeSet);
+    ctor public GuidedActionEditText(android.content.Context, android.util.AttributeSet, int);
+    method public void setImeKeyListener(android.support.v17.leanback.widget.ImeKeyMonitor.ImeKeyListener);
+  }
+
+  public class GuidedActionsStylist implements android.support.v17.leanback.widget.FragmentAnimationProvider {
+    ctor public GuidedActionsStylist();
+    method public void collapseAction(boolean);
+    method public void expandAction(android.support.v17.leanback.widget.GuidedAction, boolean);
+    method public android.support.v17.leanback.widget.VerticalGridView getActionsGridView();
+    method public android.support.v17.leanback.widget.GuidedAction getExpandedAction();
+    method public int getItemViewType(android.support.v17.leanback.widget.GuidedAction);
+    method public android.support.v17.leanback.widget.VerticalGridView getSubActionsGridView();
+    method public final boolean isBackKeyToCollapseActivatorView();
+    method public final boolean isBackKeyToCollapseSubActions();
+    method public boolean isButtonActions();
+    method public boolean isExpandTransitionSupported();
+    method public boolean isExpanded();
+    method public boolean isInExpandTransition();
+    method public boolean isSubActionsExpanded();
+    method public void onAnimateItemChecked(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, boolean);
+    method public void onAnimateItemFocused(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, boolean);
+    method public void onAnimateItemPressed(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, boolean);
+    method public void onAnimateItemPressedCancelled(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder);
+    method public void onBindActivatorView(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public void onBindCheckMarkView(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public void onBindChevronView(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public void onBindViewHolder(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public android.view.View onCreateView(android.view.LayoutInflater, android.view.ViewGroup);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder onCreateViewHolder(android.view.ViewGroup, int);
+    method public void onDestroyView();
+    method protected deprecated void onEditingModeChange(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction, boolean);
+    method protected void onEditingModeChange(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, boolean, boolean);
+    method public void onImeAppearing(java.util.List<android.animation.Animator>);
+    method public void onImeDisappearing(java.util.List<android.animation.Animator>);
+    method public int onProvideItemLayoutId();
+    method public int onProvideItemLayoutId(int);
+    method public int onProvideLayoutId();
+    method public boolean onUpdateActivatorView(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public void onUpdateExpandedViewHolder(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder);
+    method public void openInEditMode(android.support.v17.leanback.widget.GuidedAction);
+    method public void setAsButtonActions();
+    method public final void setBackKeyToCollapseActivatorView(boolean);
+    method public final void setBackKeyToCollapseSubActions(boolean);
+    method public deprecated void setEditingMode(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction, boolean);
+    method public deprecated void setExpandedViewHolder(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder);
+    method protected void setupImeOptions(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder, android.support.v17.leanback.widget.GuidedAction);
+    method public deprecated void startExpandedTransition(android.support.v17.leanback.widget.GuidedActionsStylist.ViewHolder);
+    field public static final int VIEW_TYPE_DATE_PICKER = 1; // 0x1
+    field public static final int VIEW_TYPE_DEFAULT = 0; // 0x0
+  }
+
+  public static class GuidedActionsStylist.ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder implements android.support.v17.leanback.widget.FacetProvider {
+    ctor public GuidedActionsStylist.ViewHolder(android.view.View);
+    ctor public GuidedActionsStylist.ViewHolder(android.view.View, boolean);
+    method public android.support.v17.leanback.widget.GuidedAction getAction();
+    method public android.widget.ImageView getCheckmarkView();
+    method public android.widget.ImageView getChevronView();
+    method public android.view.View getContentView();
+    method public android.widget.TextView getDescriptionView();
+    method public android.widget.EditText getEditableDescriptionView();
+    method public android.widget.EditText getEditableTitleView();
+    method public android.view.View getEditingView();
+    method public java.lang.Object getFacet(java.lang.Class<?>);
+    method public android.widget.ImageView getIconView();
+    method public android.widget.TextView getTitleView();
+    method public boolean isInEditing();
+    method public boolean isInEditingActivatorView();
+    method public boolean isInEditingDescription();
+    method public boolean isInEditingText();
+    method public boolean isInEditingTitle();
+    method public boolean isSubAction();
+  }
+
+  public class GuidedDatePickerAction extends android.support.v17.leanback.widget.GuidedAction {
+    ctor public GuidedDatePickerAction();
+    method public long getDate();
+    method public java.lang.String getDatePickerFormat();
+    method public long getMaxDate();
+    method public long getMinDate();
+    method public void setDate(long);
+  }
+
+  public static final class GuidedDatePickerAction.Builder extends android.support.v17.leanback.widget.GuidedDatePickerAction.BuilderBase {
+    ctor public GuidedDatePickerAction.Builder(android.content.Context);
+    method public android.support.v17.leanback.widget.GuidedDatePickerAction build();
+  }
+
+  public static abstract class GuidedDatePickerAction.BuilderBase<B extends android.support.v17.leanback.widget.GuidedDatePickerAction.BuilderBase> extends android.support.v17.leanback.widget.GuidedAction.BuilderBase {
+    ctor public GuidedDatePickerAction.BuilderBase(android.content.Context);
+    method protected final void applyDatePickerValues(android.support.v17.leanback.widget.GuidedDatePickerAction);
+    method public B date(long);
+    method public B datePickerFormat(java.lang.String);
+    method public B maxDate(long);
+    method public B minDate(long);
+  }
+
+  public class HeaderItem {
+    ctor public HeaderItem(long, java.lang.String);
+    ctor public HeaderItem(java.lang.String);
+    method public java.lang.CharSequence getContentDescription();
+    method public java.lang.CharSequence getDescription();
+    method public final long getId();
+    method public final java.lang.String getName();
+    method public void setContentDescription(java.lang.CharSequence);
+    method public void setDescription(java.lang.CharSequence);
+  }
+
+  public class HorizontalGridView extends android.support.v17.leanback.widget.BaseGridView {
+    ctor public HorizontalGridView(android.content.Context);
+    ctor public HorizontalGridView(android.content.Context, android.util.AttributeSet);
+    ctor public HorizontalGridView(android.content.Context, android.util.AttributeSet, int);
+    method public final boolean getFadingLeftEdge();
+    method public final int getFadingLeftEdgeLength();
+    method public final int getFadingLeftEdgeOffset();
+    method public final boolean getFadingRightEdge();
+    method public final int getFadingRightEdgeLength();
+    method public final int getFadingRightEdgeOffset();
+    method protected void initAttributes(android.content.Context, android.util.AttributeSet);
+    method public final void setFadingLeftEdge(boolean);
+    method public final void setFadingLeftEdgeLength(int);
+    method public final void setFadingLeftEdgeOffset(int);
+    method public final void setFadingRightEdge(boolean);
+    method public final void setFadingRightEdgeLength(int);
+    method public final void setFadingRightEdgeOffset(int);
+    method public void setNumRows(int);
+    method public void setRowHeight(int);
+  }
+
+  public final class HorizontalHoverCardSwitcher extends android.support.v17.leanback.widget.PresenterSwitcher {
+    ctor public HorizontalHoverCardSwitcher();
+    method protected void insertView(android.view.View);
+    method public void select(android.support.v17.leanback.widget.HorizontalGridView, android.view.View, java.lang.Object);
+  }
+
+  public class ImageCardView extends android.support.v17.leanback.widget.BaseCardView {
+    ctor public deprecated ImageCardView(android.content.Context, int);
+    ctor public ImageCardView(android.content.Context, android.util.AttributeSet, int);
+    ctor public ImageCardView(android.content.Context);
+    ctor public ImageCardView(android.content.Context, android.util.AttributeSet);
+    method public android.graphics.drawable.Drawable getBadgeImage();
+    method public java.lang.CharSequence getContentText();
+    method public android.graphics.drawable.Drawable getInfoAreaBackground();
+    method public android.graphics.drawable.Drawable getMainImage();
+    method public final android.widget.ImageView getMainImageView();
+    method public java.lang.CharSequence getTitleText();
+    method public void setBadgeImage(android.graphics.drawable.Drawable);
+    method public void setContentText(java.lang.CharSequence);
+    method public void setInfoAreaBackground(android.graphics.drawable.Drawable);
+    method public void setInfoAreaBackgroundColor(int);
+    method public void setMainImage(android.graphics.drawable.Drawable);
+    method public void setMainImage(android.graphics.drawable.Drawable, boolean);
+    method public void setMainImageAdjustViewBounds(boolean);
+    method public void setMainImageDimensions(int, int);
+    method public void setMainImageScaleType(android.widget.ImageView.ScaleType);
+    method public void setTitleText(java.lang.CharSequence);
+    field public static final int CARD_TYPE_FLAG_CONTENT = 2; // 0x2
+    field public static final int CARD_TYPE_FLAG_ICON_LEFT = 8; // 0x8
+    field public static final int CARD_TYPE_FLAG_ICON_RIGHT = 4; // 0x4
+    field public static final int CARD_TYPE_FLAG_IMAGE_ONLY = 0; // 0x0
+    field public static final int CARD_TYPE_FLAG_TITLE = 1; // 0x1
+  }
+
+  public abstract interface ImeKeyMonitor {
+    method public abstract void setImeKeyListener(android.support.v17.leanback.widget.ImeKeyMonitor.ImeKeyListener);
+  }
+
+  public static abstract interface ImeKeyMonitor.ImeKeyListener {
+    method public abstract boolean onKeyPreIme(android.widget.EditText, int, android.view.KeyEvent);
+  }
+
+  public final class ItemAlignmentFacet {
+    ctor public ItemAlignmentFacet();
+    method public android.support.v17.leanback.widget.ItemAlignmentFacet.ItemAlignmentDef[] getAlignmentDefs();
+    method public boolean isMultiAlignment();
+    method public void setAlignmentDefs(android.support.v17.leanback.widget.ItemAlignmentFacet.ItemAlignmentDef[]);
+    field public static final float ITEM_ALIGN_OFFSET_PERCENT_DISABLED = -1.0f;
+  }
+
+  public static class ItemAlignmentFacet.ItemAlignmentDef {
+    ctor public ItemAlignmentFacet.ItemAlignmentDef();
+    method public final int getItemAlignmentFocusViewId();
+    method public final int getItemAlignmentOffset();
+    method public final float getItemAlignmentOffsetPercent();
+    method public final int getItemAlignmentViewId();
+    method public boolean isAlignedToTextViewBaseLine();
+    method public final boolean isItemAlignmentOffsetWithPadding();
+    method public final void setAlignedToTextViewBaseline(boolean);
+    method public final void setItemAlignmentFocusViewId(int);
+    method public final void setItemAlignmentOffset(int);
+    method public final void setItemAlignmentOffsetPercent(float);
+    method public final void setItemAlignmentOffsetWithPadding(boolean);
+    method public final void setItemAlignmentViewId(int);
+  }
+
+  public class ItemBridgeAdapter extends android.support.v7.widget.RecyclerView.Adapter implements android.support.v17.leanback.widget.FacetProviderAdapter {
+    ctor public ItemBridgeAdapter(android.support.v17.leanback.widget.ObjectAdapter, android.support.v17.leanback.widget.PresenterSelector);
+    ctor public ItemBridgeAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    ctor public ItemBridgeAdapter();
+    method public void clear();
+    method public android.support.v17.leanback.widget.FacetProvider getFacetProvider(int);
+    method public int getItemCount();
+    method public java.util.ArrayList<android.support.v17.leanback.widget.Presenter> getPresenterMapper();
+    method public android.support.v17.leanback.widget.ItemBridgeAdapter.Wrapper getWrapper();
+    method protected void onAddPresenter(android.support.v17.leanback.widget.Presenter, int);
+    method protected void onAttachedToWindow(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method protected void onBind(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public final void onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, int);
+    method protected void onCreate(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public final android.support.v7.widget.RecyclerView.ViewHolder onCreateViewHolder(android.view.ViewGroup, int);
+    method protected void onDetachedFromWindow(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method protected void onUnbind(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public final void onViewAttachedToWindow(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void onViewDetachedFromWindow(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void onViewRecycled(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void setAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public void setAdapterListener(android.support.v17.leanback.widget.ItemBridgeAdapter.AdapterListener);
+    method public void setPresenter(android.support.v17.leanback.widget.PresenterSelector);
+    method public void setPresenterMapper(java.util.ArrayList<android.support.v17.leanback.widget.Presenter>);
+    method public void setWrapper(android.support.v17.leanback.widget.ItemBridgeAdapter.Wrapper);
+  }
+
+  public static class ItemBridgeAdapter.AdapterListener {
+    ctor public ItemBridgeAdapter.AdapterListener();
+    method public void onAddPresenter(android.support.v17.leanback.widget.Presenter, int);
+    method public void onAttachedToWindow(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public void onBind(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public void onCreate(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public void onDetachedFromWindow(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+    method public void onUnbind(android.support.v17.leanback.widget.ItemBridgeAdapter.ViewHolder);
+  }
+
+  public class ItemBridgeAdapter.ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder implements android.support.v17.leanback.widget.FacetProvider {
+    method public final java.lang.Object getExtraObject();
+    method public java.lang.Object getFacet(java.lang.Class<?>);
+    method public final java.lang.Object getItem();
+    method public final android.support.v17.leanback.widget.Presenter getPresenter();
+    method public final android.support.v17.leanback.widget.Presenter.ViewHolder getViewHolder();
+    method public void setExtraObject(java.lang.Object);
+  }
+
+  public static abstract class ItemBridgeAdapter.Wrapper {
+    ctor public ItemBridgeAdapter.Wrapper();
+    method public abstract android.view.View createWrapper(android.view.View);
+    method public abstract void wrap(android.view.View, android.view.View);
+  }
+
+  public class ItemBridgeAdapterShadowOverlayWrapper extends android.support.v17.leanback.widget.ItemBridgeAdapter.Wrapper {
+    ctor public ItemBridgeAdapterShadowOverlayWrapper(android.support.v17.leanback.widget.ShadowOverlayHelper);
+    method public android.view.View createWrapper(android.view.View);
+    method public void wrap(android.view.View, android.view.View);
+  }
+
+  public class ListRow extends android.support.v17.leanback.widget.Row {
+    ctor public ListRow(android.support.v17.leanback.widget.HeaderItem, android.support.v17.leanback.widget.ObjectAdapter);
+    ctor public ListRow(long, android.support.v17.leanback.widget.HeaderItem, android.support.v17.leanback.widget.ObjectAdapter);
+    ctor public ListRow(android.support.v17.leanback.widget.ObjectAdapter);
+    method public final android.support.v17.leanback.widget.ObjectAdapter getAdapter();
+    method public java.lang.CharSequence getContentDescription();
+    method public void setContentDescription(java.lang.CharSequence);
+  }
+
+  public final class ListRowHoverCardView extends android.widget.LinearLayout {
+    ctor public ListRowHoverCardView(android.content.Context);
+    ctor public ListRowHoverCardView(android.content.Context, android.util.AttributeSet);
+    ctor public ListRowHoverCardView(android.content.Context, android.util.AttributeSet, int);
+    method public final java.lang.CharSequence getDescription();
+    method public final java.lang.CharSequence getTitle();
+    method public final void setDescription(java.lang.CharSequence);
+    method public final void setTitle(java.lang.CharSequence);
+  }
+
+  public class ListRowPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public ListRowPresenter();
+    ctor public ListRowPresenter(int);
+    ctor public ListRowPresenter(int, boolean);
+    method protected void applySelectLevelToChild(android.support.v17.leanback.widget.ListRowPresenter.ViewHolder, android.view.View);
+    method public final boolean areChildRoundedCornersEnabled();
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method protected android.support.v17.leanback.widget.ShadowOverlayHelper.Options createShadowOverlayOptions();
+    method public final void enableChildRoundedCorners(boolean);
+    method public int getExpandedRowHeight();
+    method public final int getFocusZoomFactor();
+    method public final android.support.v17.leanback.widget.PresenterSelector getHoverCardPresenterSelector();
+    method public int getRecycledPoolSize(android.support.v17.leanback.widget.Presenter);
+    method public int getRowHeight();
+    method public final boolean getShadowEnabled();
+    method public final deprecated int getZoomFactor();
+    method public final boolean isFocusDimmerUsed();
+    method public final boolean isKeepChildForeground();
+    method public boolean isUsingDefaultListSelectEffect();
+    method public final boolean isUsingDefaultSelectEffect();
+    method public boolean isUsingDefaultShadow();
+    method public boolean isUsingZOrder(android.content.Context);
+    method public void setExpandedRowHeight(int);
+    method public final void setHoverCardPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public final void setKeepChildForeground(boolean);
+    method public void setNumRows(int);
+    method public void setRecycledPoolSize(android.support.v17.leanback.widget.Presenter, int);
+    method public void setRowHeight(int);
+    method public final void setShadowEnabled(boolean);
+  }
+
+  public static class ListRowPresenter.SelectItemViewHolderTask extends android.support.v17.leanback.widget.Presenter.ViewHolderTask {
+    ctor public ListRowPresenter.SelectItemViewHolderTask(int);
+    method public int getItemPosition();
+    method public android.support.v17.leanback.widget.Presenter.ViewHolderTask getItemTask();
+    method public boolean isSmoothScroll();
+    method public void setItemPosition(int);
+    method public void setItemTask(android.support.v17.leanback.widget.Presenter.ViewHolderTask);
+    method public void setSmoothScroll(boolean);
+  }
+
+  public static class ListRowPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public ListRowPresenter.ViewHolder(android.view.View, android.support.v17.leanback.widget.HorizontalGridView, android.support.v17.leanback.widget.ListRowPresenter);
+    method public final android.support.v17.leanback.widget.ItemBridgeAdapter getBridgeAdapter();
+    method public final android.support.v17.leanback.widget.HorizontalGridView getGridView();
+    method public android.support.v17.leanback.widget.Presenter.ViewHolder getItemViewHolder(int);
+    method public final android.support.v17.leanback.widget.ListRowPresenter getListRowPresenter();
+    method public int getSelectedPosition();
+  }
+
+  public final class ListRowView extends android.widget.LinearLayout {
+    ctor public ListRowView(android.content.Context);
+    ctor public ListRowView(android.content.Context, android.util.AttributeSet);
+    ctor public ListRowView(android.content.Context, android.util.AttributeSet, int);
+    method public android.support.v17.leanback.widget.HorizontalGridView getGridView();
+  }
+
+  public abstract interface MultiActionsProvider {
+    method public abstract android.support.v17.leanback.widget.MultiActionsProvider.MultiAction[] getActions();
+  }
+
+  public static class MultiActionsProvider.MultiAction {
+    ctor public MultiActionsProvider.MultiAction(long);
+    method public android.graphics.drawable.Drawable getCurrentDrawable();
+    method public android.graphics.drawable.Drawable[] getDrawables();
+    method public long getId();
+    method public int getIndex();
+    method public void incrementIndex();
+    method public void setDrawables(android.graphics.drawable.Drawable[]);
+    method public void setIndex(int);
+  }
+
+  public abstract class ObjectAdapter {
+    ctor public ObjectAdapter(android.support.v17.leanback.widget.PresenterSelector);
+    ctor public ObjectAdapter(android.support.v17.leanback.widget.Presenter);
+    ctor public ObjectAdapter();
+    method public abstract java.lang.Object get(int);
+    method public long getId(int);
+    method public final android.support.v17.leanback.widget.Presenter getPresenter(java.lang.Object);
+    method public final android.support.v17.leanback.widget.PresenterSelector getPresenterSelector();
+    method public final boolean hasStableIds();
+    method public boolean isImmediateNotifySupported();
+    method protected final void notifyChanged();
+    method public final void notifyItemRangeChanged(int, int);
+    method protected final void notifyItemRangeInserted(int, int);
+    method protected final void notifyItemRangeRemoved(int, int);
+    method protected void onHasStableIdsChanged();
+    method protected void onPresenterSelectorChanged();
+    method public final void registerObserver(android.support.v17.leanback.widget.ObjectAdapter.DataObserver);
+    method public final void setHasStableIds(boolean);
+    method public final void setPresenterSelector(android.support.v17.leanback.widget.PresenterSelector);
+    method public abstract int size();
+    method public final void unregisterAllObservers();
+    method public final void unregisterObserver(android.support.v17.leanback.widget.ObjectAdapter.DataObserver);
+    field public static final int NO_ID = -1; // 0xffffffff
+  }
+
+  public static abstract class ObjectAdapter.DataObserver {
+    ctor public ObjectAdapter.DataObserver();
+    method public void onChanged();
+    method public void onItemRangeChanged(int, int);
+    method public void onItemRangeInserted(int, int);
+    method public void onItemRangeRemoved(int, int);
+  }
+
+  public abstract interface OnActionClickedListener {
+    method public abstract void onActionClicked(android.support.v17.leanback.widget.Action);
+  }
+
+  public abstract interface OnChildLaidOutListener {
+    method public abstract void onChildLaidOut(android.view.ViewGroup, android.view.View, int, long);
+  }
+
+  public abstract deprecated interface OnChildSelectedListener {
+    method public abstract void onChildSelected(android.view.ViewGroup, android.view.View, int, long);
+  }
+
+  public abstract class OnChildViewHolderSelectedListener {
+    ctor public OnChildViewHolderSelectedListener();
+    method public void onChildViewHolderSelected(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, int, int);
+    method public void onChildViewHolderSelectedAndPositioned(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, int, int);
+  }
+
+  public abstract interface OnItemViewClickedListener implements android.support.v17.leanback.widget.BaseOnItemViewClickedListener {
+  }
+
+  public abstract interface OnItemViewSelectedListener implements android.support.v17.leanback.widget.BaseOnItemViewSelectedListener {
+  }
+
+  public class PageRow extends android.support.v17.leanback.widget.Row {
+    ctor public PageRow(android.support.v17.leanback.widget.HeaderItem);
+    method public final boolean isRenderedAsRowView();
+  }
+
+  public abstract class Parallax<PropertyT extends android.util.Property> {
+    ctor public Parallax();
+    method public android.support.v17.leanback.widget.ParallaxEffect addEffect(android.support.v17.leanback.widget.Parallax.PropertyMarkerValue...);
+    method public final PropertyT addProperty(java.lang.String);
+    method public abstract PropertyT createProperty(java.lang.String, int);
+    method public java.util.List<android.support.v17.leanback.widget.ParallaxEffect> getEffects();
+    method public abstract float getMaxValue();
+    method public final java.util.List<PropertyT> getProperties();
+    method public void removeAllEffects();
+    method public void removeEffect(android.support.v17.leanback.widget.ParallaxEffect);
+    method public void updateValues();
+  }
+
+  public static class Parallax.FloatProperty extends android.util.Property {
+    ctor public Parallax.FloatProperty(java.lang.String, int);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue at(float, float);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atAbsolute(float);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atFraction(float);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atMax();
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atMin();
+    method public final java.lang.Float get(android.support.v17.leanback.widget.Parallax);
+    method public final int getIndex();
+    method public final float getValue(android.support.v17.leanback.widget.Parallax);
+    method public final void set(android.support.v17.leanback.widget.Parallax, java.lang.Float);
+    method public final void setValue(android.support.v17.leanback.widget.Parallax, float);
+    field public static final float UNKNOWN_AFTER = 3.4028235E38f;
+    field public static final float UNKNOWN_BEFORE = -3.4028235E38f;
+  }
+
+  public static class Parallax.IntProperty extends android.util.Property {
+    ctor public Parallax.IntProperty(java.lang.String, int);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue at(int, float);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atAbsolute(int);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atFraction(float);
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atMax();
+    method public final android.support.v17.leanback.widget.Parallax.PropertyMarkerValue atMin();
+    method public final java.lang.Integer get(android.support.v17.leanback.widget.Parallax);
+    method public final int getIndex();
+    method public final int getValue(android.support.v17.leanback.widget.Parallax);
+    method public final void set(android.support.v17.leanback.widget.Parallax, java.lang.Integer);
+    method public final void setValue(android.support.v17.leanback.widget.Parallax, int);
+    field public static final int UNKNOWN_AFTER = 2147483647; // 0x7fffffff
+    field public static final int UNKNOWN_BEFORE = -2147483648; // 0x80000000
+  }
+
+  public static class Parallax.PropertyMarkerValue<PropertyT> {
+    ctor public Parallax.PropertyMarkerValue(PropertyT);
+    method public PropertyT getProperty();
+  }
+
+  public abstract class ParallaxEffect {
+    method public final void addTarget(android.support.v17.leanback.widget.ParallaxTarget);
+    method public final java.util.List<android.support.v17.leanback.widget.Parallax.PropertyMarkerValue> getPropertyRanges();
+    method public final java.util.List<android.support.v17.leanback.widget.ParallaxTarget> getTargets();
+    method public final void performMapping(android.support.v17.leanback.widget.Parallax);
+    method public final void removeTarget(android.support.v17.leanback.widget.ParallaxTarget);
+    method public final void setPropertyRanges(android.support.v17.leanback.widget.Parallax.PropertyMarkerValue...);
+    method public final android.support.v17.leanback.widget.ParallaxEffect target(android.support.v17.leanback.widget.ParallaxTarget);
+    method public final android.support.v17.leanback.widget.ParallaxEffect target(java.lang.Object, android.animation.PropertyValuesHolder);
+    method public final <T, V extends java.lang.Number> android.support.v17.leanback.widget.ParallaxEffect target(T, android.util.Property<T, V>);
+  }
+
+  public abstract class ParallaxTarget {
+    ctor public ParallaxTarget();
+    method public void directUpdate(java.lang.Number);
+    method public boolean isDirectMapping();
+    method public void update(float);
+  }
+
+  public static final class ParallaxTarget.DirectPropertyTarget<T, V extends java.lang.Number> extends android.support.v17.leanback.widget.ParallaxTarget {
+    ctor public ParallaxTarget.DirectPropertyTarget(java.lang.Object, android.util.Property<T, V>);
+  }
+
+  public static final class ParallaxTarget.PropertyValuesHolderTarget extends android.support.v17.leanback.widget.ParallaxTarget {
+    ctor public ParallaxTarget.PropertyValuesHolderTarget(java.lang.Object, android.animation.PropertyValuesHolder);
+  }
+
+  public class PlaybackControlsRow extends android.support.v17.leanback.widget.Row {
+    ctor public PlaybackControlsRow(java.lang.Object);
+    ctor public PlaybackControlsRow();
+    method public android.support.v17.leanback.widget.Action getActionForKeyCode(int);
+    method public android.support.v17.leanback.widget.Action getActionForKeyCode(android.support.v17.leanback.widget.ObjectAdapter, int);
+    method public long getBufferedPosition();
+    method public deprecated int getBufferedProgress();
+    method public deprecated long getBufferedProgressLong();
+    method public long getCurrentPosition();
+    method public deprecated int getCurrentTime();
+    method public deprecated long getCurrentTimeLong();
+    method public long getDuration();
+    method public final android.graphics.drawable.Drawable getImageDrawable();
+    method public final java.lang.Object getItem();
+    method public final android.support.v17.leanback.widget.ObjectAdapter getPrimaryActionsAdapter();
+    method public final android.support.v17.leanback.widget.ObjectAdapter getSecondaryActionsAdapter();
+    method public deprecated int getTotalTime();
+    method public deprecated long getTotalTimeLong();
+    method public void setBufferedPosition(long);
+    method public deprecated void setBufferedProgress(int);
+    method public deprecated void setBufferedProgressLong(long);
+    method public void setCurrentPosition(long);
+    method public deprecated void setCurrentTime(int);
+    method public deprecated void setCurrentTimeLong(long);
+    method public void setDuration(long);
+    method public final void setImageBitmap(android.content.Context, android.graphics.Bitmap);
+    method public final void setImageDrawable(android.graphics.drawable.Drawable);
+    method public void setOnPlaybackProgressChangedListener(android.support.v17.leanback.widget.PlaybackControlsRow.OnPlaybackProgressCallback);
+    method public final void setPrimaryActionsAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public final void setSecondaryActionsAdapter(android.support.v17.leanback.widget.ObjectAdapter);
+    method public deprecated void setTotalTime(int);
+    method public deprecated void setTotalTimeLong(long);
+  }
+
+  public static class PlaybackControlsRow.ClosedCaptioningAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.ClosedCaptioningAction(android.content.Context);
+    ctor public PlaybackControlsRow.ClosedCaptioningAction(android.content.Context, int);
+    field public static final int INDEX_OFF = 0; // 0x0
+    field public static final int INDEX_ON = 1; // 0x1
+    field public static deprecated int OFF;
+    field public static deprecated int ON;
+  }
+
+  public static class PlaybackControlsRow.FastForwardAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.FastForwardAction(android.content.Context);
+    ctor public PlaybackControlsRow.FastForwardAction(android.content.Context, int);
+  }
+
+  public static class PlaybackControlsRow.HighQualityAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.HighQualityAction(android.content.Context);
+    ctor public PlaybackControlsRow.HighQualityAction(android.content.Context, int);
+    field public static final int INDEX_OFF = 0; // 0x0
+    field public static final int INDEX_ON = 1; // 0x1
+    field public static deprecated int OFF;
+    field public static deprecated int ON;
+  }
+
+  public static class PlaybackControlsRow.MoreActions extends android.support.v17.leanback.widget.Action {
+    ctor public PlaybackControlsRow.MoreActions(android.content.Context);
+  }
+
+  public static abstract class PlaybackControlsRow.MultiAction extends android.support.v17.leanback.widget.Action {
+    ctor public PlaybackControlsRow.MultiAction(int);
+    method public int getActionCount();
+    method public android.graphics.drawable.Drawable getDrawable(int);
+    method public int getIndex();
+    method public java.lang.String getLabel(int);
+    method public java.lang.String getSecondaryLabel(int);
+    method public void nextIndex();
+    method public void setDrawables(android.graphics.drawable.Drawable[]);
+    method public void setIndex(int);
+    method public void setLabels(java.lang.String[]);
+    method public void setSecondaryLabels(java.lang.String[]);
+  }
+
+  public static class PlaybackControlsRow.OnPlaybackProgressCallback {
+    ctor public PlaybackControlsRow.OnPlaybackProgressCallback();
+    method public void onBufferedPositionChanged(android.support.v17.leanback.widget.PlaybackControlsRow, long);
+    method public void onCurrentPositionChanged(android.support.v17.leanback.widget.PlaybackControlsRow, long);
+    method public void onDurationChanged(android.support.v17.leanback.widget.PlaybackControlsRow, long);
+  }
+
+  public static class PlaybackControlsRow.PictureInPictureAction extends android.support.v17.leanback.widget.Action {
+    ctor public PlaybackControlsRow.PictureInPictureAction(android.content.Context);
+  }
+
+  public static class PlaybackControlsRow.PlayPauseAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.PlayPauseAction(android.content.Context);
+    field public static final int INDEX_PAUSE = 1; // 0x1
+    field public static final int INDEX_PLAY = 0; // 0x0
+    field public static deprecated int PAUSE;
+    field public static deprecated int PLAY;
+  }
+
+  public static class PlaybackControlsRow.RepeatAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.RepeatAction(android.content.Context);
+    ctor public PlaybackControlsRow.RepeatAction(android.content.Context, int);
+    ctor public PlaybackControlsRow.RepeatAction(android.content.Context, int, int);
+    field public static deprecated int ALL;
+    field public static final int INDEX_ALL = 1; // 0x1
+    field public static final int INDEX_NONE = 0; // 0x0
+    field public static final int INDEX_ONE = 2; // 0x2
+    field public static deprecated int NONE;
+    field public static deprecated int ONE;
+  }
+
+  public static class PlaybackControlsRow.RewindAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.RewindAction(android.content.Context);
+    ctor public PlaybackControlsRow.RewindAction(android.content.Context, int);
+  }
+
+  public static class PlaybackControlsRow.ShuffleAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.ShuffleAction(android.content.Context);
+    ctor public PlaybackControlsRow.ShuffleAction(android.content.Context, int);
+    field public static final int INDEX_OFF = 0; // 0x0
+    field public static final int INDEX_ON = 1; // 0x1
+    field public static deprecated int OFF;
+    field public static deprecated int ON;
+  }
+
+  public static class PlaybackControlsRow.SkipNextAction extends android.support.v17.leanback.widget.Action {
+    ctor public PlaybackControlsRow.SkipNextAction(android.content.Context);
+  }
+
+  public static class PlaybackControlsRow.SkipPreviousAction extends android.support.v17.leanback.widget.Action {
+    ctor public PlaybackControlsRow.SkipPreviousAction(android.content.Context);
+  }
+
+  public static abstract class PlaybackControlsRow.ThumbsAction extends android.support.v17.leanback.widget.PlaybackControlsRow.MultiAction {
+    ctor public PlaybackControlsRow.ThumbsAction(int, android.content.Context, int, int);
+    field public static final int INDEX_OUTLINE = 1; // 0x1
+    field public static final int INDEX_SOLID = 0; // 0x0
+    field public static deprecated int OUTLINE;
+    field public static deprecated int SOLID;
+  }
+
+  public static class PlaybackControlsRow.ThumbsDownAction extends android.support.v17.leanback.widget.PlaybackControlsRow.ThumbsAction {
+    ctor public PlaybackControlsRow.ThumbsDownAction(android.content.Context);
+  }
+
+  public static class PlaybackControlsRow.ThumbsUpAction extends android.support.v17.leanback.widget.PlaybackControlsRow.ThumbsAction {
+    ctor public PlaybackControlsRow.ThumbsUpAction(android.content.Context);
+  }
+
+  public class PlaybackControlsRowPresenter extends android.support.v17.leanback.widget.PlaybackRowPresenter {
+    ctor public PlaybackControlsRowPresenter(android.support.v17.leanback.widget.Presenter);
+    ctor public PlaybackControlsRowPresenter();
+    method public boolean areSecondaryActionsHidden();
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method public int getBackgroundColor();
+    method public android.support.v17.leanback.widget.OnActionClickedListener getOnActionClickedListener();
+    method public int getProgressColor();
+    method public void setBackgroundColor(int);
+    method public void setOnActionClickedListener(android.support.v17.leanback.widget.OnActionClickedListener);
+    method public void setProgressColor(int);
+    method public void setSecondaryActionsHidden(boolean);
+    method public void showBottomSpace(android.support.v17.leanback.widget.PlaybackControlsRowPresenter.ViewHolder, boolean);
+    method public void showPrimaryActions(android.support.v17.leanback.widget.PlaybackControlsRowPresenter.ViewHolder);
+  }
+
+  public class PlaybackControlsRowPresenter.ViewHolder extends android.support.v17.leanback.widget.PlaybackRowPresenter.ViewHolder {
+    field public final android.support.v17.leanback.widget.Presenter.ViewHolder mDescriptionViewHolder;
+  }
+
+  public abstract class PlaybackRowPresenter extends android.support.v17.leanback.widget.RowPresenter {
+    ctor public PlaybackRowPresenter();
+    method public void onReappear(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+  }
+
+  public static class PlaybackRowPresenter.ViewHolder extends android.support.v17.leanback.widget.RowPresenter.ViewHolder {
+    ctor public PlaybackRowPresenter.ViewHolder(android.view.View);
+  }
+
+  public class PlaybackSeekDataProvider {
+    ctor public PlaybackSeekDataProvider();
+    method public long[] getSeekPositions();
+    method public void getThumbnail(int, android.support.v17.leanback.widget.PlaybackSeekDataProvider.ResultCallback);
+    method public void reset();
+  }
+
+  public static class PlaybackSeekDataProvider.ResultCallback {
+    ctor public PlaybackSeekDataProvider.ResultCallback();
+    method public void onThumbnailLoaded(android.graphics.Bitmap, int);
+  }
+
+  public abstract interface PlaybackSeekUi {
+    method public abstract void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+  }
+
+  public static class PlaybackSeekUi.Client {
+    ctor public PlaybackSeekUi.Client();
+    method public android.support.v17.leanback.widget.PlaybackSeekDataProvider getPlaybackSeekDataProvider();
+    method public boolean isSeekEnabled();
+    method public void onSeekFinished(boolean);
+    method public void onSeekPositionChanged(long);
+    method public void onSeekStarted();
+  }
+
+  public class PlaybackTransportRowPresenter extends android.support.v17.leanback.widget.PlaybackRowPresenter {
+    ctor public PlaybackTransportRowPresenter();
+    method protected android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method public float getDefaultSeekIncrement();
+    method public android.support.v17.leanback.widget.OnActionClickedListener getOnActionClickedListener();
+    method public int getProgressColor();
+    method protected void onProgressBarClicked(android.support.v17.leanback.widget.PlaybackTransportRowPresenter.ViewHolder);
+    method public void setDefaultSeekIncrement(float);
+    method public void setDescriptionPresenter(android.support.v17.leanback.widget.Presenter);
+    method public void setOnActionClickedListener(android.support.v17.leanback.widget.OnActionClickedListener);
+    method public void setProgressColor(int);
+  }
+
+  public class PlaybackTransportRowPresenter.ViewHolder extends android.support.v17.leanback.widget.PlaybackRowPresenter.ViewHolder implements android.support.v17.leanback.widget.PlaybackSeekUi {
+    ctor public PlaybackTransportRowPresenter.ViewHolder(android.view.View, android.support.v17.leanback.widget.Presenter);
+    method public final android.widget.TextView getCurrentPositionView();
+    method public final android.support.v17.leanback.widget.Presenter.ViewHolder getDescriptionViewHolder();
+    method public final android.widget.TextView getDurationView();
+    method protected void onSetCurrentPositionLabel(long);
+    method protected void onSetDurationLabel(long);
+    method public void setPlaybackSeekUiClient(android.support.v17.leanback.widget.PlaybackSeekUi.Client);
+  }
+
+  public abstract class Presenter implements android.support.v17.leanback.widget.FacetProvider {
+    ctor public Presenter();
+    method protected static void cancelAnimationsRecursive(android.view.View);
+    method public final java.lang.Object getFacet(java.lang.Class<?>);
+    method public abstract void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public abstract android.support.v17.leanback.widget.Presenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public abstract void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void onViewAttachedToWindow(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void onViewDetachedFromWindow(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public final void setFacet(java.lang.Class<?>, java.lang.Object);
+    method public void setOnClickListener(android.support.v17.leanback.widget.Presenter.ViewHolder, android.view.View.OnClickListener);
+  }
+
+  public static class Presenter.ViewHolder implements android.support.v17.leanback.widget.FacetProvider {
+    ctor public Presenter.ViewHolder(android.view.View);
+    method public final java.lang.Object getFacet(java.lang.Class<?>);
+    method public final void setFacet(java.lang.Class<?>, java.lang.Object);
+    field public final android.view.View view;
+  }
+
+  public static abstract class Presenter.ViewHolderTask {
+    ctor public Presenter.ViewHolderTask();
+    method public void run(android.support.v17.leanback.widget.Presenter.ViewHolder);
+  }
+
+  public abstract class PresenterSelector {
+    ctor public PresenterSelector();
+    method public abstract android.support.v17.leanback.widget.Presenter getPresenter(java.lang.Object);
+    method public android.support.v17.leanback.widget.Presenter[] getPresenters();
+  }
+
+  public abstract class PresenterSwitcher {
+    ctor public PresenterSwitcher();
+    method public void clear();
+    method public final android.view.ViewGroup getParentViewGroup();
+    method public void init(android.view.ViewGroup, android.support.v17.leanback.widget.PresenterSelector);
+    method protected abstract void insertView(android.view.View);
+    method protected void onViewSelected(android.view.View);
+    method public void select(java.lang.Object);
+    method protected void showView(android.view.View, boolean);
+    method public void unselect();
+  }
+
+  public class RecyclerViewParallax extends android.support.v17.leanback.widget.Parallax {
+    ctor public RecyclerViewParallax();
+    method public android.support.v17.leanback.widget.RecyclerViewParallax.ChildPositionProperty createProperty(java.lang.String, int);
+    method public float getMaxValue();
+    method public android.support.v7.widget.RecyclerView getRecyclerView();
+    method public void setRecyclerView(android.support.v7.widget.RecyclerView);
+  }
+
+  public static final class RecyclerViewParallax.ChildPositionProperty extends android.support.v17.leanback.widget.Parallax.IntProperty {
+    method public android.support.v17.leanback.widget.RecyclerViewParallax.ChildPositionProperty adapterPosition(int);
+    method public android.support.v17.leanback.widget.RecyclerViewParallax.ChildPositionProperty fraction(float);
+    method public int getAdapterPosition();
+    method public float getFraction();
+    method public int getOffset();
+    method public int getViewId();
+    method public android.support.v17.leanback.widget.RecyclerViewParallax.ChildPositionProperty offset(int);
+    method public android.support.v17.leanback.widget.RecyclerViewParallax.ChildPositionProperty viewId(int);
+  }
+
+  public class Row {
+    ctor public Row(long, android.support.v17.leanback.widget.HeaderItem);
+    ctor public Row(android.support.v17.leanback.widget.HeaderItem);
+    ctor public Row();
+    method public final android.support.v17.leanback.widget.HeaderItem getHeaderItem();
+    method public final long getId();
+    method public boolean isRenderedAsRowView();
+    method public final void setHeaderItem(android.support.v17.leanback.widget.HeaderItem);
+    method public final void setId(long);
+  }
+
+  public class RowHeaderPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public RowHeaderPresenter();
+    method protected static float getFontDescent(android.widget.TextView, android.graphics.Paint);
+    method public int getSpaceUnderBaseline(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder);
+    method public boolean isNullItemVisibilityGone();
+    method public void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public android.support.v17.leanback.widget.Presenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method protected void onSelectLevelChanged(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder);
+    method public void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void setNullItemVisibilityGone(boolean);
+    method public final void setSelectLevel(android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder, float);
+  }
+
+  public static class RowHeaderPresenter.ViewHolder extends android.support.v17.leanback.widget.Presenter.ViewHolder {
+    ctor public RowHeaderPresenter.ViewHolder(android.view.View);
+    method public final float getSelectLevel();
+  }
+
+  public final class RowHeaderView extends android.widget.TextView {
+    ctor public RowHeaderView(android.content.Context);
+    ctor public RowHeaderView(android.content.Context, android.util.AttributeSet);
+    ctor public RowHeaderView(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public abstract class RowPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public RowPresenter();
+    method protected abstract android.support.v17.leanback.widget.RowPresenter.ViewHolder createRowViewHolder(android.view.ViewGroup);
+    method protected void dispatchItemSelectedListener(android.support.v17.leanback.widget.RowPresenter.ViewHolder, boolean);
+    method public void freeze(android.support.v17.leanback.widget.RowPresenter.ViewHolder, boolean);
+    method public final android.support.v17.leanback.widget.RowHeaderPresenter getHeaderPresenter();
+    method public final android.support.v17.leanback.widget.RowPresenter.ViewHolder getRowViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public final boolean getSelectEffectEnabled();
+    method public final float getSelectLevel(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public final int getSyncActivatePolicy();
+    method protected void initializeRowViewHolder(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+    method protected boolean isClippingChildren();
+    method public boolean isUsingDefaultSelectEffect();
+    method protected void onBindRowViewHolder(android.support.v17.leanback.widget.RowPresenter.ViewHolder, java.lang.Object);
+    method public final void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public final android.support.v17.leanback.widget.Presenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method protected void onRowViewAttachedToWindow(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+    method protected void onRowViewDetachedFromWindow(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+    method protected void onRowViewExpanded(android.support.v17.leanback.widget.RowPresenter.ViewHolder, boolean);
+    method protected void onRowViewSelected(android.support.v17.leanback.widget.RowPresenter.ViewHolder, boolean);
+    method protected void onSelectLevelChanged(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+    method protected void onUnbindRowViewHolder(android.support.v17.leanback.widget.RowPresenter.ViewHolder);
+    method public final void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public final void onViewAttachedToWindow(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public final void onViewDetachedFromWindow(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void setEntranceTransitionState(android.support.v17.leanback.widget.RowPresenter.ViewHolder, boolean);
+    method public final void setHeaderPresenter(android.support.v17.leanback.widget.RowHeaderPresenter);
+    method public final void setRowViewExpanded(android.support.v17.leanback.widget.Presenter.ViewHolder, boolean);
+    method public final void setRowViewSelected(android.support.v17.leanback.widget.Presenter.ViewHolder, boolean);
+    method public final void setSelectEffectEnabled(boolean);
+    method public final void setSelectLevel(android.support.v17.leanback.widget.Presenter.ViewHolder, float);
+    method public final void setSyncActivatePolicy(int);
+    field public static final int SYNC_ACTIVATED_CUSTOM = 0; // 0x0
+    field public static final int SYNC_ACTIVATED_TO_EXPANDED = 1; // 0x1
+    field public static final int SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED = 3; // 0x3
+    field public static final int SYNC_ACTIVATED_TO_SELECTED = 2; // 0x2
+  }
+
+  public static class RowPresenter.ViewHolder extends android.support.v17.leanback.widget.Presenter.ViewHolder {
+    ctor public RowPresenter.ViewHolder(android.view.View);
+    method public final android.support.v17.leanback.widget.RowHeaderPresenter.ViewHolder getHeaderViewHolder();
+    method public final android.support.v17.leanback.widget.BaseOnItemViewClickedListener getOnItemViewClickedListener();
+    method public final android.support.v17.leanback.widget.BaseOnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public android.view.View.OnKeyListener getOnKeyListener();
+    method public final android.support.v17.leanback.widget.Row getRow();
+    method public final java.lang.Object getRowObject();
+    method public final float getSelectLevel();
+    method public java.lang.Object getSelectedItem();
+    method public android.support.v17.leanback.widget.Presenter.ViewHolder getSelectedItemViewHolder();
+    method public final boolean isExpanded();
+    method public final boolean isSelected();
+    method public final void setActivated(boolean);
+    method public final void setOnItemViewClickedListener(android.support.v17.leanback.widget.BaseOnItemViewClickedListener);
+    method public final void setOnItemViewSelectedListener(android.support.v17.leanback.widget.BaseOnItemViewSelectedListener);
+    method public void setOnKeyListener(android.view.View.OnKeyListener);
+    method public final void syncActivatedStatus(android.view.View);
+    field protected final android.support.v17.leanback.graphics.ColorOverlayDimmer mColorDimmer;
+  }
+
+  public class SearchBar extends android.widget.RelativeLayout {
+    ctor public SearchBar(android.content.Context);
+    ctor public SearchBar(android.content.Context, android.util.AttributeSet);
+    ctor public SearchBar(android.content.Context, android.util.AttributeSet, int);
+    method public void displayCompletions(java.util.List<java.lang.String>);
+    method public void displayCompletions(android.view.inputmethod.CompletionInfo[]);
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public java.lang.CharSequence getHint();
+    method public java.lang.String getTitle();
+    method public boolean isRecognizing();
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setPermissionListener(android.support.v17.leanback.widget.SearchBar.SearchBarPermissionListener);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchAffordanceColorsInListening(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSearchBarListener(android.support.v17.leanback.widget.SearchBar.SearchBarListener);
+    method public void setSearchQuery(java.lang.String);
+    method public void setSpeechRecognitionCallback(android.support.v17.leanback.widget.SpeechRecognitionCallback);
+    method public void setSpeechRecognizer(android.speech.SpeechRecognizer);
+    method public void setTitle(java.lang.String);
+    method public void startRecognition();
+    method public void stopRecognition();
+  }
+
+  public static abstract interface SearchBar.SearchBarListener {
+    method public abstract void onKeyboardDismiss(java.lang.String);
+    method public abstract void onSearchQueryChange(java.lang.String);
+    method public abstract void onSearchQuerySubmit(java.lang.String);
+  }
+
+  public static abstract interface SearchBar.SearchBarPermissionListener {
+    method public abstract void requestAudioPermission();
+  }
+
+  public class SearchEditText extends android.support.v17.leanback.widget.StreamingTextView {
+    ctor public SearchEditText(android.content.Context);
+    ctor public SearchEditText(android.content.Context, android.util.AttributeSet);
+    ctor public SearchEditText(android.content.Context, android.util.AttributeSet, int);
+    method public void setOnKeyboardDismissListener(android.support.v17.leanback.widget.SearchEditText.OnKeyboardDismissListener);
+  }
+
+  public static abstract interface SearchEditText.OnKeyboardDismissListener {
+    method public abstract void onKeyboardDismiss();
+  }
+
+  public class SearchOrbView extends android.widget.FrameLayout implements android.view.View.OnClickListener {
+    ctor public SearchOrbView(android.content.Context);
+    ctor public SearchOrbView(android.content.Context, android.util.AttributeSet);
+    ctor public SearchOrbView(android.content.Context, android.util.AttributeSet, int);
+    method public void enableOrbColorAnimation(boolean);
+    method public int getOrbColor();
+    method public android.support.v17.leanback.widget.SearchOrbView.Colors getOrbColors();
+    method public android.graphics.drawable.Drawable getOrbIcon();
+    method public void onClick(android.view.View);
+    method public void setOnOrbClickedListener(android.view.View.OnClickListener);
+    method public void setOrbColor(int);
+    method public deprecated void setOrbColor(int, int);
+    method public void setOrbColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setOrbIcon(android.graphics.drawable.Drawable);
+  }
+
+  public static class SearchOrbView.Colors {
+    ctor public SearchOrbView.Colors(int);
+    ctor public SearchOrbView.Colors(int, int);
+    ctor public SearchOrbView.Colors(int, int, int);
+    method public static int getBrightColor(int);
+    field public int brightColor;
+    field public int color;
+    field public int iconColor;
+  }
+
+  public class SectionRow extends android.support.v17.leanback.widget.Row {
+    ctor public SectionRow(android.support.v17.leanback.widget.HeaderItem);
+    ctor public SectionRow(long, java.lang.String);
+    ctor public SectionRow(java.lang.String);
+    method public final boolean isRenderedAsRowView();
+  }
+
+  public class ShadowOverlayContainer extends android.widget.FrameLayout {
+    ctor public ShadowOverlayContainer(android.content.Context);
+    ctor public ShadowOverlayContainer(android.content.Context, android.util.AttributeSet);
+    ctor public ShadowOverlayContainer(android.content.Context, android.util.AttributeSet, int);
+    method public int getShadowType();
+    method public android.view.View getWrappedView();
+    method public deprecated void initialize(boolean, boolean);
+    method public deprecated void initialize(boolean, boolean, boolean);
+    method public static void prepareParentForShadow(android.view.ViewGroup);
+    method public void setOverlayColor(int);
+    method public void setShadowFocusLevel(float);
+    method public static boolean supportsDynamicShadow();
+    method public static boolean supportsShadow();
+    method public void useDynamicShadow();
+    method public void useDynamicShadow(float, float);
+    method public void useStaticShadow();
+    method public void wrap(android.view.View);
+    field public static final int SHADOW_DYNAMIC = 3; // 0x3
+    field public static final int SHADOW_NONE = 1; // 0x1
+    field public static final int SHADOW_STATIC = 2; // 0x2
+  }
+
+  public final class ShadowOverlayHelper {
+    method public android.support.v17.leanback.widget.ShadowOverlayContainer createShadowOverlayContainer(android.content.Context);
+    method public int getShadowType();
+    method public boolean needsOverlay();
+    method public boolean needsRoundedCorner();
+    method public boolean needsWrapper();
+    method public void onViewCreated(android.view.View);
+    method public void prepareParentForShadow(android.view.ViewGroup);
+    method public static void setNoneWrapperOverlayColor(android.view.View, int);
+    method public static void setNoneWrapperShadowFocusLevel(android.view.View, float);
+    method public void setOverlayColor(android.view.View, int);
+    method public void setShadowFocusLevel(android.view.View, float);
+    method public static boolean supportsDynamicShadow();
+    method public static boolean supportsForeground();
+    method public static boolean supportsRoundedCorner();
+    method public static boolean supportsShadow();
+    field public static final int SHADOW_DYNAMIC = 3; // 0x3
+    field public static final int SHADOW_NONE = 1; // 0x1
+    field public static final int SHADOW_STATIC = 2; // 0x2
+  }
+
+  public static final class ShadowOverlayHelper.Builder {
+    ctor public ShadowOverlayHelper.Builder();
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper build(android.content.Context);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder keepForegroundDrawable(boolean);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder needsOverlay(boolean);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder needsRoundedCorner(boolean);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder needsShadow(boolean);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder options(android.support.v17.leanback.widget.ShadowOverlayHelper.Options);
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Builder preferZOrder(boolean);
+  }
+
+  public static final class ShadowOverlayHelper.Options {
+    ctor public ShadowOverlayHelper.Options();
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Options dynamicShadowZ(float, float);
+    method public final float getDynamicShadowFocusedZ();
+    method public final float getDynamicShadowUnfocusedZ();
+    method public final int getRoundedCornerRadius();
+    method public android.support.v17.leanback.widget.ShadowOverlayHelper.Options roundedCornerRadius(int);
+    field public static final android.support.v17.leanback.widget.ShadowOverlayHelper.Options DEFAULT;
+  }
+
+  public final class SinglePresenterSelector extends android.support.v17.leanback.widget.PresenterSelector {
+    ctor public SinglePresenterSelector(android.support.v17.leanback.widget.Presenter);
+    method public android.support.v17.leanback.widget.Presenter getPresenter(java.lang.Object);
+  }
+
+  public class SparseArrayObjectAdapter extends android.support.v17.leanback.widget.ObjectAdapter {
+    ctor public SparseArrayObjectAdapter(android.support.v17.leanback.widget.PresenterSelector);
+    ctor public SparseArrayObjectAdapter(android.support.v17.leanback.widget.Presenter);
+    ctor public SparseArrayObjectAdapter();
+    method public void clear(int);
+    method public void clear();
+    method public java.lang.Object get(int);
+    method public int indexOf(java.lang.Object);
+    method public int indexOf(int);
+    method public java.lang.Object lookup(int);
+    method public void notifyArrayItemRangeChanged(int, int);
+    method public void set(int, java.lang.Object);
+    method public int size();
+  }
+
+  public class SpeechOrbView extends android.support.v17.leanback.widget.SearchOrbView {
+    ctor public SpeechOrbView(android.content.Context);
+    ctor public SpeechOrbView(android.content.Context, android.util.AttributeSet);
+    ctor public SpeechOrbView(android.content.Context, android.util.AttributeSet, int);
+    method public void setListeningOrbColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setNotListeningOrbColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setSoundLevel(int);
+    method public void showListening();
+    method public void showNotListening();
+  }
+
+  public abstract interface SpeechRecognitionCallback {
+    method public abstract void recognizeSpeech();
+  }
+
+   class StreamingTextView extends android.widget.EditText {
+    ctor public StreamingTextView(android.content.Context, android.util.AttributeSet);
+    ctor public StreamingTextView(android.content.Context, android.util.AttributeSet, int);
+    method public static boolean isLayoutRtl(android.view.View);
+    method public void reset();
+    method public void setFinalRecognizedText(java.lang.CharSequence);
+    method public void updateRecognizedText(java.lang.String, java.lang.String);
+    method public void updateRecognizedText(java.lang.String, java.util.List<java.lang.Float>);
+  }
+
+  public class TitleHelper {
+    ctor public TitleHelper(android.view.ViewGroup, android.view.View);
+    method public android.support.v17.leanback.widget.BrowseFrameLayout.OnFocusSearchListener getOnFocusSearchListener();
+    method public android.view.ViewGroup getSceneRoot();
+    method public android.view.View getTitleView();
+    method public void showTitle(boolean);
+  }
+
+  public class TitleView extends android.widget.FrameLayout implements android.support.v17.leanback.widget.TitleViewAdapter.Provider {
+    ctor public TitleView(android.content.Context);
+    ctor public TitleView(android.content.Context, android.util.AttributeSet);
+    ctor public TitleView(android.content.Context, android.util.AttributeSet, int);
+    method public void enableAnimation(boolean);
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public android.support.v17.leanback.widget.SearchOrbView.Colors getSearchAffordanceColors();
+    method public android.view.View getSearchAffordanceView();
+    method public java.lang.CharSequence getTitle();
+    method public android.support.v17.leanback.widget.TitleViewAdapter getTitleViewAdapter();
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnSearchClickedListener(android.view.View.OnClickListener);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setTitle(java.lang.CharSequence);
+    method public void updateComponentsVisibility(int);
+  }
+
+  public abstract class TitleViewAdapter {
+    ctor public TitleViewAdapter();
+    method public android.graphics.drawable.Drawable getBadgeDrawable();
+    method public android.support.v17.leanback.widget.SearchOrbView.Colors getSearchAffordanceColors();
+    method public abstract android.view.View getSearchAffordanceView();
+    method public java.lang.CharSequence getTitle();
+    method public void setAnimationEnabled(boolean);
+    method public void setBadgeDrawable(android.graphics.drawable.Drawable);
+    method public void setOnSearchClickedListener(android.view.View.OnClickListener);
+    method public void setSearchAffordanceColors(android.support.v17.leanback.widget.SearchOrbView.Colors);
+    method public void setTitle(java.lang.CharSequence);
+    method public void updateComponentsVisibility(int);
+    field public static final int BRANDING_VIEW_VISIBLE = 2; // 0x2
+    field public static final int FULL_VIEW_VISIBLE = 6; // 0x6
+    field public static final int SEARCH_VIEW_VISIBLE = 4; // 0x4
+  }
+
+  public static abstract interface TitleViewAdapter.Provider {
+    method public abstract android.support.v17.leanback.widget.TitleViewAdapter getTitleViewAdapter();
+  }
+
+  public class VerticalGridPresenter extends android.support.v17.leanback.widget.Presenter {
+    ctor public VerticalGridPresenter();
+    ctor public VerticalGridPresenter(int);
+    ctor public VerticalGridPresenter(int, boolean);
+    method public final boolean areChildRoundedCornersEnabled();
+    method protected android.support.v17.leanback.widget.VerticalGridPresenter.ViewHolder createGridViewHolder(android.view.ViewGroup);
+    method protected android.support.v17.leanback.widget.ShadowOverlayHelper.Options createShadowOverlayOptions();
+    method public final void enableChildRoundedCorners(boolean);
+    method public final int getFocusZoomFactor();
+    method public final boolean getKeepChildForeground();
+    method public int getNumberOfColumns();
+    method public final android.support.v17.leanback.widget.OnItemViewClickedListener getOnItemViewClickedListener();
+    method public final android.support.v17.leanback.widget.OnItemViewSelectedListener getOnItemViewSelectedListener();
+    method public final boolean getShadowEnabled();
+    method protected void initializeGridViewHolder(android.support.v17.leanback.widget.VerticalGridPresenter.ViewHolder);
+    method public final boolean isFocusDimmerUsed();
+    method public boolean isUsingDefaultShadow();
+    method public boolean isUsingZOrder(android.content.Context);
+    method public void onBindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder, java.lang.Object);
+    method public final android.support.v17.leanback.widget.VerticalGridPresenter.ViewHolder onCreateViewHolder(android.view.ViewGroup);
+    method public void onUnbindViewHolder(android.support.v17.leanback.widget.Presenter.ViewHolder);
+    method public void setEntranceTransitionState(android.support.v17.leanback.widget.VerticalGridPresenter.ViewHolder, boolean);
+    method public final void setKeepChildForeground(boolean);
+    method public void setNumberOfColumns(int);
+    method public final void setOnItemViewClickedListener(android.support.v17.leanback.widget.OnItemViewClickedListener);
+    method public final void setOnItemViewSelectedListener(android.support.v17.leanback.widget.OnItemViewSelectedListener);
+    method public final void setShadowEnabled(boolean);
+  }
+
+  public static class VerticalGridPresenter.ViewHolder extends android.support.v17.leanback.widget.Presenter.ViewHolder {
+    ctor public VerticalGridPresenter.ViewHolder(android.support.v17.leanback.widget.VerticalGridView);
+    method public android.support.v17.leanback.widget.VerticalGridView getGridView();
+  }
+
+  public class VerticalGridView extends android.support.v17.leanback.widget.BaseGridView {
+    ctor public VerticalGridView(android.content.Context);
+    ctor public VerticalGridView(android.content.Context, android.util.AttributeSet);
+    ctor public VerticalGridView(android.content.Context, android.util.AttributeSet, int);
+    method protected void initAttributes(android.content.Context, android.util.AttributeSet);
+    method public void setColumnWidth(int);
+    method public void setNumColumns(int);
+  }
+
+  public abstract interface ViewHolderTask {
+    method public abstract void run(android.support.v7.widget.RecyclerView.ViewHolder);
+  }
+
+}
+
+package android.support.v17.leanback.widget.picker {
+
+  public class Picker extends android.widget.FrameLayout {
+    ctor public Picker(android.content.Context, android.util.AttributeSet, int);
+    method public void addOnValueChangedListener(android.support.v17.leanback.widget.picker.Picker.PickerValueListener);
+    method public float getActivatedVisibleItemCount();
+    method public android.support.v17.leanback.widget.picker.PickerColumn getColumnAt(int);
+    method public int getColumnsCount();
+    method protected int getPickerItemHeightPixels();
+    method public final int getPickerItemLayoutId();
+    method public final int getPickerItemTextViewId();
+    method public int getSelectedColumn();
+    method public final java.lang.CharSequence getSeparator();
+    method public float getVisibleItemCount();
+    method public void onColumnValueChanged(int, int);
+    method public void removeOnValueChangedListener(android.support.v17.leanback.widget.picker.Picker.PickerValueListener);
+    method public void setActivatedVisibleItemCount(float);
+    method public void setColumnAt(int, android.support.v17.leanback.widget.picker.PickerColumn);
+    method public void setColumnValue(int, int, boolean);
+    method public void setColumns(java.util.List<android.support.v17.leanback.widget.picker.PickerColumn>);
+    method public final void setPickerItemTextViewId(int);
+    method public void setSelectedColumn(int);
+    method public final void setSeparator(java.lang.CharSequence);
+    method public void setVisibleItemCount(float);
+  }
+
+  public static abstract interface Picker.PickerValueListener {
+    method public abstract void onValueChanged(android.support.v17.leanback.widget.picker.Picker, int);
+  }
+
+  public class PickerColumn {
+    ctor public PickerColumn();
+    method public int getCount();
+    method public int getCurrentValue();
+    method public java.lang.CharSequence getLabelFor(int);
+    method public java.lang.String getLabelFormat();
+    method public int getMaxValue();
+    method public int getMinValue();
+    method public java.lang.CharSequence[] getStaticLabels();
+    method public void setCurrentValue(int);
+    method public void setLabelFormat(java.lang.String);
+    method public void setMaxValue(int);
+    method public void setMinValue(int);
+    method public void setStaticLabels(java.lang.CharSequence[]);
+  }
+
+  public class TimePicker extends android.support.v17.leanback.widget.picker.Picker {
+    ctor public TimePicker(android.content.Context, android.util.AttributeSet);
+    ctor public TimePicker(android.content.Context, android.util.AttributeSet, int);
+    method public int getHour();
+    method public int getMinute();
+    method public boolean is24Hour();
+    method public boolean isPm();
+    method public void setHour(int);
+    method public void setIs24Hour(boolean);
+    method public void setMinute(int);
+  }
+
+}
+
+package android.support.v17.preference {
+
+  public abstract class BaseLeanbackPreferenceFragment extends android.support.v14.preference.PreferenceFragment {
+    ctor public BaseLeanbackPreferenceFragment();
+  }
+
+  public class LeanbackListPreferenceDialogFragment extends android.support.v17.preference.LeanbackPreferenceDialogFragment {
+    ctor public LeanbackListPreferenceDialogFragment();
+    method public static android.support.v17.preference.LeanbackListPreferenceDialogFragment newInstanceMulti(java.lang.String);
+    method public static android.support.v17.preference.LeanbackListPreferenceDialogFragment newInstanceSingle(java.lang.String);
+    method public android.support.v7.widget.RecyclerView.Adapter onCreateAdapter();
+  }
+
+  public class LeanbackListPreferenceDialogFragment.AdapterMulti extends android.support.v7.widget.RecyclerView.Adapter implements android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder.OnItemClickListener {
+    ctor public LeanbackListPreferenceDialogFragment.AdapterMulti(java.lang.CharSequence[], java.lang.CharSequence[], java.util.Set<java.lang.String>);
+    method public int getItemCount();
+    method public void onBindViewHolder(android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder, int);
+    method public android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder onCreateViewHolder(android.view.ViewGroup, int);
+    method public void onItemClick(android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder);
+  }
+
+  public class LeanbackListPreferenceDialogFragment.AdapterSingle extends android.support.v7.widget.RecyclerView.Adapter implements android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder.OnItemClickListener {
+    ctor public LeanbackListPreferenceDialogFragment.AdapterSingle(java.lang.CharSequence[], java.lang.CharSequence[], java.lang.CharSequence);
+    method public int getItemCount();
+    method public void onBindViewHolder(android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder, int);
+    method public android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder onCreateViewHolder(android.view.ViewGroup, int);
+    method public void onItemClick(android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder);
+  }
+
+  public static class LeanbackListPreferenceDialogFragment.ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder implements android.view.View.OnClickListener {
+    ctor public LeanbackListPreferenceDialogFragment.ViewHolder(android.view.View, android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder.OnItemClickListener);
+    method public android.view.ViewGroup getContainer();
+    method public android.widget.TextView getTitleView();
+    method public android.widget.Checkable getWidgetView();
+    method public void onClick(android.view.View);
+  }
+
+  public static abstract interface LeanbackListPreferenceDialogFragment.ViewHolder.OnItemClickListener {
+    method public abstract void onItemClick(android.support.v17.preference.LeanbackListPreferenceDialogFragment.ViewHolder);
+  }
+
+  public class LeanbackPreferenceDialogFragment extends android.app.Fragment {
+    ctor public LeanbackPreferenceDialogFragment();
+    method public android.support.v7.preference.DialogPreference getPreference();
+    field public static final java.lang.String ARG_KEY = "key";
+  }
+
+  public abstract class LeanbackPreferenceFragment extends android.support.v17.preference.BaseLeanbackPreferenceFragment {
+    ctor public LeanbackPreferenceFragment();
+    method public void setTitle(java.lang.CharSequence);
+  }
+
+  public abstract class LeanbackSettingsFragment extends android.app.Fragment implements android.support.v14.preference.PreferenceFragment.OnPreferenceDisplayDialogCallback android.support.v14.preference.PreferenceFragment.OnPreferenceStartFragmentCallback android.support.v14.preference.PreferenceFragment.OnPreferenceStartScreenCallback {
+    ctor public LeanbackSettingsFragment();
+    method public boolean onPreferenceDisplayDialog(android.support.v14.preference.PreferenceFragment, android.support.v7.preference.Preference);
+    method public abstract void onPreferenceStartInitialScreen();
+    method public void startImmersiveFragment(android.app.Fragment);
+    method public void startPreferenceFragment(android.app.Fragment);
+  }
+
+}
+
+package android.support.v4.accessibilityservice {
+
+  public final class AccessibilityServiceInfoCompat {
+    method public static java.lang.String capabilityToString(int);
+    method public static java.lang.String feedbackTypeToString(int);
+    method public static java.lang.String flagToString(int);
+    method public static deprecated boolean getCanRetrieveWindowContent(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static int getCapabilities(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static deprecated java.lang.String getDescription(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static deprecated java.lang.String getId(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static deprecated android.content.pm.ResolveInfo getResolveInfo(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static deprecated java.lang.String getSettingsActivityName(android.accessibilityservice.AccessibilityServiceInfo);
+    method public static java.lang.String loadDescription(android.accessibilityservice.AccessibilityServiceInfo, android.content.pm.PackageManager);
+    field public static final int CAPABILITY_CAN_FILTER_KEY_EVENTS = 8; // 0x8
+    field public static final int CAPABILITY_CAN_REQUEST_ENHANCED_WEB_ACCESSIBILITY = 4; // 0x4
+    field public static final int CAPABILITY_CAN_REQUEST_TOUCH_EXPLORATION = 2; // 0x2
+    field public static final int CAPABILITY_CAN_RETRIEVE_WINDOW_CONTENT = 1; // 0x1
+    field public static final deprecated int DEFAULT = 1; // 0x1
+    field public static final int FEEDBACK_ALL_MASK = -1; // 0xffffffff
+    field public static final int FEEDBACK_BRAILLE = 32; // 0x20
+    field public static final int FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 2; // 0x2
+    field public static final int FLAG_REPORT_VIEW_IDS = 16; // 0x10
+    field public static final int FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY = 8; // 0x8
+    field public static final int FLAG_REQUEST_FILTER_KEY_EVENTS = 32; // 0x20
+    field public static final int FLAG_REQUEST_TOUCH_EXPLORATION_MODE = 4; // 0x4
+  }
+
+}
+
+package android.support.v4.app {
+
+  public deprecated class ActionBarDrawerToggle implements android.support.v4.widget.DrawerLayout.DrawerListener {
+    ctor public ActionBarDrawerToggle(android.app.Activity, android.support.v4.widget.DrawerLayout, int, int, int);
+    ctor public ActionBarDrawerToggle(android.app.Activity, android.support.v4.widget.DrawerLayout, boolean, int, int, int);
+    method public boolean isDrawerIndicatorEnabled();
+    method public void onConfigurationChanged(android.content.res.Configuration);
+    method public void onDrawerClosed(android.view.View);
+    method public void onDrawerOpened(android.view.View);
+    method public void onDrawerSlide(android.view.View, float);
+    method public void onDrawerStateChanged(int);
+    method public boolean onOptionsItemSelected(android.view.MenuItem);
+    method public void setDrawerIndicatorEnabled(boolean);
+    method public void setHomeAsUpIndicator(android.graphics.drawable.Drawable);
+    method public void setHomeAsUpIndicator(int);
+    method public void syncState();
+  }
+
+  public static abstract deprecated interface ActionBarDrawerToggle.Delegate {
+    method public abstract android.graphics.drawable.Drawable getThemeUpIndicator();
+    method public abstract void setActionBarDescription(int);
+    method public abstract void setActionBarUpIndicator(android.graphics.drawable.Drawable, int);
+  }
+
+  public static abstract deprecated interface ActionBarDrawerToggle.DelegateProvider {
+    method public abstract android.support.v4.app.ActionBarDrawerToggle.Delegate getDrawerToggleDelegate();
+  }
+
+  public class ActivityCompat extends android.support.v4.content.ContextCompat {
+    ctor protected ActivityCompat();
+    method public static void finishAffinity(android.app.Activity);
+    method public static void finishAfterTransition(android.app.Activity);
+    method public static android.net.Uri getReferrer(android.app.Activity);
+    method public static boolean invalidateOptionsMenu(android.app.Activity);
+    method public static void postponeEnterTransition(android.app.Activity);
+    method public static void requestPermissions(android.app.Activity, java.lang.String[], int);
+    method public static void setEnterSharedElementCallback(android.app.Activity, android.support.v4.app.SharedElementCallback);
+    method public static void setExitSharedElementCallback(android.app.Activity, android.support.v4.app.SharedElementCallback);
+    method public static boolean shouldShowRequestPermissionRationale(android.app.Activity, java.lang.String);
+    method public static void startActivityForResult(android.app.Activity, android.content.Intent, int, android.os.Bundle);
+    method public static void startIntentSenderForResult(android.app.Activity, android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public static void startPostponedEnterTransition(android.app.Activity);
+  }
+
+  public static abstract interface ActivityCompat.OnRequestPermissionsResultCallback {
+    method public abstract void onRequestPermissionsResult(int, java.lang.String[], int[]);
+  }
+
+  public final class ActivityManagerCompat {
+    method public static boolean isLowRamDevice(android.app.ActivityManager);
+  }
+
+  public class ActivityOptionsCompat {
+    ctor protected ActivityOptionsCompat();
+    method public android.graphics.Rect getLaunchBounds();
+    method public static android.support.v4.app.ActivityOptionsCompat makeBasic();
+    method public static android.support.v4.app.ActivityOptionsCompat makeClipRevealAnimation(android.view.View, int, int, int, int);
+    method public static android.support.v4.app.ActivityOptionsCompat makeCustomAnimation(android.content.Context, int, int);
+    method public static android.support.v4.app.ActivityOptionsCompat makeScaleUpAnimation(android.view.View, int, int, int, int);
+    method public static android.support.v4.app.ActivityOptionsCompat makeSceneTransitionAnimation(android.app.Activity, android.view.View, java.lang.String);
+    method public static android.support.v4.app.ActivityOptionsCompat makeSceneTransitionAnimation(android.app.Activity, android.support.v4.util.Pair<android.view.View, java.lang.String>...);
+    method public static android.support.v4.app.ActivityOptionsCompat makeTaskLaunchBehind();
+    method public static android.support.v4.app.ActivityOptionsCompat makeThumbnailScaleUpAnimation(android.view.View, android.graphics.Bitmap, int, int);
+    method public void requestUsageTimeReport(android.app.PendingIntent);
+    method public android.support.v4.app.ActivityOptionsCompat setLaunchBounds(android.graphics.Rect);
+    method public android.os.Bundle toBundle();
+    method public void update(android.support.v4.app.ActivityOptionsCompat);
+    field public static final java.lang.String EXTRA_USAGE_TIME_REPORT = "android.activity.usage_time";
+    field public static final java.lang.String EXTRA_USAGE_TIME_REPORT_PACKAGES = "android.usage_time_packages";
+  }
+
+  public final class AlarmManagerCompat {
+    method public static void setAlarmClock(android.app.AlarmManager, long, android.app.PendingIntent, android.app.PendingIntent);
+    method public static void setAndAllowWhileIdle(android.app.AlarmManager, int, long, android.app.PendingIntent);
+    method public static void setExact(android.app.AlarmManager, int, long, android.app.PendingIntent);
+    method public static void setExactAndAllowWhileIdle(android.app.AlarmManager, int, long, android.app.PendingIntent);
+  }
+
+  public class AppLaunchChecker {
+    ctor public AppLaunchChecker();
+    method public static boolean hasStartedFromLauncher(android.content.Context);
+    method public static void onActivityCreate(android.app.Activity);
+  }
+
+  public final class AppOpsManagerCompat {
+    method public static int noteOp(android.content.Context, java.lang.String, int, java.lang.String);
+    method public static int noteProxyOp(android.content.Context, java.lang.String, java.lang.String);
+    method public static java.lang.String permissionToOp(java.lang.String);
+    field public static final int MODE_ALLOWED = 0; // 0x0
+    field public static final int MODE_DEFAULT = 3; // 0x3
+    field public static final int MODE_IGNORED = 1; // 0x1
+  }
+
+  public final class BundleCompat {
+    method public static android.os.IBinder getBinder(android.os.Bundle, java.lang.String);
+    method public static void putBinder(android.os.Bundle, java.lang.String, android.os.IBinder);
+  }
+
+  public class DialogFragment extends android.support.v4.app.Fragment implements android.content.DialogInterface.OnCancelListener android.content.DialogInterface.OnDismissListener {
+    ctor public DialogFragment();
+    method public void dismiss();
+    method public void dismissAllowingStateLoss();
+    method public android.app.Dialog getDialog();
+    method public boolean getShowsDialog();
+    method public int getTheme();
+    method public boolean isCancelable();
+    method public void onCancel(android.content.DialogInterface);
+    method public android.app.Dialog onCreateDialog(android.os.Bundle);
+    method public void onDismiss(android.content.DialogInterface);
+    method public void setCancelable(boolean);
+    method public void setShowsDialog(boolean);
+    method public void setStyle(int, int);
+    method public void show(android.support.v4.app.FragmentManager, java.lang.String);
+    method public int show(android.support.v4.app.FragmentTransaction, java.lang.String);
+    field public static final int STYLE_NORMAL = 0; // 0x0
+    field public static final int STYLE_NO_FRAME = 2; // 0x2
+    field public static final int STYLE_NO_INPUT = 3; // 0x3
+    field public static final int STYLE_NO_TITLE = 1; // 0x1
+  }
+
+  public class Fragment implements android.content.ComponentCallbacks android.view.View.OnCreateContextMenuListener {
+    ctor public Fragment();
+    method public void dump(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public final boolean equals(java.lang.Object);
+    method public final android.support.v4.app.FragmentActivity getActivity();
+    method public boolean getAllowEnterTransitionOverlap();
+    method public boolean getAllowReturnTransitionOverlap();
+    method public final android.os.Bundle getArguments();
+    method public final android.support.v4.app.FragmentManager getChildFragmentManager();
+    method public android.content.Context getContext();
+    method public java.lang.Object getEnterTransition();
+    method public java.lang.Object getExitTransition();
+    method public final android.support.v4.app.FragmentManager getFragmentManager();
+    method public final java.lang.Object getHost();
+    method public final int getId();
+    method public final android.view.LayoutInflater getLayoutInflater();
+    method public android.support.v4.app.LoaderManager getLoaderManager();
+    method public final android.support.v4.app.Fragment getParentFragment();
+    method public java.lang.Object getReenterTransition();
+    method public final android.content.res.Resources getResources();
+    method public final boolean getRetainInstance();
+    method public java.lang.Object getReturnTransition();
+    method public java.lang.Object getSharedElementEnterTransition();
+    method public java.lang.Object getSharedElementReturnTransition();
+    method public final java.lang.String getString(int);
+    method public final java.lang.String getString(int, java.lang.Object...);
+    method public final java.lang.String getTag();
+    method public final android.support.v4.app.Fragment getTargetFragment();
+    method public final int getTargetRequestCode();
+    method public final java.lang.CharSequence getText(int);
+    method public boolean getUserVisibleHint();
+    method public android.view.View getView();
+    method public final int hashCode();
+    method public static android.support.v4.app.Fragment instantiate(android.content.Context, java.lang.String);
+    method public static android.support.v4.app.Fragment instantiate(android.content.Context, java.lang.String, android.os.Bundle);
+    method public final boolean isAdded();
+    method public final boolean isDetached();
+    method public final boolean isHidden();
+    method public final boolean isInLayout();
+    method public final boolean isRemoving();
+    method public final boolean isResumed();
+    method public final boolean isStateSaved();
+    method public final boolean isVisible();
+    method public void onActivityCreated(android.os.Bundle);
+    method public void onActivityResult(int, int, android.content.Intent);
+    method public void onAttach(android.content.Context);
+    method public deprecated void onAttach(android.app.Activity);
+    method public void onAttachFragment(android.support.v4.app.Fragment);
+    method public void onConfigurationChanged(android.content.res.Configuration);
+    method public boolean onContextItemSelected(android.view.MenuItem);
+    method public void onCreate(android.os.Bundle);
+    method public android.view.animation.Animation onCreateAnimation(int, boolean, int);
+    method public android.animation.Animator onCreateAnimator(int, boolean, int);
+    method public void onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo);
+    method public void onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater);
+    method public android.view.View onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void onDestroy();
+    method public void onDestroyOptionsMenu();
+    method public void onDestroyView();
+    method public void onDetach();
+    method public android.view.LayoutInflater onGetLayoutInflater(android.os.Bundle);
+    method public void onHiddenChanged(boolean);
+    method public void onInflate(android.content.Context, android.util.AttributeSet, android.os.Bundle);
+    method public deprecated void onInflate(android.app.Activity, android.util.AttributeSet, android.os.Bundle);
+    method public void onLowMemory();
+    method public void onMultiWindowModeChanged(boolean);
+    method public boolean onOptionsItemSelected(android.view.MenuItem);
+    method public void onOptionsMenuClosed(android.view.Menu);
+    method public void onPause();
+    method public void onPictureInPictureModeChanged(boolean);
+    method public void onPrepareOptionsMenu(android.view.Menu);
+    method public void onRequestPermissionsResult(int, java.lang.String[], int[]);
+    method public void onResume();
+    method public void onSaveInstanceState(android.os.Bundle);
+    method public void onStart();
+    method public void onStop();
+    method public void onViewCreated(android.view.View, android.os.Bundle);
+    method public void onViewStateRestored(android.os.Bundle);
+    method public void postponeEnterTransition();
+    method public void registerForContextMenu(android.view.View);
+    method public final void requestPermissions(java.lang.String[], int);
+    method public void setAllowEnterTransitionOverlap(boolean);
+    method public void setAllowReturnTransitionOverlap(boolean);
+    method public void setArguments(android.os.Bundle);
+    method public void setEnterSharedElementCallback(android.support.v4.app.SharedElementCallback);
+    method public void setEnterTransition(java.lang.Object);
+    method public void setExitSharedElementCallback(android.support.v4.app.SharedElementCallback);
+    method public void setExitTransition(java.lang.Object);
+    method public void setHasOptionsMenu(boolean);
+    method public void setInitialSavedState(android.support.v4.app.Fragment.SavedState);
+    method public void setMenuVisibility(boolean);
+    method public void setReenterTransition(java.lang.Object);
+    method public void setRetainInstance(boolean);
+    method public void setReturnTransition(java.lang.Object);
+    method public void setSharedElementEnterTransition(java.lang.Object);
+    method public void setSharedElementReturnTransition(java.lang.Object);
+    method public void setTargetFragment(android.support.v4.app.Fragment, int);
+    method public void setUserVisibleHint(boolean);
+    method public boolean shouldShowRequestPermissionRationale(java.lang.String);
+    method public void startActivity(android.content.Intent);
+    method public void startActivity(android.content.Intent, android.os.Bundle);
+    method public void startActivityForResult(android.content.Intent, int);
+    method public void startActivityForResult(android.content.Intent, int, android.os.Bundle);
+    method public void startIntentSenderForResult(android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void startPostponedEnterTransition();
+    method public void unregisterForContextMenu(android.view.View);
+  }
+
+  public static class Fragment.InstantiationException extends java.lang.RuntimeException {
+    ctor public Fragment.InstantiationException(java.lang.String, java.lang.Exception);
+  }
+
+  public static class Fragment.SavedState implements android.os.Parcelable {
+    method public int describeContents();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.app.Fragment.SavedState> CREATOR;
+  }
+
+  public class FragmentActivity extends android.app.Activity implements android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback {
+    ctor public FragmentActivity();
+    method public java.lang.Object getLastCustomNonConfigurationInstance();
+    method public android.support.v4.app.FragmentManager getSupportFragmentManager();
+    method public android.support.v4.app.LoaderManager getSupportLoaderManager();
+    method public void onAttachFragment(android.support.v4.app.Fragment);
+    method public void onMultiWindowModeChanged(boolean);
+    method public void onPictureInPictureModeChanged(boolean);
+    method protected void onResumeFragments();
+    method public java.lang.Object onRetainCustomNonConfigurationInstance();
+    method public final java.lang.Object onRetainNonConfigurationInstance();
+    method public void setEnterSharedElementCallback(android.support.v4.app.SharedElementCallback);
+    method public void setExitSharedElementCallback(android.support.v4.app.SharedElementCallback);
+    method public void startActivityFromFragment(android.support.v4.app.Fragment, android.content.Intent, int);
+    method public void startActivityFromFragment(android.support.v4.app.Fragment, android.content.Intent, int, android.os.Bundle);
+    method public void startIntentSenderFromFragment(android.support.v4.app.Fragment, android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void supportFinishAfterTransition();
+    method public deprecated void supportInvalidateOptionsMenu();
+    method public void supportPostponeEnterTransition();
+    method public void supportStartPostponedEnterTransition();
+    method public final void validateRequestPermissionsRequestCode(int);
+  }
+
+  public abstract class FragmentContainer {
+    ctor public FragmentContainer();
+    method public android.support.v4.app.Fragment instantiate(android.content.Context, java.lang.String, android.os.Bundle);
+    method public abstract android.view.View onFindViewById(int);
+    method public abstract boolean onHasView();
+  }
+
+  public class FragmentController {
+    method public void attachHost(android.support.v4.app.Fragment);
+    method public static final android.support.v4.app.FragmentController createController(android.support.v4.app.FragmentHostCallback<?>);
+    method public void dispatchActivityCreated();
+    method public void dispatchConfigurationChanged(android.content.res.Configuration);
+    method public boolean dispatchContextItemSelected(android.view.MenuItem);
+    method public void dispatchCreate();
+    method public boolean dispatchCreateOptionsMenu(android.view.Menu, android.view.MenuInflater);
+    method public void dispatchDestroy();
+    method public void dispatchDestroyView();
+    method public void dispatchLowMemory();
+    method public void dispatchMultiWindowModeChanged(boolean);
+    method public boolean dispatchOptionsItemSelected(android.view.MenuItem);
+    method public void dispatchOptionsMenuClosed(android.view.Menu);
+    method public void dispatchPause();
+    method public void dispatchPictureInPictureModeChanged(boolean);
+    method public boolean dispatchPrepareOptionsMenu(android.view.Menu);
+    method public void dispatchReallyStop();
+    method public void dispatchResume();
+    method public void dispatchStart();
+    method public void dispatchStop();
+    method public void doLoaderDestroy();
+    method public void doLoaderRetain();
+    method public void doLoaderStart();
+    method public void doLoaderStop(boolean);
+    method public void dumpLoaders(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public boolean execPendingActions();
+    method public android.support.v4.app.Fragment findFragmentByWho(java.lang.String);
+    method public java.util.List<android.support.v4.app.Fragment> getActiveFragments(java.util.List<android.support.v4.app.Fragment>);
+    method public int getActiveFragmentsCount();
+    method public android.support.v4.app.FragmentManager getSupportFragmentManager();
+    method public android.support.v4.app.LoaderManager getSupportLoaderManager();
+    method public void noteStateNotSaved();
+    method public android.view.View onCreateView(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet);
+    method public void reportLoaderStart();
+    method public deprecated void restoreAllState(android.os.Parcelable, java.util.List<android.support.v4.app.Fragment>);
+    method public void restoreAllState(android.os.Parcelable, android.support.v4.app.FragmentManagerNonConfig);
+    method public void restoreLoaderNonConfig(android.support.v4.util.SimpleArrayMap<java.lang.String, android.support.v4.app.LoaderManager>);
+    method public android.support.v4.util.SimpleArrayMap<java.lang.String, android.support.v4.app.LoaderManager> retainLoaderNonConfig();
+    method public android.support.v4.app.FragmentManagerNonConfig retainNestedNonConfig();
+    method public deprecated java.util.List<android.support.v4.app.Fragment> retainNonConfig();
+    method public android.os.Parcelable saveAllState();
+  }
+
+  public abstract class FragmentHostCallback<E> extends android.support.v4.app.FragmentContainer {
+    ctor public FragmentHostCallback(android.content.Context, android.os.Handler, int);
+    method public void onDump(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public android.view.View onFindViewById(int);
+    method public abstract E onGetHost();
+    method public android.view.LayoutInflater onGetLayoutInflater();
+    method public int onGetWindowAnimations();
+    method public boolean onHasView();
+    method public boolean onHasWindowAnimations();
+    method public void onRequestPermissionsFromFragment(android.support.v4.app.Fragment, java.lang.String[], int);
+    method public boolean onShouldSaveFragmentState(android.support.v4.app.Fragment);
+    method public boolean onShouldShowRequestPermissionRationale(java.lang.String);
+    method public void onStartActivityFromFragment(android.support.v4.app.Fragment, android.content.Intent, int);
+    method public void onStartActivityFromFragment(android.support.v4.app.Fragment, android.content.Intent, int, android.os.Bundle);
+    method public void onStartIntentSenderFromFragment(android.support.v4.app.Fragment, android.content.IntentSender, int, android.content.Intent, int, int, int, android.os.Bundle) throws android.content.IntentSender.SendIntentException;
+    method public void onSupportInvalidateOptionsMenu();
+  }
+
+  public abstract class FragmentManager {
+    ctor public FragmentManager();
+    method public abstract void addOnBackStackChangedListener(android.support.v4.app.FragmentManager.OnBackStackChangedListener);
+    method public abstract android.support.v4.app.FragmentTransaction beginTransaction();
+    method public abstract void dump(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public static void enableDebugLogging(boolean);
+    method public abstract boolean executePendingTransactions();
+    method public abstract android.support.v4.app.Fragment findFragmentById(int);
+    method public abstract android.support.v4.app.Fragment findFragmentByTag(java.lang.String);
+    method public abstract android.support.v4.app.FragmentManager.BackStackEntry getBackStackEntryAt(int);
+    method public abstract int getBackStackEntryCount();
+    method public abstract android.support.v4.app.Fragment getFragment(android.os.Bundle, java.lang.String);
+    method public abstract java.util.List<android.support.v4.app.Fragment> getFragments();
+    method public abstract android.support.v4.app.Fragment getPrimaryNavigationFragment();
+    method public abstract boolean isDestroyed();
+    method public abstract boolean isStateSaved();
+    method public abstract void popBackStack();
+    method public abstract void popBackStack(java.lang.String, int);
+    method public abstract void popBackStack(int, int);
+    method public abstract boolean popBackStackImmediate();
+    method public abstract boolean popBackStackImmediate(java.lang.String, int);
+    method public abstract boolean popBackStackImmediate(int, int);
+    method public abstract void putFragment(android.os.Bundle, java.lang.String, android.support.v4.app.Fragment);
+    method public abstract void registerFragmentLifecycleCallbacks(android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks, boolean);
+    method public abstract void removeOnBackStackChangedListener(android.support.v4.app.FragmentManager.OnBackStackChangedListener);
+    method public abstract android.support.v4.app.Fragment.SavedState saveFragmentInstanceState(android.support.v4.app.Fragment);
+    method public abstract void unregisterFragmentLifecycleCallbacks(android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks);
+    field public static final int POP_BACK_STACK_INCLUSIVE = 1; // 0x1
+  }
+
+  public static abstract interface FragmentManager.BackStackEntry {
+    method public abstract java.lang.CharSequence getBreadCrumbShortTitle();
+    method public abstract int getBreadCrumbShortTitleRes();
+    method public abstract java.lang.CharSequence getBreadCrumbTitle();
+    method public abstract int getBreadCrumbTitleRes();
+    method public abstract int getId();
+    method public abstract java.lang.String getName();
+  }
+
+  public static abstract class FragmentManager.FragmentLifecycleCallbacks {
+    ctor public FragmentManager.FragmentLifecycleCallbacks();
+    method public void onFragmentActivityCreated(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.os.Bundle);
+    method public void onFragmentAttached(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.content.Context);
+    method public void onFragmentCreated(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.os.Bundle);
+    method public void onFragmentDestroyed(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentDetached(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentPaused(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentPreAttached(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.content.Context);
+    method public void onFragmentPreCreated(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.os.Bundle);
+    method public void onFragmentResumed(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentSaveInstanceState(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.os.Bundle);
+    method public void onFragmentStarted(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentStopped(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+    method public void onFragmentViewCreated(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment, android.view.View, android.os.Bundle);
+    method public void onFragmentViewDestroyed(android.support.v4.app.FragmentManager, android.support.v4.app.Fragment);
+  }
+
+  public static abstract interface FragmentManager.OnBackStackChangedListener {
+    method public abstract void onBackStackChanged();
+  }
+
+  public class FragmentManagerNonConfig {
+  }
+
+  public abstract class FragmentPagerAdapter extends android.support.v4.view.PagerAdapter {
+    ctor public FragmentPagerAdapter(android.support.v4.app.FragmentManager);
+    method public abstract android.support.v4.app.Fragment getItem(int);
+    method public long getItemId(int);
+    method public boolean isViewFromObject(android.view.View, java.lang.Object);
+  }
+
+  public abstract class FragmentStatePagerAdapter extends android.support.v4.view.PagerAdapter {
+    ctor public FragmentStatePagerAdapter(android.support.v4.app.FragmentManager);
+    method public abstract android.support.v4.app.Fragment getItem(int);
+    method public boolean isViewFromObject(android.view.View, java.lang.Object);
+  }
+
+  public class FragmentTabHost extends android.widget.TabHost implements android.widget.TabHost.OnTabChangeListener {
+    ctor public FragmentTabHost(android.content.Context);
+    ctor public FragmentTabHost(android.content.Context, android.util.AttributeSet);
+    method public void addTab(android.widget.TabHost.TabSpec, java.lang.Class<?>, android.os.Bundle);
+    method public void onTabChanged(java.lang.String);
+    method public deprecated void setup();
+    method public void setup(android.content.Context, android.support.v4.app.FragmentManager);
+    method public void setup(android.content.Context, android.support.v4.app.FragmentManager, int);
+  }
+
+  public abstract class FragmentTransaction {
+    ctor public FragmentTransaction();
+    method public abstract android.support.v4.app.FragmentTransaction add(android.support.v4.app.Fragment, java.lang.String);
+    method public abstract android.support.v4.app.FragmentTransaction add(int, android.support.v4.app.Fragment);
+    method public abstract android.support.v4.app.FragmentTransaction add(int, android.support.v4.app.Fragment, java.lang.String);
+    method public abstract android.support.v4.app.FragmentTransaction addSharedElement(android.view.View, java.lang.String);
+    method public abstract android.support.v4.app.FragmentTransaction addToBackStack(java.lang.String);
+    method public abstract android.support.v4.app.FragmentTransaction attach(android.support.v4.app.Fragment);
+    method public abstract int commit();
+    method public abstract int commitAllowingStateLoss();
+    method public abstract void commitNow();
+    method public abstract void commitNowAllowingStateLoss();
+    method public abstract android.support.v4.app.FragmentTransaction detach(android.support.v4.app.Fragment);
+    method public abstract android.support.v4.app.FragmentTransaction disallowAddToBackStack();
+    method public abstract android.support.v4.app.FragmentTransaction hide(android.support.v4.app.Fragment);
+    method public abstract boolean isAddToBackStackAllowed();
+    method public abstract boolean isEmpty();
+    method public abstract android.support.v4.app.FragmentTransaction remove(android.support.v4.app.Fragment);
+    method public abstract android.support.v4.app.FragmentTransaction replace(int, android.support.v4.app.Fragment);
+    method public abstract android.support.v4.app.FragmentTransaction replace(int, android.support.v4.app.Fragment, java.lang.String);
+    method public abstract android.support.v4.app.FragmentTransaction runOnCommit(java.lang.Runnable);
+    method public abstract deprecated android.support.v4.app.FragmentTransaction setAllowOptimization(boolean);
+    method public abstract android.support.v4.app.FragmentTransaction setBreadCrumbShortTitle(int);
+    method public abstract android.support.v4.app.FragmentTransaction setBreadCrumbShortTitle(java.lang.CharSequence);
+    method public abstract android.support.v4.app.FragmentTransaction setBreadCrumbTitle(int);
+    method public abstract android.support.v4.app.FragmentTransaction setBreadCrumbTitle(java.lang.CharSequence);
+    method public abstract android.support.v4.app.FragmentTransaction setCustomAnimations(int, int);
+    method public abstract android.support.v4.app.FragmentTransaction setCustomAnimations(int, int, int, int);
+    method public abstract android.support.v4.app.FragmentTransaction setPrimaryNavigationFragment(android.support.v4.app.Fragment);
+    method public abstract android.support.v4.app.FragmentTransaction setReorderingAllowed(boolean);
+    method public abstract android.support.v4.app.FragmentTransaction setTransition(int);
+    method public abstract android.support.v4.app.FragmentTransaction setTransitionStyle(int);
+    method public abstract android.support.v4.app.FragmentTransaction show(android.support.v4.app.Fragment);
+    field public static final int TRANSIT_ENTER_MASK = 4096; // 0x1000
+    field public static final int TRANSIT_EXIT_MASK = 8192; // 0x2000
+    field public static final int TRANSIT_FRAGMENT_CLOSE = 8194; // 0x2002
+    field public static final int TRANSIT_FRAGMENT_FADE = 4099; // 0x1003
+    field public static final int TRANSIT_FRAGMENT_OPEN = 4097; // 0x1001
+    field public static final int TRANSIT_NONE = 0; // 0x0
+    field public static final int TRANSIT_UNSET = -1; // 0xffffffff
+  }
+
+  public class FrameMetricsAggregator {
+    ctor public FrameMetricsAggregator();
+    ctor public FrameMetricsAggregator(int);
+    method public void add(android.app.Activity);
+    method public android.util.SparseIntArray[] getMetrics();
+    method public android.util.SparseIntArray[] remove(android.app.Activity);
+    method public android.util.SparseIntArray[] reset();
+    method public android.util.SparseIntArray[] stop();
+    field public static final int ANIMATION_DURATION = 256; // 0x100
+    field public static final int ANIMATION_INDEX = 8; // 0x8
+    field public static final int COMMAND_DURATION = 32; // 0x20
+    field public static final int COMMAND_INDEX = 5; // 0x5
+    field public static final int DELAY_DURATION = 128; // 0x80
+    field public static final int DELAY_INDEX = 7; // 0x7
+    field public static final int DRAW_DURATION = 8; // 0x8
+    field public static final int DRAW_INDEX = 3; // 0x3
+    field public static final int EVERY_DURATION = 511; // 0x1ff
+    field public static final int INPUT_DURATION = 2; // 0x2
+    field public static final int INPUT_INDEX = 1; // 0x1
+    field public static final int LAYOUT_MEASURE_DURATION = 4; // 0x4
+    field public static final int LAYOUT_MEASURE_INDEX = 2; // 0x2
+    field public static final int SWAP_DURATION = 64; // 0x40
+    field public static final int SWAP_INDEX = 6; // 0x6
+    field public static final int SYNC_DURATION = 16; // 0x10
+    field public static final int SYNC_INDEX = 4; // 0x4
+    field public static final int TOTAL_DURATION = 1; // 0x1
+    field public static final int TOTAL_INDEX = 0; // 0x0
+  }
+
+  public abstract class JobIntentService extends android.app.Service {
+    ctor public JobIntentService();
+    method public static void enqueueWork(android.content.Context, java.lang.Class, int, android.content.Intent);
+    method public static void enqueueWork(android.content.Context, android.content.ComponentName, int, android.content.Intent);
+    method public boolean isStopped();
+    method public android.os.IBinder onBind(android.content.Intent);
+    method protected abstract void onHandleWork(android.content.Intent);
+    method public boolean onStopCurrentWork();
+    method public void setInterruptIfStopped(boolean);
+  }
+
+  public class ListFragment extends android.support.v4.app.Fragment {
+    ctor public ListFragment();
+    method public android.widget.ListAdapter getListAdapter();
+    method public android.widget.ListView getListView();
+    method public long getSelectedItemId();
+    method public int getSelectedItemPosition();
+    method public void onListItemClick(android.widget.ListView, android.view.View, int, long);
+    method public void setEmptyText(java.lang.CharSequence);
+    method public void setListAdapter(android.widget.ListAdapter);
+    method public void setListShown(boolean);
+    method public void setListShownNoAnimation(boolean);
+    method public void setSelection(int);
+  }
+
+  public abstract class LoaderManager {
+    ctor public LoaderManager();
+    method public abstract void destroyLoader(int);
+    method public abstract void dump(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public static void enableDebugLogging(boolean);
+    method public abstract <D> android.support.v4.content.Loader<D> getLoader(int);
+    method public boolean hasRunningLoaders();
+    method public abstract <D> android.support.v4.content.Loader<D> initLoader(int, android.os.Bundle, android.support.v4.app.LoaderManager.LoaderCallbacks<D>);
+    method public abstract <D> android.support.v4.content.Loader<D> restartLoader(int, android.os.Bundle, android.support.v4.app.LoaderManager.LoaderCallbacks<D>);
+  }
+
+  public static abstract interface LoaderManager.LoaderCallbacks<D> {
+    method public abstract android.support.v4.content.Loader<D> onCreateLoader(int, android.os.Bundle);
+    method public abstract void onLoadFinished(android.support.v4.content.Loader<D>, D);
+    method public abstract void onLoaderReset(android.support.v4.content.Loader<D>);
+  }
+
+  public final class NavUtils {
+    method public static android.content.Intent getParentActivityIntent(android.app.Activity);
+    method public static android.content.Intent getParentActivityIntent(android.content.Context, java.lang.Class<?>) throws android.content.pm.PackageManager.NameNotFoundException;
+    method public static android.content.Intent getParentActivityIntent(android.content.Context, android.content.ComponentName) throws android.content.pm.PackageManager.NameNotFoundException;
+    method public static java.lang.String getParentActivityName(android.app.Activity);
+    method public static java.lang.String getParentActivityName(android.content.Context, android.content.ComponentName) throws android.content.pm.PackageManager.NameNotFoundException;
+    method public static void navigateUpFromSameTask(android.app.Activity);
+    method public static void navigateUpTo(android.app.Activity, android.content.Intent);
+    method public static boolean shouldUpRecreateTask(android.app.Activity, android.content.Intent);
+    field public static final java.lang.String PARENT_ACTIVITY = "android.support.PARENT_ACTIVITY";
+  }
+
+  public class NotificationCompat {
+    ctor public NotificationCompat();
+    method public static android.support.v4.app.NotificationCompat.Action getAction(android.app.Notification, int);
+    method public static int getActionCount(android.app.Notification);
+    method public static int getBadgeIconType(android.app.Notification);
+    method public static java.lang.String getCategory(android.app.Notification);
+    method public static java.lang.String getChannelId(android.app.Notification);
+    method public static android.os.Bundle getExtras(android.app.Notification);
+    method public static java.lang.String getGroup(android.app.Notification);
+    method public static int getGroupAlertBehavior(android.app.Notification);
+    method public static boolean getLocalOnly(android.app.Notification);
+    method public static java.lang.String getShortcutId(android.app.Notification);
+    method public static java.lang.String getSortKey(android.app.Notification);
+    method public static long getTimeoutAfter(android.app.Notification);
+    method public static boolean isGroupSummary(android.app.Notification);
+    field public static final int BADGE_ICON_LARGE = 2; // 0x2
+    field public static final int BADGE_ICON_NONE = 0; // 0x0
+    field public static final int BADGE_ICON_SMALL = 1; // 0x1
+    field public static final java.lang.String CATEGORY_ALARM = "alarm";
+    field public static final java.lang.String CATEGORY_CALL = "call";
+    field public static final java.lang.String CATEGORY_EMAIL = "email";
+    field public static final java.lang.String CATEGORY_ERROR = "err";
+    field public static final java.lang.String CATEGORY_EVENT = "event";
+    field public static final java.lang.String CATEGORY_MESSAGE = "msg";
+    field public static final java.lang.String CATEGORY_PROGRESS = "progress";
+    field public static final java.lang.String CATEGORY_PROMO = "promo";
+    field public static final java.lang.String CATEGORY_RECOMMENDATION = "recommendation";
+    field public static final java.lang.String CATEGORY_REMINDER = "reminder";
+    field public static final java.lang.String CATEGORY_SERVICE = "service";
+    field public static final java.lang.String CATEGORY_SOCIAL = "social";
+    field public static final java.lang.String CATEGORY_STATUS = "status";
+    field public static final java.lang.String CATEGORY_SYSTEM = "sys";
+    field public static final java.lang.String CATEGORY_TRANSPORT = "transport";
+    field public static final int COLOR_DEFAULT = 0; // 0x0
+    field public static final int DEFAULT_ALL = -1; // 0xffffffff
+    field public static final int DEFAULT_LIGHTS = 4; // 0x4
+    field public static final int DEFAULT_SOUND = 1; // 0x1
+    field public static final int DEFAULT_VIBRATE = 2; // 0x2
+    field public static final java.lang.String EXTRA_AUDIO_CONTENTS_URI = "android.audioContents";
+    field public static final java.lang.String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
+    field public static final java.lang.String EXTRA_BIG_TEXT = "android.bigText";
+    field public static final java.lang.String EXTRA_COMPACT_ACTIONS = "android.compactActions";
+    field public static final java.lang.String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";
+    field public static final java.lang.String EXTRA_INFO_TEXT = "android.infoText";
+    field public static final java.lang.String EXTRA_LARGE_ICON = "android.largeIcon";
+    field public static final java.lang.String EXTRA_LARGE_ICON_BIG = "android.largeIcon.big";
+    field public static final java.lang.String EXTRA_MEDIA_SESSION = "android.mediaSession";
+    field public static final java.lang.String EXTRA_MESSAGES = "android.messages";
+    field public static final java.lang.String EXTRA_PEOPLE = "android.people";
+    field public static final java.lang.String EXTRA_PICTURE = "android.picture";
+    field public static final java.lang.String EXTRA_PROGRESS = "android.progress";
+    field public static final java.lang.String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
+    field public static final java.lang.String EXTRA_PROGRESS_MAX = "android.progressMax";
+    field public static final java.lang.String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory";
+    field public static final java.lang.String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
+    field public static final java.lang.String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
+    field public static final java.lang.String EXTRA_SHOW_WHEN = "android.showWhen";
+    field public static final java.lang.String EXTRA_SMALL_ICON = "android.icon";
+    field public static final java.lang.String EXTRA_SUB_TEXT = "android.subText";
+    field public static final java.lang.String EXTRA_SUMMARY_TEXT = "android.summaryText";
+    field public static final java.lang.String EXTRA_TEMPLATE = "android.template";
+    field public static final java.lang.String EXTRA_TEXT = "android.text";
+    field public static final java.lang.String EXTRA_TEXT_LINES = "android.textLines";
+    field public static final java.lang.String EXTRA_TITLE = "android.title";
+    field public static final java.lang.String EXTRA_TITLE_BIG = "android.title.big";
+    field public static final int FLAG_AUTO_CANCEL = 16; // 0x10
+    field public static final int FLAG_FOREGROUND_SERVICE = 64; // 0x40
+    field public static final int FLAG_GROUP_SUMMARY = 512; // 0x200
+    field public static final deprecated int FLAG_HIGH_PRIORITY = 128; // 0x80
+    field public static final int FLAG_INSISTENT = 4; // 0x4
+    field public static final int FLAG_LOCAL_ONLY = 256; // 0x100
+    field public static final int FLAG_NO_CLEAR = 32; // 0x20
+    field public static final int FLAG_ONGOING_EVENT = 2; // 0x2
+    field public static final int FLAG_ONLY_ALERT_ONCE = 8; // 0x8
+    field public static final int FLAG_SHOW_LIGHTS = 1; // 0x1
+    field public static final int GROUP_ALERT_ALL = 0; // 0x0
+    field public static final int GROUP_ALERT_CHILDREN = 2; // 0x2
+    field public static final int GROUP_ALERT_SUMMARY = 1; // 0x1
+    field public static final int PRIORITY_DEFAULT = 0; // 0x0
+    field public static final int PRIORITY_HIGH = 1; // 0x1
+    field public static final int PRIORITY_LOW = -1; // 0xffffffff
+    field public static final int PRIORITY_MAX = 2; // 0x2
+    field public static final int PRIORITY_MIN = -2; // 0xfffffffe
+    field public static final int STREAM_DEFAULT = -1; // 0xffffffff
+    field public static final int VISIBILITY_PRIVATE = 0; // 0x0
+    field public static final int VISIBILITY_PUBLIC = 1; // 0x1
+    field public static final int VISIBILITY_SECRET = -1; // 0xffffffff
+  }
+
+  public static class NotificationCompat.Action {
+    ctor public NotificationCompat.Action(int, java.lang.CharSequence, android.app.PendingIntent);
+    method public android.app.PendingIntent getActionIntent();
+    method public boolean getAllowGeneratedReplies();
+    method public android.support.v4.app.RemoteInput[] getDataOnlyRemoteInputs();
+    method public android.os.Bundle getExtras();
+    method public int getIcon();
+    method public android.support.v4.app.RemoteInput[] getRemoteInputs();
+    method public java.lang.CharSequence getTitle();
+    field public android.app.PendingIntent actionIntent;
+    field public int icon;
+    field public java.lang.CharSequence title;
+  }
+
+  public static final class NotificationCompat.Action.Builder {
+    ctor public NotificationCompat.Action.Builder(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public NotificationCompat.Action.Builder(android.support.v4.app.NotificationCompat.Action);
+    method public android.support.v4.app.NotificationCompat.Action.Builder addExtras(android.os.Bundle);
+    method public android.support.v4.app.NotificationCompat.Action.Builder addRemoteInput(android.support.v4.app.RemoteInput);
+    method public android.support.v4.app.NotificationCompat.Action build();
+    method public android.support.v4.app.NotificationCompat.Action.Builder extend(android.support.v4.app.NotificationCompat.Action.Extender);
+    method public android.os.Bundle getExtras();
+    method public android.support.v4.app.NotificationCompat.Action.Builder setAllowGeneratedReplies(boolean);
+  }
+
+  public static abstract interface NotificationCompat.Action.Extender {
+    method public abstract android.support.v4.app.NotificationCompat.Action.Builder extend(android.support.v4.app.NotificationCompat.Action.Builder);
+  }
+
+  public static final class NotificationCompat.Action.WearableExtender implements android.support.v4.app.NotificationCompat.Action.Extender {
+    ctor public NotificationCompat.Action.WearableExtender();
+    ctor public NotificationCompat.Action.WearableExtender(android.support.v4.app.NotificationCompat.Action);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender clone();
+    method public android.support.v4.app.NotificationCompat.Action.Builder extend(android.support.v4.app.NotificationCompat.Action.Builder);
+    method public java.lang.CharSequence getCancelLabel();
+    method public java.lang.CharSequence getConfirmLabel();
+    method public boolean getHintDisplayActionInline();
+    method public boolean getHintLaunchesActivity();
+    method public java.lang.CharSequence getInProgressLabel();
+    method public boolean isAvailableOffline();
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setAvailableOffline(boolean);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setCancelLabel(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setConfirmLabel(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setHintDisplayActionInline(boolean);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setHintLaunchesActivity(boolean);
+    method public android.support.v4.app.NotificationCompat.Action.WearableExtender setInProgressLabel(java.lang.CharSequence);
+  }
+
+  public static class NotificationCompat.BigPictureStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.BigPictureStyle();
+    ctor public NotificationCompat.BigPictureStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public android.support.v4.app.NotificationCompat.BigPictureStyle bigLargeIcon(android.graphics.Bitmap);
+    method public android.support.v4.app.NotificationCompat.BigPictureStyle bigPicture(android.graphics.Bitmap);
+    method public android.support.v4.app.NotificationCompat.BigPictureStyle setBigContentTitle(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.BigPictureStyle setSummaryText(java.lang.CharSequence);
+  }
+
+  public static class NotificationCompat.BigTextStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.BigTextStyle();
+    ctor public NotificationCompat.BigTextStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public android.support.v4.app.NotificationCompat.BigTextStyle bigText(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.BigTextStyle setBigContentTitle(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.BigTextStyle setSummaryText(java.lang.CharSequence);
+  }
+
+  public static class NotificationCompat.Builder {
+    ctor public NotificationCompat.Builder(android.content.Context, java.lang.String);
+    ctor public deprecated NotificationCompat.Builder(android.content.Context);
+    method public android.support.v4.app.NotificationCompat.Builder addAction(int, java.lang.CharSequence, android.app.PendingIntent);
+    method public android.support.v4.app.NotificationCompat.Builder addAction(android.support.v4.app.NotificationCompat.Action);
+    method public android.support.v4.app.NotificationCompat.Builder addExtras(android.os.Bundle);
+    method public android.support.v4.app.NotificationCompat.Builder addPerson(java.lang.String);
+    method public android.app.Notification build();
+    method public android.support.v4.app.NotificationCompat.Builder extend(android.support.v4.app.NotificationCompat.Extender);
+    method public android.os.Bundle getExtras();
+    method public deprecated android.app.Notification getNotification();
+    method protected static java.lang.CharSequence limitCharSequenceLength(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setAutoCancel(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setBadgeIconType(int);
+    method public android.support.v4.app.NotificationCompat.Builder setCategory(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.Builder setChannelId(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.Builder setColor(int);
+    method public android.support.v4.app.NotificationCompat.Builder setColorized(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setContent(android.widget.RemoteViews);
+    method public android.support.v4.app.NotificationCompat.Builder setContentInfo(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setContentIntent(android.app.PendingIntent);
+    method public android.support.v4.app.NotificationCompat.Builder setContentText(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setContentTitle(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setCustomBigContentView(android.widget.RemoteViews);
+    method public android.support.v4.app.NotificationCompat.Builder setCustomContentView(android.widget.RemoteViews);
+    method public android.support.v4.app.NotificationCompat.Builder setCustomHeadsUpContentView(android.widget.RemoteViews);
+    method public android.support.v4.app.NotificationCompat.Builder setDefaults(int);
+    method public android.support.v4.app.NotificationCompat.Builder setDeleteIntent(android.app.PendingIntent);
+    method public android.support.v4.app.NotificationCompat.Builder setExtras(android.os.Bundle);
+    method public android.support.v4.app.NotificationCompat.Builder setFullScreenIntent(android.app.PendingIntent, boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setGroup(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.Builder setGroupAlertBehavior(int);
+    method public android.support.v4.app.NotificationCompat.Builder setGroupSummary(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setLargeIcon(android.graphics.Bitmap);
+    method public android.support.v4.app.NotificationCompat.Builder setLights(int, int, int);
+    method public android.support.v4.app.NotificationCompat.Builder setLocalOnly(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setNumber(int);
+    method public android.support.v4.app.NotificationCompat.Builder setOngoing(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setOnlyAlertOnce(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setPriority(int);
+    method public android.support.v4.app.NotificationCompat.Builder setProgress(int, int, boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setPublicVersion(android.app.Notification);
+    method public android.support.v4.app.NotificationCompat.Builder setRemoteInputHistory(java.lang.CharSequence[]);
+    method public android.support.v4.app.NotificationCompat.Builder setShortcutId(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.Builder setShowWhen(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setSmallIcon(int);
+    method public android.support.v4.app.NotificationCompat.Builder setSmallIcon(int, int);
+    method public android.support.v4.app.NotificationCompat.Builder setSortKey(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.Builder setSound(android.net.Uri);
+    method public android.support.v4.app.NotificationCompat.Builder setSound(android.net.Uri, int);
+    method public android.support.v4.app.NotificationCompat.Builder setStyle(android.support.v4.app.NotificationCompat.Style);
+    method public android.support.v4.app.NotificationCompat.Builder setSubText(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setTicker(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.Builder setTicker(java.lang.CharSequence, android.widget.RemoteViews);
+    method public android.support.v4.app.NotificationCompat.Builder setTimeoutAfter(long);
+    method public android.support.v4.app.NotificationCompat.Builder setUsesChronometer(boolean);
+    method public android.support.v4.app.NotificationCompat.Builder setVibrate(long[]);
+    method public android.support.v4.app.NotificationCompat.Builder setVisibility(int);
+    method public android.support.v4.app.NotificationCompat.Builder setWhen(long);
+    field public java.util.ArrayList<java.lang.String> mPeople;
+  }
+
+  public static final class NotificationCompat.CarExtender implements android.support.v4.app.NotificationCompat.Extender {
+    ctor public NotificationCompat.CarExtender();
+    ctor public NotificationCompat.CarExtender(android.app.Notification);
+    method public android.support.v4.app.NotificationCompat.Builder extend(android.support.v4.app.NotificationCompat.Builder);
+    method public int getColor();
+    method public android.graphics.Bitmap getLargeIcon();
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation getUnreadConversation();
+    method public android.support.v4.app.NotificationCompat.CarExtender setColor(int);
+    method public android.support.v4.app.NotificationCompat.CarExtender setLargeIcon(android.graphics.Bitmap);
+    method public android.support.v4.app.NotificationCompat.CarExtender setUnreadConversation(android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation);
+  }
+
+  public static class NotificationCompat.CarExtender.UnreadConversation {
+    method public long getLatestTimestamp();
+    method public java.lang.String[] getMessages();
+    method public java.lang.String getParticipant();
+    method public java.lang.String[] getParticipants();
+    method public android.app.PendingIntent getReadPendingIntent();
+    method public android.support.v4.app.RemoteInput getRemoteInput();
+    method public android.app.PendingIntent getReplyPendingIntent();
+  }
+
+  public static class NotificationCompat.CarExtender.UnreadConversation.Builder {
+    ctor public NotificationCompat.CarExtender.UnreadConversation.Builder(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation.Builder addMessage(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation build();
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation.Builder setLatestTimestamp(long);
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation.Builder setReadPendingIntent(android.app.PendingIntent);
+    method public android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation.Builder setReplyAction(android.app.PendingIntent, android.support.v4.app.RemoteInput);
+  }
+
+  public static class NotificationCompat.DecoratedCustomViewStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.DecoratedCustomViewStyle();
+  }
+
+  public static abstract interface NotificationCompat.Extender {
+    method public abstract android.support.v4.app.NotificationCompat.Builder extend(android.support.v4.app.NotificationCompat.Builder);
+  }
+
+  public static class NotificationCompat.InboxStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.InboxStyle();
+    ctor public NotificationCompat.InboxStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public android.support.v4.app.NotificationCompat.InboxStyle addLine(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.InboxStyle setBigContentTitle(java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.InboxStyle setSummaryText(java.lang.CharSequence);
+  }
+
+  public static class NotificationCompat.MessagingStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.MessagingStyle(java.lang.CharSequence);
+    method public void addCompatExtras(android.os.Bundle);
+    method public android.support.v4.app.NotificationCompat.MessagingStyle addMessage(java.lang.CharSequence, long, java.lang.CharSequence);
+    method public android.support.v4.app.NotificationCompat.MessagingStyle addMessage(android.support.v4.app.NotificationCompat.MessagingStyle.Message);
+    method public static android.support.v4.app.NotificationCompat.MessagingStyle extractMessagingStyleFromNotification(android.app.Notification);
+    method public java.lang.CharSequence getConversationTitle();
+    method public java.util.List<android.support.v4.app.NotificationCompat.MessagingStyle.Message> getMessages();
+    method public java.lang.CharSequence getUserDisplayName();
+    method public android.support.v4.app.NotificationCompat.MessagingStyle setConversationTitle(java.lang.CharSequence);
+    field public static final int MAXIMUM_RETAINED_MESSAGES = 25; // 0x19
+  }
+
+  public static final class NotificationCompat.MessagingStyle.Message {
+    ctor public NotificationCompat.MessagingStyle.Message(java.lang.CharSequence, long, java.lang.CharSequence);
+    method public java.lang.String getDataMimeType();
+    method public android.net.Uri getDataUri();
+    method public android.os.Bundle getExtras();
+    method public java.lang.CharSequence getSender();
+    method public java.lang.CharSequence getText();
+    method public long getTimestamp();
+    method public android.support.v4.app.NotificationCompat.MessagingStyle.Message setData(java.lang.String, android.net.Uri);
+  }
+
+  public static abstract class NotificationCompat.Style {
+    ctor public NotificationCompat.Style();
+    method public android.app.Notification build();
+    method public void setBuilder(android.support.v4.app.NotificationCompat.Builder);
+  }
+
+  public static final class NotificationCompat.WearableExtender implements android.support.v4.app.NotificationCompat.Extender {
+    ctor public NotificationCompat.WearableExtender();
+    ctor public NotificationCompat.WearableExtender(android.app.Notification);
+    method public android.support.v4.app.NotificationCompat.WearableExtender addAction(android.support.v4.app.NotificationCompat.Action);
+    method public android.support.v4.app.NotificationCompat.WearableExtender addActions(java.util.List<android.support.v4.app.NotificationCompat.Action>);
+    method public android.support.v4.app.NotificationCompat.WearableExtender addPage(android.app.Notification);
+    method public android.support.v4.app.NotificationCompat.WearableExtender addPages(java.util.List<android.app.Notification>);
+    method public android.support.v4.app.NotificationCompat.WearableExtender clearActions();
+    method public android.support.v4.app.NotificationCompat.WearableExtender clearPages();
+    method public android.support.v4.app.NotificationCompat.WearableExtender clone();
+    method public android.support.v4.app.NotificationCompat.Builder extend(android.support.v4.app.NotificationCompat.Builder);
+    method public java.util.List<android.support.v4.app.NotificationCompat.Action> getActions();
+    method public android.graphics.Bitmap getBackground();
+    method public java.lang.String getBridgeTag();
+    method public int getContentAction();
+    method public int getContentIcon();
+    method public int getContentIconGravity();
+    method public boolean getContentIntentAvailableOffline();
+    method public int getCustomContentHeight();
+    method public int getCustomSizePreset();
+    method public java.lang.String getDismissalId();
+    method public android.app.PendingIntent getDisplayIntent();
+    method public int getGravity();
+    method public boolean getHintAmbientBigPicture();
+    method public boolean getHintAvoidBackgroundClipping();
+    method public boolean getHintContentIntentLaunchesActivity();
+    method public boolean getHintHideIcon();
+    method public int getHintScreenTimeout();
+    method public boolean getHintShowBackgroundOnly();
+    method public java.util.List<android.app.Notification> getPages();
+    method public boolean getStartScrollBottom();
+    method public android.support.v4.app.NotificationCompat.WearableExtender setBackground(android.graphics.Bitmap);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setBridgeTag(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setContentAction(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setContentIcon(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setContentIconGravity(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setContentIntentAvailableOffline(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setCustomContentHeight(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setCustomSizePreset(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setDismissalId(java.lang.String);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setDisplayIntent(android.app.PendingIntent);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setGravity(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintAmbientBigPicture(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintAvoidBackgroundClipping(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintContentIntentLaunchesActivity(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintHideIcon(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintScreenTimeout(int);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setHintShowBackgroundOnly(boolean);
+    method public android.support.v4.app.NotificationCompat.WearableExtender setStartScrollBottom(boolean);
+    field public static final int SCREEN_TIMEOUT_LONG = -1; // 0xffffffff
+    field public static final int SCREEN_TIMEOUT_SHORT = 0; // 0x0
+    field public static final int SIZE_DEFAULT = 0; // 0x0
+    field public static final int SIZE_FULL_SCREEN = 5; // 0x5
+    field public static final int SIZE_LARGE = 4; // 0x4
+    field public static final int SIZE_MEDIUM = 3; // 0x3
+    field public static final int SIZE_SMALL = 2; // 0x2
+    field public static final int SIZE_XSMALL = 1; // 0x1
+    field public static final int UNSET_ACTION_INDEX = -1; // 0xffffffff
+  }
+
+  public final class NotificationCompatExtras {
+    field public static final java.lang.String EXTRA_ACTION_EXTRAS = "android.support.actionExtras";
+    field public static final java.lang.String EXTRA_GROUP_KEY = "android.support.groupKey";
+    field public static final java.lang.String EXTRA_GROUP_SUMMARY = "android.support.isGroupSummary";
+    field public static final java.lang.String EXTRA_LOCAL_ONLY = "android.support.localOnly";
+    field public static final java.lang.String EXTRA_REMOTE_INPUTS = "android.support.remoteInputs";
+    field public static final java.lang.String EXTRA_SORT_KEY = "android.support.sortKey";
+  }
+
+  public abstract class NotificationCompatSideChannelService extends android.app.Service {
+    ctor public NotificationCompatSideChannelService();
+    method public abstract void cancel(java.lang.String, int, java.lang.String);
+    method public abstract void cancelAll(java.lang.String);
+    method public abstract void notify(java.lang.String, int, java.lang.String, android.app.Notification);
+    method public android.os.IBinder onBind(android.content.Intent);
+  }
+
+  public final class NotificationManagerCompat {
+    method public boolean areNotificationsEnabled();
+    method public void cancel(int);
+    method public void cancel(java.lang.String, int);
+    method public void cancelAll();
+    method public static android.support.v4.app.NotificationManagerCompat from(android.content.Context);
+    method public static java.util.Set<java.lang.String> getEnabledListenerPackages(android.content.Context);
+    method public int getImportance();
+    method public void notify(int, android.app.Notification);
+    method public void notify(java.lang.String, int, android.app.Notification);
+    field public static final java.lang.String ACTION_BIND_SIDE_CHANNEL = "android.support.BIND_NOTIFICATION_SIDE_CHANNEL";
+    field public static final java.lang.String EXTRA_USE_SIDE_CHANNEL = "android.support.useSideChannel";
+    field public static final int IMPORTANCE_DEFAULT = 3; // 0x3
+    field public static final int IMPORTANCE_HIGH = 4; // 0x4
+    field public static final int IMPORTANCE_LOW = 2; // 0x2
+    field public static final int IMPORTANCE_MAX = 5; // 0x5
+    field public static final int IMPORTANCE_MIN = 1; // 0x1
+    field public static final int IMPORTANCE_NONE = 0; // 0x0
+    field public static final int IMPORTANCE_UNSPECIFIED = -1000; // 0xfffffc18
+  }
+
+  public final class RemoteInput extends android.support.v4.app.RemoteInputCompatBase.RemoteInput {
+    method public static void addDataResultToIntent(android.support.v4.app.RemoteInput, android.content.Intent, java.util.Map<java.lang.String, android.net.Uri>);
+    method public static void addResultsToIntent(android.support.v4.app.RemoteInput[], android.content.Intent, android.os.Bundle);
+    method public boolean getAllowFreeFormInput();
+    method public java.util.Set<java.lang.String> getAllowedDataTypes();
+    method public java.lang.CharSequence[] getChoices();
+    method public static java.util.Map<java.lang.String, android.net.Uri> getDataResultsFromIntent(android.content.Intent, java.lang.String);
+    method public android.os.Bundle getExtras();
+    method public java.lang.CharSequence getLabel();
+    method public java.lang.String getResultKey();
+    method public static android.os.Bundle getResultsFromIntent(android.content.Intent);
+    method public boolean isDataOnly();
+    field public static final java.lang.String EXTRA_RESULTS_DATA = "android.remoteinput.resultsData";
+    field public static final java.lang.String RESULTS_CLIP_LABEL = "android.remoteinput.results";
+  }
+
+  public static final class RemoteInput.Builder {
+    ctor public RemoteInput.Builder(java.lang.String);
+    method public android.support.v4.app.RemoteInput.Builder addExtras(android.os.Bundle);
+    method public android.support.v4.app.RemoteInput build();
+    method public android.os.Bundle getExtras();
+    method public android.support.v4.app.RemoteInput.Builder setAllowDataType(java.lang.String, boolean);
+    method public android.support.v4.app.RemoteInput.Builder setAllowFreeFormInput(boolean);
+    method public android.support.v4.app.RemoteInput.Builder setChoices(java.lang.CharSequence[]);
+    method public android.support.v4.app.RemoteInput.Builder setLabel(java.lang.CharSequence);
+  }
+
+   deprecated class RemoteInputCompatBase {
+  }
+
+  public static abstract class RemoteInputCompatBase.RemoteInput {
+    ctor public RemoteInputCompatBase.RemoteInput();
+    method protected abstract boolean getAllowFreeFormInput();
+    method protected abstract java.util.Set<java.lang.String> getAllowedDataTypes();
+    method protected abstract java.lang.CharSequence[] getChoices();
+    method protected abstract android.os.Bundle getExtras();
+    method protected abstract java.lang.CharSequence getLabel();
+    method protected abstract java.lang.String getResultKey();
+  }
+
+  public final class ServiceCompat {
+    method public static void stopForeground(android.app.Service, int);
+    field public static final int START_STICKY = 1; // 0x1
+    field public static final int STOP_FOREGROUND_DETACH = 2; // 0x2
+    field public static final int STOP_FOREGROUND_REMOVE = 1; // 0x1
+  }
+
+  public final class ShareCompat {
+    method public static void configureMenuItem(android.view.MenuItem, android.support.v4.app.ShareCompat.IntentBuilder);
+    method public static void configureMenuItem(android.view.Menu, int, android.support.v4.app.ShareCompat.IntentBuilder);
+    method public static android.content.ComponentName getCallingActivity(android.app.Activity);
+    method public static java.lang.String getCallingPackage(android.app.Activity);
+    field public static final java.lang.String EXTRA_CALLING_ACTIVITY = "android.support.v4.app.EXTRA_CALLING_ACTIVITY";
+    field public static final java.lang.String EXTRA_CALLING_PACKAGE = "android.support.v4.app.EXTRA_CALLING_PACKAGE";
+  }
+
+  public static class ShareCompat.IntentBuilder {
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailBcc(java.lang.String);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailBcc(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailCc(java.lang.String);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailCc(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailTo(java.lang.String);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addEmailTo(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder addStream(android.net.Uri);
+    method public android.content.Intent createChooserIntent();
+    method public static android.support.v4.app.ShareCompat.IntentBuilder from(android.app.Activity);
+    method public android.content.Intent getIntent();
+    method public android.support.v4.app.ShareCompat.IntentBuilder setChooserTitle(java.lang.CharSequence);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setChooserTitle(int);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setEmailBcc(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setEmailCc(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setEmailTo(java.lang.String[]);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setHtmlText(java.lang.String);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setStream(android.net.Uri);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setSubject(java.lang.String);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setText(java.lang.CharSequence);
+    method public android.support.v4.app.ShareCompat.IntentBuilder setType(java.lang.String);
+    method public void startChooser();
+  }
+
+  public static class ShareCompat.IntentReader {
+    method public static android.support.v4.app.ShareCompat.IntentReader from(android.app.Activity);
+    method public android.content.ComponentName getCallingActivity();
+    method public android.graphics.drawable.Drawable getCallingActivityIcon();
+    method public android.graphics.drawable.Drawable getCallingApplicationIcon();
+    method public java.lang.CharSequence getCallingApplicationLabel();
+    method public java.lang.String getCallingPackage();
+    method public java.lang.String[] getEmailBcc();
+    method public java.lang.String[] getEmailCc();
+    method public java.lang.String[] getEmailTo();
+    method public java.lang.String getHtmlText();
+    method public android.net.Uri getStream();
+    method public android.net.Uri getStream(int);
+    method public int getStreamCount();
+    method public java.lang.String getSubject();
+    method public java.lang.CharSequence getText();
+    method public java.lang.String getType();
+    method public boolean isMultipleShare();
+    method public boolean isShareIntent();
+    method public boolean isSingleShare();
+  }
+
+  public abstract class SharedElementCallback {
+    ctor public SharedElementCallback();
+    method public android.os.Parcelable onCaptureSharedElementSnapshot(android.view.View, android.graphics.Matrix, android.graphics.RectF);
+    method public android.view.View onCreateSnapshotView(android.content.Context, android.os.Parcelable);
+    method public void onMapSharedElements(java.util.List<java.lang.String>, java.util.Map<java.lang.String, android.view.View>);
+    method public void onRejectSharedElements(java.util.List<android.view.View>);
+    method public void onSharedElementEnd(java.util.List<java.lang.String>, java.util.List<android.view.View>, java.util.List<android.view.View>);
+    method public void onSharedElementStart(java.util.List<java.lang.String>, java.util.List<android.view.View>, java.util.List<android.view.View>);
+    method public void onSharedElementsArrived(java.util.List<java.lang.String>, java.util.List<android.view.View>, android.support.v4.app.SharedElementCallback.OnSharedElementsReadyListener);
+  }
+
+  public static abstract interface SharedElementCallback.OnSharedElementsReadyListener {
+    method public abstract void onSharedElementsReady();
+  }
+
+  public final class TaskStackBuilder implements java.lang.Iterable {
+    method public android.support.v4.app.TaskStackBuilder addNextIntent(android.content.Intent);
+    method public android.support.v4.app.TaskStackBuilder addNextIntentWithParentStack(android.content.Intent);
+    method public android.support.v4.app.TaskStackBuilder addParentStack(android.app.Activity);
+    method public android.support.v4.app.TaskStackBuilder addParentStack(java.lang.Class<?>);
+    method public android.support.v4.app.TaskStackBuilder addParentStack(android.content.ComponentName);
+    method public static android.support.v4.app.TaskStackBuilder create(android.content.Context);
+    method public android.content.Intent editIntentAt(int);
+    method public static deprecated android.support.v4.app.TaskStackBuilder from(android.content.Context);
+    method public deprecated android.content.Intent getIntent(int);
+    method public int getIntentCount();
+    method public android.content.Intent[] getIntents();
+    method public android.app.PendingIntent getPendingIntent(int, int);
+    method public android.app.PendingIntent getPendingIntent(int, int, android.os.Bundle);
+    method public deprecated java.util.Iterator<android.content.Intent> iterator();
+    method public void startActivities();
+    method public void startActivities(android.os.Bundle);
+  }
+
+  public static abstract interface TaskStackBuilder.SupportParentable {
+    method public abstract android.content.Intent getSupportParentActivityIntent();
+  }
+
+}
+
+package android.support.v4.content {
+
+  public abstract class AsyncTaskLoader<D> extends android.support.v4.content.Loader {
+    ctor public AsyncTaskLoader(android.content.Context);
+    method public void cancelLoadInBackground();
+    method public boolean isLoadInBackgroundCanceled();
+    method public abstract D loadInBackground();
+    method public void onCanceled(D);
+    method protected D onLoadInBackground();
+    method public void setUpdateThrottle(long);
+  }
+
+  public final class ContentResolverCompat {
+    method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, android.support.v4.os.CancellationSignal);
+  }
+
+  public class ContextCompat {
+    ctor protected ContextCompat();
+    method public static int checkSelfPermission(android.content.Context, java.lang.String);
+    method public static android.content.Context createDeviceProtectedStorageContext(android.content.Context);
+    method public static java.io.File getCodeCacheDir(android.content.Context);
+    method public static final int getColor(android.content.Context, int);
+    method public static final android.content.res.ColorStateList getColorStateList(android.content.Context, int);
+    method public static java.io.File getDataDir(android.content.Context);
+    method public static final android.graphics.drawable.Drawable getDrawable(android.content.Context, int);
+    method public static java.io.File[] getExternalCacheDirs(android.content.Context);
+    method public static java.io.File[] getExternalFilesDirs(android.content.Context, java.lang.String);
+    method public static final java.io.File getNoBackupFilesDir(android.content.Context);
+    method public static java.io.File[] getObbDirs(android.content.Context);
+    method public static boolean isDeviceProtectedStorage(android.content.Context);
+    method public static boolean startActivities(android.content.Context, android.content.Intent[]);
+    method public static boolean startActivities(android.content.Context, android.content.Intent[], android.os.Bundle);
+    method public static void startActivity(android.content.Context, android.content.Intent, android.os.Bundle);
+    method public static void startForegroundService(android.content.Context, android.content.Intent);
+  }
+
+  public class CursorLoader extends android.support.v4.content.AsyncTaskLoader {
+    ctor public CursorLoader(android.content.Context);
+    ctor public CursorLoader(android.content.Context, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String);
+    method public void deliverResult(android.database.Cursor);
+    method public java.lang.String[] getProjection();
+    method public java.lang.String getSelection();
+    method public java.lang.String[] getSelectionArgs();
+    method public java.lang.String getSortOrder();
+    method public android.net.Uri getUri();
+    method public android.database.Cursor loadInBackground();
+    method public void onCanceled(android.database.Cursor);
+    method public void setProjection(java.lang.String[]);
+    method public void setSelection(java.lang.String);
+    method public void setSelectionArgs(java.lang.String[]);
+    method public void setSortOrder(java.lang.String);
+    method public void setUri(android.net.Uri);
+  }
+
+  public class FileProvider extends android.content.ContentProvider {
+    ctor public FileProvider();
+    method public int delete(android.net.Uri, java.lang.String, java.lang.String[]);
+    method public java.lang.String getType(android.net.Uri);
+    method public static android.net.Uri getUriForFile(android.content.Context, java.lang.String, java.io.File);
+    method public android.net.Uri insert(android.net.Uri, android.content.ContentValues);
+    method public boolean onCreate();
+    method public android.database.Cursor query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String);
+    method public int update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[]);
+  }
+
+  public final class IntentCompat {
+    method public static deprecated android.content.Intent makeMainActivity(android.content.ComponentName);
+    method public static android.content.Intent makeMainSelectorActivity(java.lang.String, java.lang.String);
+    method public static deprecated android.content.Intent makeRestartActivityTask(android.content.ComponentName);
+    field public static final deprecated java.lang.String ACTION_EXTERNAL_APPLICATIONS_AVAILABLE = "android.intent.action.EXTERNAL_APPLICATIONS_AVAILABLE";
+    field public static final deprecated java.lang.String ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE = "android.intent.action.EXTERNAL_APPLICATIONS_UNAVAILABLE";
+    field public static final java.lang.String CATEGORY_LEANBACK_LAUNCHER = "android.intent.category.LEANBACK_LAUNCHER";
+    field public static final deprecated java.lang.String EXTRA_CHANGED_PACKAGE_LIST = "android.intent.extra.changed_package_list";
+    field public static final deprecated java.lang.String EXTRA_CHANGED_UID_LIST = "android.intent.extra.changed_uid_list";
+    field public static final java.lang.String EXTRA_HTML_TEXT = "android.intent.extra.HTML_TEXT";
+    field public static final java.lang.String EXTRA_START_PLAYBACK = "android.intent.extra.START_PLAYBACK";
+    field public static final deprecated int FLAG_ACTIVITY_CLEAR_TASK = 32768; // 0x8000
+    field public static final deprecated int FLAG_ACTIVITY_TASK_ON_HOME = 16384; // 0x4000
+  }
+
+  public class Loader<D> {
+    ctor public Loader(android.content.Context);
+    method public void abandon();
+    method public boolean cancelLoad();
+    method public void commitContentChanged();
+    method public java.lang.String dataToString(D);
+    method public void deliverCancellation();
+    method public void deliverResult(D);
+    method public void dump(java.lang.String, java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public void forceLoad();
+    method public android.content.Context getContext();
+    method public int getId();
+    method public boolean isAbandoned();
+    method public boolean isReset();
+    method public boolean isStarted();
+    method protected void onAbandon();
+    method protected boolean onCancelLoad();
+    method public void onContentChanged();
+    method protected void onForceLoad();
+    method protected void onReset();
+    method protected void onStartLoading();
+    method protected void onStopLoading();
+    method public void registerListener(int, android.support.v4.content.Loader.OnLoadCompleteListener<D>);
+    method public void registerOnLoadCanceledListener(android.support.v4.content.Loader.OnLoadCanceledListener<D>);
+    method public void reset();
+    method public void rollbackContentChanged();
+    method public final void startLoading();
+    method public void stopLoading();
+    method public boolean takeContentChanged();
+    method public void unregisterListener(android.support.v4.content.Loader.OnLoadCompleteListener<D>);
+    method public void unregisterOnLoadCanceledListener(android.support.v4.content.Loader.OnLoadCanceledListener<D>);
+  }
+
+  public final class Loader.ForceLoadContentObserver extends android.database.ContentObserver {
+    ctor public Loader.ForceLoadContentObserver();
+  }
+
+  public static abstract interface Loader.OnLoadCanceledListener<D> {
+    method public abstract void onLoadCanceled(android.support.v4.content.Loader<D>);
+  }
+
+  public static abstract interface Loader.OnLoadCompleteListener<D> {
+    method public abstract void onLoadComplete(android.support.v4.content.Loader<D>, D);
+  }
+
+  public final class LocalBroadcastManager {
+    method public static android.support.v4.content.LocalBroadcastManager getInstance(android.content.Context);
+    method public void registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter);
+    method public boolean sendBroadcast(android.content.Intent);
+    method public void sendBroadcastSync(android.content.Intent);
+    method public void unregisterReceiver(android.content.BroadcastReceiver);
+  }
+
+  public final class MimeTypeFilter {
+    method public static boolean matches(java.lang.String, java.lang.String);
+    method public static java.lang.String matches(java.lang.String, java.lang.String[]);
+    method public static java.lang.String matches(java.lang.String[], java.lang.String);
+    method public static java.lang.String[] matchesMany(java.lang.String[], java.lang.String);
+  }
+
+  public final deprecated class ParallelExecutorCompat {
+    method public static deprecated java.util.concurrent.Executor getParallelExecutor();
+  }
+
+  public final class PermissionChecker {
+    method public static int checkCallingOrSelfPermission(android.content.Context, java.lang.String);
+    method public static int checkCallingPermission(android.content.Context, java.lang.String, java.lang.String);
+    method public static int checkPermission(android.content.Context, java.lang.String, int, int, java.lang.String);
+    method public static int checkSelfPermission(android.content.Context, java.lang.String);
+    field public static final int PERMISSION_DENIED = -1; // 0xffffffff
+    field public static final int PERMISSION_DENIED_APP_OP = -2; // 0xfffffffe
+    field public static final int PERMISSION_GRANTED = 0; // 0x0
+  }
+
+  public final class SharedPreferencesCompat {
+  }
+
+  public static final class SharedPreferencesCompat.EditorCompat {
+    method public void apply(android.content.SharedPreferences.Editor);
+    method public static android.support.v4.content.SharedPreferencesCompat.EditorCompat getInstance();
+  }
+
+  public abstract deprecated class WakefulBroadcastReceiver extends android.content.BroadcastReceiver {
+    ctor public WakefulBroadcastReceiver();
+    method public static boolean completeWakefulIntent(android.content.Intent);
+    method public static android.content.ComponentName startWakefulService(android.content.Context, android.content.Intent);
+  }
+
+}
+
+package android.support.v4.content.pm {
+
+  public final class ActivityInfoCompat {
+    field public static final int CONFIG_UI_MODE = 512; // 0x200
+  }
+
+  public class ShortcutInfoCompat {
+    method public android.content.ComponentName getActivity();
+    method public java.lang.CharSequence getDisabledMessage();
+    method public java.lang.String getId();
+    method public android.content.Intent getIntent();
+    method public android.content.Intent[] getIntents();
+    method public java.lang.CharSequence getLongLabel();
+    method public java.lang.CharSequence getShortLabel();
+  }
+
+  public static class ShortcutInfoCompat.Builder {
+    ctor public ShortcutInfoCompat.Builder(android.content.Context, java.lang.String);
+    method public android.support.v4.content.pm.ShortcutInfoCompat build();
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setActivity(android.content.ComponentName);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setDisabledMessage(java.lang.CharSequence);
+    method public deprecated android.support.v4.content.pm.ShortcutInfoCompat.Builder setIcon(android.graphics.Bitmap);
+    method public deprecated android.support.v4.content.pm.ShortcutInfoCompat.Builder setIcon(int);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setIcon(android.support.v4.graphics.drawable.IconCompat);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setIntent(android.content.Intent);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setIntents(android.content.Intent[]);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setLongLabel(java.lang.CharSequence);
+    method public android.support.v4.content.pm.ShortcutInfoCompat.Builder setShortLabel(java.lang.CharSequence);
+  }
+
+  public class ShortcutManagerCompat {
+    method public static android.content.Intent createShortcutResultIntent(android.content.Context, android.support.v4.content.pm.ShortcutInfoCompat);
+    method public static boolean isRequestPinShortcutSupported(android.content.Context);
+    method public static boolean requestPinShortcut(android.content.Context, android.support.v4.content.pm.ShortcutInfoCompat, android.content.IntentSender);
+  }
+
+}
+
+package android.support.v4.content.res {
+
+  public final class ConfigurationHelper {
+    method public static int getDensityDpi(android.content.res.Resources);
+    method public static deprecated int getScreenHeightDp(android.content.res.Resources);
+    method public static deprecated int getScreenWidthDp(android.content.res.Resources);
+    method public static deprecated int getSmallestScreenWidthDp(android.content.res.Resources);
+  }
+
+  public final class ResourcesCompat {
+    method public static int getColor(android.content.res.Resources, int, android.content.res.Resources.Theme) throws android.content.res.Resources.NotFoundException;
+    method public static android.content.res.ColorStateList getColorStateList(android.content.res.Resources, int, android.content.res.Resources.Theme) throws android.content.res.Resources.NotFoundException;
+    method public static android.graphics.drawable.Drawable getDrawable(android.content.res.Resources, int, android.content.res.Resources.Theme) throws android.content.res.Resources.NotFoundException;
+    method public static android.graphics.drawable.Drawable getDrawableForDensity(android.content.res.Resources, int, int, android.content.res.Resources.Theme) throws android.content.res.Resources.NotFoundException;
+    method public static android.graphics.Typeface getFont(android.content.Context, int) throws android.content.res.Resources.NotFoundException;
+  }
+
+}
+
+package android.support.v4.database {
+
+  public final class DatabaseUtilsCompat {
+    method public static java.lang.String[] appendSelectionArgs(java.lang.String[], java.lang.String[]);
+    method public static java.lang.String concatenateWhere(java.lang.String, java.lang.String);
+  }
+
+}
+
+package android.support.v4.graphics {
+
+  public final class BitmapCompat {
+    method public static int getAllocationByteCount(android.graphics.Bitmap);
+    method public static boolean hasMipMap(android.graphics.Bitmap);
+    method public static void setHasMipMap(android.graphics.Bitmap, boolean);
+  }
+
+  public final class ColorUtils {
+    method public static int HSLToColor(float[]);
+    method public static int LABToColor(double, double, double);
+    method public static void LABToXYZ(double, double, double, double[]);
+    method public static void RGBToHSL(int, int, int, float[]);
+    method public static void RGBToLAB(int, int, int, double[]);
+    method public static void RGBToXYZ(int, int, int, double[]);
+    method public static int XYZToColor(double, double, double);
+    method public static void XYZToLAB(double, double, double, double[]);
+    method public static int blendARGB(int, int, float);
+    method public static void blendHSL(float[], float[], float, float[]);
+    method public static void blendLAB(double[], double[], double, double[]);
+    method public static double calculateContrast(int, int);
+    method public static double calculateLuminance(int);
+    method public static int calculateMinimumAlpha(int, int, float);
+    method public static void colorToHSL(int, float[]);
+    method public static void colorToLAB(int, double[]);
+    method public static void colorToXYZ(int, double[]);
+    method public static int compositeColors(int, int);
+    method public static double distanceEuclidean(double[], double[]);
+    method public static int setAlphaComponent(int, int);
+  }
+
+  public final class PaintCompat {
+    method public static boolean hasGlyph(android.graphics.Paint, java.lang.String);
+  }
+
+}
+
+package android.support.v4.graphics.drawable {
+
+  public final class DrawableCompat {
+    method public static void applyTheme(android.graphics.drawable.Drawable, android.content.res.Resources.Theme);
+    method public static boolean canApplyTheme(android.graphics.drawable.Drawable);
+    method public static void clearColorFilter(android.graphics.drawable.Drawable);
+    method public static int getAlpha(android.graphics.drawable.Drawable);
+    method public static android.graphics.ColorFilter getColorFilter(android.graphics.drawable.Drawable);
+    method public static int getLayoutDirection(android.graphics.drawable.Drawable);
+    method public static void inflate(android.graphics.drawable.Drawable, android.content.res.Resources, org.xmlpull.v1.XmlPullParser, android.util.AttributeSet, android.content.res.Resources.Theme) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method public static boolean isAutoMirrored(android.graphics.drawable.Drawable);
+    method public static void jumpToCurrentState(android.graphics.drawable.Drawable);
+    method public static void setAutoMirrored(android.graphics.drawable.Drawable, boolean);
+    method public static void setHotspot(android.graphics.drawable.Drawable, float, float);
+    method public static void setHotspotBounds(android.graphics.drawable.Drawable, int, int, int, int);
+    method public static boolean setLayoutDirection(android.graphics.drawable.Drawable, int);
+    method public static void setTint(android.graphics.drawable.Drawable, int);
+    method public static void setTintList(android.graphics.drawable.Drawable, android.content.res.ColorStateList);
+    method public static void setTintMode(android.graphics.drawable.Drawable, android.graphics.PorterDuff.Mode);
+    method public static <T extends android.graphics.drawable.Drawable> T unwrap(android.graphics.drawable.Drawable);
+    method public static android.graphics.drawable.Drawable wrap(android.graphics.drawable.Drawable);
+  }
+
+  public class IconCompat {
+    method public static android.support.v4.graphics.drawable.IconCompat createWithAdaptiveBitmap(android.graphics.Bitmap);
+    method public static android.support.v4.graphics.drawable.IconCompat createWithBitmap(android.graphics.Bitmap);
+    method public static android.support.v4.graphics.drawable.IconCompat createWithContentUri(java.lang.String);
+    method public static android.support.v4.graphics.drawable.IconCompat createWithContentUri(android.net.Uri);
+    method public static android.support.v4.graphics.drawable.IconCompat createWithData(byte[], int, int);
+    method public static android.support.v4.graphics.drawable.IconCompat createWithResource(android.content.Context, int);
+  }
+
+  public abstract class RoundedBitmapDrawable extends android.graphics.drawable.Drawable {
+    method public void draw(android.graphics.Canvas);
+    method public final android.graphics.Bitmap getBitmap();
+    method public float getCornerRadius();
+    method public int getGravity();
+    method public int getOpacity();
+    method public final android.graphics.Paint getPaint();
+    method public boolean hasAntiAlias();
+    method public boolean hasMipMap();
+    method public boolean isCircular();
+    method public void setAlpha(int);
+    method public void setAntiAlias(boolean);
+    method public void setCircular(boolean);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setCornerRadius(float);
+    method public void setDither(boolean);
+    method public void setGravity(int);
+    method public void setMipMap(boolean);
+    method public void setTargetDensity(android.graphics.Canvas);
+    method public void setTargetDensity(android.util.DisplayMetrics);
+    method public void setTargetDensity(int);
+  }
+
+  public final class RoundedBitmapDrawableFactory {
+    method public static android.support.v4.graphics.drawable.RoundedBitmapDrawable create(android.content.res.Resources, android.graphics.Bitmap);
+    method public static android.support.v4.graphics.drawable.RoundedBitmapDrawable create(android.content.res.Resources, java.lang.String);
+    method public static android.support.v4.graphics.drawable.RoundedBitmapDrawable create(android.content.res.Resources, java.io.InputStream);
+  }
+
+}
+
+package android.support.v4.hardware.display {
+
+  public abstract class DisplayManagerCompat {
+    method public abstract android.view.Display getDisplay(int);
+    method public abstract android.view.Display[] getDisplays();
+    method public abstract android.view.Display[] getDisplays(java.lang.String);
+    method public static android.support.v4.hardware.display.DisplayManagerCompat getInstance(android.content.Context);
+    field public static final java.lang.String DISPLAY_CATEGORY_PRESENTATION = "android.hardware.display.category.PRESENTATION";
+  }
+
+}
+
+package android.support.v4.hardware.fingerprint {
+
+  public final class FingerprintManagerCompat {
+    method public void authenticate(android.support.v4.hardware.fingerprint.FingerprintManagerCompat.CryptoObject, int, android.support.v4.os.CancellationSignal, android.support.v4.hardware.fingerprint.FingerprintManagerCompat.AuthenticationCallback, android.os.Handler);
+    method public static android.support.v4.hardware.fingerprint.FingerprintManagerCompat from(android.content.Context);
+    method public boolean hasEnrolledFingerprints();
+    method public boolean isHardwareDetected();
+  }
+
+  public static abstract class FingerprintManagerCompat.AuthenticationCallback {
+    ctor public FingerprintManagerCompat.AuthenticationCallback();
+    method public void onAuthenticationError(int, java.lang.CharSequence);
+    method public void onAuthenticationFailed();
+    method public void onAuthenticationHelp(int, java.lang.CharSequence);
+    method public void onAuthenticationSucceeded(android.support.v4.hardware.fingerprint.FingerprintManagerCompat.AuthenticationResult);
+  }
+
+  public static final class FingerprintManagerCompat.AuthenticationResult {
+    ctor public FingerprintManagerCompat.AuthenticationResult(android.support.v4.hardware.fingerprint.FingerprintManagerCompat.CryptoObject);
+    method public android.support.v4.hardware.fingerprint.FingerprintManagerCompat.CryptoObject getCryptoObject();
+  }
+
+  public static class FingerprintManagerCompat.CryptoObject {
+    ctor public FingerprintManagerCompat.CryptoObject(java.security.Signature);
+    ctor public FingerprintManagerCompat.CryptoObject(javax.crypto.Cipher);
+    ctor public FingerprintManagerCompat.CryptoObject(javax.crypto.Mac);
+    method public javax.crypto.Cipher getCipher();
+    method public javax.crypto.Mac getMac();
+    method public java.security.Signature getSignature();
+  }
+
+}
+
+package android.support.v4.math {
+
+  public class MathUtils {
+    method public static float clamp(float, float, float);
+    method public static double clamp(double, double, double);
+    method public static int clamp(int, int, int);
+  }
+
+}
+
+package android.support.v4.media {
+
+  public class AudioAttributesCompat {
+    method public int getContentType();
+    method public int getFlags();
+    method public int getLegacyStreamType();
+    method public int getUsage();
+    method public int getVolumeControlStream();
+    method public java.lang.Object unwrap();
+    method public static android.support.v4.media.AudioAttributesCompat wrap(java.lang.Object);
+    field public static final int CONTENT_TYPE_MOVIE = 3; // 0x3
+    field public static final int CONTENT_TYPE_MUSIC = 2; // 0x2
+    field public static final int CONTENT_TYPE_SONIFICATION = 4; // 0x4
+    field public static final int CONTENT_TYPE_SPEECH = 1; // 0x1
+    field public static final int CONTENT_TYPE_UNKNOWN = 0; // 0x0
+    field public static final int FLAG_AUDIBILITY_ENFORCED = 1; // 0x1
+    field public static final int FLAG_HW_AV_SYNC = 16; // 0x10
+    field public static final int USAGE_ALARM = 4; // 0x4
+    field public static final int USAGE_ASSISTANCE_ACCESSIBILITY = 11; // 0xb
+    field public static final int USAGE_ASSISTANCE_NAVIGATION_GUIDANCE = 12; // 0xc
+    field public static final int USAGE_ASSISTANCE_SONIFICATION = 13; // 0xd
+    field public static final int USAGE_ASSISTANT = 16; // 0x10
+    field public static final int USAGE_GAME = 14; // 0xe
+    field public static final int USAGE_MEDIA = 1; // 0x1
+    field public static final int USAGE_NOTIFICATION = 5; // 0x5
+    field public static final int USAGE_NOTIFICATION_COMMUNICATION_DELAYED = 9; // 0x9
+    field public static final int USAGE_NOTIFICATION_COMMUNICATION_INSTANT = 8; // 0x8
+    field public static final int USAGE_NOTIFICATION_COMMUNICATION_REQUEST = 7; // 0x7
+    field public static final int USAGE_NOTIFICATION_EVENT = 10; // 0xa
+    field public static final int USAGE_NOTIFICATION_RINGTONE = 6; // 0x6
+    field public static final int USAGE_UNKNOWN = 0; // 0x0
+    field public static final int USAGE_VOICE_COMMUNICATION = 2; // 0x2
+    field public static final int USAGE_VOICE_COMMUNICATION_SIGNALLING = 3; // 0x3
+  }
+
+  public static class AudioAttributesCompat.Builder {
+    ctor public AudioAttributesCompat.Builder();
+    ctor public AudioAttributesCompat.Builder(android.support.v4.media.AudioAttributesCompat);
+    method public android.support.v4.media.AudioAttributesCompat build();
+    method public android.support.v4.media.AudioAttributesCompat.Builder setContentType(int);
+    method public android.support.v4.media.AudioAttributesCompat.Builder setFlags(int);
+    method public android.support.v4.media.AudioAttributesCompat.Builder setLegacyStreamType(int);
+    method public android.support.v4.media.AudioAttributesCompat.Builder setUsage(int);
+  }
+
+  public final class MediaBrowserCompat {
+    ctor public MediaBrowserCompat(android.content.Context, android.content.ComponentName, android.support.v4.media.MediaBrowserCompat.ConnectionCallback, android.os.Bundle);
+    method public void connect();
+    method public void disconnect();
+    method public android.os.Bundle getExtras();
+    method public void getItem(java.lang.String, android.support.v4.media.MediaBrowserCompat.ItemCallback);
+    method public java.lang.String getRoot();
+    method public android.content.ComponentName getServiceComponent();
+    method public android.support.v4.media.session.MediaSessionCompat.Token getSessionToken();
+    method public boolean isConnected();
+    method public void search(java.lang.String, android.os.Bundle, android.support.v4.media.MediaBrowserCompat.SearchCallback);
+    method public void sendCustomAction(java.lang.String, android.os.Bundle, android.support.v4.media.MediaBrowserCompat.CustomActionCallback);
+    method public void subscribe(java.lang.String, android.support.v4.media.MediaBrowserCompat.SubscriptionCallback);
+    method public void subscribe(java.lang.String, android.os.Bundle, android.support.v4.media.MediaBrowserCompat.SubscriptionCallback);
+    method public void unsubscribe(java.lang.String);
+    method public void unsubscribe(java.lang.String, android.support.v4.media.MediaBrowserCompat.SubscriptionCallback);
+    field public static final java.lang.String CUSTOM_ACTION_DOWNLOAD = "android.support.v4.media.action.DOWNLOAD";
+    field public static final java.lang.String CUSTOM_ACTION_REMOVE_DOWNLOADED_FILE = "android.support.v4.media.action.REMOVE_DOWNLOADED_FILE";
+    field public static final java.lang.String EXTRA_DOWNLOAD_PROGRESS = "android.media.browse.extra.DOWNLOAD_PROGRESS";
+    field public static final java.lang.String EXTRA_MEDIA_ID = "android.media.browse.extra.MEDIA_ID";
+    field public static final java.lang.String EXTRA_PAGE = "android.media.browse.extra.PAGE";
+    field public static final java.lang.String EXTRA_PAGE_SIZE = "android.media.browse.extra.PAGE_SIZE";
+  }
+
+  public static class MediaBrowserCompat.ConnectionCallback {
+    ctor public MediaBrowserCompat.ConnectionCallback();
+    method public void onConnected();
+    method public void onConnectionFailed();
+    method public void onConnectionSuspended();
+  }
+
+  public static abstract class MediaBrowserCompat.CustomActionCallback {
+    ctor public MediaBrowserCompat.CustomActionCallback();
+    method public void onError(java.lang.String, android.os.Bundle, android.os.Bundle);
+    method public void onProgressUpdate(java.lang.String, android.os.Bundle, android.os.Bundle);
+    method public void onResult(java.lang.String, android.os.Bundle, android.os.Bundle);
+  }
+
+  public static abstract class MediaBrowserCompat.ItemCallback {
+    ctor public MediaBrowserCompat.ItemCallback();
+    method public void onError(java.lang.String);
+    method public void onItemLoaded(android.support.v4.media.MediaBrowserCompat.MediaItem);
+  }
+
+  public static class MediaBrowserCompat.MediaItem implements android.os.Parcelable {
+    ctor public MediaBrowserCompat.MediaItem(android.support.v4.media.MediaDescriptionCompat, int);
+    method public int describeContents();
+    method public static android.support.v4.media.MediaBrowserCompat.MediaItem fromMediaItem(java.lang.Object);
+    method public static java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem> fromMediaItemList(java.util.List<?>);
+    method public android.support.v4.media.MediaDescriptionCompat getDescription();
+    method public int getFlags();
+    method public java.lang.String getMediaId();
+    method public boolean isBrowsable();
+    method public boolean isPlayable();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.MediaBrowserCompat.MediaItem> CREATOR;
+    field public static final int FLAG_BROWSABLE = 1; // 0x1
+    field public static final int FLAG_PLAYABLE = 2; // 0x2
+  }
+
+  public static abstract class MediaBrowserCompat.SearchCallback {
+    ctor public MediaBrowserCompat.SearchCallback();
+    method public void onError(java.lang.String, android.os.Bundle);
+    method public void onSearchResult(java.lang.String, android.os.Bundle, java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>);
+  }
+
+  public static abstract class MediaBrowserCompat.SubscriptionCallback {
+    ctor public MediaBrowserCompat.SubscriptionCallback();
+    method public void onChildrenLoaded(java.lang.String, java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>);
+    method public void onChildrenLoaded(java.lang.String, java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>, android.os.Bundle);
+    method public void onError(java.lang.String);
+    method public void onError(java.lang.String, android.os.Bundle);
+  }
+
+  public abstract class MediaBrowserServiceCompat extends android.app.Service {
+    ctor public MediaBrowserServiceCompat();
+    method public void dump(java.io.FileDescriptor, java.io.PrintWriter, java.lang.String[]);
+    method public final android.os.Bundle getBrowserRootHints();
+    method public android.support.v4.media.session.MediaSessionCompat.Token getSessionToken();
+    method public void notifyChildrenChanged(java.lang.String);
+    method public void notifyChildrenChanged(java.lang.String, android.os.Bundle);
+    method public android.os.IBinder onBind(android.content.Intent);
+    method public void onCustomAction(java.lang.String, android.os.Bundle, android.support.v4.media.MediaBrowserServiceCompat.Result<android.os.Bundle>);
+    method public abstract android.support.v4.media.MediaBrowserServiceCompat.BrowserRoot onGetRoot(java.lang.String, int, android.os.Bundle);
+    method public abstract void onLoadChildren(java.lang.String, android.support.v4.media.MediaBrowserServiceCompat.Result<java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>>);
+    method public void onLoadChildren(java.lang.String, android.support.v4.media.MediaBrowserServiceCompat.Result<java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>>, android.os.Bundle);
+    method public void onLoadItem(java.lang.String, android.support.v4.media.MediaBrowserServiceCompat.Result<android.support.v4.media.MediaBrowserCompat.MediaItem>);
+    method public void onSearch(java.lang.String, android.os.Bundle, android.support.v4.media.MediaBrowserServiceCompat.Result<java.util.List<android.support.v4.media.MediaBrowserCompat.MediaItem>>);
+    method public void setSessionToken(android.support.v4.media.session.MediaSessionCompat.Token);
+    field public static final java.lang.String SERVICE_INTERFACE = "android.media.browse.MediaBrowserService";
+  }
+
+  public static final class MediaBrowserServiceCompat.BrowserRoot {
+    ctor public MediaBrowserServiceCompat.BrowserRoot(java.lang.String, android.os.Bundle);
+    method public android.os.Bundle getExtras();
+    method public java.lang.String getRootId();
+    field public static final java.lang.String EXTRA_OFFLINE = "android.service.media.extra.OFFLINE";
+    field public static final java.lang.String EXTRA_RECENT = "android.service.media.extra.RECENT";
+    field public static final java.lang.String EXTRA_SUGGESTED = "android.service.media.extra.SUGGESTED";
+    field public static final deprecated java.lang.String EXTRA_SUGGESTION_KEYWORDS = "android.service.media.extra.SUGGESTION_KEYWORDS";
+  }
+
+  public static class MediaBrowserServiceCompat.Result<T> {
+    method public void detach();
+    method public void sendError(android.os.Bundle);
+    method public void sendProgressUpdate(android.os.Bundle);
+    method public void sendResult(T);
+  }
+
+  public final class MediaDescriptionCompat implements android.os.Parcelable {
+    method public int describeContents();
+    method public static android.support.v4.media.MediaDescriptionCompat fromMediaDescription(java.lang.Object);
+    method public java.lang.CharSequence getDescription();
+    method public android.os.Bundle getExtras();
+    method public android.graphics.Bitmap getIconBitmap();
+    method public android.net.Uri getIconUri();
+    method public java.lang.Object getMediaDescription();
+    method public java.lang.String getMediaId();
+    method public android.net.Uri getMediaUri();
+    method public java.lang.CharSequence getSubtitle();
+    method public java.lang.CharSequence getTitle();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final long BT_FOLDER_TYPE_ALBUMS = 2L; // 0x2L
+    field public static final long BT_FOLDER_TYPE_ARTISTS = 3L; // 0x3L
+    field public static final long BT_FOLDER_TYPE_GENRES = 4L; // 0x4L
+    field public static final long BT_FOLDER_TYPE_MIXED = 0L; // 0x0L
+    field public static final long BT_FOLDER_TYPE_PLAYLISTS = 5L; // 0x5L
+    field public static final long BT_FOLDER_TYPE_TITLES = 1L; // 0x1L
+    field public static final long BT_FOLDER_TYPE_YEARS = 6L; // 0x6L
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.MediaDescriptionCompat> CREATOR;
+    field public static final java.lang.String EXTRA_BT_FOLDER_TYPE = "android.media.extra.BT_FOLDER_TYPE";
+    field public static final java.lang.String EXTRA_DOWNLOAD_STATUS = "android.media.extra.DOWNLOAD_STATUS";
+    field public static final long STATUS_DOWNLOADED = 2L; // 0x2L
+    field public static final long STATUS_DOWNLOADING = 1L; // 0x1L
+    field public static final long STATUS_NOT_DOWNLOADED = 0L; // 0x0L
+  }
+
+  public static final class MediaDescriptionCompat.Builder {
+    ctor public MediaDescriptionCompat.Builder();
+    method public android.support.v4.media.MediaDescriptionCompat build();
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setDescription(java.lang.CharSequence);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setExtras(android.os.Bundle);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setIconBitmap(android.graphics.Bitmap);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setIconUri(android.net.Uri);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setMediaId(java.lang.String);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setMediaUri(android.net.Uri);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setSubtitle(java.lang.CharSequence);
+    method public android.support.v4.media.MediaDescriptionCompat.Builder setTitle(java.lang.CharSequence);
+  }
+
+  public final class MediaMetadataCompat implements android.os.Parcelable {
+    method public boolean containsKey(java.lang.String);
+    method public int describeContents();
+    method public static android.support.v4.media.MediaMetadataCompat fromMediaMetadata(java.lang.Object);
+    method public android.graphics.Bitmap getBitmap(java.lang.String);
+    method public android.os.Bundle getBundle();
+    method public android.support.v4.media.MediaDescriptionCompat getDescription();
+    method public long getLong(java.lang.String);
+    method public java.lang.Object getMediaMetadata();
+    method public android.support.v4.media.RatingCompat getRating(java.lang.String);
+    method public java.lang.String getString(java.lang.String);
+    method public java.lang.CharSequence getText(java.lang.String);
+    method public java.util.Set<java.lang.String> keySet();
+    method public int size();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.MediaMetadataCompat> CREATOR;
+    field public static final java.lang.String METADATA_KEY_ADVERTISEMENT = "android.media.metadata.ADVERTISEMENT";
+    field public static final java.lang.String METADATA_KEY_ALBUM = "android.media.metadata.ALBUM";
+    field public static final java.lang.String METADATA_KEY_ALBUM_ART = "android.media.metadata.ALBUM_ART";
+    field public static final java.lang.String METADATA_KEY_ALBUM_ARTIST = "android.media.metadata.ALBUM_ARTIST";
+    field public static final java.lang.String METADATA_KEY_ALBUM_ART_URI = "android.media.metadata.ALBUM_ART_URI";
+    field public static final java.lang.String METADATA_KEY_ART = "android.media.metadata.ART";
+    field public static final java.lang.String METADATA_KEY_ARTIST = "android.media.metadata.ARTIST";
+    field public static final java.lang.String METADATA_KEY_ART_URI = "android.media.metadata.ART_URI";
+    field public static final java.lang.String METADATA_KEY_AUTHOR = "android.media.metadata.AUTHOR";
+    field public static final java.lang.String METADATA_KEY_BT_FOLDER_TYPE = "android.media.metadata.BT_FOLDER_TYPE";
+    field public static final java.lang.String METADATA_KEY_COMPILATION = "android.media.metadata.COMPILATION";
+    field public static final java.lang.String METADATA_KEY_COMPOSER = "android.media.metadata.COMPOSER";
+    field public static final java.lang.String METADATA_KEY_DATE = "android.media.metadata.DATE";
+    field public static final java.lang.String METADATA_KEY_DISC_NUMBER = "android.media.metadata.DISC_NUMBER";
+    field public static final java.lang.String METADATA_KEY_DISPLAY_DESCRIPTION = "android.media.metadata.DISPLAY_DESCRIPTION";
+    field public static final java.lang.String METADATA_KEY_DISPLAY_ICON = "android.media.metadata.DISPLAY_ICON";
+    field public static final java.lang.String METADATA_KEY_DISPLAY_ICON_URI = "android.media.metadata.DISPLAY_ICON_URI";
+    field public static final java.lang.String METADATA_KEY_DISPLAY_SUBTITLE = "android.media.metadata.DISPLAY_SUBTITLE";
+    field public static final java.lang.String METADATA_KEY_DISPLAY_TITLE = "android.media.metadata.DISPLAY_TITLE";
+    field public static final java.lang.String METADATA_KEY_DOWNLOAD_STATUS = "android.media.metadata.DOWNLOAD_STATUS";
+    field public static final java.lang.String METADATA_KEY_DURATION = "android.media.metadata.DURATION";
+    field public static final java.lang.String METADATA_KEY_GENRE = "android.media.metadata.GENRE";
+    field public static final java.lang.String METADATA_KEY_MEDIA_ID = "android.media.metadata.MEDIA_ID";
+    field public static final java.lang.String METADATA_KEY_MEDIA_URI = "android.media.metadata.MEDIA_URI";
+    field public static final java.lang.String METADATA_KEY_NUM_TRACKS = "android.media.metadata.NUM_TRACKS";
+    field public static final java.lang.String METADATA_KEY_RATING = "android.media.metadata.RATING";
+    field public static final java.lang.String METADATA_KEY_TITLE = "android.media.metadata.TITLE";
+    field public static final java.lang.String METADATA_KEY_TRACK_NUMBER = "android.media.metadata.TRACK_NUMBER";
+    field public static final java.lang.String METADATA_KEY_USER_RATING = "android.media.metadata.USER_RATING";
+    field public static final java.lang.String METADATA_KEY_WRITER = "android.media.metadata.WRITER";
+    field public static final java.lang.String METADATA_KEY_YEAR = "android.media.metadata.YEAR";
+  }
+
+  public static final class MediaMetadataCompat.Builder {
+    ctor public MediaMetadataCompat.Builder();
+    ctor public MediaMetadataCompat.Builder(android.support.v4.media.MediaMetadataCompat);
+    method public android.support.v4.media.MediaMetadataCompat build();
+    method public android.support.v4.media.MediaMetadataCompat.Builder putBitmap(java.lang.String, android.graphics.Bitmap);
+    method public android.support.v4.media.MediaMetadataCompat.Builder putLong(java.lang.String, long);
+    method public android.support.v4.media.MediaMetadataCompat.Builder putRating(java.lang.String, android.support.v4.media.RatingCompat);
+    method public android.support.v4.media.MediaMetadataCompat.Builder putString(java.lang.String, java.lang.String);
+    method public android.support.v4.media.MediaMetadataCompat.Builder putText(java.lang.String, java.lang.CharSequence);
+  }
+
+  public final class RatingCompat implements android.os.Parcelable {
+    method public int describeContents();
+    method public static android.support.v4.media.RatingCompat fromRating(java.lang.Object);
+    method public float getPercentRating();
+    method public java.lang.Object getRating();
+    method public int getRatingStyle();
+    method public float getStarRating();
+    method public boolean hasHeart();
+    method public boolean isRated();
+    method public boolean isThumbUp();
+    method public static android.support.v4.media.RatingCompat newHeartRating(boolean);
+    method public static android.support.v4.media.RatingCompat newPercentageRating(float);
+    method public static android.support.v4.media.RatingCompat newStarRating(int, float);
+    method public static android.support.v4.media.RatingCompat newThumbRating(boolean);
+    method public static android.support.v4.media.RatingCompat newUnratedRating(int);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.RatingCompat> CREATOR;
+    field public static final int RATING_3_STARS = 3; // 0x3
+    field public static final int RATING_4_STARS = 4; // 0x4
+    field public static final int RATING_5_STARS = 5; // 0x5
+    field public static final int RATING_HEART = 1; // 0x1
+    field public static final int RATING_NONE = 0; // 0x0
+    field public static final int RATING_PERCENTAGE = 6; // 0x6
+    field public static final int RATING_THUMB_UP_DOWN = 2; // 0x2
+  }
+
+  public abstract class VolumeProviderCompat {
+    ctor public VolumeProviderCompat(int, int, int);
+    method public final int getCurrentVolume();
+    method public final int getMaxVolume();
+    method public final int getVolumeControl();
+    method public java.lang.Object getVolumeProvider();
+    method public void onAdjustVolume(int);
+    method public void onSetVolumeTo(int);
+    method public void setCallback(android.support.v4.media.VolumeProviderCompat.Callback);
+    method public final void setCurrentVolume(int);
+    field public static final int VOLUME_CONTROL_ABSOLUTE = 2; // 0x2
+    field public static final int VOLUME_CONTROL_FIXED = 0; // 0x0
+    field public static final int VOLUME_CONTROL_RELATIVE = 1; // 0x1
+  }
+
+  public static abstract class VolumeProviderCompat.Callback {
+    ctor public VolumeProviderCompat.Callback();
+    method public abstract void onVolumeChanged(android.support.v4.media.VolumeProviderCompat);
+  }
+
+}
+
+package android.support.v4.media.app {
+
+  public class NotificationCompat {
+  }
+
+  public static class NotificationCompat.DecoratedMediaCustomViewStyle extends android.support.v4.media.app.NotificationCompat.MediaStyle {
+    ctor public NotificationCompat.DecoratedMediaCustomViewStyle();
+  }
+
+  public static class NotificationCompat.MediaStyle extends android.support.v4.app.NotificationCompat.Style {
+    ctor public NotificationCompat.MediaStyle();
+    ctor public NotificationCompat.MediaStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public static android.support.v4.media.session.MediaSessionCompat.Token getMediaSession(android.app.Notification);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setCancelButtonIntent(android.app.PendingIntent);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setMediaSession(android.support.v4.media.session.MediaSessionCompat.Token);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setShowActionsInCompactView(int...);
+    method public android.support.v4.media.app.NotificationCompat.MediaStyle setShowCancelButton(boolean);
+  }
+
+}
+
+package android.support.v4.media.session {
+
+  public class MediaButtonReceiver extends android.content.BroadcastReceiver {
+    ctor public MediaButtonReceiver();
+    method public static android.app.PendingIntent buildMediaButtonPendingIntent(android.content.Context, long);
+    method public static android.app.PendingIntent buildMediaButtonPendingIntent(android.content.Context, android.content.ComponentName, long);
+    method public static android.view.KeyEvent handleIntent(android.support.v4.media.session.MediaSessionCompat, android.content.Intent);
+    method public void onReceive(android.content.Context, android.content.Intent);
+  }
+
+  public final class MediaControllerCompat {
+    ctor public MediaControllerCompat(android.content.Context, android.support.v4.media.session.MediaSessionCompat);
+    ctor public MediaControllerCompat(android.content.Context, android.support.v4.media.session.MediaSessionCompat.Token) throws android.os.RemoteException;
+    method public void addQueueItem(android.support.v4.media.MediaDescriptionCompat);
+    method public void addQueueItem(android.support.v4.media.MediaDescriptionCompat, int);
+    method public void adjustVolume(int, int);
+    method public boolean dispatchMediaButtonEvent(android.view.KeyEvent);
+    method public android.os.Bundle getExtras();
+    method public long getFlags();
+    method public static android.support.v4.media.session.MediaControllerCompat getMediaController(android.app.Activity);
+    method public java.lang.Object getMediaController();
+    method public android.support.v4.media.MediaMetadataCompat getMetadata();
+    method public java.lang.String getPackageName();
+    method public android.support.v4.media.session.MediaControllerCompat.PlaybackInfo getPlaybackInfo();
+    method public android.support.v4.media.session.PlaybackStateCompat getPlaybackState();
+    method public java.util.List<android.support.v4.media.session.MediaSessionCompat.QueueItem> getQueue();
+    method public java.lang.CharSequence getQueueTitle();
+    method public int getRatingType();
+    method public int getRepeatMode();
+    method public android.app.PendingIntent getSessionActivity();
+    method public android.support.v4.media.session.MediaSessionCompat.Token getSessionToken();
+    method public int getShuffleMode();
+    method public android.support.v4.media.session.MediaControllerCompat.TransportControls getTransportControls();
+    method public boolean isCaptioningEnabled();
+    method public deprecated boolean isShuffleModeEnabled();
+    method public void registerCallback(android.support.v4.media.session.MediaControllerCompat.Callback);
+    method public void registerCallback(android.support.v4.media.session.MediaControllerCompat.Callback, android.os.Handler);
+    method public void removeQueueItem(android.support.v4.media.MediaDescriptionCompat);
+    method public deprecated void removeQueueItemAt(int);
+    method public void sendCommand(java.lang.String, android.os.Bundle, android.os.ResultReceiver);
+    method public static void setMediaController(android.app.Activity, android.support.v4.media.session.MediaControllerCompat);
+    method public void setVolumeTo(int, int);
+    method public void unregisterCallback(android.support.v4.media.session.MediaControllerCompat.Callback);
+  }
+
+  public static abstract class MediaControllerCompat.Callback implements android.os.IBinder.DeathRecipient {
+    ctor public MediaControllerCompat.Callback();
+    method public void binderDied();
+    method public void onAudioInfoChanged(android.support.v4.media.session.MediaControllerCompat.PlaybackInfo);
+    method public void onCaptioningEnabledChanged(boolean);
+    method public void onExtrasChanged(android.os.Bundle);
+    method public void onMetadataChanged(android.support.v4.media.MediaMetadataCompat);
+    method public void onPlaybackStateChanged(android.support.v4.media.session.PlaybackStateCompat);
+    method public void onQueueChanged(java.util.List<android.support.v4.media.session.MediaSessionCompat.QueueItem>);
+    method public void onQueueTitleChanged(java.lang.CharSequence);
+    method public void onRepeatModeChanged(int);
+    method public void onSessionDestroyed();
+    method public void onSessionEvent(java.lang.String, android.os.Bundle);
+    method public deprecated void onShuffleModeChanged(boolean);
+    method public void onShuffleModeChanged(int);
+  }
+
+  public static final class MediaControllerCompat.PlaybackInfo {
+    method public int getAudioStream();
+    method public int getCurrentVolume();
+    method public int getMaxVolume();
+    method public int getPlaybackType();
+    method public int getVolumeControl();
+    field public static final int PLAYBACK_TYPE_LOCAL = 1; // 0x1
+    field public static final int PLAYBACK_TYPE_REMOTE = 2; // 0x2
+  }
+
+  public static abstract class MediaControllerCompat.TransportControls {
+    method public abstract void fastForward();
+    method public abstract void pause();
+    method public abstract void play();
+    method public abstract void playFromMediaId(java.lang.String, android.os.Bundle);
+    method public abstract void playFromSearch(java.lang.String, android.os.Bundle);
+    method public abstract void playFromUri(android.net.Uri, android.os.Bundle);
+    method public abstract void prepare();
+    method public abstract void prepareFromMediaId(java.lang.String, android.os.Bundle);
+    method public abstract void prepareFromSearch(java.lang.String, android.os.Bundle);
+    method public abstract void prepareFromUri(android.net.Uri, android.os.Bundle);
+    method public abstract void rewind();
+    method public abstract void seekTo(long);
+    method public abstract void sendCustomAction(android.support.v4.media.session.PlaybackStateCompat.CustomAction, android.os.Bundle);
+    method public abstract void sendCustomAction(java.lang.String, android.os.Bundle);
+    method public abstract void setCaptioningEnabled(boolean);
+    method public abstract void setRating(android.support.v4.media.RatingCompat);
+    method public abstract void setRating(android.support.v4.media.RatingCompat, android.os.Bundle);
+    method public abstract void setRepeatMode(int);
+    method public abstract void setShuffleMode(int);
+    method public abstract deprecated void setShuffleModeEnabled(boolean);
+    method public abstract void skipToNext();
+    method public abstract void skipToPrevious();
+    method public abstract void skipToQueueItem(long);
+    method public abstract void stop();
+    field public static final java.lang.String EXTRA_LEGACY_STREAM_TYPE = "android.media.session.extra.LEGACY_STREAM_TYPE";
+  }
+
+  public class MediaSessionCompat {
+    ctor public MediaSessionCompat(android.content.Context, java.lang.String);
+    ctor public MediaSessionCompat(android.content.Context, java.lang.String, android.content.ComponentName, android.app.PendingIntent);
+    method public void addOnActiveChangeListener(android.support.v4.media.session.MediaSessionCompat.OnActiveChangeListener);
+    method public static android.support.v4.media.session.MediaSessionCompat fromMediaSession(android.content.Context, java.lang.Object);
+    method public android.support.v4.media.session.MediaControllerCompat getController();
+    method public java.lang.Object getMediaSession();
+    method public java.lang.Object getRemoteControlClient();
+    method public android.support.v4.media.session.MediaSessionCompat.Token getSessionToken();
+    method public boolean isActive();
+    method public void release();
+    method public void removeOnActiveChangeListener(android.support.v4.media.session.MediaSessionCompat.OnActiveChangeListener);
+    method public void sendSessionEvent(java.lang.String, android.os.Bundle);
+    method public void setActive(boolean);
+    method public void setCallback(android.support.v4.media.session.MediaSessionCompat.Callback);
+    method public void setCallback(android.support.v4.media.session.MediaSessionCompat.Callback, android.os.Handler);
+    method public void setCaptioningEnabled(boolean);
+    method public void setExtras(android.os.Bundle);
+    method public void setFlags(int);
+    method public void setMediaButtonReceiver(android.app.PendingIntent);
+    method public void setMetadata(android.support.v4.media.MediaMetadataCompat);
+    method public void setPlaybackState(android.support.v4.media.session.PlaybackStateCompat);
+    method public void setPlaybackToLocal(int);
+    method public void setPlaybackToRemote(android.support.v4.media.VolumeProviderCompat);
+    method public void setQueue(java.util.List<android.support.v4.media.session.MediaSessionCompat.QueueItem>);
+    method public void setQueueTitle(java.lang.CharSequence);
+    method public void setRatingType(int);
+    method public void setRepeatMode(int);
+    method public void setSessionActivity(android.app.PendingIntent);
+    method public void setShuffleMode(int);
+    method public deprecated void setShuffleModeEnabled(boolean);
+    field public static final java.lang.String ACTION_FLAG_AS_INAPPROPRIATE = "android.support.v4.media.session.action.FLAG_AS_INAPPROPRIATE";
+    field public static final java.lang.String ACTION_FOLLOW = "android.support.v4.media.session.action.FOLLOW";
+    field public static final java.lang.String ACTION_SKIP_AD = "android.support.v4.media.session.action.SKIP_AD";
+    field public static final java.lang.String ACTION_UNFOLLOW = "android.support.v4.media.session.action.UNFOLLOW";
+    field public static final java.lang.String ARGUMENT_MEDIA_ATTRIBUTE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE";
+    field public static final java.lang.String ARGUMENT_MEDIA_ATTRIBUTE_VALUE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE_VALUE";
+    field public static final int FLAG_HANDLES_MEDIA_BUTTONS = 1; // 0x1
+    field public static final int FLAG_HANDLES_QUEUE_COMMANDS = 4; // 0x4
+    field public static final int FLAG_HANDLES_TRANSPORT_CONTROLS = 2; // 0x2
+    field public static final int MEDIA_ATTRIBUTE_ALBUM = 1; // 0x1
+    field public static final int MEDIA_ATTRIBUTE_ARTIST = 0; // 0x0
+    field public static final int MEDIA_ATTRIBUTE_PLAYLIST = 2; // 0x2
+  }
+
+  public static abstract class MediaSessionCompat.Callback {
+    ctor public MediaSessionCompat.Callback();
+    method public void onAddQueueItem(android.support.v4.media.MediaDescriptionCompat);
+    method public void onAddQueueItem(android.support.v4.media.MediaDescriptionCompat, int);
+    method public void onCommand(java.lang.String, android.os.Bundle, android.os.ResultReceiver);
+    method public void onCustomAction(java.lang.String, android.os.Bundle);
+    method public void onFastForward();
+    method public boolean onMediaButtonEvent(android.content.Intent);
+    method public void onPause();
+    method public void onPlay();
+    method public void onPlayFromMediaId(java.lang.String, android.os.Bundle);
+    method public void onPlayFromSearch(java.lang.String, android.os.Bundle);
+    method public void onPlayFromUri(android.net.Uri, android.os.Bundle);
+    method public void onPrepare();
+    method public void onPrepareFromMediaId(java.lang.String, android.os.Bundle);
+    method public void onPrepareFromSearch(java.lang.String, android.os.Bundle);
+    method public void onPrepareFromUri(android.net.Uri, android.os.Bundle);
+    method public void onRemoveQueueItem(android.support.v4.media.MediaDescriptionCompat);
+    method public deprecated void onRemoveQueueItemAt(int);
+    method public void onRewind();
+    method public void onSeekTo(long);
+    method public void onSetCaptioningEnabled(boolean);
+    method public void onSetRating(android.support.v4.media.RatingCompat);
+    method public void onSetRating(android.support.v4.media.RatingCompat, android.os.Bundle);
+    method public void onSetRepeatMode(int);
+    method public void onSetShuffleMode(int);
+    method public deprecated void onSetShuffleModeEnabled(boolean);
+    method public void onSkipToNext();
+    method public void onSkipToPrevious();
+    method public void onSkipToQueueItem(long);
+    method public void onStop();
+  }
+
+  public static abstract interface MediaSessionCompat.OnActiveChangeListener {
+    method public abstract void onActiveChanged();
+  }
+
+  public static final class MediaSessionCompat.QueueItem implements android.os.Parcelable {
+    ctor public MediaSessionCompat.QueueItem(android.support.v4.media.MediaDescriptionCompat, long);
+    method public int describeContents();
+    method public static android.support.v4.media.session.MediaSessionCompat.QueueItem fromQueueItem(java.lang.Object);
+    method public static java.util.List<android.support.v4.media.session.MediaSessionCompat.QueueItem> fromQueueItemList(java.util.List<?>);
+    method public android.support.v4.media.MediaDescriptionCompat getDescription();
+    method public long getQueueId();
+    method public java.lang.Object getQueueItem();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.session.MediaSessionCompat.QueueItem> CREATOR;
+    field public static final int UNKNOWN_ID = -1; // 0xffffffff
+  }
+
+  public static final class MediaSessionCompat.Token implements android.os.Parcelable {
+    method public int describeContents();
+    method public static android.support.v4.media.session.MediaSessionCompat.Token fromToken(java.lang.Object);
+    method public java.lang.Object getToken();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.session.MediaSessionCompat.Token> CREATOR;
+  }
+
+  public class ParcelableVolumeInfo implements android.os.Parcelable {
+    ctor public ParcelableVolumeInfo(int, int, int, int, int);
+    ctor public ParcelableVolumeInfo(android.os.Parcel);
+    method public int describeContents();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.session.ParcelableVolumeInfo> CREATOR;
+    field public int audioStream;
+    field public int controlType;
+    field public int currentVolume;
+    field public int maxVolume;
+    field public int volumeType;
+  }
+
+  public final class PlaybackStateCompat implements android.os.Parcelable {
+    method public int describeContents();
+    method public static android.support.v4.media.session.PlaybackStateCompat fromPlaybackState(java.lang.Object);
+    method public long getActions();
+    method public long getActiveQueueItemId();
+    method public long getBufferedPosition();
+    method public java.util.List<android.support.v4.media.session.PlaybackStateCompat.CustomAction> getCustomActions();
+    method public int getErrorCode();
+    method public java.lang.CharSequence getErrorMessage();
+    method public android.os.Bundle getExtras();
+    method public long getLastPositionUpdateTime();
+    method public float getPlaybackSpeed();
+    method public java.lang.Object getPlaybackState();
+    method public long getPosition();
+    method public int getState();
+    method public static int toKeyCode(long);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final long ACTION_FAST_FORWARD = 64L; // 0x40L
+    field public static final long ACTION_PAUSE = 2L; // 0x2L
+    field public static final long ACTION_PLAY = 4L; // 0x4L
+    field public static final long ACTION_PLAY_FROM_MEDIA_ID = 1024L; // 0x400L
+    field public static final long ACTION_PLAY_FROM_SEARCH = 2048L; // 0x800L
+    field public static final long ACTION_PLAY_FROM_URI = 8192L; // 0x2000L
+    field public static final long ACTION_PLAY_PAUSE = 512L; // 0x200L
+    field public static final long ACTION_PREPARE = 16384L; // 0x4000L
+    field public static final long ACTION_PREPARE_FROM_MEDIA_ID = 32768L; // 0x8000L
+    field public static final long ACTION_PREPARE_FROM_SEARCH = 65536L; // 0x10000L
+    field public static final long ACTION_PREPARE_FROM_URI = 131072L; // 0x20000L
+    field public static final long ACTION_REWIND = 8L; // 0x8L
+    field public static final long ACTION_SEEK_TO = 256L; // 0x100L
+    field public static final long ACTION_SET_CAPTIONING_ENABLED = 1048576L; // 0x100000L
+    field public static final long ACTION_SET_RATING = 128L; // 0x80L
+    field public static final long ACTION_SET_REPEAT_MODE = 262144L; // 0x40000L
+    field public static final long ACTION_SET_SHUFFLE_MODE_ENABLED = 524288L; // 0x80000L
+    field public static final long ACTION_SKIP_TO_NEXT = 32L; // 0x20L
+    field public static final long ACTION_SKIP_TO_PREVIOUS = 16L; // 0x10L
+    field public static final long ACTION_SKIP_TO_QUEUE_ITEM = 4096L; // 0x1000L
+    field public static final long ACTION_STOP = 1L; // 0x1L
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.session.PlaybackStateCompat> CREATOR;
+    field public static final int ERROR_CODE_ACTION_ABORTED = 10; // 0xa
+    field public static final int ERROR_CODE_APP_ERROR = 1; // 0x1
+    field public static final int ERROR_CODE_AUTHENTICATION_EXPIRED = 3; // 0x3
+    field public static final int ERROR_CODE_CONCURRENT_STREAM_LIMIT = 5; // 0x5
+    field public static final int ERROR_CODE_CONTENT_ALREADY_PLAYING = 8; // 0x8
+    field public static final int ERROR_CODE_END_OF_QUEUE = 11; // 0xb
+    field public static final int ERROR_CODE_NOT_AVAILABLE_IN_REGION = 7; // 0x7
+    field public static final int ERROR_CODE_NOT_SUPPORTED = 2; // 0x2
+    field public static final int ERROR_CODE_PARENTAL_CONTROL_RESTRICTED = 6; // 0x6
+    field public static final int ERROR_CODE_PREMIUM_ACCOUNT_REQUIRED = 4; // 0x4
+    field public static final int ERROR_CODE_SKIP_LIMIT_REACHED = 9; // 0x9
+    field public static final int ERROR_CODE_UNKNOWN_ERROR = 0; // 0x0
+    field public static final long PLAYBACK_POSITION_UNKNOWN = -1L; // 0xffffffffffffffffL
+    field public static final int REPEAT_MODE_ALL = 2; // 0x2
+    field public static final int REPEAT_MODE_GROUP = 3; // 0x3
+    field public static final int REPEAT_MODE_NONE = 0; // 0x0
+    field public static final int REPEAT_MODE_ONE = 1; // 0x1
+    field public static final int SHUFFLE_MODE_ALL = 1; // 0x1
+    field public static final int SHUFFLE_MODE_GROUP = 2; // 0x2
+    field public static final int SHUFFLE_MODE_NONE = 0; // 0x0
+    field public static final int STATE_BUFFERING = 6; // 0x6
+    field public static final int STATE_CONNECTING = 8; // 0x8
+    field public static final int STATE_ERROR = 7; // 0x7
+    field public static final int STATE_FAST_FORWARDING = 4; // 0x4
+    field public static final int STATE_NONE = 0; // 0x0
+    field public static final int STATE_PAUSED = 2; // 0x2
+    field public static final int STATE_PLAYING = 3; // 0x3
+    field public static final int STATE_REWINDING = 5; // 0x5
+    field public static final int STATE_SKIPPING_TO_NEXT = 10; // 0xa
+    field public static final int STATE_SKIPPING_TO_PREVIOUS = 9; // 0x9
+    field public static final int STATE_SKIPPING_TO_QUEUE_ITEM = 11; // 0xb
+    field public static final int STATE_STOPPED = 1; // 0x1
+  }
+
+  public static final class PlaybackStateCompat.Builder {
+    ctor public PlaybackStateCompat.Builder();
+    ctor public PlaybackStateCompat.Builder(android.support.v4.media.session.PlaybackStateCompat);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder addCustomAction(java.lang.String, java.lang.String, int);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder addCustomAction(android.support.v4.media.session.PlaybackStateCompat.CustomAction);
+    method public android.support.v4.media.session.PlaybackStateCompat build();
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setActions(long);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setActiveQueueItemId(long);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setBufferedPosition(long);
+    method public deprecated android.support.v4.media.session.PlaybackStateCompat.Builder setErrorMessage(java.lang.CharSequence);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setErrorMessage(int, java.lang.CharSequence);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setExtras(android.os.Bundle);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setState(int, long, float);
+    method public android.support.v4.media.session.PlaybackStateCompat.Builder setState(int, long, float, long);
+  }
+
+  public static final class PlaybackStateCompat.CustomAction implements android.os.Parcelable {
+    method public int describeContents();
+    method public static android.support.v4.media.session.PlaybackStateCompat.CustomAction fromCustomAction(java.lang.Object);
+    method public java.lang.String getAction();
+    method public java.lang.Object getCustomAction();
+    method public android.os.Bundle getExtras();
+    method public int getIcon();
+    method public java.lang.CharSequence getName();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.media.session.PlaybackStateCompat.CustomAction> CREATOR;
+  }
+
+  public static final class PlaybackStateCompat.CustomAction.Builder {
+    ctor public PlaybackStateCompat.CustomAction.Builder(java.lang.String, java.lang.CharSequence, int);
+    method public android.support.v4.media.session.PlaybackStateCompat.CustomAction build();
+    method public android.support.v4.media.session.PlaybackStateCompat.CustomAction.Builder setExtras(android.os.Bundle);
+  }
+
+}
+
+package android.support.v4.net {
+
+  public final class ConnectivityManagerCompat {
+    method public static android.net.NetworkInfo getNetworkInfoFromBroadcast(android.net.ConnectivityManager, android.content.Intent);
+    method public static int getRestrictBackgroundStatus(android.net.ConnectivityManager);
+    method public static boolean isActiveNetworkMetered(android.net.ConnectivityManager);
+    field public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1; // 0x1
+    field public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3; // 0x3
+    field public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2; // 0x2
+  }
+
+  public final class TrafficStatsCompat {
+    method public static deprecated void clearThreadStatsTag();
+    method public static deprecated int getThreadStatsTag();
+    method public static deprecated void incrementOperationCount(int);
+    method public static deprecated void incrementOperationCount(int, int);
+    method public static deprecated void setThreadStatsTag(int);
+    method public static void tagDatagramSocket(java.net.DatagramSocket) throws java.net.SocketException;
+    method public static deprecated void tagSocket(java.net.Socket) throws java.net.SocketException;
+    method public static void untagDatagramSocket(java.net.DatagramSocket) throws java.net.SocketException;
+    method public static deprecated void untagSocket(java.net.Socket) throws java.net.SocketException;
+  }
+
+}
+
+package android.support.v4.os {
+
+  public final deprecated class AsyncTaskCompat {
+    method public static deprecated <Params, Progress, Result> android.os.AsyncTask<Params, Progress, Result> executeParallel(android.os.AsyncTask<Params, Progress, Result>, Params...);
+  }
+
+  public class BuildCompat {
+    method public static deprecated boolean isAtLeastN();
+    method public static deprecated boolean isAtLeastNMR1();
+    method public static deprecated boolean isAtLeastO();
+    method public static boolean isAtLeastOMR1();
+    method public static boolean isAtLeastP();
+  }
+
+  public final class CancellationSignal {
+    ctor public CancellationSignal();
+    method public void cancel();
+    method public java.lang.Object getCancellationSignalObject();
+    method public boolean isCanceled();
+    method public void setOnCancelListener(android.support.v4.os.CancellationSignal.OnCancelListener);
+    method public void throwIfCanceled();
+  }
+
+  public static abstract interface CancellationSignal.OnCancelListener {
+    method public abstract void onCancel();
+  }
+
+  public final class ConfigurationCompat {
+    method public static android.support.v4.os.LocaleListCompat getLocales(android.content.res.Configuration);
+  }
+
+  public final class EnvironmentCompat {
+    method public static java.lang.String getStorageState(java.io.File);
+    field public static final java.lang.String MEDIA_UNKNOWN = "unknown";
+  }
+
+  public final class LocaleListCompat {
+    method public static android.support.v4.os.LocaleListCompat create(java.util.Locale...);
+    method public static android.support.v4.os.LocaleListCompat forLanguageTags(java.lang.String);
+    method public java.util.Locale get(int);
+    method public static android.support.v4.os.LocaleListCompat getAdjustedDefault();
+    method public static android.support.v4.os.LocaleListCompat getDefault();
+    method public static android.support.v4.os.LocaleListCompat getEmptyLocaleList();
+    method public java.util.Locale getFirstMatch(java.lang.String[]);
+    method public int indexOf(java.util.Locale);
+    method public boolean isEmpty();
+    method public int size();
+    method public java.lang.String toLanguageTags();
+    method public java.lang.Object unwrap();
+    method public static android.support.v4.os.LocaleListCompat wrap(java.lang.Object);
+  }
+
+  public class OperationCanceledException extends java.lang.RuntimeException {
+    ctor public OperationCanceledException();
+    ctor public OperationCanceledException(java.lang.String);
+  }
+
+  public final deprecated class ParcelableCompat {
+    method public static deprecated <T> android.os.Parcelable.Creator<T> newCreator(android.support.v4.os.ParcelableCompatCreatorCallbacks<T>);
+  }
+
+  public abstract deprecated interface ParcelableCompatCreatorCallbacks<T> {
+    method public abstract T createFromParcel(android.os.Parcel, java.lang.ClassLoader);
+    method public abstract T[] newArray(int);
+  }
+
+  public final class TraceCompat {
+    method public static void beginSection(java.lang.String);
+    method public static void endSection();
+  }
+
+  public class UserManagerCompat {
+    method public static boolean isUserUnlocked(android.content.Context);
+  }
+
+}
+
+package android.support.v4.print {
+
+  public final class PrintHelper {
+    ctor public PrintHelper(android.content.Context);
+    method public int getColorMode();
+    method public int getOrientation();
+    method public int getScaleMode();
+    method public void printBitmap(java.lang.String, android.graphics.Bitmap);
+    method public void printBitmap(java.lang.String, android.graphics.Bitmap, android.support.v4.print.PrintHelper.OnPrintFinishCallback);
+    method public void printBitmap(java.lang.String, android.net.Uri) throws java.io.FileNotFoundException;
+    method public void printBitmap(java.lang.String, android.net.Uri, android.support.v4.print.PrintHelper.OnPrintFinishCallback) throws java.io.FileNotFoundException;
+    method public void setColorMode(int);
+    method public void setOrientation(int);
+    method public void setScaleMode(int);
+    method public static boolean systemSupportsPrint();
+    field public static final int COLOR_MODE_COLOR = 2; // 0x2
+    field public static final int COLOR_MODE_MONOCHROME = 1; // 0x1
+    field public static final int ORIENTATION_LANDSCAPE = 1; // 0x1
+    field public static final int ORIENTATION_PORTRAIT = 2; // 0x2
+    field public static final int SCALE_MODE_FILL = 2; // 0x2
+    field public static final int SCALE_MODE_FIT = 1; // 0x1
+  }
+
+  public static abstract interface PrintHelper.OnPrintFinishCallback {
+    method public abstract void onFinish();
+  }
+
+}
+
+package android.support.v4.provider {
+
+  public abstract class DocumentFile {
+    method public abstract boolean canRead();
+    method public abstract boolean canWrite();
+    method public abstract android.support.v4.provider.DocumentFile createDirectory(java.lang.String);
+    method public abstract android.support.v4.provider.DocumentFile createFile(java.lang.String, java.lang.String);
+    method public abstract boolean delete();
+    method public abstract boolean exists();
+    method public android.support.v4.provider.DocumentFile findFile(java.lang.String);
+    method public static android.support.v4.provider.DocumentFile fromFile(java.io.File);
+    method public static android.support.v4.provider.DocumentFile fromSingleUri(android.content.Context, android.net.Uri);
+    method public static android.support.v4.provider.DocumentFile fromTreeUri(android.content.Context, android.net.Uri);
+    method public abstract java.lang.String getName();
+    method public android.support.v4.provider.DocumentFile getParentFile();
+    method public abstract java.lang.String getType();
+    method public abstract android.net.Uri getUri();
+    method public abstract boolean isDirectory();
+    method public static boolean isDocumentUri(android.content.Context, android.net.Uri);
+    method public abstract boolean isFile();
+    method public abstract boolean isVirtual();
+    method public abstract long lastModified();
+    method public abstract long length();
+    method public abstract android.support.v4.provider.DocumentFile[] listFiles();
+    method public abstract boolean renameTo(java.lang.String);
+  }
+
+  public final class FontRequest {
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String, java.util.List<java.util.List<byte[]>>);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String, int);
+    method public java.util.List<java.util.List<byte[]>> getCertificates();
+    method public int getCertificatesArrayResId();
+    method public java.lang.String getProviderAuthority();
+    method public java.lang.String getProviderPackage();
+    method public java.lang.String getQuery();
+  }
+
+  public class FontsContractCompat {
+    method public static android.graphics.Typeface buildTypeface(android.content.Context, android.os.CancellationSignal, android.support.v4.provider.FontsContractCompat.FontInfo[]);
+    method public static android.support.v4.provider.FontsContractCompat.FontFamilyResult fetchFonts(android.content.Context, android.os.CancellationSignal, android.support.v4.provider.FontRequest) throws android.content.pm.PackageManager.NameNotFoundException;
+    method public static void requestFont(android.content.Context, android.support.v4.provider.FontRequest, android.support.v4.provider.FontsContractCompat.FontRequestCallback, android.os.Handler);
+  }
+
+  public static final class FontsContractCompat.Columns {
+    ctor public FontsContractCompat.Columns();
+    field public static final java.lang.String FILE_ID = "file_id";
+    field public static final java.lang.String ITALIC = "font_italic";
+    field public static final java.lang.String RESULT_CODE = "result_code";
+    field public static final int RESULT_CODE_FONT_NOT_FOUND = 1; // 0x1
+    field public static final int RESULT_CODE_FONT_UNAVAILABLE = 2; // 0x2
+    field public static final int RESULT_CODE_MALFORMED_QUERY = 3; // 0x3
+    field public static final int RESULT_CODE_OK = 0; // 0x0
+    field public static final java.lang.String TTC_INDEX = "font_ttc_index";
+    field public static final java.lang.String VARIATION_SETTINGS = "font_variation_settings";
+    field public static final java.lang.String WEIGHT = "font_weight";
+  }
+
+  public static class FontsContractCompat.FontFamilyResult {
+    method public android.support.v4.provider.FontsContractCompat.FontInfo[] getFonts();
+    method public int getStatusCode();
+    field public static final int STATUS_OK = 0; // 0x0
+    field public static final int STATUS_UNEXPECTED_DATA_PROVIDED = 2; // 0x2
+    field public static final int STATUS_WRONG_CERTIFICATES = 1; // 0x1
+  }
+
+  public static class FontsContractCompat.FontInfo {
+    method public int getResultCode();
+    method public int getTtcIndex();
+    method public android.net.Uri getUri();
+    method public int getWeight();
+    method public boolean isItalic();
+  }
+
+  public static class FontsContractCompat.FontRequestCallback {
+    ctor public FontsContractCompat.FontRequestCallback();
+    method public void onTypefaceRequestFailed(int);
+    method public void onTypefaceRetrieved(android.graphics.Typeface);
+    field public static final int FAIL_REASON_FONT_LOAD_ERROR = -3; // 0xfffffffd
+    field public static final int FAIL_REASON_FONT_NOT_FOUND = 1; // 0x1
+    field public static final int FAIL_REASON_FONT_UNAVAILABLE = 2; // 0x2
+    field public static final int FAIL_REASON_MALFORMED_QUERY = 3; // 0x3
+    field public static final int FAIL_REASON_PROVIDER_NOT_FOUND = -1; // 0xffffffff
+    field public static final int FAIL_REASON_WRONG_CERTIFICATES = -2; // 0xfffffffe
+  }
+
+}
+
+package android.support.v4.text {
+
+  public final class BidiFormatter {
+    method public static android.support.v4.text.BidiFormatter getInstance();
+    method public static android.support.v4.text.BidiFormatter getInstance(boolean);
+    method public static android.support.v4.text.BidiFormatter getInstance(java.util.Locale);
+    method public boolean getStereoReset();
+    method public boolean isRtl(java.lang.String);
+    method public boolean isRtl(java.lang.CharSequence);
+    method public boolean isRtlContext();
+    method public java.lang.String unicodeWrap(java.lang.String, android.support.v4.text.TextDirectionHeuristicCompat, boolean);
+    method public java.lang.CharSequence unicodeWrap(java.lang.CharSequence, android.support.v4.text.TextDirectionHeuristicCompat, boolean);
+    method public java.lang.String unicodeWrap(java.lang.String, android.support.v4.text.TextDirectionHeuristicCompat);
+    method public java.lang.CharSequence unicodeWrap(java.lang.CharSequence, android.support.v4.text.TextDirectionHeuristicCompat);
+    method public java.lang.String unicodeWrap(java.lang.String, boolean);
+    method public java.lang.CharSequence unicodeWrap(java.lang.CharSequence, boolean);
+    method public java.lang.String unicodeWrap(java.lang.String);
+    method public java.lang.CharSequence unicodeWrap(java.lang.CharSequence);
+  }
+
+  public static final class BidiFormatter.Builder {
+    ctor public BidiFormatter.Builder();
+    ctor public BidiFormatter.Builder(boolean);
+    ctor public BidiFormatter.Builder(java.util.Locale);
+    method public android.support.v4.text.BidiFormatter build();
+    method public android.support.v4.text.BidiFormatter.Builder setTextDirectionHeuristic(android.support.v4.text.TextDirectionHeuristicCompat);
+    method public android.support.v4.text.BidiFormatter.Builder stereoReset(boolean);
+  }
+
+  public final class ICUCompat {
+    method public static java.lang.String maximizeAndGetScript(java.util.Locale);
+  }
+
+  public abstract interface TextDirectionHeuristicCompat {
+    method public abstract boolean isRtl(char[], int, int);
+    method public abstract boolean isRtl(java.lang.CharSequence, int, int);
+  }
+
+  public final class TextDirectionHeuristicsCompat {
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat ANYRTL_LTR;
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat FIRSTSTRONG_LTR;
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat FIRSTSTRONG_RTL;
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat LOCALE;
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat LTR;
+    field public static final android.support.v4.text.TextDirectionHeuristicCompat RTL;
+  }
+
+  public final class TextUtilsCompat {
+    method public static int getLayoutDirectionFromLocale(java.util.Locale);
+    method public static java.lang.String htmlEncode(java.lang.String);
+    field public static final deprecated java.util.Locale ROOT;
+  }
+
+}
+
+package android.support.v4.text.util {
+
+  public final class LinkifyCompat {
+    method public static final boolean addLinks(android.text.Spannable, int);
+    method public static final boolean addLinks(android.widget.TextView, int);
+    method public static final void addLinks(android.widget.TextView, java.util.regex.Pattern, java.lang.String);
+    method public static final void addLinks(android.widget.TextView, java.util.regex.Pattern, java.lang.String, android.text.util.Linkify.MatchFilter, android.text.util.Linkify.TransformFilter);
+    method public static final void addLinks(android.widget.TextView, java.util.regex.Pattern, java.lang.String, java.lang.String[], android.text.util.Linkify.MatchFilter, android.text.util.Linkify.TransformFilter);
+    method public static final boolean addLinks(android.text.Spannable, java.util.regex.Pattern, java.lang.String);
+    method public static final boolean addLinks(android.text.Spannable, java.util.regex.Pattern, java.lang.String, android.text.util.Linkify.MatchFilter, android.text.util.Linkify.TransformFilter);
+    method public static final boolean addLinks(android.text.Spannable, java.util.regex.Pattern, java.lang.String, java.lang.String[], android.text.util.Linkify.MatchFilter, android.text.util.Linkify.TransformFilter);
+  }
+
+}
+
+package android.support.v4.util {
+
+  public class ArrayMap<K, V> extends android.support.v4.util.SimpleArrayMap implements java.util.Map {
+    ctor public ArrayMap();
+    ctor public ArrayMap(int);
+    ctor public ArrayMap(android.support.v4.util.SimpleArrayMap);
+    method public boolean containsAll(java.util.Collection<?>);
+    method public java.util.Set<java.util.Map.Entry<K, V>> entrySet();
+    method public java.util.Set<K> keySet();
+    method public void putAll(java.util.Map<? extends K, ? extends V>);
+    method public boolean removeAll(java.util.Collection<?>);
+    method public boolean retainAll(java.util.Collection<?>);
+    method public java.util.Collection<V> values();
+  }
+
+  public final class ArraySet<E> implements java.util.Collection java.util.Set {
+    ctor public ArraySet();
+    ctor public ArraySet(int);
+    ctor public ArraySet(android.support.v4.util.ArraySet<E>);
+    method public boolean add(E);
+    method public void addAll(android.support.v4.util.ArraySet<? extends E>);
+    method public boolean addAll(java.util.Collection<? extends E>);
+    method public void clear();
+    method public boolean contains(java.lang.Object);
+    method public boolean containsAll(java.util.Collection<?>);
+    method public void ensureCapacity(int);
+    method public int indexOf(java.lang.Object);
+    method public boolean isEmpty();
+    method public java.util.Iterator<E> iterator();
+    method public boolean remove(java.lang.Object);
+    method public boolean removeAll(android.support.v4.util.ArraySet<? extends E>);
+    method public boolean removeAll(java.util.Collection<?>);
+    method public E removeAt(int);
+    method public boolean retainAll(java.util.Collection<?>);
+    method public int size();
+    method public java.lang.Object[] toArray();
+    method public <T> T[] toArray(T[]);
+    method public E valueAt(int);
+  }
+
+  public class AtomicFile {
+    ctor public AtomicFile(java.io.File);
+    method public void delete();
+    method public void failWrite(java.io.FileOutputStream);
+    method public void finishWrite(java.io.FileOutputStream);
+    method public java.io.File getBaseFile();
+    method public java.io.FileInputStream openRead() throws java.io.FileNotFoundException;
+    method public byte[] readFully() throws java.io.IOException;
+    method public java.io.FileOutputStream startWrite() throws java.io.IOException;
+  }
+
+  public final class CircularArray<E> {
+    ctor public CircularArray();
+    ctor public CircularArray(int);
+    method public void addFirst(E);
+    method public void addLast(E);
+    method public void clear();
+    method public E get(int);
+    method public E getFirst();
+    method public E getLast();
+    method public boolean isEmpty();
+    method public E popFirst();
+    method public E popLast();
+    method public void removeFromEnd(int);
+    method public void removeFromStart(int);
+    method public int size();
+  }
+
+  public final class CircularIntArray {
+    ctor public CircularIntArray();
+    ctor public CircularIntArray(int);
+    method public void addFirst(int);
+    method public void addLast(int);
+    method public void clear();
+    method public int get(int);
+    method public int getFirst();
+    method public int getLast();
+    method public boolean isEmpty();
+    method public int popFirst();
+    method public int popLast();
+    method public void removeFromEnd(int);
+    method public void removeFromStart(int);
+    method public int size();
+  }
+
+  public class LongSparseArray<E> {
+    ctor public LongSparseArray();
+    ctor public LongSparseArray(int);
+    method public void append(long, E);
+    method public void clear();
+    method public android.support.v4.util.LongSparseArray<E> clone();
+    method public void delete(long);
+    method public E get(long);
+    method public E get(long, E);
+    method public int indexOfKey(long);
+    method public int indexOfValue(E);
+    method public long keyAt(int);
+    method public void put(long, E);
+    method public void remove(long);
+    method public void removeAt(int);
+    method public void setValueAt(int, E);
+    method public int size();
+    method public E valueAt(int);
+  }
+
+  public class LruCache<K, V> {
+    ctor public LruCache(int);
+    method protected V create(K);
+    method public final synchronized int createCount();
+    method protected void entryRemoved(boolean, K, V, V);
+    method public final void evictAll();
+    method public final synchronized int evictionCount();
+    method public final V get(K);
+    method public final synchronized int hitCount();
+    method public final synchronized int maxSize();
+    method public final synchronized int missCount();
+    method public final V put(K, V);
+    method public final synchronized int putCount();
+    method public final V remove(K);
+    method public void resize(int);
+    method public final synchronized int size();
+    method protected int sizeOf(K, V);
+    method public final synchronized java.util.Map<K, V> snapshot();
+    method public final synchronized java.lang.String toString();
+    method public void trimToSize(int);
+  }
+
+  public class ObjectsCompat {
+    method public static boolean equals(java.lang.Object, java.lang.Object);
+  }
+
+  public class Pair<F, S> {
+    ctor public Pair(F, S);
+    method public static <A, B> android.support.v4.util.Pair<A, B> create(A, B);
+    field public final F first;
+    field public final S second;
+  }
+
+  public final class PatternsCompat {
+    field public static final java.util.regex.Pattern DOMAIN_NAME;
+    field public static final java.util.regex.Pattern EMAIL_ADDRESS;
+    field public static final java.util.regex.Pattern IP_ADDRESS;
+    field public static final java.util.regex.Pattern WEB_URL;
+  }
+
+  public final class Pools {
+  }
+
+  public static abstract interface Pools.Pool<T> {
+    method public abstract T acquire();
+    method public abstract boolean release(T);
+  }
+
+  public static class Pools.SimplePool<T> implements android.support.v4.util.Pools.Pool {
+    ctor public Pools.SimplePool(int);
+    method public T acquire();
+    method public boolean release(T);
+  }
+
+  public static class Pools.SynchronizedPool<T> extends android.support.v4.util.Pools.SimplePool {
+    ctor public Pools.SynchronizedPool(int);
+  }
+
+  public class SimpleArrayMap<K, V> {
+    ctor public SimpleArrayMap();
+    ctor public SimpleArrayMap(int);
+    ctor public SimpleArrayMap(android.support.v4.util.SimpleArrayMap<K, V>);
+    method public void clear();
+    method public boolean containsKey(java.lang.Object);
+    method public boolean containsValue(java.lang.Object);
+    method public void ensureCapacity(int);
+    method public V get(java.lang.Object);
+    method public int indexOfKey(java.lang.Object);
+    method public boolean isEmpty();
+    method public K keyAt(int);
+    method public V put(K, V);
+    method public void putAll(android.support.v4.util.SimpleArrayMap<? extends K, ? extends V>);
+    method public V remove(java.lang.Object);
+    method public V removeAt(int);
+    method public V setValueAt(int, V);
+    method public int size();
+    method public V valueAt(int);
+  }
+
+  public class SparseArrayCompat<E> {
+    ctor public SparseArrayCompat();
+    ctor public SparseArrayCompat(int);
+    method public void append(int, E);
+    method public void clear();
+    method public android.support.v4.util.SparseArrayCompat<E> clone();
+    method public void delete(int);
+    method public E get(int);
+    method public E get(int, E);
+    method public int indexOfKey(int);
+    method public int indexOfValue(E);
+    method public int keyAt(int);
+    method public void put(int, E);
+    method public void remove(int);
+    method public void removeAt(int);
+    method public void removeAtRange(int, int);
+    method public void setValueAt(int, E);
+    method public int size();
+    method public E valueAt(int);
+  }
+
+}
+
+package android.support.v4.view {
+
+  public abstract class AbsSavedState implements android.os.Parcelable {
+    ctor protected AbsSavedState(android.os.Parcelable);
+    ctor protected AbsSavedState(android.os.Parcel);
+    ctor protected AbsSavedState(android.os.Parcel, java.lang.ClassLoader);
+    method public int describeContents();
+    method public final android.os.Parcelable getSuperState();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.support.v4.view.AbsSavedState> CREATOR;
+    field public static final android.support.v4.view.AbsSavedState EMPTY_STATE;
+  }
+
+  public class AccessibilityDelegateCompat {
+    ctor public AccessibilityDelegateCompat();
+    method public boolean dispatchPopulateAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public android.support.v4.view.accessibility.AccessibilityNodeProviderCompat getAccessibilityNodeProvider(android.view.View);
+    method public void onInitializeAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public void onInitializeAccessibilityNodeInfo(android.view.View, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public void onPopulateAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public boolean onRequestSendAccessibilityEvent(android.view.ViewGroup, android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public boolean performAccessibilityAction(android.view.View, int, android.os.Bundle);
+    method public void sendAccessibilityEvent(android.view.View, int);
+    method public void sendAccessibilityEventUnchecked(android.view.View, android.view.accessibility.AccessibilityEvent);
+  }
+
+  public abstract class ActionProvider {
+    ctor public ActionProvider(android.content.Context);
+    method public android.content.Context getContext();
+    method public boolean hasSubMenu();
+    method public boolean isVisible();
+    method public abstract android.view.View onCreateActionView();
+    method public android.view.View onCreateActionView(android.view.MenuItem);
+    method public boolean onPerformDefaultAction();
+    method public void onPrepareSubMenu(android.view.SubMenu);
+    method public boolean overridesItemVisibility();
+    method public void refreshVisibility();
+    method public void setVisibilityListener(android.support.v4.view.ActionProvider.VisibilityListener);
+  }
+
+  public static abstract interface ActionProvider.VisibilityListener {
+    method public abstract void onActionProviderVisibilityChanged(boolean);
+  }
+
+  public final class AsyncLayoutInflater {
+    ctor public AsyncLayoutInflater(android.content.Context);
+    method public void inflate(int, android.view.ViewGroup, android.support.v4.view.AsyncLayoutInflater.OnInflateFinishedListener);
+  }
+
+  public static abstract interface AsyncLayoutInflater.OnInflateFinishedListener {
+    method public abstract void onInflateFinished(android.view.View, int, android.view.ViewGroup);
+  }
+
+  public final class GestureDetectorCompat {
+    ctor public GestureDetectorCompat(android.content.Context, android.view.GestureDetector.OnGestureListener);
+    ctor public GestureDetectorCompat(android.content.Context, android.view.GestureDetector.OnGestureListener, android.os.Handler);
+    method public boolean isLongpressEnabled();
+    method public boolean onTouchEvent(android.view.MotionEvent);
+    method public void setIsLongpressEnabled(boolean);
+    method public void setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener);
+  }
+
+  public final class GravityCompat {
+    method public static void apply(int, int, int, android.graphics.Rect, android.graphics.Rect, int);
+    method public static void apply(int, int, int, android.graphics.Rect, int, int, android.graphics.Rect, int);
+    method public static void applyDisplay(int, android.graphics.Rect, android.graphics.Rect, int);
+    method public static int getAbsoluteGravity(int, int);
+    field public static final int END = 8388613; // 0x800005
+    field public static final int RELATIVE_HORIZONTAL_GRAVITY_MASK = 8388615; // 0x800007
+    field public static final int RELATIVE_LAYOUT_DIRECTION = 8388608; // 0x800000
+    field public static final int START = 8388611; // 0x800003
+  }
+
+  public final class InputDeviceCompat {
+    field public static final int SOURCE_ANY = -256; // 0xffffff00
+    field public static final int SOURCE_CLASS_BUTTON = 1; // 0x1
+    field public static final int SOURCE_CLASS_JOYSTICK = 16; // 0x10
+    field public static final int SOURCE_CLASS_MASK = 255; // 0xff
+    field public static final int SOURCE_CLASS_NONE = 0; // 0x0
+    field public static final int SOURCE_CLASS_POINTER = 2; // 0x2
+    field public static final int SOURCE_CLASS_POSITION = 8; // 0x8
+    field public static final int SOURCE_CLASS_TRACKBALL = 4; // 0x4
+    field public static final int SOURCE_DPAD = 513; // 0x201
+    field public static final int SOURCE_GAMEPAD = 1025; // 0x401
+    field public static final int SOURCE_HDMI = 33554433; // 0x2000001
+    field public static final int SOURCE_JOYSTICK = 16777232; // 0x1000010
+    field public static final int SOURCE_KEYBOARD = 257; // 0x101
+    field public static final int SOURCE_MOUSE = 8194; // 0x2002
+    field public static final int SOURCE_ROTARY_ENCODER = 4194304; // 0x400000
+    field public static final int SOURCE_STYLUS = 16386; // 0x4002
+    field public static final int SOURCE_TOUCHPAD = 1048584; // 0x100008
+    field public static final int SOURCE_TOUCHSCREEN = 4098; // 0x1002
+    field public static final int SOURCE_TOUCH_NAVIGATION = 2097152; // 0x200000
+    field public static final int SOURCE_TRACKBALL = 65540; // 0x10004
+    field public static final int SOURCE_UNKNOWN = 0; // 0x0
+  }
+
+  public final deprecated class KeyEventCompat {
+    method public static deprecated boolean dispatch(android.view.KeyEvent, android.view.KeyEvent.Callback, java.lang.Object, java.lang.Object);
+    method public static deprecated java.lang.Object getKeyDispatcherState(android.view.View);
+    method public static deprecated boolean hasModifiers(android.view.KeyEvent, int);
+    method public static deprecated boolean hasNoModifiers(android.view.KeyEvent);
+    method public static deprecated boolean isCtrlPressed(android.view.KeyEvent);
+    method public static deprecated boolean isTracking(android.view.KeyEvent);
+    method public static deprecated boolean metaStateHasModifiers(int, int);
+    method public static deprecated boolean metaStateHasNoModifiers(int);
+    method public static deprecated int normalizeMetaState(int);
+    method public static deprecated void startTracking(android.view.KeyEvent);
+  }
+
+  public final class LayoutInflaterCompat {
+    method public static deprecated android.support.v4.view.LayoutInflaterFactory getFactory(android.view.LayoutInflater);
+    method public static deprecated void setFactory(android.view.LayoutInflater, android.support.v4.view.LayoutInflaterFactory);
+    method public static void setFactory2(android.view.LayoutInflater, android.view.LayoutInflater.Factory2);
+  }
+
+  public abstract deprecated interface LayoutInflaterFactory {
+    method public abstract android.view.View onCreateView(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet);
+  }
+
+  public final class MarginLayoutParamsCompat {
+    method public static int getLayoutDirection(android.view.ViewGroup.MarginLayoutParams);
+    method public static int getMarginEnd(android.view.ViewGroup.MarginLayoutParams);
+    method public static int getMarginStart(android.view.ViewGroup.MarginLayoutParams);
+    method public static boolean isMarginRelative(android.view.ViewGroup.MarginLayoutParams);
+    method public static void resolveLayoutDirection(android.view.ViewGroup.MarginLayoutParams, int);
+    method public static void setLayoutDirection(android.view.ViewGroup.MarginLayoutParams, int);
+    method public static void setMarginEnd(android.view.ViewGroup.MarginLayoutParams, int);
+    method public static void setMarginStart(android.view.ViewGroup.MarginLayoutParams, int);
+  }
+
+  public final class MenuCompat {
+    method public static deprecated void setShowAsAction(android.view.MenuItem, int);
+  }
+
+  public final class MenuItemCompat {
+    method public static deprecated boolean collapseActionView(android.view.MenuItem);
+    method public static deprecated boolean expandActionView(android.view.MenuItem);
+    method public static android.support.v4.view.ActionProvider getActionProvider(android.view.MenuItem);
+    method public static deprecated android.view.View getActionView(android.view.MenuItem);
+    method public static int getAlphabeticModifiers(android.view.MenuItem);
+    method public static java.lang.CharSequence getContentDescription(android.view.MenuItem);
+    method public static android.content.res.ColorStateList getIconTintList(android.view.MenuItem);
+    method public static android.graphics.PorterDuff.Mode getIconTintMode(android.view.MenuItem);
+    method public static int getNumericModifiers(android.view.MenuItem);
+    method public static java.lang.CharSequence getTooltipText(android.view.MenuItem);
+    method public static deprecated boolean isActionViewExpanded(android.view.MenuItem);
+    method public static android.view.MenuItem setActionProvider(android.view.MenuItem, android.support.v4.view.ActionProvider);
+    method public static deprecated android.view.MenuItem setActionView(android.view.MenuItem, android.view.View);
+    method public static deprecated android.view.MenuItem setActionView(android.view.MenuItem, int);
+    method public static void setAlphabeticShortcut(android.view.MenuItem, char, int);
+    method public static void setContentDescription(android.view.MenuItem, java.lang.CharSequence);
+    method public static void setIconTintList(android.view.MenuItem, android.content.res.ColorStateList);
+    method public static void setIconTintMode(android.view.MenuItem, android.graphics.PorterDuff.Mode);
+    method public static void setNumericShortcut(android.view.MenuItem, char, int);
+    method public static deprecated android.view.MenuItem setOnActionExpandListener(android.view.MenuItem, android.support.v4.view.MenuItemCompat.OnActionExpandListener);
+    method public static void setShortcut(android.view.MenuItem, char, char, int, int);
+    method public static deprecated void setShowAsAction(android.view.MenuItem, int);
+    method public static void setTooltipText(android.view.MenuItem, java.lang.CharSequence);
+    field public static final deprecated int SHOW_AS_ACTION_ALWAYS = 2; // 0x2
+    field public static final deprecated int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = 8; // 0x8
+    field public static final deprecated int SHOW_AS_ACTION_IF_ROOM = 1; // 0x1
+    field public static final deprecated int SHOW_AS_ACTION_NEVER = 0; // 0x0
+    field public static final deprecated int SHOW_AS_ACTION_WITH_TEXT = 4; // 0x4
+  }
+
+  public static abstract deprecated interface MenuItemCompat.OnActionExpandListener {
+    method public abstract boolean onMenuItemActionCollapse(android.view.MenuItem);
+    method public abstract boolean onMenuItemActionExpand(android.view.MenuItem);
+  }
+
+  public final class MotionEventCompat {
+    method public static deprecated int findPointerIndex(android.view.MotionEvent, int);
+    method public static deprecated int getActionIndex(android.view.MotionEvent);
+    method public static deprecated int getActionMasked(android.view.MotionEvent);
+    method public static deprecated float getAxisValue(android.view.MotionEvent, int);
+    method public static deprecated float getAxisValue(android.view.MotionEvent, int, int);
+    method public static deprecated int getButtonState(android.view.MotionEvent);
+    method public static deprecated int getPointerCount(android.view.MotionEvent);
+    method public static deprecated int getPointerId(android.view.MotionEvent, int);
+    method public static deprecated int getSource(android.view.MotionEvent);
+    method public static deprecated float getX(android.view.MotionEvent, int);
+    method public static deprecated float getY(android.view.MotionEvent, int);
+    method public static boolean isFromSource(android.view.MotionEvent, int);
+    field public static final deprecated int ACTION_HOVER_ENTER = 9; // 0x9
+    field public static final deprecated int ACTION_HOVER_EXIT = 10; // 0xa
+    field public static final deprecated int ACTION_HOVER_MOVE = 7; // 0x7
+    field public static final deprecated int ACTION_MASK = 255; // 0xff
+    field public static final deprecated int ACTION_POINTER_DOWN = 5; // 0x5
+    field public static final deprecated int ACTION_POINTER_INDEX_MASK = 65280; // 0xff00
+    field public static final deprecated int ACTION_POINTER_INDEX_SHIFT = 8; // 0x8
+    field public static final deprecated int ACTION_POINTER_UP = 6; // 0x6
+    field public static final deprecated int ACTION_SCROLL = 8; // 0x8
+    field public static final deprecated int AXIS_BRAKE = 23; // 0x17
+    field public static final deprecated int AXIS_DISTANCE = 24; // 0x18
+    field public static final deprecated int AXIS_GAS = 22; // 0x16
+    field public static final deprecated int AXIS_GENERIC_1 = 32; // 0x20
+    field public static final deprecated int AXIS_GENERIC_10 = 41; // 0x29
+    field public static final deprecated int AXIS_GENERIC_11 = 42; // 0x2a
+    field public static final deprecated int AXIS_GENERIC_12 = 43; // 0x2b
+    field public static final deprecated int AXIS_GENERIC_13 = 44; // 0x2c
+    field public static final deprecated int AXIS_GENERIC_14 = 45; // 0x2d
+    field public static final deprecated int AXIS_GENERIC_15 = 46; // 0x2e
+    field public static final deprecated int AXIS_GENERIC_16 = 47; // 0x2f
+    field public static final deprecated int AXIS_GENERIC_2 = 33; // 0x21
+    field public static final deprecated int AXIS_GENERIC_3 = 34; // 0x22
+    field public static final deprecated int AXIS_GENERIC_4 = 35; // 0x23
+    field public static final deprecated int AXIS_GENERIC_5 = 36; // 0x24
+    field public static final deprecated int AXIS_GENERIC_6 = 37; // 0x25
+    field public static final deprecated int AXIS_GENERIC_7 = 38; // 0x26
+    field public static final deprecated int AXIS_GENERIC_8 = 39; // 0x27
+    field public static final deprecated int AXIS_GENERIC_9 = 40; // 0x28
+    field public static final deprecated int AXIS_HAT_X = 15; // 0xf
+    field public static final deprecated int AXIS_HAT_Y = 16; // 0x10
+    field public static final deprecated int AXIS_HSCROLL = 10; // 0xa
+    field public static final deprecated int AXIS_LTRIGGER = 17; // 0x11
+    field public static final deprecated int AXIS_ORIENTATION = 8; // 0x8
+    field public static final deprecated int AXIS_PRESSURE = 2; // 0x2
+    field public static final int AXIS_RELATIVE_X = 27; // 0x1b
+    field public static final int AXIS_RELATIVE_Y = 28; // 0x1c
+    field public static final deprecated int AXIS_RTRIGGER = 18; // 0x12
+    field public static final deprecated int AXIS_RUDDER = 20; // 0x14
+    field public static final deprecated int AXIS_RX = 12; // 0xc
+    field public static final deprecated int AXIS_RY = 13; // 0xd
+    field public static final deprecated int AXIS_RZ = 14; // 0xe
+    field public static final int AXIS_SCROLL = 26; // 0x1a
+    field public static final deprecated int AXIS_SIZE = 3; // 0x3
+    field public static final deprecated int AXIS_THROTTLE = 19; // 0x13
+    field public static final deprecated int AXIS_TILT = 25; // 0x19
+    field public static final deprecated int AXIS_TOOL_MAJOR = 6; // 0x6
+    field public static final deprecated int AXIS_TOOL_MINOR = 7; // 0x7
+    field public static final deprecated int AXIS_TOUCH_MAJOR = 4; // 0x4
+    field public static final deprecated int AXIS_TOUCH_MINOR = 5; // 0x5
+    field public static final deprecated int AXIS_VSCROLL = 9; // 0x9
+    field public static final deprecated int AXIS_WHEEL = 21; // 0x15
+    field public static final deprecated int AXIS_X = 0; // 0x0
+    field public static final deprecated int AXIS_Y = 1; // 0x1
+    field public static final deprecated int AXIS_Z = 11; // 0xb
+    field public static final deprecated int BUTTON_PRIMARY = 1; // 0x1
+  }
+
+  public abstract interface NestedScrollingChild {
+    method public abstract boolean dispatchNestedFling(float, float, boolean);
+    method public abstract boolean dispatchNestedPreFling(float, float);
+    method public abstract boolean dispatchNestedPreScroll(int, int, int[], int[]);
+    method public abstract boolean dispatchNestedScroll(int, int, int, int, int[]);
+    method public abstract boolean hasNestedScrollingParent();
+    method public abstract boolean isNestedScrollingEnabled();
+    method public abstract void setNestedScrollingEnabled(boolean);
+    method public abstract boolean startNestedScroll(int);
+    method public abstract void stopNestedScroll();
+  }
+
+  public abstract interface NestedScrollingChild2 implements android.support.v4.view.NestedScrollingChild {
+    method public abstract boolean dispatchNestedPreScroll(int, int, int[], int[], int);
+    method public abstract boolean dispatchNestedScroll(int, int, int, int, int[], int);
+    method public abstract boolean hasNestedScrollingParent(int);
+    method public abstract boolean startNestedScroll(int, int);
+    method public abstract void stopNestedScroll(int);
+  }
+
+  public class NestedScrollingChildHelper {
+    ctor public NestedScrollingChildHelper(android.view.View);
+    method public boolean dispatchNestedFling(float, float, boolean);
+    method public boolean dispatchNestedPreFling(float, float);
+    method public boolean dispatchNestedPreScroll(int, int, int[], int[]);
+    method public boolean dispatchNestedPreScroll(int, int, int[], int[], int);
+    method public boolean dispatchNestedScroll(int, int, int, int, int[]);
+    method public boolean dispatchNestedScroll(int, int, int, int, int[], int);
+    method public boolean hasNestedScrollingParent();
+    method public boolean hasNestedScrollingParent(int);
+    method public boolean isNestedScrollingEnabled();
+    method public void onDetachedFromWindow();
+    method public void onStopNestedScroll(android.view.View);
+    method public void setNestedScrollingEnabled(boolean);
+    method public boolean startNestedScroll(int);
+    method public boolean startNestedScroll(int, int);
+    method public void stopNestedScroll();
+    method public void stopNestedScroll(int);
+  }
+
+  public abstract interface NestedScrollingParent {
+    method public abstract int getNestedScrollAxes();
+    method public abstract boolean onNestedFling(android.view.View, float, float, boolean);
+    method public abstract boolean onNestedPreFling(android.view.View, float, float);
+    method public abstract void onNestedPreScroll(android.view.View, int, int, int[]);
+    method public abstract void onNestedScroll(android.view.View, int, int, int, int);
+    method public abstract void onNestedScrollAccepted(android.view.View, android.view.View, int);
+    method public abstract boolean onStartNestedScroll(android.view.View, android.view.View, int);
+    method public abstract void onStopNestedScroll(android.view.View);
+  }
+
+  public abstract interface NestedScrollingParent2 implements android.support.v4.view.NestedScrollingParent {
+    method public abstract void onNestedPreScroll(android.view.View, int, int, int[], int);
+    method public abstract void onNestedScroll(android.view.View, int, int, int, int, int);
+    method public abstract void onNestedScrollAccepted(android.view.View, android.view.View, int, int);
+    method public abstract boolean onStartNestedScroll(android.view.View, android.view.View, int, int);
+    method public abstract void onStopNestedScroll(android.view.View, int);
+  }
+
+  public class NestedScrollingParentHelper {
+    ctor public NestedScrollingParentHelper(android.view.ViewGroup);
+    method public int getNestedScrollAxes();
+    method public void onNestedScrollAccepted(android.view.View, android.view.View, int);
+    method public void onNestedScrollAccepted(android.view.View, android.view.View, int, int);
+    method public void onStopNestedScroll(android.view.View);
+    method public void onStopNestedScroll(android.view.View, int);
+  }
+
+  public abstract interface OnApplyWindowInsetsListener {
+    method public abstract android.support.v4.view.WindowInsetsCompat onApplyWindowInsets(android.view.View, android.support.v4.view.WindowInsetsCompat);
+  }
+
+  public abstract class PagerAdapter {
+    ctor public PagerAdapter();
+    method public void destroyItem(android.view.ViewGroup, int, java.lang.Object);
+    method public deprecated void destroyItem(android.view.View, int, java.lang.Object);
+    method public void finishUpdate(android.view.ViewGroup);
+    method public deprecated void finishUpdate(android.view.View);
+    method public abstract int getCount();
+    method public int getItemPosition(java.lang.Object);
+    method public java.lang.CharSequence getPageTitle(int);
+    method public float getPageWidth(int);
+    method public java.lang.Object instantiateItem(android.view.ViewGroup, int);
+    method public deprecated java.lang.Object instantiateItem(android.view.View, int);
+    method public abstract boolean isViewFromObject(android.view.View, java.lang.Object);
+    method public void notifyDataSetChanged();
+    method public void registerDataSetObserver(android.database.DataSetObserver);
+    method public void restoreState(android.os.Parcelable, java.lang.ClassLoader);
+    method public android.os.Parcelable saveState();
+    method public void setPrimaryItem(android.view.ViewGroup, int, java.lang.Object);
+    method public deprecated void setPrimaryItem(android.view.View, int, java.lang.Object);
+    method public void startUpdate(android.view.ViewGroup);
+    method public deprecated void startUpdate(android.view.View);
+    method public void unregisterDataSetObserver(android.database.DataSetObserver);
+    field public static final int POSITION_NONE = -2; // 0xfffffffe
+    field public static final int POSITION_UNCHANGED = -1; // 0xffffffff
+  }
+
+  public class PagerTabStrip extends android.support.v4.view.PagerTitleStrip {
+    ctor public PagerTabStrip(android.content.Context);
+    ctor public PagerTabStrip(android.content.Context, android.util.AttributeSet);
+    method public boolean getDrawFullUnderline();
+    method public int getTabIndicatorColor();
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setDrawFullUnderline(boolean);
+    method public void setTabIndicatorColor(int);
+    method public void setTabIndicatorColorResource(int);
+  }
+
+  public class PagerTitleStrip extends android.view.ViewGroup {
+    ctor public PagerTitleStrip(android.content.Context);
+    ctor public PagerTitleStrip(android.content.Context, android.util.AttributeSet);
+    method public int getTextSpacing();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void setGravity(int);
+    method public void setNonPrimaryAlpha(float);
+    method public void setTextColor(int);
+    method public void setTextSize(int, float);
+    method public void setTextSpacing(int);
+  }
+
+  public final class PointerIconCompat {
+    method public static android.support.v4.view.PointerIconCompat create(android.graphics.Bitmap, float, float);
+    method public static android.support.v4.view.PointerIconCompat getSystemIcon(android.content.Context, int);
+    method public static android.support.v4.view.PointerIconCompat load(android.content.res.Resources, int);
+    field public static final int TYPE_ALIAS = 1010; // 0x3f2
+    field public static final int TYPE_ALL_SCROLL = 1013; // 0x3f5
+    field public static final int TYPE_ARROW = 1000; // 0x3e8
+    field public static final int TYPE_CELL = 1006; // 0x3ee
+    field public static final int TYPE_CONTEXT_MENU = 1001; // 0x3e9
+    field public static final int TYPE_COPY = 1011; // 0x3f3
+    field public static final int TYPE_CROSSHAIR = 1007; // 0x3ef
+    field public static final int TYPE_DEFAULT = 1000; // 0x3e8
+    field public static final int TYPE_GRAB = 1020; // 0x3fc
+    field public static final int TYPE_GRABBING = 1021; // 0x3fd
+    field public static final int TYPE_HAND = 1002; // 0x3ea
+    field public static final int TYPE_HELP = 1003; // 0x3eb
+    field public static final int TYPE_HORIZONTAL_DOUBLE_ARROW = 1014; // 0x3f6
+    field public static final int TYPE_NO_DROP = 1012; // 0x3f4
+    field public static final int TYPE_NULL = 0; // 0x0
+    field public static final int TYPE_TEXT = 1008; // 0x3f0
+    field public static final int TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW = 1017; // 0x3f9
+    field public static final int TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW = 1016; // 0x3f8
+    field public static final int TYPE_VERTICAL_DOUBLE_ARROW = 1015; // 0x3f7
+    field public static final int TYPE_VERTICAL_TEXT = 1009; // 0x3f1
+    field public static final int TYPE_WAIT = 1004; // 0x3ec
+    field public static final int TYPE_ZOOM_IN = 1018; // 0x3fa
+    field public static final int TYPE_ZOOM_OUT = 1019; // 0x3fb
+  }
+
+  public final class ScaleGestureDetectorCompat {
+    method public static deprecated boolean isQuickScaleEnabled(java.lang.Object);
+    method public static boolean isQuickScaleEnabled(android.view.ScaleGestureDetector);
+    method public static deprecated void setQuickScaleEnabled(java.lang.Object, boolean);
+    method public static void setQuickScaleEnabled(android.view.ScaleGestureDetector, boolean);
+  }
+
+  public abstract interface ScrollingView {
+    method public abstract int computeHorizontalScrollExtent();
+    method public abstract int computeHorizontalScrollOffset();
+    method public abstract int computeHorizontalScrollRange();
+    method public abstract int computeVerticalScrollExtent();
+    method public abstract int computeVerticalScrollOffset();
+    method public abstract int computeVerticalScrollRange();
+  }
+
+  public abstract interface TintableBackgroundView {
+    method public abstract android.content.res.ColorStateList getSupportBackgroundTintList();
+    method public abstract android.graphics.PorterDuff.Mode getSupportBackgroundTintMode();
+    method public abstract void setSupportBackgroundTintList(android.content.res.ColorStateList);
+    method public abstract void setSupportBackgroundTintMode(android.graphics.PorterDuff.Mode);
+  }
+
+  public final deprecated class VelocityTrackerCompat {
+    method public static deprecated float getXVelocity(android.view.VelocityTracker, int);
+    method public static deprecated float getYVelocity(android.view.VelocityTracker, int);
+  }
+
+  public class ViewCompat {
+    ctor protected ViewCompat();
+    method public static void addKeyboardNavigationClusters(android.view.View, java.util.Collection<android.view.View>, int);
+    method public static android.support.v4.view.ViewPropertyAnimatorCompat animate(android.view.View);
+    method public static deprecated boolean canScrollHorizontally(android.view.View, int);
+    method public static deprecated boolean canScrollVertically(android.view.View, int);
+    method public static void cancelDragAndDrop(android.view.View);
+    method public static deprecated int combineMeasuredStates(int, int);
+    method public static android.support.v4.view.WindowInsetsCompat dispatchApplyWindowInsets(android.view.View, android.support.v4.view.WindowInsetsCompat);
+    method public static void dispatchFinishTemporaryDetach(android.view.View);
+    method public static boolean dispatchNestedFling(android.view.View, float, float, boolean);
+    method public static boolean dispatchNestedPreFling(android.view.View, float, float);
+    method public static boolean dispatchNestedPreScroll(android.view.View, int, int, int[], int[]);
+    method public static boolean dispatchNestedPreScroll(android.view.View, int, int, int[], int[], int);
+    method public static boolean dispatchNestedScroll(android.view.View, int, int, int, int, int[]);
+    method public static boolean dispatchNestedScroll(android.view.View, int, int, int, int, int[], int);
+    method public static void dispatchStartTemporaryDetach(android.view.View);
+    method public static int getAccessibilityLiveRegion(android.view.View);
+    method public static android.support.v4.view.accessibility.AccessibilityNodeProviderCompat getAccessibilityNodeProvider(android.view.View);
+    method public static deprecated float getAlpha(android.view.View);
+    method public static android.content.res.ColorStateList getBackgroundTintList(android.view.View);
+    method public static android.graphics.PorterDuff.Mode getBackgroundTintMode(android.view.View);
+    method public static android.graphics.Rect getClipBounds(android.view.View);
+    method public static android.view.Display getDisplay(android.view.View);
+    method public static float getElevation(android.view.View);
+    method public static boolean getFitsSystemWindows(android.view.View);
+    method public static int getImportantForAccessibility(android.view.View);
+    method public static int getLabelFor(android.view.View);
+    method public static deprecated int getLayerType(android.view.View);
+    method public static int getLayoutDirection(android.view.View);
+    method public static deprecated android.graphics.Matrix getMatrix(android.view.View);
+    method public static deprecated int getMeasuredHeightAndState(android.view.View);
+    method public static deprecated int getMeasuredState(android.view.View);
+    method public static deprecated int getMeasuredWidthAndState(android.view.View);
+    method public static int getMinimumHeight(android.view.View);
+    method public static int getMinimumWidth(android.view.View);
+    method public static int getNextClusterForwardId(android.view.View);
+    method public static deprecated int getOverScrollMode(android.view.View);
+    method public static int getPaddingEnd(android.view.View);
+    method public static int getPaddingStart(android.view.View);
+    method public static android.view.ViewParent getParentForAccessibility(android.view.View);
+    method public static deprecated float getPivotX(android.view.View);
+    method public static deprecated float getPivotY(android.view.View);
+    method public static deprecated float getRotation(android.view.View);
+    method public static deprecated float getRotationX(android.view.View);
+    method public static deprecated float getRotationY(android.view.View);
+    method public static deprecated float getScaleX(android.view.View);
+    method public static deprecated float getScaleY(android.view.View);
+    method public static int getScrollIndicators(android.view.View);
+    method public static java.lang.String getTransitionName(android.view.View);
+    method public static deprecated float getTranslationX(android.view.View);
+    method public static deprecated float getTranslationY(android.view.View);
+    method public static float getTranslationZ(android.view.View);
+    method public static int getWindowSystemUiVisibility(android.view.View);
+    method public static deprecated float getX(android.view.View);
+    method public static deprecated float getY(android.view.View);
+    method public static float getZ(android.view.View);
+    method public static boolean hasAccessibilityDelegate(android.view.View);
+    method public static boolean hasExplicitFocusable(android.view.View);
+    method public static boolean hasNestedScrollingParent(android.view.View);
+    method public static boolean hasNestedScrollingParent(android.view.View, int);
+    method public static boolean hasOnClickListeners(android.view.View);
+    method public static boolean hasOverlappingRendering(android.view.View);
+    method public static boolean hasTransientState(android.view.View);
+    method public static boolean isAttachedToWindow(android.view.View);
+    method public static boolean isFocusedByDefault(android.view.View);
+    method public static boolean isImportantForAccessibility(android.view.View);
+    method public static boolean isInLayout(android.view.View);
+    method public static boolean isKeyboardNavigationCluster(android.view.View);
+    method public static boolean isLaidOut(android.view.View);
+    method public static boolean isLayoutDirectionResolved(android.view.View);
+    method public static boolean isNestedScrollingEnabled(android.view.View);
+    method public static deprecated boolean isOpaque(android.view.View);
+    method public static boolean isPaddingRelative(android.view.View);
+    method public static deprecated void jumpDrawablesToCurrentState(android.view.View);
+    method public static android.view.View keyboardNavigationClusterSearch(android.view.View, android.view.View, int);
+    method public static void offsetLeftAndRight(android.view.View, int);
+    method public static void offsetTopAndBottom(android.view.View, int);
+    method public static android.support.v4.view.WindowInsetsCompat onApplyWindowInsets(android.view.View, android.support.v4.view.WindowInsetsCompat);
+    method public static deprecated void onInitializeAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public static void onInitializeAccessibilityNodeInfo(android.view.View, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public static deprecated void onPopulateAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public static boolean performAccessibilityAction(android.view.View, int, android.os.Bundle);
+    method public static void postInvalidateOnAnimation(android.view.View);
+    method public static void postInvalidateOnAnimation(android.view.View, int, int, int, int);
+    method public static void postOnAnimation(android.view.View, java.lang.Runnable);
+    method public static void postOnAnimationDelayed(android.view.View, java.lang.Runnable, long);
+    method public static void requestApplyInsets(android.view.View);
+    method public static deprecated int resolveSizeAndState(int, int, int);
+    method public static boolean restoreDefaultFocus(android.view.View);
+    method public static void setAccessibilityDelegate(android.view.View, android.support.v4.view.AccessibilityDelegateCompat);
+    method public static void setAccessibilityLiveRegion(android.view.View, int);
+    method public static deprecated void setActivated(android.view.View, boolean);
+    method public static deprecated void setAlpha(android.view.View, float);
+    method public static void setBackground(android.view.View, android.graphics.drawable.Drawable);
+    method public static void setBackgroundTintList(android.view.View, android.content.res.ColorStateList);
+    method public static void setBackgroundTintMode(android.view.View, android.graphics.PorterDuff.Mode);
+    method public static void setChildrenDrawingOrderEnabled(android.view.ViewGroup, boolean);
+    method public static void setClipBounds(android.view.View, android.graphics.Rect);
+    method public static void setElevation(android.view.View, float);
+    method public static deprecated void setFitsSystemWindows(android.view.View, boolean);
+    method public static void setFocusedByDefault(android.view.View, boolean);
+    method public static void setHasTransientState(android.view.View, boolean);
+    method public static void setImportantForAccessibility(android.view.View, int);
+    method public static void setKeyboardNavigationCluster(android.view.View, boolean);
+    method public static void setLabelFor(android.view.View, int);
+    method public static void setLayerPaint(android.view.View, android.graphics.Paint);
+    method public static deprecated void setLayerType(android.view.View, int, android.graphics.Paint);
+    method public static void setLayoutDirection(android.view.View, int);
+    method public static void setNestedScrollingEnabled(android.view.View, boolean);
+    method public static void setNextClusterForwardId(android.view.View, int);
+    method public static void setOnApplyWindowInsetsListener(android.view.View, android.support.v4.view.OnApplyWindowInsetsListener);
+    method public static deprecated void setOverScrollMode(android.view.View, int);
+    method public static void setPaddingRelative(android.view.View, int, int, int, int);
+    method public static deprecated void setPivotX(android.view.View, float);
+    method public static deprecated void setPivotY(android.view.View, float);
+    method public static void setPointerIcon(android.view.View, android.support.v4.view.PointerIconCompat);
+    method public static deprecated void setRotation(android.view.View, float);
+    method public static deprecated void setRotationX(android.view.View, float);
+    method public static deprecated void setRotationY(android.view.View, float);
+    method public static deprecated void setSaveFromParentEnabled(android.view.View, boolean);
+    method public static deprecated void setScaleX(android.view.View, float);
+    method public static deprecated void setScaleY(android.view.View, float);
+    method public static void setScrollIndicators(android.view.View, int);
+    method public static void setScrollIndicators(android.view.View, int, int);
+    method public static void setTooltipText(android.view.View, java.lang.CharSequence);
+    method public static void setTransitionName(android.view.View, java.lang.String);
+    method public static deprecated void setTranslationX(android.view.View, float);
+    method public static deprecated void setTranslationY(android.view.View, float);
+    method public static void setTranslationZ(android.view.View, float);
+    method public static deprecated void setX(android.view.View, float);
+    method public static deprecated void setY(android.view.View, float);
+    method public static void setZ(android.view.View, float);
+    method public static boolean startDragAndDrop(android.view.View, android.content.ClipData, android.view.View.DragShadowBuilder, java.lang.Object, int);
+    method public static boolean startNestedScroll(android.view.View, int);
+    method public static boolean startNestedScroll(android.view.View, int, int);
+    method public static void stopNestedScroll(android.view.View);
+    method public static void stopNestedScroll(android.view.View, int);
+    method public static void updateDragShadow(android.view.View, android.view.View.DragShadowBuilder);
+    field public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 2; // 0x2
+    field public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0; // 0x0
+    field public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 1; // 0x1
+    field public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0; // 0x0
+    field public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 2; // 0x2
+    field public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 4; // 0x4
+    field public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 1; // 0x1
+    field public static final deprecated int LAYER_TYPE_HARDWARE = 2; // 0x2
+    field public static final deprecated int LAYER_TYPE_NONE = 0; // 0x0
+    field public static final deprecated int LAYER_TYPE_SOFTWARE = 1; // 0x1
+    field public static final int LAYOUT_DIRECTION_INHERIT = 2; // 0x2
+    field public static final int LAYOUT_DIRECTION_LOCALE = 3; // 0x3
+    field public static final int LAYOUT_DIRECTION_LTR = 0; // 0x0
+    field public static final int LAYOUT_DIRECTION_RTL = 1; // 0x1
+    field public static final deprecated int MEASURED_HEIGHT_STATE_SHIFT = 16; // 0x10
+    field public static final deprecated int MEASURED_SIZE_MASK = 16777215; // 0xffffff
+    field public static final deprecated int MEASURED_STATE_MASK = -16777216; // 0xff000000
+    field public static final deprecated int MEASURED_STATE_TOO_SMALL = 16777216; // 0x1000000
+    field public static final deprecated int OVER_SCROLL_ALWAYS = 0; // 0x0
+    field public static final deprecated int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; // 0x1
+    field public static final deprecated int OVER_SCROLL_NEVER = 2; // 0x2
+    field public static final int SCROLL_AXIS_HORIZONTAL = 1; // 0x1
+    field public static final int SCROLL_AXIS_NONE = 0; // 0x0
+    field public static final int SCROLL_AXIS_VERTICAL = 2; // 0x2
+    field public static final int SCROLL_INDICATOR_BOTTOM = 2; // 0x2
+    field public static final int SCROLL_INDICATOR_END = 32; // 0x20
+    field public static final int SCROLL_INDICATOR_LEFT = 4; // 0x4
+    field public static final int SCROLL_INDICATOR_RIGHT = 8; // 0x8
+    field public static final int SCROLL_INDICATOR_START = 16; // 0x10
+    field public static final int SCROLL_INDICATOR_TOP = 1; // 0x1
+    field public static final int TYPE_NON_TOUCH = 1; // 0x1
+    field public static final int TYPE_TOUCH = 0; // 0x0
+  }
+
+  public final deprecated class ViewConfigurationCompat {
+    method public static float getScaledHorizontalScrollFactor(android.view.ViewConfiguration, android.content.Context);
+    method public static deprecated int getScaledPagingTouchSlop(android.view.ViewConfiguration);
+    method public static float getScaledVerticalScrollFactor(android.view.ViewConfiguration, android.content.Context);
+    method public static deprecated boolean hasPermanentMenuKey(android.view.ViewConfiguration);
+  }
+
+  public final class ViewGroupCompat {
+    method public static int getLayoutMode(android.view.ViewGroup);
+    method public static int getNestedScrollAxes(android.view.ViewGroup);
+    method public static boolean isTransitionGroup(android.view.ViewGroup);
+    method public static deprecated boolean onRequestSendAccessibilityEvent(android.view.ViewGroup, android.view.View, android.view.accessibility.AccessibilityEvent);
+    method public static void setLayoutMode(android.view.ViewGroup, int);
+    method public static deprecated void setMotionEventSplittingEnabled(android.view.ViewGroup, boolean);
+    method public static void setTransitionGroup(android.view.ViewGroup, boolean);
+    field public static final int LAYOUT_MODE_CLIP_BOUNDS = 0; // 0x0
+    field public static final int LAYOUT_MODE_OPTICAL_BOUNDS = 1; // 0x1
+  }
+
+  public class ViewPager extends android.view.ViewGroup {
+    ctor public ViewPager(android.content.Context);
+    ctor public ViewPager(android.content.Context, android.util.AttributeSet);
+    method public void addOnAdapterChangeListener(android.support.v4.view.ViewPager.OnAdapterChangeListener);
+    method public void addOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener);
+    method public boolean arrowScroll(int);
+    method public boolean beginFakeDrag();
+    method protected boolean canScroll(android.view.View, boolean, int, int, int);
+    method public void clearOnPageChangeListeners();
+    method public void endFakeDrag();
+    method public boolean executeKeyEvent(android.view.KeyEvent);
+    method public void fakeDragBy(float);
+    method public android.support.v4.view.PagerAdapter getAdapter();
+    method public int getCurrentItem();
+    method public int getOffscreenPageLimit();
+    method public int getPageMargin();
+    method public boolean isFakeDragging();
+    method protected void onLayout(boolean, int, int, int, int);
+    method protected void onPageScrolled(int, float, int);
+    method public void onRestoreInstanceState(android.os.Parcelable);
+    method public android.os.Parcelable onSaveInstanceState();
+    method public void removeOnAdapterChangeListener(android.support.v4.view.ViewPager.OnAdapterChangeListener);
+    method public void removeOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener);
+    method public void setAdapter(android.support.v4.view.PagerAdapter);
+    method public void setCurrentItem(int);
+    method public void setCurrentItem(int, boolean);
+    method public void setOffscreenPageLimit(int);
+    method public deprecated void setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener);
+    method public void setPageMargin(int);
+    method public void setPageMarginDrawable(android.graphics.drawable.Drawable);
+    method public void setPageMarginDrawable(int);
+    method public void setPageTransformer(boolean, android.support.v4.view.ViewPager.PageTransformer);
+    method public void setPageTransformer(boolean, android.support.v4.view.ViewPager.PageTransformer, int);
+    field public static final int SCROLL_STATE_DRAGGING = 1; // 0x1
+    field public static final int SCROLL_STATE_IDLE = 0; // 0x0
+    field public static final int SCROLL_STATE_SETTLING = 2; // 0x2
+  }
+
+  public static abstract class ViewPager.DecorView implements java.lang.annotation.Annotation {
+  }
+
+  public static class ViewPager.LayoutParams extends android.view.ViewGroup.LayoutParams {
+    ctor public ViewPager.LayoutParams();
+    ctor public ViewPager.LayoutParams(android.content.Context, android.util.AttributeSet);
+    field public int gravity;
+    field public boolean isDecor;
+  }
+
+  public static abstract interface ViewPager.OnAdapterChangeListener {
+    method public abstract void onAdapterChanged(android.support.v4.view.ViewPager, android.support.v4.view.PagerAdapter, android.support.v4.view.PagerAdapter);
+  }
+
+  public static abstract interface ViewPager.OnPageChangeListener {
+    method public abstract void onPageScrollStateChanged(int);
+    method public abstract void onPageScrolled(int, float, int);
+    method public abstract void onPageSelected(int);
+  }
+
+  public static abstract interface ViewPager.PageTransformer {
+    method public abstract void transformPage(android.view.View, float);
+  }
+
+  public static class ViewPager.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public ViewPager.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.v4.view.ViewPager.SavedState> CREATOR;
+  }
+
+  public static class ViewPager.SimpleOnPageChangeListener implements android.support.v4.view.ViewPager.OnPageChangeListener {
+    ctor public ViewPager.SimpleOnPageChangeListener();
+    method public void onPageScrollStateChanged(int);
+    method public void onPageScrolled(int, float, int);
+    method public void onPageSelected(int);
+  }
+
+  public final class ViewParentCompat {
+    method public static void notifySubtreeAccessibilityStateChanged(android.view.ViewParent, android.view.View, android.view.View, int);
+    method public static boolean onNestedFling(android.view.ViewParent, android.view.View, float, float, boolean);
+    method public static boolean onNestedPreFling(android.view.ViewParent, android.view.View, float, float);
+    method public static void onNestedPreScroll(android.view.ViewParent, android.view.View, int, int, int[]);
+    method public static void onNestedPreScroll(android.view.ViewParent, android.view.View, int, int, int[], int);
+    method public static void onNestedScroll(android.view.ViewParent, android.view.View, int, int, int, int);
+    method public static void onNestedScroll(android.view.ViewParent, android.view.View, int, int, int, int, int);
+    method public static void onNestedScrollAccepted(android.view.ViewParent, android.view.View, android.view.View, int);
+    method public static void onNestedScrollAccepted(android.view.ViewParent, android.view.View, android.view.View, int, int);
+    method public static boolean onStartNestedScroll(android.view.ViewParent, android.view.View, android.view.View, int);
+    method public static boolean onStartNestedScroll(android.view.ViewParent, android.view.View, android.view.View, int, int);
+    method public static void onStopNestedScroll(android.view.ViewParent, android.view.View);
+    method public static void onStopNestedScroll(android.view.ViewParent, android.view.View, int);
+    method public static deprecated boolean requestSendAccessibilityEvent(android.view.ViewParent, android.view.View, android.view.accessibility.AccessibilityEvent);
+  }
+
+  public final class ViewPropertyAnimatorCompat {
+    method public android.support.v4.view.ViewPropertyAnimatorCompat alpha(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat alphaBy(float);
+    method public void cancel();
+    method public long getDuration();
+    method public android.view.animation.Interpolator getInterpolator();
+    method public long getStartDelay();
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotation(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotationBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotationX(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotationXBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotationY(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat rotationYBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat scaleX(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat scaleXBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat scaleY(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat scaleYBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat setDuration(long);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat setInterpolator(android.view.animation.Interpolator);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat setListener(android.support.v4.view.ViewPropertyAnimatorListener);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat setStartDelay(long);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat setUpdateListener(android.support.v4.view.ViewPropertyAnimatorUpdateListener);
+    method public void start();
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationX(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationXBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationY(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationYBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationZ(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat translationZBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat withEndAction(java.lang.Runnable);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat withLayer();
+    method public android.support.v4.view.ViewPropertyAnimatorCompat withStartAction(java.lang.Runnable);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat x(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat xBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat y(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat yBy(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat z(float);
+    method public android.support.v4.view.ViewPropertyAnimatorCompat zBy(float);
+  }
+
+  public abstract interface ViewPropertyAnimatorListener {
+    method public abstract void onAnimationCancel(android.view.View);
+    method public abstract void onAnimationEnd(android.view.View);
+    method public abstract void onAnimationStart(android.view.View);
+  }
+
+  public class ViewPropertyAnimatorListenerAdapter implements android.support.v4.view.ViewPropertyAnimatorListener {
+    ctor public ViewPropertyAnimatorListenerAdapter();
+    method public void onAnimationCancel(android.view.View);
+    method public void onAnimationEnd(android.view.View);
+    method public void onAnimationStart(android.view.View);
+  }
+
+  public abstract interface ViewPropertyAnimatorUpdateListener {
+    method public abstract void onAnimationUpdate(android.view.View);
+  }
+
+  public final class WindowCompat {
+    field public static final int FEATURE_ACTION_BAR = 8; // 0x8
+    field public static final int FEATURE_ACTION_BAR_OVERLAY = 9; // 0x9
+    field public static final int FEATURE_ACTION_MODE_OVERLAY = 10; // 0xa
+  }
+
+  public class WindowInsetsCompat {
+    ctor public WindowInsetsCompat(android.support.v4.view.WindowInsetsCompat);
+    method public android.support.v4.view.WindowInsetsCompat consumeStableInsets();
+    method public android.support.v4.view.WindowInsetsCompat consumeSystemWindowInsets();
+    method public int getStableInsetBottom();
+    method public int getStableInsetLeft();
+    method public int getStableInsetRight();
+    method public int getStableInsetTop();
+    method public int getSystemWindowInsetBottom();
+    method public int getSystemWindowInsetLeft();
+    method public int getSystemWindowInsetRight();
+    method public int getSystemWindowInsetTop();
+    method public boolean hasInsets();
+    method public boolean hasStableInsets();
+    method public boolean hasSystemWindowInsets();
+    method public boolean isConsumed();
+    method public boolean isRound();
+    method public android.support.v4.view.WindowInsetsCompat replaceSystemWindowInsets(int, int, int, int);
+    method public android.support.v4.view.WindowInsetsCompat replaceSystemWindowInsets(android.graphics.Rect);
+  }
+
+}
+
+package android.support.v4.view.accessibility {
+
+  public final class AccessibilityEventCompat {
+    method public static deprecated void appendRecord(android.view.accessibility.AccessibilityEvent, android.support.v4.view.accessibility.AccessibilityRecordCompat);
+    method public static deprecated android.support.v4.view.accessibility.AccessibilityRecordCompat asRecord(android.view.accessibility.AccessibilityEvent);
+    method public int getAction(android.view.accessibility.AccessibilityEvent);
+    method public static int getContentChangeTypes(android.view.accessibility.AccessibilityEvent);
+    method public int getMovementGranularity(android.view.accessibility.AccessibilityEvent);
+    method public static deprecated android.support.v4.view.accessibility.AccessibilityRecordCompat getRecord(android.view.accessibility.AccessibilityEvent, int);
+    method public static deprecated int getRecordCount(android.view.accessibility.AccessibilityEvent);
+    method public void setAction(android.view.accessibility.AccessibilityEvent, int);
+    method public static void setContentChangeTypes(android.view.accessibility.AccessibilityEvent, int);
+    method public void setMovementGranularity(android.view.accessibility.AccessibilityEvent, int);
+    field public static final int CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION = 4; // 0x4
+    field public static final int CONTENT_CHANGE_TYPE_SUBTREE = 1; // 0x1
+    field public static final int CONTENT_CHANGE_TYPE_TEXT = 2; // 0x2
+    field public static final int CONTENT_CHANGE_TYPE_UNDEFINED = 0; // 0x0
+    field public static final int TYPES_ALL_MASK = -1; // 0xffffffff
+    field public static final int TYPE_ANNOUNCEMENT = 16384; // 0x4000
+    field public static final int TYPE_ASSIST_READING_CONTEXT = 16777216; // 0x1000000
+    field public static final int TYPE_GESTURE_DETECTION_END = 524288; // 0x80000
+    field public static final int TYPE_GESTURE_DETECTION_START = 262144; // 0x40000
+    field public static final deprecated int TYPE_TOUCH_EXPLORATION_GESTURE_END = 1024; // 0x400
+    field public static final deprecated int TYPE_TOUCH_EXPLORATION_GESTURE_START = 512; // 0x200
+    field public static final int TYPE_TOUCH_INTERACTION_END = 2097152; // 0x200000
+    field public static final int TYPE_TOUCH_INTERACTION_START = 1048576; // 0x100000
+    field public static final int TYPE_VIEW_ACCESSIBILITY_FOCUSED = 32768; // 0x8000
+    field public static final int TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED = 65536; // 0x10000
+    field public static final int TYPE_VIEW_CONTEXT_CLICKED = 8388608; // 0x800000
+    field public static final deprecated int TYPE_VIEW_HOVER_ENTER = 128; // 0x80
+    field public static final deprecated int TYPE_VIEW_HOVER_EXIT = 256; // 0x100
+    field public static final deprecated int TYPE_VIEW_SCROLLED = 4096; // 0x1000
+    field public static final deprecated int TYPE_VIEW_TEXT_SELECTION_CHANGED = 8192; // 0x2000
+    field public static final int TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY = 131072; // 0x20000
+    field public static final int TYPE_WINDOWS_CHANGED = 4194304; // 0x400000
+    field public static final deprecated int TYPE_WINDOW_CONTENT_CHANGED = 2048; // 0x800
+  }
+
+  public final class AccessibilityManagerCompat {
+    method public static deprecated boolean addAccessibilityStateChangeListener(android.view.accessibility.AccessibilityManager, android.support.v4.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener);
+    method public static boolean addTouchExplorationStateChangeListener(android.view.accessibility.AccessibilityManager, android.support.v4.view.accessibility.AccessibilityManagerCompat.TouchExplorationStateChangeListener);
+    method public static deprecated java.util.List<android.accessibilityservice.AccessibilityServiceInfo> getEnabledAccessibilityServiceList(android.view.accessibility.AccessibilityManager, int);
+    method public static deprecated java.util.List<android.accessibilityservice.AccessibilityServiceInfo> getInstalledAccessibilityServiceList(android.view.accessibility.AccessibilityManager);
+    method public static deprecated boolean isTouchExplorationEnabled(android.view.accessibility.AccessibilityManager);
+    method public static deprecated boolean removeAccessibilityStateChangeListener(android.view.accessibility.AccessibilityManager, android.support.v4.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener);
+    method public static boolean removeTouchExplorationStateChangeListener(android.view.accessibility.AccessibilityManager, android.support.v4.view.accessibility.AccessibilityManagerCompat.TouchExplorationStateChangeListener);
+  }
+
+  public static abstract deprecated interface AccessibilityManagerCompat.AccessibilityStateChangeListener {
+    method public abstract deprecated void onAccessibilityStateChanged(boolean);
+  }
+
+  public static abstract deprecated class AccessibilityManagerCompat.AccessibilityStateChangeListenerCompat implements android.support.v4.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener {
+    ctor public AccessibilityManagerCompat.AccessibilityStateChangeListenerCompat();
+  }
+
+  public static abstract interface AccessibilityManagerCompat.TouchExplorationStateChangeListener {
+    method public abstract void onTouchExplorationStateChanged(boolean);
+  }
+
+  public class AccessibilityNodeInfoCompat {
+    ctor public deprecated AccessibilityNodeInfoCompat(java.lang.Object);
+    method public void addAction(int);
+    method public void addAction(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat);
+    method public void addChild(android.view.View);
+    method public void addChild(android.view.View, int);
+    method public boolean canOpenPopup();
+    method public java.util.List<android.support.v4.view.accessibility.AccessibilityNodeInfoCompat> findAccessibilityNodeInfosByText(java.lang.String);
+    method public java.util.List<android.support.v4.view.accessibility.AccessibilityNodeInfoCompat> findAccessibilityNodeInfosByViewId(java.lang.String);
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat findFocus(int);
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat focusSearch(int);
+    method public java.util.List<android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat> getActionList();
+    method public int getActions();
+    method public void getBoundsInParent(android.graphics.Rect);
+    method public void getBoundsInScreen(android.graphics.Rect);
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getChild(int);
+    method public int getChildCount();
+    method public java.lang.CharSequence getClassName();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat getCollectionInfo();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat getCollectionItemInfo();
+    method public java.lang.CharSequence getContentDescription();
+    method public int getDrawingOrder();
+    method public java.lang.CharSequence getError();
+    method public android.os.Bundle getExtras();
+    method public deprecated java.lang.Object getInfo();
+    method public int getInputType();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getLabelFor();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getLabeledBy();
+    method public int getLiveRegion();
+    method public int getMaxTextLength();
+    method public int getMovementGranularities();
+    method public java.lang.CharSequence getPackageName();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getParent();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat getRangeInfo();
+    method public java.lang.CharSequence getRoleDescription();
+    method public java.lang.CharSequence getText();
+    method public int getTextSelectionEnd();
+    method public int getTextSelectionStart();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getTraversalAfter();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getTraversalBefore();
+    method public java.lang.String getViewIdResourceName();
+    method public android.support.v4.view.accessibility.AccessibilityWindowInfoCompat getWindow();
+    method public int getWindowId();
+    method public boolean isAccessibilityFocused();
+    method public boolean isCheckable();
+    method public boolean isChecked();
+    method public boolean isClickable();
+    method public boolean isContentInvalid();
+    method public boolean isContextClickable();
+    method public boolean isDismissable();
+    method public boolean isEditable();
+    method public boolean isEnabled();
+    method public boolean isFocusable();
+    method public boolean isFocused();
+    method public boolean isImportantForAccessibility();
+    method public boolean isLongClickable();
+    method public boolean isMultiLine();
+    method public boolean isPassword();
+    method public boolean isScrollable();
+    method public boolean isSelected();
+    method public boolean isVisibleToUser();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat obtain(android.view.View);
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat obtain(android.view.View, int);
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat obtain();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat obtain(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public boolean performAction(int);
+    method public boolean performAction(int, android.os.Bundle);
+    method public void recycle();
+    method public boolean refresh();
+    method public boolean removeAction(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat);
+    method public boolean removeChild(android.view.View);
+    method public boolean removeChild(android.view.View, int);
+    method public void setAccessibilityFocused(boolean);
+    method public void setBoundsInParent(android.graphics.Rect);
+    method public void setBoundsInScreen(android.graphics.Rect);
+    method public void setCanOpenPopup(boolean);
+    method public void setCheckable(boolean);
+    method public void setChecked(boolean);
+    method public void setClassName(java.lang.CharSequence);
+    method public void setClickable(boolean);
+    method public void setCollectionInfo(java.lang.Object);
+    method public void setCollectionItemInfo(java.lang.Object);
+    method public void setContentDescription(java.lang.CharSequence);
+    method public void setContentInvalid(boolean);
+    method public void setContextClickable(boolean);
+    method public void setDismissable(boolean);
+    method public void setDrawingOrder(int);
+    method public void setEditable(boolean);
+    method public void setEnabled(boolean);
+    method public void setError(java.lang.CharSequence);
+    method public void setFocusable(boolean);
+    method public void setFocused(boolean);
+    method public void setImportantForAccessibility(boolean);
+    method public void setInputType(int);
+    method public void setLabelFor(android.view.View);
+    method public void setLabelFor(android.view.View, int);
+    method public void setLabeledBy(android.view.View);
+    method public void setLabeledBy(android.view.View, int);
+    method public void setLiveRegion(int);
+    method public void setLongClickable(boolean);
+    method public void setMaxTextLength(int);
+    method public void setMovementGranularities(int);
+    method public void setMultiLine(boolean);
+    method public void setPackageName(java.lang.CharSequence);
+    method public void setParent(android.view.View);
+    method public void setParent(android.view.View, int);
+    method public void setPassword(boolean);
+    method public void setRangeInfo(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat);
+    method public void setRoleDescription(java.lang.CharSequence);
+    method public void setScrollable(boolean);
+    method public void setSelected(boolean);
+    method public void setSource(android.view.View);
+    method public void setSource(android.view.View, int);
+    method public void setText(java.lang.CharSequence);
+    method public void setTextSelection(int, int);
+    method public void setTraversalAfter(android.view.View);
+    method public void setTraversalAfter(android.view.View, int);
+    method public void setTraversalBefore(android.view.View);
+    method public void setTraversalBefore(android.view.View, int);
+    method public void setViewIdResourceName(java.lang.String);
+    method public void setVisibleToUser(boolean);
+    method public android.view.accessibility.AccessibilityNodeInfo unwrap();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat wrap(android.view.accessibility.AccessibilityNodeInfo);
+    field public static final int ACTION_ACCESSIBILITY_FOCUS = 64; // 0x40
+    field public static final java.lang.String ACTION_ARGUMENT_COLUMN_INT = "android.view.accessibility.action.ARGUMENT_COLUMN_INT";
+    field public static final java.lang.String ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN = "ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN";
+    field public static final java.lang.String ACTION_ARGUMENT_HTML_ELEMENT_STRING = "ACTION_ARGUMENT_HTML_ELEMENT_STRING";
+    field public static final java.lang.String ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT = "ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT";
+    field public static final java.lang.String ACTION_ARGUMENT_PROGRESS_VALUE = "android.view.accessibility.action.ARGUMENT_PROGRESS_VALUE";
+    field public static final java.lang.String ACTION_ARGUMENT_ROW_INT = "android.view.accessibility.action.ARGUMENT_ROW_INT";
+    field public static final java.lang.String ACTION_ARGUMENT_SELECTION_END_INT = "ACTION_ARGUMENT_SELECTION_END_INT";
+    field public static final java.lang.String ACTION_ARGUMENT_SELECTION_START_INT = "ACTION_ARGUMENT_SELECTION_START_INT";
+    field public static final java.lang.String ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE = "ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE";
+    field public static final int ACTION_CLEAR_ACCESSIBILITY_FOCUS = 128; // 0x80
+    field public static final int ACTION_CLEAR_FOCUS = 2; // 0x2
+    field public static final int ACTION_CLEAR_SELECTION = 8; // 0x8
+    field public static final int ACTION_CLICK = 16; // 0x10
+    field public static final int ACTION_COLLAPSE = 524288; // 0x80000
+    field public static final int ACTION_COPY = 16384; // 0x4000
+    field public static final int ACTION_CUT = 65536; // 0x10000
+    field public static final int ACTION_DISMISS = 1048576; // 0x100000
+    field public static final int ACTION_EXPAND = 262144; // 0x40000
+    field public static final int ACTION_FOCUS = 1; // 0x1
+    field public static final int ACTION_LONG_CLICK = 32; // 0x20
+    field public static final int ACTION_NEXT_AT_MOVEMENT_GRANULARITY = 256; // 0x100
+    field public static final int ACTION_NEXT_HTML_ELEMENT = 1024; // 0x400
+    field public static final int ACTION_PASTE = 32768; // 0x8000
+    field public static final int ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY = 512; // 0x200
+    field public static final int ACTION_PREVIOUS_HTML_ELEMENT = 2048; // 0x800
+    field public static final int ACTION_SCROLL_BACKWARD = 8192; // 0x2000
+    field public static final int ACTION_SCROLL_FORWARD = 4096; // 0x1000
+    field public static final int ACTION_SELECT = 4; // 0x4
+    field public static final int ACTION_SET_SELECTION = 131072; // 0x20000
+    field public static final int ACTION_SET_TEXT = 2097152; // 0x200000
+    field public static final int FOCUS_ACCESSIBILITY = 2; // 0x2
+    field public static final int FOCUS_INPUT = 1; // 0x1
+    field public static final int MOVEMENT_GRANULARITY_CHARACTER = 1; // 0x1
+    field public static final int MOVEMENT_GRANULARITY_LINE = 4; // 0x4
+    field public static final int MOVEMENT_GRANULARITY_PAGE = 16; // 0x10
+    field public static final int MOVEMENT_GRANULARITY_PARAGRAPH = 8; // 0x8
+    field public static final int MOVEMENT_GRANULARITY_WORD = 2; // 0x2
+  }
+
+  public static class AccessibilityNodeInfoCompat.AccessibilityActionCompat {
+    ctor public AccessibilityNodeInfoCompat.AccessibilityActionCompat(int, java.lang.CharSequence);
+    method public int getId();
+    method public java.lang.CharSequence getLabel();
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_ACCESSIBILITY_FOCUS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CLEAR_ACCESSIBILITY_FOCUS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CLEAR_FOCUS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CLEAR_SELECTION;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CLICK;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_COLLAPSE;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CONTEXT_CLICK;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_COPY;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_CUT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_DISMISS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_EXPAND;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_FOCUS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_LONG_CLICK;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_NEXT_AT_MOVEMENT_GRANULARITY;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_NEXT_HTML_ELEMENT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_PASTE;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_PREVIOUS_HTML_ELEMENT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_BACKWARD;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_DOWN;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_FORWARD;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_LEFT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_RIGHT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_TO_POSITION;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SCROLL_UP;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SELECT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SET_PROGRESS;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SET_SELECTION;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SET_TEXT;
+    field public static final android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat ACTION_SHOW_ON_SCREEN;
+  }
+
+  public static class AccessibilityNodeInfoCompat.CollectionInfoCompat {
+    method public int getColumnCount();
+    method public int getRowCount();
+    method public int getSelectionMode();
+    method public boolean isHierarchical();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat obtain(int, int, boolean, int);
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat obtain(int, int, boolean);
+    field public static final int SELECTION_MODE_MULTIPLE = 2; // 0x2
+    field public static final int SELECTION_MODE_NONE = 0; // 0x0
+    field public static final int SELECTION_MODE_SINGLE = 1; // 0x1
+  }
+
+  public static class AccessibilityNodeInfoCompat.CollectionItemInfoCompat {
+    method public int getColumnIndex();
+    method public int getColumnSpan();
+    method public int getRowIndex();
+    method public int getRowSpan();
+    method public boolean isHeading();
+    method public boolean isSelected();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat obtain(int, int, int, int, boolean, boolean);
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat obtain(int, int, int, int, boolean);
+  }
+
+  public static class AccessibilityNodeInfoCompat.RangeInfoCompat {
+    method public float getCurrent();
+    method public float getMax();
+    method public float getMin();
+    method public int getType();
+    method public static android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat obtain(int, float, float, float);
+    field public static final int RANGE_TYPE_FLOAT = 1; // 0x1
+    field public static final int RANGE_TYPE_INT = 0; // 0x0
+    field public static final int RANGE_TYPE_PERCENT = 2; // 0x2
+  }
+
+  public class AccessibilityNodeProviderCompat {
+    ctor public AccessibilityNodeProviderCompat();
+    ctor public AccessibilityNodeProviderCompat(java.lang.Object);
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat createAccessibilityNodeInfo(int);
+    method public java.util.List<android.support.v4.view.accessibility.AccessibilityNodeInfoCompat> findAccessibilityNodeInfosByText(java.lang.String, int);
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat findFocus(int);
+    method public java.lang.Object getProvider();
+    method public boolean performAction(int, int, android.os.Bundle);
+    field public static final int HOST_VIEW_ID = -1; // 0xffffffff
+  }
+
+  public class AccessibilityRecordCompat {
+    ctor public deprecated AccessibilityRecordCompat(java.lang.Object);
+    method public deprecated boolean equals(java.lang.Object);
+    method public deprecated int getAddedCount();
+    method public deprecated java.lang.CharSequence getBeforeText();
+    method public deprecated java.lang.CharSequence getClassName();
+    method public deprecated java.lang.CharSequence getContentDescription();
+    method public deprecated int getCurrentItemIndex();
+    method public deprecated int getFromIndex();
+    method public deprecated java.lang.Object getImpl();
+    method public deprecated int getItemCount();
+    method public deprecated int getMaxScrollX();
+    method public static int getMaxScrollX(android.view.accessibility.AccessibilityRecord);
+    method public deprecated int getMaxScrollY();
+    method public static int getMaxScrollY(android.view.accessibility.AccessibilityRecord);
+    method public deprecated android.os.Parcelable getParcelableData();
+    method public deprecated int getRemovedCount();
+    method public deprecated int getScrollX();
+    method public deprecated int getScrollY();
+    method public deprecated android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getSource();
+    method public deprecated java.util.List<java.lang.CharSequence> getText();
+    method public deprecated int getToIndex();
+    method public deprecated int getWindowId();
+    method public deprecated int hashCode();
+    method public deprecated boolean isChecked();
+    method public deprecated boolean isEnabled();
+    method public deprecated boolean isFullScreen();
+    method public deprecated boolean isPassword();
+    method public deprecated boolean isScrollable();
+    method public static deprecated android.support.v4.view.accessibility.AccessibilityRecordCompat obtain(android.support.v4.view.accessibility.AccessibilityRecordCompat);
+    method public static deprecated android.support.v4.view.accessibility.AccessibilityRecordCompat obtain();
+    method public deprecated void recycle();
+    method public deprecated void setAddedCount(int);
+    method public deprecated void setBeforeText(java.lang.CharSequence);
+    method public deprecated void setChecked(boolean);
+    method public deprecated void setClassName(java.lang.CharSequence);
+    method public deprecated void setContentDescription(java.lang.CharSequence);
+    method public deprecated void setCurrentItemIndex(int);
+    method public deprecated void setEnabled(boolean);
+    method public deprecated void setFromIndex(int);
+    method public deprecated void setFullScreen(boolean);
+    method public deprecated void setItemCount(int);
+    method public deprecated void setMaxScrollX(int);
+    method public static void setMaxScrollX(android.view.accessibility.AccessibilityRecord, int);
+    method public deprecated void setMaxScrollY(int);
+    method public static void setMaxScrollY(android.view.accessibility.AccessibilityRecord, int);
+    method public deprecated void setParcelableData(android.os.Parcelable);
+    method public deprecated void setPassword(boolean);
+    method public deprecated void setRemovedCount(int);
+    method public deprecated void setScrollX(int);
+    method public deprecated void setScrollY(int);
+    method public deprecated void setScrollable(boolean);
+    method public deprecated void setSource(android.view.View);
+    method public deprecated void setSource(android.view.View, int);
+    method public static void setSource(android.view.accessibility.AccessibilityRecord, android.view.View, int);
+    method public deprecated void setToIndex(int);
+  }
+
+  public class AccessibilityWindowInfoCompat {
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getAnchor();
+    method public void getBoundsInScreen(android.graphics.Rect);
+    method public android.support.v4.view.accessibility.AccessibilityWindowInfoCompat getChild(int);
+    method public int getChildCount();
+    method public int getId();
+    method public int getLayer();
+    method public android.support.v4.view.accessibility.AccessibilityWindowInfoCompat getParent();
+    method public android.support.v4.view.accessibility.AccessibilityNodeInfoCompat getRoot();
+    method public java.lang.CharSequence getTitle();
+    method public int getType();
+    method public boolean isAccessibilityFocused();
+    method public boolean isActive();
+    method public boolean isFocused();
+    method public static android.support.v4.view.accessibility.AccessibilityWindowInfoCompat obtain();
+    method public static android.support.v4.view.accessibility.AccessibilityWindowInfoCompat obtain(android.support.v4.view.accessibility.AccessibilityWindowInfoCompat);
+    method public void recycle();
+    field public static final int TYPE_ACCESSIBILITY_OVERLAY = 4; // 0x4
+    field public static final int TYPE_APPLICATION = 1; // 0x1
+    field public static final int TYPE_INPUT_METHOD = 2; // 0x2
+    field public static final int TYPE_SPLIT_SCREEN_DIVIDER = 5; // 0x5
+    field public static final int TYPE_SYSTEM = 3; // 0x3
+  }
+
+}
+
+package android.support.v4.view.animation {
+
+  public class FastOutLinearInInterpolator extends android.support.v4.view.animation.LookupTableInterpolator {
+    ctor public FastOutLinearInInterpolator();
+  }
+
+  public class FastOutSlowInInterpolator extends android.support.v4.view.animation.LookupTableInterpolator {
+    ctor public FastOutSlowInInterpolator();
+  }
+
+  public class LinearOutSlowInInterpolator extends android.support.v4.view.animation.LookupTableInterpolator {
+    ctor public LinearOutSlowInInterpolator();
+  }
+
+   abstract class LookupTableInterpolator implements android.view.animation.Interpolator {
+    ctor public LookupTableInterpolator(float[]);
+    method public float getInterpolation(float);
+  }
+
+  public final class PathInterpolatorCompat {
+    method public static android.view.animation.Interpolator create(android.graphics.Path);
+    method public static android.view.animation.Interpolator create(float, float);
+    method public static android.view.animation.Interpolator create(float, float, float, float);
+  }
+
+}
+
+package android.support.v4.widget {
+
+  public abstract class AutoScrollHelper implements android.view.View.OnTouchListener {
+    ctor public AutoScrollHelper(android.view.View);
+    method public abstract boolean canTargetScrollHorizontally(int);
+    method public abstract boolean canTargetScrollVertically(int);
+    method public boolean isEnabled();
+    method public boolean isExclusive();
+    method public boolean onTouch(android.view.View, android.view.MotionEvent);
+    method public abstract void scrollTargetBy(int, int);
+    method public android.support.v4.widget.AutoScrollHelper setActivationDelay(int);
+    method public android.support.v4.widget.AutoScrollHelper setEdgeType(int);
+    method public android.support.v4.widget.AutoScrollHelper setEnabled(boolean);
+    method public android.support.v4.widget.AutoScrollHelper setExclusive(boolean);
+    method public android.support.v4.widget.AutoScrollHelper setMaximumEdges(float, float);
+    method public android.support.v4.widget.AutoScrollHelper setMaximumVelocity(float, float);
+    method public android.support.v4.widget.AutoScrollHelper setMinimumVelocity(float, float);
+    method public android.support.v4.widget.AutoScrollHelper setRampDownDuration(int);
+    method public android.support.v4.widget.AutoScrollHelper setRampUpDuration(int);
+    method public android.support.v4.widget.AutoScrollHelper setRelativeEdges(float, float);
+    method public android.support.v4.widget.AutoScrollHelper setRelativeVelocity(float, float);
+    field public static final int EDGE_TYPE_INSIDE = 0; // 0x0
+    field public static final int EDGE_TYPE_INSIDE_EXTEND = 1; // 0x1
+    field public static final int EDGE_TYPE_OUTSIDE = 2; // 0x2
+    field public static final float NO_MAX = 3.4028235E38f;
+    field public static final float NO_MIN = 0.0f;
+    field public static final float RELATIVE_UNSPECIFIED = 0.0f;
+  }
+
+  public class CircularProgressDrawable extends android.graphics.drawable.Drawable {
+    ctor public CircularProgressDrawable(android.content.Context);
+    method public void draw(android.graphics.Canvas);
+    method public boolean getArrowEnabled();
+    method public float getArrowHeight();
+    method public float getArrowScale();
+    method public float getArrowWidth();
+    method public int getBackgroundColor();
+    method public float getCenterRadius();
+    method public int[] getColorSchemeColors();
+    method public float getEndTrim();
+    method public int getOpacity();
+    method public float getProgressRotation();
+    method public float getStartTrim();
+    method public android.graphics.Paint.Cap getStrokeCap();
+    method public float getStrokeWidth();
+    method public boolean isRunning();
+    method public void setAlpha(int);
+    method public void setArrowDimensions(float, float);
+    method public void setArrowEnabled(boolean);
+    method public void setArrowScale(float);
+    method public void setBackgroundColor(int);
+    method public void setCenterRadius(float);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setColorSchemeColors(int...);
+    method public void setProgressRotation(float);
+    method public void setStartEndTrim(float, float);
+    method public void setStrokeCap(android.graphics.Paint.Cap);
+    method public void setStrokeWidth(float);
+    method public void setStyle(int);
+    method public void start();
+    method public void stop();
+    field public static final int DEFAULT = 1; // 0x1
+    field public static final int LARGE = 0; // 0x0
+  }
+
+  public final class CompoundButtonCompat {
+    method public static android.graphics.drawable.Drawable getButtonDrawable(android.widget.CompoundButton);
+    method public static android.content.res.ColorStateList getButtonTintList(android.widget.CompoundButton);
+    method public static android.graphics.PorterDuff.Mode getButtonTintMode(android.widget.CompoundButton);
+    method public static void setButtonTintList(android.widget.CompoundButton, android.content.res.ColorStateList);
+    method public static void setButtonTintMode(android.widget.CompoundButton, android.graphics.PorterDuff.Mode);
+  }
+
+  public class ContentLoadingProgressBar extends android.widget.ProgressBar {
+    ctor public ContentLoadingProgressBar(android.content.Context);
+    ctor public ContentLoadingProgressBar(android.content.Context, android.util.AttributeSet);
+    method public void hide();
+    method public void onAttachedToWindow();
+    method public void onDetachedFromWindow();
+    method public void show();
+  }
+
+  public abstract class CursorAdapter extends android.widget.BaseAdapter {
+    ctor public deprecated CursorAdapter(android.content.Context, android.database.Cursor);
+    ctor public CursorAdapter(android.content.Context, android.database.Cursor, boolean);
+    ctor public CursorAdapter(android.content.Context, android.database.Cursor, int);
+    method public abstract void bindView(android.view.View, android.content.Context, android.database.Cursor);
+    method public void changeCursor(android.database.Cursor);
+    method public java.lang.CharSequence convertToString(android.database.Cursor);
+    method public int getCount();
+    method public android.database.Cursor getCursor();
+    method public android.widget.Filter getFilter();
+    method public android.widget.FilterQueryProvider getFilterQueryProvider();
+    method public java.lang.Object getItem(int);
+    method public long getItemId(int);
+    method public android.view.View getView(int, android.view.View, android.view.ViewGroup);
+    method protected deprecated void init(android.content.Context, android.database.Cursor, boolean);
+    method public android.view.View newDropDownView(android.content.Context, android.database.Cursor, android.view.ViewGroup);
+    method public abstract android.view.View newView(android.content.Context, android.database.Cursor, android.view.ViewGroup);
+    method protected void onContentChanged();
+    method public android.database.Cursor runQueryOnBackgroundThread(java.lang.CharSequence);
+    method public void setFilterQueryProvider(android.widget.FilterQueryProvider);
+    method public android.database.Cursor swapCursor(android.database.Cursor);
+    field public static final deprecated int FLAG_AUTO_REQUERY = 1; // 0x1
+    field public static final int FLAG_REGISTER_CONTENT_OBSERVER = 2; // 0x2
+  }
+
+  public class DrawerLayout extends android.view.ViewGroup {
+    ctor public DrawerLayout(android.content.Context);
+    ctor public DrawerLayout(android.content.Context, android.util.AttributeSet);
+    ctor public DrawerLayout(android.content.Context, android.util.AttributeSet, int);
+    method public void addDrawerListener(android.support.v4.widget.DrawerLayout.DrawerListener);
+    method public void closeDrawer(android.view.View);
+    method public void closeDrawer(android.view.View, boolean);
+    method public void closeDrawer(int);
+    method public void closeDrawer(int, boolean);
+    method public void closeDrawers();
+    method public float getDrawerElevation();
+    method public int getDrawerLockMode(int);
+    method public int getDrawerLockMode(android.view.View);
+    method public java.lang.CharSequence getDrawerTitle(int);
+    method public android.graphics.drawable.Drawable getStatusBarBackgroundDrawable();
+    method public boolean isDrawerOpen(android.view.View);
+    method public boolean isDrawerOpen(int);
+    method public boolean isDrawerVisible(android.view.View);
+    method public boolean isDrawerVisible(int);
+    method public void onDraw(android.graphics.Canvas);
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void openDrawer(android.view.View);
+    method public void openDrawer(android.view.View, boolean);
+    method public void openDrawer(int);
+    method public void openDrawer(int, boolean);
+    method public void removeDrawerListener(android.support.v4.widget.DrawerLayout.DrawerListener);
+    method public void setDrawerElevation(float);
+    method public deprecated void setDrawerListener(android.support.v4.widget.DrawerLayout.DrawerListener);
+    method public void setDrawerLockMode(int);
+    method public void setDrawerLockMode(int, int);
+    method public void setDrawerLockMode(int, android.view.View);
+    method public void setDrawerShadow(android.graphics.drawable.Drawable, int);
+    method public void setDrawerShadow(int, int);
+    method public void setDrawerTitle(int, java.lang.CharSequence);
+    method public void setScrimColor(int);
+    method public void setStatusBarBackground(android.graphics.drawable.Drawable);
+    method public void setStatusBarBackground(int);
+    method public void setStatusBarBackgroundColor(int);
+    field public static final int LOCK_MODE_LOCKED_CLOSED = 1; // 0x1
+    field public static final int LOCK_MODE_LOCKED_OPEN = 2; // 0x2
+    field public static final int LOCK_MODE_UNDEFINED = 3; // 0x3
+    field public static final int LOCK_MODE_UNLOCKED = 0; // 0x0
+    field public static final int STATE_DRAGGING = 1; // 0x1
+    field public static final int STATE_IDLE = 0; // 0x0
+    field public static final int STATE_SETTLING = 2; // 0x2
+  }
+
+  public static abstract interface DrawerLayout.DrawerListener {
+    method public abstract void onDrawerClosed(android.view.View);
+    method public abstract void onDrawerOpened(android.view.View);
+    method public abstract void onDrawerSlide(android.view.View, float);
+    method public abstract void onDrawerStateChanged(int);
+  }
+
+  public static class DrawerLayout.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public DrawerLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public DrawerLayout.LayoutParams(int, int);
+    ctor public DrawerLayout.LayoutParams(int, int, int);
+    ctor public DrawerLayout.LayoutParams(android.support.v4.widget.DrawerLayout.LayoutParams);
+    ctor public DrawerLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public DrawerLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    field public int gravity;
+  }
+
+  protected static class DrawerLayout.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public DrawerLayout.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public DrawerLayout.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.v4.widget.DrawerLayout.SavedState> CREATOR;
+  }
+
+  public static abstract class DrawerLayout.SimpleDrawerListener implements android.support.v4.widget.DrawerLayout.DrawerListener {
+    ctor public DrawerLayout.SimpleDrawerListener();
+    method public void onDrawerClosed(android.view.View);
+    method public void onDrawerOpened(android.view.View);
+    method public void onDrawerSlide(android.view.View, float);
+    method public void onDrawerStateChanged(int);
+  }
+
+  public final class EdgeEffectCompat {
+    ctor public deprecated EdgeEffectCompat(android.content.Context);
+    method public deprecated boolean draw(android.graphics.Canvas);
+    method public deprecated void finish();
+    method public deprecated boolean isFinished();
+    method public deprecated boolean onAbsorb(int);
+    method public deprecated boolean onPull(float);
+    method public deprecated boolean onPull(float, float);
+    method public static void onPull(android.widget.EdgeEffect, float, float);
+    method public deprecated boolean onRelease();
+    method public deprecated void setSize(int, int);
+  }
+
+  public abstract class ExploreByTouchHelper extends android.support.v4.view.AccessibilityDelegateCompat {
+    ctor public ExploreByTouchHelper(android.view.View);
+    method public final boolean clearKeyboardFocusForVirtualView(int);
+    method public final boolean dispatchHoverEvent(android.view.MotionEvent);
+    method public final boolean dispatchKeyEvent(android.view.KeyEvent);
+    method public final int getAccessibilityFocusedVirtualViewId();
+    method public deprecated int getFocusedVirtualView();
+    method public final int getKeyboardFocusedVirtualViewId();
+    method protected abstract int getVirtualViewAt(float, float);
+    method protected abstract void getVisibleVirtualViews(java.util.List<java.lang.Integer>);
+    method public final void invalidateRoot();
+    method public final void invalidateVirtualView(int);
+    method public final void invalidateVirtualView(int, int);
+    method public final void onFocusChanged(boolean, int, android.graphics.Rect);
+    method protected abstract boolean onPerformActionForVirtualView(int, int, android.os.Bundle);
+    method protected void onPopulateEventForHost(android.view.accessibility.AccessibilityEvent);
+    method protected void onPopulateEventForVirtualView(int, android.view.accessibility.AccessibilityEvent);
+    method protected void onPopulateNodeForHost(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method protected abstract void onPopulateNodeForVirtualView(int, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method protected void onVirtualViewKeyboardFocusChanged(int, boolean);
+    method public final boolean requestKeyboardFocusForVirtualView(int);
+    method public final boolean sendEventForVirtualView(int, int);
+    field public static final int HOST_ID = -1; // 0xffffffff
+    field public static final int INVALID_ID = -2147483648; // 0x80000000
+  }
+
+  public class ImageViewCompat {
+    method public static android.content.res.ColorStateList getImageTintList(android.widget.ImageView);
+    method public static android.graphics.PorterDuff.Mode getImageTintMode(android.widget.ImageView);
+    method public static void setImageTintList(android.widget.ImageView, android.content.res.ColorStateList);
+    method public static void setImageTintMode(android.widget.ImageView, android.graphics.PorterDuff.Mode);
+  }
+
+  public final class ListPopupWindowCompat {
+    method public static deprecated android.view.View.OnTouchListener createDragToOpenListener(java.lang.Object, android.view.View);
+    method public static android.view.View.OnTouchListener createDragToOpenListener(android.widget.ListPopupWindow, android.view.View);
+  }
+
+  public class ListViewAutoScrollHelper extends android.support.v4.widget.AutoScrollHelper {
+    ctor public ListViewAutoScrollHelper(android.widget.ListView);
+    method public boolean canTargetScrollHorizontally(int);
+    method public boolean canTargetScrollVertically(int);
+    method public void scrollTargetBy(int, int);
+  }
+
+  public final class ListViewCompat {
+    method public static boolean canScrollList(android.widget.ListView, int);
+    method public static void scrollListBy(android.widget.ListView, int);
+  }
+
+  public class NestedScrollView extends android.widget.FrameLayout implements android.support.v4.view.NestedScrollingChild2 android.support.v4.view.NestedScrollingParent android.support.v4.view.ScrollingView {
+    ctor public NestedScrollView(android.content.Context);
+    ctor public NestedScrollView(android.content.Context, android.util.AttributeSet);
+    ctor public NestedScrollView(android.content.Context, android.util.AttributeSet, int);
+    method public boolean arrowScroll(int);
+    method protected int computeScrollDeltaToGetChildRectOnScreen(android.graphics.Rect);
+    method public boolean dispatchNestedPreScroll(int, int, int[], int[], int);
+    method public boolean dispatchNestedScroll(int, int, int, int, int[], int);
+    method public boolean executeKeyEvent(android.view.KeyEvent);
+    method public void fling(int);
+    method public boolean fullScroll(int);
+    method public int getMaxScrollAmount();
+    method public boolean hasNestedScrollingParent(int);
+    method public boolean isFillViewport();
+    method public boolean isSmoothScrollingEnabled();
+    method public void onAttachedToWindow();
+    method public boolean pageScroll(int);
+    method public void setFillViewport(boolean);
+    method public void setOnScrollChangeListener(android.support.v4.widget.NestedScrollView.OnScrollChangeListener);
+    method public void setSmoothScrollingEnabled(boolean);
+    method public final void smoothScrollBy(int, int);
+    method public final void smoothScrollTo(int, int);
+    method public boolean startNestedScroll(int, int);
+    method public void stopNestedScroll(int);
+  }
+
+  public static abstract interface NestedScrollView.OnScrollChangeListener {
+    method public abstract void onScrollChange(android.support.v4.widget.NestedScrollView, int, int, int, int);
+  }
+
+  public final class PopupMenuCompat {
+    method public static android.view.View.OnTouchListener getDragToOpenListener(java.lang.Object);
+  }
+
+  public final class PopupWindowCompat {
+    method public static boolean getOverlapAnchor(android.widget.PopupWindow);
+    method public static int getWindowLayoutType(android.widget.PopupWindow);
+    method public static void setOverlapAnchor(android.widget.PopupWindow, boolean);
+    method public static void setWindowLayoutType(android.widget.PopupWindow, int);
+    method public static void showAsDropDown(android.widget.PopupWindow, android.view.View, int, int, int);
+  }
+
+  public abstract class ResourceCursorAdapter extends android.support.v4.widget.CursorAdapter {
+    ctor public deprecated ResourceCursorAdapter(android.content.Context, int, android.database.Cursor);
+    ctor public deprecated ResourceCursorAdapter(android.content.Context, int, android.database.Cursor, boolean);
+    ctor public ResourceCursorAdapter(android.content.Context, int, android.database.Cursor, int);
+    method public android.view.View newView(android.content.Context, android.database.Cursor, android.view.ViewGroup);
+    method public void setDropDownViewResource(int);
+    method public void setViewResource(int);
+  }
+
+  public final deprecated class ScrollerCompat {
+    method public deprecated void abortAnimation();
+    method public deprecated boolean computeScrollOffset();
+    method public static deprecated android.support.v4.widget.ScrollerCompat create(android.content.Context);
+    method public static deprecated android.support.v4.widget.ScrollerCompat create(android.content.Context, android.view.animation.Interpolator);
+    method public deprecated void fling(int, int, int, int, int, int, int, int);
+    method public deprecated void fling(int, int, int, int, int, int, int, int, int, int);
+    method public deprecated float getCurrVelocity();
+    method public deprecated int getCurrX();
+    method public deprecated int getCurrY();
+    method public deprecated int getFinalX();
+    method public deprecated int getFinalY();
+    method public deprecated boolean isFinished();
+    method public deprecated boolean isOverScrolled();
+    method public deprecated void notifyHorizontalEdgeReached(int, int, int);
+    method public deprecated void notifyVerticalEdgeReached(int, int, int);
+    method public deprecated boolean springBack(int, int, int, int, int, int);
+    method public deprecated void startScroll(int, int, int, int);
+    method public deprecated void startScroll(int, int, int, int, int);
+  }
+
+  public final deprecated class SearchViewCompat {
+    method public static deprecated java.lang.CharSequence getQuery(android.view.View);
+    method public static deprecated boolean isIconified(android.view.View);
+    method public static deprecated boolean isQueryRefinementEnabled(android.view.View);
+    method public static deprecated boolean isSubmitButtonEnabled(android.view.View);
+    method public static deprecated android.view.View newSearchView(android.content.Context);
+    method public static deprecated void setIconified(android.view.View, boolean);
+    method public static deprecated void setImeOptions(android.view.View, int);
+    method public static deprecated void setInputType(android.view.View, int);
+    method public static deprecated void setMaxWidth(android.view.View, int);
+    method public static deprecated void setOnCloseListener(android.view.View, android.support.v4.widget.SearchViewCompat.OnCloseListener);
+    method public static deprecated void setOnQueryTextListener(android.view.View, android.support.v4.widget.SearchViewCompat.OnQueryTextListener);
+    method public static deprecated void setQuery(android.view.View, java.lang.CharSequence, boolean);
+    method public static deprecated void setQueryHint(android.view.View, java.lang.CharSequence);
+    method public static deprecated void setQueryRefinementEnabled(android.view.View, boolean);
+    method public static deprecated void setSearchableInfo(android.view.View, android.content.ComponentName);
+    method public static deprecated void setSubmitButtonEnabled(android.view.View, boolean);
+  }
+
+  public static abstract deprecated interface SearchViewCompat.OnCloseListener {
+    method public abstract boolean onClose();
+  }
+
+  public static abstract deprecated class SearchViewCompat.OnCloseListenerCompat implements android.support.v4.widget.SearchViewCompat.OnCloseListener {
+    ctor public SearchViewCompat.OnCloseListenerCompat();
+    method public boolean onClose();
+  }
+
+  public static abstract deprecated interface SearchViewCompat.OnQueryTextListener {
+    method public abstract boolean onQueryTextChange(java.lang.String);
+    method public abstract boolean onQueryTextSubmit(java.lang.String);
+  }
+
+  public static abstract deprecated class SearchViewCompat.OnQueryTextListenerCompat implements android.support.v4.widget.SearchViewCompat.OnQueryTextListener {
+    ctor public SearchViewCompat.OnQueryTextListenerCompat();
+    method public boolean onQueryTextChange(java.lang.String);
+    method public boolean onQueryTextSubmit(java.lang.String);
+  }
+
+  public class SimpleCursorAdapter extends android.support.v4.widget.ResourceCursorAdapter {
+    ctor public deprecated SimpleCursorAdapter(android.content.Context, int, android.database.Cursor, java.lang.String[], int[]);
+    ctor public SimpleCursorAdapter(android.content.Context, int, android.database.Cursor, java.lang.String[], int[], int);
+    method public void bindView(android.view.View, android.content.Context, android.database.Cursor);
+    method public void changeCursorAndColumns(android.database.Cursor, java.lang.String[], int[]);
+    method public android.support.v4.widget.SimpleCursorAdapter.CursorToStringConverter getCursorToStringConverter();
+    method public int getStringConversionColumn();
+    method public android.support.v4.widget.SimpleCursorAdapter.ViewBinder getViewBinder();
+    method public void setCursorToStringConverter(android.support.v4.widget.SimpleCursorAdapter.CursorToStringConverter);
+    method public void setStringConversionColumn(int);
+    method public void setViewBinder(android.support.v4.widget.SimpleCursorAdapter.ViewBinder);
+    method public void setViewImage(android.widget.ImageView, java.lang.String);
+    method public void setViewText(android.widget.TextView, java.lang.String);
+  }
+
+  public static abstract interface SimpleCursorAdapter.CursorToStringConverter {
+    method public abstract java.lang.CharSequence convertToString(android.database.Cursor);
+  }
+
+  public static abstract interface SimpleCursorAdapter.ViewBinder {
+    method public abstract boolean setViewValue(android.view.View, android.database.Cursor, int);
+  }
+
+  public class SlidingPaneLayout extends android.view.ViewGroup {
+    ctor public SlidingPaneLayout(android.content.Context);
+    ctor public SlidingPaneLayout(android.content.Context, android.util.AttributeSet);
+    ctor public SlidingPaneLayout(android.content.Context, android.util.AttributeSet, int);
+    method protected boolean canScroll(android.view.View, boolean, int, int, int);
+    method public deprecated boolean canSlide();
+    method public boolean closePane();
+    method public int getCoveredFadeColor();
+    method public int getParallaxDistance();
+    method public int getSliderFadeColor();
+    method public boolean isOpen();
+    method public boolean isSlideable();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public boolean openPane();
+    method public void setCoveredFadeColor(int);
+    method public void setPanelSlideListener(android.support.v4.widget.SlidingPaneLayout.PanelSlideListener);
+    method public void setParallaxDistance(int);
+    method public deprecated void setShadowDrawable(android.graphics.drawable.Drawable);
+    method public void setShadowDrawableLeft(android.graphics.drawable.Drawable);
+    method public void setShadowDrawableRight(android.graphics.drawable.Drawable);
+    method public deprecated void setShadowResource(int);
+    method public void setShadowResourceLeft(int);
+    method public void setShadowResourceRight(int);
+    method public void setSliderFadeColor(int);
+    method public deprecated void smoothSlideClosed();
+    method public deprecated void smoothSlideOpen();
+  }
+
+  public static class SlidingPaneLayout.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public SlidingPaneLayout.LayoutParams();
+    ctor public SlidingPaneLayout.LayoutParams(int, int);
+    ctor public SlidingPaneLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public SlidingPaneLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public SlidingPaneLayout.LayoutParams(android.support.v4.widget.SlidingPaneLayout.LayoutParams);
+    ctor public SlidingPaneLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    field public float weight;
+  }
+
+  public static abstract interface SlidingPaneLayout.PanelSlideListener {
+    method public abstract void onPanelClosed(android.view.View);
+    method public abstract void onPanelOpened(android.view.View);
+    method public abstract void onPanelSlide(android.view.View, float);
+  }
+
+  public static class SlidingPaneLayout.SimplePanelSlideListener implements android.support.v4.widget.SlidingPaneLayout.PanelSlideListener {
+    ctor public SlidingPaneLayout.SimplePanelSlideListener();
+    method public void onPanelClosed(android.view.View);
+    method public void onPanelOpened(android.view.View);
+    method public void onPanelSlide(android.view.View, float);
+  }
+
+  public class Space extends android.view.View {
+    ctor public Space(android.content.Context, android.util.AttributeSet, int);
+    ctor public Space(android.content.Context, android.util.AttributeSet);
+    ctor public Space(android.content.Context);
+  }
+
+  public class SwipeRefreshLayout extends android.view.ViewGroup implements android.support.v4.view.NestedScrollingChild android.support.v4.view.NestedScrollingParent {
+    ctor public SwipeRefreshLayout(android.content.Context);
+    ctor public SwipeRefreshLayout(android.content.Context, android.util.AttributeSet);
+    method public boolean canChildScrollUp();
+    method public int getProgressCircleDiameter();
+    method public int getProgressViewEndOffset();
+    method public int getProgressViewStartOffset();
+    method public boolean isRefreshing();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void onMeasure(int, int);
+    method public deprecated void setColorScheme(int...);
+    method public void setColorSchemeColors(int...);
+    method public void setColorSchemeResources(int...);
+    method public void setDistanceToTriggerSync(int);
+    method public void setOnChildScrollUpCallback(android.support.v4.widget.SwipeRefreshLayout.OnChildScrollUpCallback);
+    method public void setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener);
+    method public deprecated void setProgressBackgroundColor(int);
+    method public void setProgressBackgroundColorSchemeColor(int);
+    method public void setProgressBackgroundColorSchemeResource(int);
+    method public void setProgressViewEndTarget(boolean, int);
+    method public void setProgressViewOffset(boolean, int, int);
+    method public void setRefreshing(boolean);
+    method public void setSize(int);
+    field public static final int DEFAULT = 1; // 0x1
+    field public static final int LARGE = 0; // 0x0
+    field protected int mFrom;
+    field protected int mOriginalOffsetTop;
+  }
+
+  public static abstract interface SwipeRefreshLayout.OnChildScrollUpCallback {
+    method public abstract boolean canChildScrollUp(android.support.v4.widget.SwipeRefreshLayout, android.view.View);
+  }
+
+  public static abstract interface SwipeRefreshLayout.OnRefreshListener {
+    method public abstract void onRefresh();
+  }
+
+  public final class TextViewCompat {
+    method public static int getAutoSizeMaxTextSize(android.widget.TextView);
+    method public static int getAutoSizeMinTextSize(android.widget.TextView);
+    method public static int getAutoSizeStepGranularity(android.widget.TextView);
+    method public static int[] getAutoSizeTextAvailableSizes(android.widget.TextView);
+    method public static int getAutoSizeTextType(android.widget.TextView);
+    method public static android.graphics.drawable.Drawable[] getCompoundDrawablesRelative(android.widget.TextView);
+    method public static int getMaxLines(android.widget.TextView);
+    method public static int getMinLines(android.widget.TextView);
+    method public static void setAutoSizeTextTypeUniformWithConfiguration(android.widget.TextView, int, int, int, int) throws java.lang.IllegalArgumentException;
+    method public static void setAutoSizeTextTypeUniformWithPresetSizes(android.widget.TextView, int[], int) throws java.lang.IllegalArgumentException;
+    method public static void setAutoSizeTextTypeWithDefaults(android.widget.TextView, int);
+    method public static void setCompoundDrawablesRelative(android.widget.TextView, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable);
+    method public static void setCompoundDrawablesRelativeWithIntrinsicBounds(android.widget.TextView, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable);
+    method public static void setCompoundDrawablesRelativeWithIntrinsicBounds(android.widget.TextView, int, int, int, int);
+    method public static void setTextAppearance(android.widget.TextView, int);
+    field public static final int AUTO_SIZE_TEXT_TYPE_NONE = 0; // 0x0
+    field public static final int AUTO_SIZE_TEXT_TYPE_UNIFORM = 1; // 0x1
+  }
+
+  public abstract interface TintableCompoundButton {
+    method public abstract android.content.res.ColorStateList getSupportButtonTintList();
+    method public abstract android.graphics.PorterDuff.Mode getSupportButtonTintMode();
+    method public abstract void setSupportButtonTintList(android.content.res.ColorStateList);
+    method public abstract void setSupportButtonTintMode(android.graphics.PorterDuff.Mode);
+  }
+
+  public class ViewDragHelper {
+    method public void abort();
+    method protected boolean canScroll(android.view.View, boolean, int, int, int, int);
+    method public void cancel();
+    method public void captureChildView(android.view.View, int);
+    method public boolean checkTouchSlop(int);
+    method public boolean checkTouchSlop(int, int);
+    method public boolean continueSettling(boolean);
+    method public static android.support.v4.widget.ViewDragHelper create(android.view.ViewGroup, android.support.v4.widget.ViewDragHelper.Callback);
+    method public static android.support.v4.widget.ViewDragHelper create(android.view.ViewGroup, float, android.support.v4.widget.ViewDragHelper.Callback);
+    method public android.view.View findTopChildUnder(int, int);
+    method public void flingCapturedView(int, int, int, int);
+    method public int getActivePointerId();
+    method public android.view.View getCapturedView();
+    method public int getEdgeSize();
+    method public float getMinVelocity();
+    method public int getTouchSlop();
+    method public int getViewDragState();
+    method public boolean isCapturedViewUnder(int, int);
+    method public boolean isEdgeTouched(int);
+    method public boolean isEdgeTouched(int, int);
+    method public boolean isPointerDown(int);
+    method public boolean isViewUnder(android.view.View, int, int);
+    method public void processTouchEvent(android.view.MotionEvent);
+    method public void setEdgeTrackingEnabled(int);
+    method public void setMinVelocity(float);
+    method public boolean settleCapturedViewAt(int, int);
+    method public boolean shouldInterceptTouchEvent(android.view.MotionEvent);
+    method public boolean smoothSlideViewTo(android.view.View, int, int);
+    field public static final int DIRECTION_ALL = 3; // 0x3
+    field public static final int DIRECTION_HORIZONTAL = 1; // 0x1
+    field public static final int DIRECTION_VERTICAL = 2; // 0x2
+    field public static final int EDGE_ALL = 15; // 0xf
+    field public static final int EDGE_BOTTOM = 8; // 0x8
+    field public static final int EDGE_LEFT = 1; // 0x1
+    field public static final int EDGE_RIGHT = 2; // 0x2
+    field public static final int EDGE_TOP = 4; // 0x4
+    field public static final int INVALID_POINTER = -1; // 0xffffffff
+    field public static final int STATE_DRAGGING = 1; // 0x1
+    field public static final int STATE_IDLE = 0; // 0x0
+    field public static final int STATE_SETTLING = 2; // 0x2
+  }
+
+  public static abstract class ViewDragHelper.Callback {
+    ctor public ViewDragHelper.Callback();
+    method public int clampViewPositionHorizontal(android.view.View, int, int);
+    method public int clampViewPositionVertical(android.view.View, int, int);
+    method public int getOrderedChildIndex(int);
+    method public int getViewHorizontalDragRange(android.view.View);
+    method public int getViewVerticalDragRange(android.view.View);
+    method public void onEdgeDragStarted(int, int);
+    method public boolean onEdgeLock(int);
+    method public void onEdgeTouched(int, int);
+    method public void onViewCaptured(android.view.View, int);
+    method public void onViewDragStateChanged(int);
+    method public void onViewPositionChanged(android.view.View, int, int, int, int);
+    method public void onViewReleased(android.view.View, float, float);
+    method public abstract boolean tryCaptureView(android.view.View, int);
+  }
+
+}
+
+package android.support.v7.app {
+
+  public abstract class ActionBar {
+    ctor public ActionBar();
+    method public abstract void addOnMenuVisibilityListener(android.support.v7.app.ActionBar.OnMenuVisibilityListener);
+    method public abstract deprecated void addTab(android.support.v7.app.ActionBar.Tab);
+    method public abstract deprecated void addTab(android.support.v7.app.ActionBar.Tab, boolean);
+    method public abstract deprecated void addTab(android.support.v7.app.ActionBar.Tab, int);
+    method public abstract deprecated void addTab(android.support.v7.app.ActionBar.Tab, int, boolean);
+    method public abstract android.view.View getCustomView();
+    method public abstract int getDisplayOptions();
+    method public float getElevation();
+    method public abstract int getHeight();
+    method public int getHideOffset();
+    method public abstract deprecated int getNavigationItemCount();
+    method public abstract deprecated int getNavigationMode();
+    method public abstract deprecated int getSelectedNavigationIndex();
+    method public abstract deprecated android.support.v7.app.ActionBar.Tab getSelectedTab();
+    method public abstract java.lang.CharSequence getSubtitle();
+    method public abstract deprecated android.support.v7.app.ActionBar.Tab getTabAt(int);
+    method public abstract deprecated int getTabCount();
+    method public android.content.Context getThemedContext();
+    method public abstract java.lang.CharSequence getTitle();
+    method public abstract void hide();
+    method public boolean isHideOnContentScrollEnabled();
+    method public abstract boolean isShowing();
+    method public abstract deprecated android.support.v7.app.ActionBar.Tab newTab();
+    method public abstract deprecated void removeAllTabs();
+    method public abstract void removeOnMenuVisibilityListener(android.support.v7.app.ActionBar.OnMenuVisibilityListener);
+    method public abstract deprecated void removeTab(android.support.v7.app.ActionBar.Tab);
+    method public abstract deprecated void removeTabAt(int);
+    method public abstract deprecated void selectTab(android.support.v7.app.ActionBar.Tab);
+    method public abstract void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public abstract void setCustomView(android.view.View);
+    method public abstract void setCustomView(android.view.View, android.support.v7.app.ActionBar.LayoutParams);
+    method public abstract void setCustomView(int);
+    method public abstract void setDisplayHomeAsUpEnabled(boolean);
+    method public abstract void setDisplayOptions(int);
+    method public abstract void setDisplayOptions(int, int);
+    method public abstract void setDisplayShowCustomEnabled(boolean);
+    method public abstract void setDisplayShowHomeEnabled(boolean);
+    method public abstract void setDisplayShowTitleEnabled(boolean);
+    method public abstract void setDisplayUseLogoEnabled(boolean);
+    method public void setElevation(float);
+    method public void setHideOffset(int);
+    method public void setHideOnContentScrollEnabled(boolean);
+    method public void setHomeActionContentDescription(java.lang.CharSequence);
+    method public void setHomeActionContentDescription(int);
+    method public void setHomeAsUpIndicator(android.graphics.drawable.Drawable);
+    method public void setHomeAsUpIndicator(int);
+    method public void setHomeButtonEnabled(boolean);
+    method public abstract void setIcon(int);
+    method public abstract void setIcon(android.graphics.drawable.Drawable);
+    method public abstract deprecated void setListNavigationCallbacks(android.widget.SpinnerAdapter, android.support.v7.app.ActionBar.OnNavigationListener);
+    method public abstract void setLogo(int);
+    method public abstract void setLogo(android.graphics.drawable.Drawable);
+    method public abstract deprecated void setNavigationMode(int);
+    method public abstract deprecated void setSelectedNavigationItem(int);
+    method public void setSplitBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setStackedBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public abstract void setSubtitle(java.lang.CharSequence);
+    method public abstract void setSubtitle(int);
+    method public abstract void setTitle(java.lang.CharSequence);
+    method public abstract void setTitle(int);
+    method public abstract void show();
+    field public static final int DISPLAY_HOME_AS_UP = 4; // 0x4
+    field public static final int DISPLAY_SHOW_CUSTOM = 16; // 0x10
+    field public static final int DISPLAY_SHOW_HOME = 2; // 0x2
+    field public static final int DISPLAY_SHOW_TITLE = 8; // 0x8
+    field public static final int DISPLAY_USE_LOGO = 1; // 0x1
+    field public static final deprecated int NAVIGATION_MODE_LIST = 1; // 0x1
+    field public static final deprecated int NAVIGATION_MODE_STANDARD = 0; // 0x0
+    field public static final deprecated int NAVIGATION_MODE_TABS = 2; // 0x2
+  }
+
+  public static class ActionBar.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public ActionBar.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public ActionBar.LayoutParams(int, int);
+    ctor public ActionBar.LayoutParams(int, int, int);
+    ctor public ActionBar.LayoutParams(int);
+    ctor public ActionBar.LayoutParams(android.support.v7.app.ActionBar.LayoutParams);
+    ctor public ActionBar.LayoutParams(android.view.ViewGroup.LayoutParams);
+    field public int gravity;
+  }
+
+  public static abstract interface ActionBar.OnMenuVisibilityListener {
+    method public abstract void onMenuVisibilityChanged(boolean);
+  }
+
+  public static abstract deprecated interface ActionBar.OnNavigationListener {
+    method public abstract boolean onNavigationItemSelected(int, long);
+  }
+
+  public static abstract deprecated class ActionBar.Tab {
+    ctor public ActionBar.Tab();
+    method public abstract java.lang.CharSequence getContentDescription();
+    method public abstract android.view.View getCustomView();
+    method public abstract android.graphics.drawable.Drawable getIcon();
+    method public abstract int getPosition();
+    method public abstract java.lang.Object getTag();
+    method public abstract java.lang.CharSequence getText();
+    method public abstract void select();
+    method public abstract android.support.v7.app.ActionBar.Tab setContentDescription(int);
+    method public abstract android.support.v7.app.ActionBar.Tab setContentDescription(java.lang.CharSequence);
+    method public abstract android.support.v7.app.ActionBar.Tab setCustomView(android.view.View);
+    method public abstract android.support.v7.app.ActionBar.Tab setCustomView(int);
+    method public abstract android.support.v7.app.ActionBar.Tab setIcon(android.graphics.drawable.Drawable);
+    method public abstract android.support.v7.app.ActionBar.Tab setIcon(int);
+    method public abstract android.support.v7.app.ActionBar.Tab setTabListener(android.support.v7.app.ActionBar.TabListener);
+    method public abstract android.support.v7.app.ActionBar.Tab setTag(java.lang.Object);
+    method public abstract android.support.v7.app.ActionBar.Tab setText(java.lang.CharSequence);
+    method public abstract android.support.v7.app.ActionBar.Tab setText(int);
+    field public static final int INVALID_POSITION = -1; // 0xffffffff
+  }
+
+  public static abstract deprecated interface ActionBar.TabListener {
+    method public abstract void onTabReselected(android.support.v7.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction);
+    method public abstract void onTabSelected(android.support.v7.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction);
+    method public abstract void onTabUnselected(android.support.v7.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction);
+  }
+
+  public class ActionBarDrawerToggle implements android.support.v4.widget.DrawerLayout.DrawerListener {
+    ctor public ActionBarDrawerToggle(android.app.Activity, android.support.v4.widget.DrawerLayout, int, int);
+    ctor public ActionBarDrawerToggle(android.app.Activity, android.support.v4.widget.DrawerLayout, android.support.v7.widget.Toolbar, int, int);
+    method public android.support.v7.graphics.drawable.DrawerArrowDrawable getDrawerArrowDrawable();
+    method public android.view.View.OnClickListener getToolbarNavigationClickListener();
+    method public boolean isDrawerIndicatorEnabled();
+    method public boolean isDrawerSlideAnimationEnabled();
+    method public void onConfigurationChanged(android.content.res.Configuration);
+    method public void onDrawerClosed(android.view.View);
+    method public void onDrawerOpened(android.view.View);
+    method public void onDrawerSlide(android.view.View, float);
+    method public void onDrawerStateChanged(int);
+    method public boolean onOptionsItemSelected(android.view.MenuItem);
+    method public void setDrawerArrowDrawable(android.support.v7.graphics.drawable.DrawerArrowDrawable);
+    method public void setDrawerIndicatorEnabled(boolean);
+    method public void setDrawerSlideAnimationEnabled(boolean);
+    method public void setHomeAsUpIndicator(android.graphics.drawable.Drawable);
+    method public void setHomeAsUpIndicator(int);
+    method public void setToolbarNavigationClickListener(android.view.View.OnClickListener);
+    method public void syncState();
+  }
+
+  public static abstract interface ActionBarDrawerToggle.Delegate {
+    method public abstract android.content.Context getActionBarThemedContext();
+    method public abstract android.graphics.drawable.Drawable getThemeUpIndicator();
+    method public abstract boolean isNavigationVisible();
+    method public abstract void setActionBarDescription(int);
+    method public abstract void setActionBarUpIndicator(android.graphics.drawable.Drawable, int);
+  }
+
+  public static abstract interface ActionBarDrawerToggle.DelegateProvider {
+    method public abstract android.support.v7.app.ActionBarDrawerToggle.Delegate getDrawerToggleDelegate();
+  }
+
+  public class AlertDialog extends android.support.v7.app.AppCompatDialog implements android.content.DialogInterface {
+    ctor protected AlertDialog(android.content.Context);
+    ctor protected AlertDialog(android.content.Context, int);
+    ctor protected AlertDialog(android.content.Context, boolean, android.content.DialogInterface.OnCancelListener);
+    method public android.widget.Button getButton(int);
+    method public android.widget.ListView getListView();
+    method public void setButton(int, java.lang.CharSequence, android.os.Message);
+    method public void setButton(int, java.lang.CharSequence, android.content.DialogInterface.OnClickListener);
+    method public void setCustomTitle(android.view.View);
+    method public void setIcon(int);
+    method public void setIcon(android.graphics.drawable.Drawable);
+    method public void setIconAttribute(int);
+    method public void setMessage(java.lang.CharSequence);
+    method public void setView(android.view.View);
+    method public void setView(android.view.View, int, int, int, int);
+  }
+
+  public static class AlertDialog.Builder {
+    ctor public AlertDialog.Builder(android.content.Context);
+    ctor public AlertDialog.Builder(android.content.Context, int);
+    method public android.support.v7.app.AlertDialog create();
+    method public android.content.Context getContext();
+    method public android.support.v7.app.AlertDialog.Builder setAdapter(android.widget.ListAdapter, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setCancelable(boolean);
+    method public android.support.v7.app.AlertDialog.Builder setCursor(android.database.Cursor, android.content.DialogInterface.OnClickListener, java.lang.String);
+    method public android.support.v7.app.AlertDialog.Builder setCustomTitle(android.view.View);
+    method public android.support.v7.app.AlertDialog.Builder setIcon(int);
+    method public android.support.v7.app.AlertDialog.Builder setIcon(android.graphics.drawable.Drawable);
+    method public android.support.v7.app.AlertDialog.Builder setIconAttribute(int);
+    method public deprecated android.support.v7.app.AlertDialog.Builder setInverseBackgroundForced(boolean);
+    method public android.support.v7.app.AlertDialog.Builder setItems(int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setItems(java.lang.CharSequence[], android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setMessage(int);
+    method public android.support.v7.app.AlertDialog.Builder setMessage(java.lang.CharSequence);
+    method public android.support.v7.app.AlertDialog.Builder setMultiChoiceItems(int, boolean[], android.content.DialogInterface.OnMultiChoiceClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setMultiChoiceItems(java.lang.CharSequence[], boolean[], android.content.DialogInterface.OnMultiChoiceClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setMultiChoiceItems(android.database.Cursor, java.lang.String, java.lang.String, android.content.DialogInterface.OnMultiChoiceClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setNegativeButton(int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setNegativeButton(java.lang.CharSequence, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setNeutralButton(int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setNeutralButton(java.lang.CharSequence, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setOnCancelListener(android.content.DialogInterface.OnCancelListener);
+    method public android.support.v7.app.AlertDialog.Builder setOnDismissListener(android.content.DialogInterface.OnDismissListener);
+    method public android.support.v7.app.AlertDialog.Builder setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener);
+    method public android.support.v7.app.AlertDialog.Builder setOnKeyListener(android.content.DialogInterface.OnKeyListener);
+    method public android.support.v7.app.AlertDialog.Builder setPositiveButton(int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setPositiveButton(java.lang.CharSequence, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setSingleChoiceItems(int, int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setSingleChoiceItems(android.database.Cursor, int, java.lang.String, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setSingleChoiceItems(java.lang.CharSequence[], int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setSingleChoiceItems(android.widget.ListAdapter, int, android.content.DialogInterface.OnClickListener);
+    method public android.support.v7.app.AlertDialog.Builder setTitle(int);
+    method public android.support.v7.app.AlertDialog.Builder setTitle(java.lang.CharSequence);
+    method public android.support.v7.app.AlertDialog.Builder setView(int);
+    method public android.support.v7.app.AlertDialog.Builder setView(android.view.View);
+    method public android.support.v7.app.AlertDialog show();
+  }
+
+  public class AppCompatActivity extends android.support.v4.app.FragmentActivity implements android.support.v7.app.ActionBarDrawerToggle.DelegateProvider android.support.v7.app.AppCompatCallback android.support.v4.app.TaskStackBuilder.SupportParentable {
+    ctor public AppCompatActivity();
+    method public android.support.v7.app.AppCompatDelegate getDelegate();
+    method public android.support.v7.app.ActionBarDrawerToggle.Delegate getDrawerToggleDelegate();
+    method public android.support.v7.app.ActionBar getSupportActionBar();
+    method public android.content.Intent getSupportParentActivityIntent();
+    method public void onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder);
+    method public final boolean onMenuItemSelected(int, android.view.MenuItem);
+    method public void onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder);
+    method public void onSupportActionModeFinished(android.support.v7.view.ActionMode);
+    method public void onSupportActionModeStarted(android.support.v7.view.ActionMode);
+    method public deprecated void onSupportContentChanged();
+    method public boolean onSupportNavigateUp();
+    method public android.support.v7.view.ActionMode onWindowStartingSupportActionMode(android.support.v7.view.ActionMode.Callback);
+    method public void setSupportActionBar(android.support.v7.widget.Toolbar);
+    method public deprecated void setSupportProgress(int);
+    method public deprecated void setSupportProgressBarIndeterminate(boolean);
+    method public deprecated void setSupportProgressBarIndeterminateVisibility(boolean);
+    method public deprecated void setSupportProgressBarVisibility(boolean);
+    method public android.support.v7.view.ActionMode startSupportActionMode(android.support.v7.view.ActionMode.Callback);
+    method public void supportInvalidateOptionsMenu();
+    method public void supportNavigateUpTo(android.content.Intent);
+    method public boolean supportRequestWindowFeature(int);
+    method public boolean supportShouldUpRecreateTask(android.content.Intent);
+  }
+
+  public abstract interface AppCompatCallback {
+    method public abstract void onSupportActionModeFinished(android.support.v7.view.ActionMode);
+    method public abstract void onSupportActionModeStarted(android.support.v7.view.ActionMode);
+    method public abstract android.support.v7.view.ActionMode onWindowStartingSupportActionMode(android.support.v7.view.ActionMode.Callback);
+  }
+
+  public abstract class AppCompatDelegate {
+    method public abstract void addContentView(android.view.View, android.view.ViewGroup.LayoutParams);
+    method public abstract boolean applyDayNight();
+    method public static android.support.v7.app.AppCompatDelegate create(android.app.Activity, android.support.v7.app.AppCompatCallback);
+    method public static android.support.v7.app.AppCompatDelegate create(android.app.Dialog, android.support.v7.app.AppCompatCallback);
+    method public abstract android.view.View createView(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet);
+    method public abstract <T extends android.view.View> T findViewById(int);
+    method public static int getDefaultNightMode();
+    method public abstract android.support.v7.app.ActionBarDrawerToggle.Delegate getDrawerToggleDelegate();
+    method public abstract android.view.MenuInflater getMenuInflater();
+    method public abstract android.support.v7.app.ActionBar getSupportActionBar();
+    method public abstract boolean hasWindowFeature(int);
+    method public abstract void installViewFactory();
+    method public abstract void invalidateOptionsMenu();
+    method public static boolean isCompatVectorFromResourcesEnabled();
+    method public abstract boolean isHandleNativeActionModesEnabled();
+    method public abstract void onConfigurationChanged(android.content.res.Configuration);
+    method public abstract void onCreate(android.os.Bundle);
+    method public abstract void onDestroy();
+    method public abstract void onPostCreate(android.os.Bundle);
+    method public abstract void onPostResume();
+    method public abstract void onSaveInstanceState(android.os.Bundle);
+    method public abstract void onStart();
+    method public abstract void onStop();
+    method public abstract boolean requestWindowFeature(int);
+    method public static void setCompatVectorFromResourcesEnabled(boolean);
+    method public abstract void setContentView(android.view.View);
+    method public abstract void setContentView(int);
+    method public abstract void setContentView(android.view.View, android.view.ViewGroup.LayoutParams);
+    method public static void setDefaultNightMode(int);
+    method public abstract void setHandleNativeActionModesEnabled(boolean);
+    method public abstract void setLocalNightMode(int);
+    method public abstract void setSupportActionBar(android.support.v7.widget.Toolbar);
+    method public abstract void setTitle(java.lang.CharSequence);
+    method public abstract android.support.v7.view.ActionMode startSupportActionMode(android.support.v7.view.ActionMode.Callback);
+    field public static final int FEATURE_ACTION_MODE_OVERLAY = 10; // 0xa
+    field public static final int FEATURE_SUPPORT_ACTION_BAR = 108; // 0x6c
+    field public static final int FEATURE_SUPPORT_ACTION_BAR_OVERLAY = 109; // 0x6d
+    field public static final int MODE_NIGHT_AUTO = 0; // 0x0
+    field public static final int MODE_NIGHT_FOLLOW_SYSTEM = -1; // 0xffffffff
+    field public static final int MODE_NIGHT_NO = 1; // 0x1
+    field public static final int MODE_NIGHT_YES = 2; // 0x2
+  }
+
+  public class AppCompatDialog extends android.app.Dialog implements android.support.v7.app.AppCompatCallback {
+    ctor public AppCompatDialog(android.content.Context);
+    ctor public AppCompatDialog(android.content.Context, int);
+    ctor protected AppCompatDialog(android.content.Context, boolean, android.content.DialogInterface.OnCancelListener);
+    method public android.support.v7.app.AppCompatDelegate getDelegate();
+    method public android.support.v7.app.ActionBar getSupportActionBar();
+    method public void onSupportActionModeFinished(android.support.v7.view.ActionMode);
+    method public void onSupportActionModeStarted(android.support.v7.view.ActionMode);
+    method public android.support.v7.view.ActionMode onWindowStartingSupportActionMode(android.support.v7.view.ActionMode.Callback);
+    method public boolean supportRequestWindowFeature(int);
+  }
+
+  public class AppCompatDialogFragment extends android.support.v4.app.DialogFragment {
+    ctor public AppCompatDialogFragment();
+  }
+
+  public class MediaRouteActionProvider extends android.support.v4.view.ActionProvider {
+    ctor public MediaRouteActionProvider(android.content.Context);
+    method public android.support.v7.app.MediaRouteDialogFactory getDialogFactory();
+    method public android.support.v7.app.MediaRouteButton getMediaRouteButton();
+    method public android.support.v7.media.MediaRouteSelector getRouteSelector();
+    method public android.view.View onCreateActionView();
+    method public android.support.v7.app.MediaRouteButton onCreateMediaRouteButton();
+    method public void setDialogFactory(android.support.v7.app.MediaRouteDialogFactory);
+    method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
+  }
+
+  public class MediaRouteButton extends android.view.View {
+    ctor public MediaRouteButton(android.content.Context);
+    ctor public MediaRouteButton(android.content.Context, android.util.AttributeSet);
+    ctor public MediaRouteButton(android.content.Context, android.util.AttributeSet, int);
+    method public android.support.v7.app.MediaRouteDialogFactory getDialogFactory();
+    method public android.support.v7.media.MediaRouteSelector getRouteSelector();
+    method public void onAttachedToWindow();
+    method public void onDetachedFromWindow();
+    method public void setDialogFactory(android.support.v7.app.MediaRouteDialogFactory);
+    method public void setRemoteIndicatorDrawable(android.graphics.drawable.Drawable);
+    method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
+    method public boolean showDialog();
+  }
+
+  public class MediaRouteChooserDialog extends android.support.v7.app.AppCompatDialog {
+    ctor public MediaRouteChooserDialog(android.content.Context);
+    ctor public MediaRouteChooserDialog(android.content.Context, int);
+    method public android.support.v7.media.MediaRouteSelector getRouteSelector();
+    method public boolean onFilterRoute(android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onFilterRoutes(java.util.List<android.support.v7.media.MediaRouter.RouteInfo>);
+    method public void refreshRoutes();
+    method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
+  }
+
+  public class MediaRouteChooserDialogFragment extends android.support.v4.app.DialogFragment {
+    ctor public MediaRouteChooserDialogFragment();
+    method public android.support.v7.media.MediaRouteSelector getRouteSelector();
+    method public android.support.v7.app.MediaRouteChooserDialog onCreateChooserDialog(android.content.Context, android.os.Bundle);
+    method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
+  }
+
+  public class MediaRouteControllerDialog extends android.support.v7.app.AlertDialog {
+    ctor public MediaRouteControllerDialog(android.content.Context);
+    ctor public MediaRouteControllerDialog(android.content.Context, int);
+    method public android.view.View getMediaControlView();
+    method public android.support.v4.media.session.MediaSessionCompat.Token getMediaSession();
+    method public android.support.v7.media.MediaRouter.RouteInfo getRoute();
+    method public boolean isVolumeControlEnabled();
+    method public android.view.View onCreateMediaControlView(android.os.Bundle);
+    method public void setVolumeControlEnabled(boolean);
+  }
+
+  public class MediaRouteControllerDialogFragment extends android.support.v4.app.DialogFragment {
+    ctor public MediaRouteControllerDialogFragment();
+    method public android.support.v7.app.MediaRouteControllerDialog onCreateControllerDialog(android.content.Context, android.os.Bundle);
+  }
+
+  public class MediaRouteDialogFactory {
+    ctor public MediaRouteDialogFactory();
+    method public static android.support.v7.app.MediaRouteDialogFactory getDefault();
+    method public android.support.v7.app.MediaRouteChooserDialogFragment onCreateChooserDialogFragment();
+    method public android.support.v7.app.MediaRouteControllerDialogFragment onCreateControllerDialogFragment();
+  }
+
+  public class MediaRouteDiscoveryFragment extends android.support.v4.app.Fragment {
+    ctor public MediaRouteDiscoveryFragment();
+    method public android.support.v7.media.MediaRouter getMediaRouter();
+    method public android.support.v7.media.MediaRouteSelector getRouteSelector();
+    method public android.support.v7.media.MediaRouter.Callback onCreateCallback();
+    method public int onPrepareCallbackFlags();
+    method public void setRouteSelector(android.support.v7.media.MediaRouteSelector);
+  }
+
+  public deprecated class NotificationCompat extends android.support.v4.app.NotificationCompat {
+    ctor public deprecated NotificationCompat();
+    method public static deprecated android.support.v4.media.session.MediaSessionCompat.Token getMediaSession(android.app.Notification);
+  }
+
+  public static deprecated class NotificationCompat.Builder extends android.support.v4.app.NotificationCompat.Builder {
+    ctor public deprecated NotificationCompat.Builder(android.content.Context);
+  }
+
+  public static deprecated class NotificationCompat.DecoratedCustomViewStyle extends android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle {
+    ctor public deprecated NotificationCompat.DecoratedCustomViewStyle();
+  }
+
+  public static deprecated class NotificationCompat.DecoratedMediaCustomViewStyle extends android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle {
+    ctor public deprecated NotificationCompat.DecoratedMediaCustomViewStyle();
+  }
+
+  public static deprecated class NotificationCompat.MediaStyle extends android.support.v4.media.app.NotificationCompat.MediaStyle {
+    ctor public deprecated NotificationCompat.MediaStyle();
+    ctor public deprecated NotificationCompat.MediaStyle(android.support.v4.app.NotificationCompat.Builder);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setCancelButtonIntent(android.app.PendingIntent);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setMediaSession(android.support.v4.media.session.MediaSessionCompat.Token);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setShowActionsInCompactView(int...);
+    method public deprecated android.support.v7.app.NotificationCompat.MediaStyle setShowCancelButton(boolean);
+  }
+
+}
+
+package android.support.v7.content.res {
+
+  public final class AppCompatResources {
+    method public static android.content.res.ColorStateList getColorStateList(android.content.Context, int);
+    method public static android.graphics.drawable.Drawable getDrawable(android.content.Context, int);
+  }
+
+}
+
+package android.support.v7.graphics {
+
+  public final class Palette {
+    method public static android.support.v7.graphics.Palette.Builder from(android.graphics.Bitmap);
+    method public static android.support.v7.graphics.Palette from(java.util.List<android.support.v7.graphics.Palette.Swatch>);
+    method public static deprecated android.support.v7.graphics.Palette generate(android.graphics.Bitmap);
+    method public static deprecated android.support.v7.graphics.Palette generate(android.graphics.Bitmap, int);
+    method public static deprecated android.os.AsyncTask<android.graphics.Bitmap, java.lang.Void, android.support.v7.graphics.Palette> generateAsync(android.graphics.Bitmap, android.support.v7.graphics.Palette.PaletteAsyncListener);
+    method public static deprecated android.os.AsyncTask<android.graphics.Bitmap, java.lang.Void, android.support.v7.graphics.Palette> generateAsync(android.graphics.Bitmap, int, android.support.v7.graphics.Palette.PaletteAsyncListener);
+    method public int getColorForTarget(android.support.v7.graphics.Target, int);
+    method public int getDarkMutedColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getDarkMutedSwatch();
+    method public int getDarkVibrantColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getDarkVibrantSwatch();
+    method public int getDominantColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getDominantSwatch();
+    method public int getLightMutedColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getLightMutedSwatch();
+    method public int getLightVibrantColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getLightVibrantSwatch();
+    method public int getMutedColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getMutedSwatch();
+    method public android.support.v7.graphics.Palette.Swatch getSwatchForTarget(android.support.v7.graphics.Target);
+    method public java.util.List<android.support.v7.graphics.Palette.Swatch> getSwatches();
+    method public java.util.List<android.support.v7.graphics.Target> getTargets();
+    method public int getVibrantColor(int);
+    method public android.support.v7.graphics.Palette.Swatch getVibrantSwatch();
+  }
+
+  public static final class Palette.Builder {
+    ctor public Palette.Builder(android.graphics.Bitmap);
+    ctor public Palette.Builder(java.util.List<android.support.v7.graphics.Palette.Swatch>);
+    method public android.support.v7.graphics.Palette.Builder addFilter(android.support.v7.graphics.Palette.Filter);
+    method public android.support.v7.graphics.Palette.Builder addTarget(android.support.v7.graphics.Target);
+    method public android.support.v7.graphics.Palette.Builder clearFilters();
+    method public android.support.v7.graphics.Palette.Builder clearRegion();
+    method public android.support.v7.graphics.Palette.Builder clearTargets();
+    method public android.support.v7.graphics.Palette generate();
+    method public android.os.AsyncTask<android.graphics.Bitmap, java.lang.Void, android.support.v7.graphics.Palette> generate(android.support.v7.graphics.Palette.PaletteAsyncListener);
+    method public android.support.v7.graphics.Palette.Builder maximumColorCount(int);
+    method public android.support.v7.graphics.Palette.Builder resizeBitmapArea(int);
+    method public deprecated android.support.v7.graphics.Palette.Builder resizeBitmapSize(int);
+    method public android.support.v7.graphics.Palette.Builder setRegion(int, int, int, int);
+  }
+
+  public static abstract interface Palette.Filter {
+    method public abstract boolean isAllowed(int, float[]);
+  }
+
+  public static abstract interface Palette.PaletteAsyncListener {
+    method public abstract void onGenerated(android.support.v7.graphics.Palette);
+  }
+
+  public static final class Palette.Swatch {
+    ctor public Palette.Swatch(int, int);
+    method public int getBodyTextColor();
+    method public float[] getHsl();
+    method public int getPopulation();
+    method public int getRgb();
+    method public int getTitleTextColor();
+  }
+
+  public final class Target {
+    method public float getLightnessWeight();
+    method public float getMaximumLightness();
+    method public float getMaximumSaturation();
+    method public float getMinimumLightness();
+    method public float getMinimumSaturation();
+    method public float getPopulationWeight();
+    method public float getSaturationWeight();
+    method public float getTargetLightness();
+    method public float getTargetSaturation();
+    method public boolean isExclusive();
+    field public static final android.support.v7.graphics.Target DARK_MUTED;
+    field public static final android.support.v7.graphics.Target DARK_VIBRANT;
+    field public static final android.support.v7.graphics.Target LIGHT_MUTED;
+    field public static final android.support.v7.graphics.Target LIGHT_VIBRANT;
+    field public static final android.support.v7.graphics.Target MUTED;
+    field public static final android.support.v7.graphics.Target VIBRANT;
+  }
+
+  public static final class Target.Builder {
+    ctor public Target.Builder();
+    ctor public Target.Builder(android.support.v7.graphics.Target);
+    method public android.support.v7.graphics.Target build();
+    method public android.support.v7.graphics.Target.Builder setExclusive(boolean);
+    method public android.support.v7.graphics.Target.Builder setLightnessWeight(float);
+    method public android.support.v7.graphics.Target.Builder setMaximumLightness(float);
+    method public android.support.v7.graphics.Target.Builder setMaximumSaturation(float);
+    method public android.support.v7.graphics.Target.Builder setMinimumLightness(float);
+    method public android.support.v7.graphics.Target.Builder setMinimumSaturation(float);
+    method public android.support.v7.graphics.Target.Builder setPopulationWeight(float);
+    method public android.support.v7.graphics.Target.Builder setSaturationWeight(float);
+    method public android.support.v7.graphics.Target.Builder setTargetLightness(float);
+    method public android.support.v7.graphics.Target.Builder setTargetSaturation(float);
+  }
+
+}
+
+package android.support.v7.graphics.drawable {
+
+  public class DrawerArrowDrawable extends android.graphics.drawable.Drawable {
+    ctor public DrawerArrowDrawable(android.content.Context);
+    method public void draw(android.graphics.Canvas);
+    method public float getArrowHeadLength();
+    method public float getArrowShaftLength();
+    method public float getBarLength();
+    method public float getBarThickness();
+    method public int getColor();
+    method public int getDirection();
+    method public float getGapSize();
+    method public int getOpacity();
+    method public final android.graphics.Paint getPaint();
+    method public float getProgress();
+    method public boolean isSpinEnabled();
+    method public void setAlpha(int);
+    method public void setArrowHeadLength(float);
+    method public void setArrowShaftLength(float);
+    method public void setBarLength(float);
+    method public void setBarThickness(float);
+    method public void setColor(int);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setDirection(int);
+    method public void setGapSize(float);
+    method public void setProgress(float);
+    method public void setSpinEnabled(boolean);
+    method public void setVerticalMirror(boolean);
+    field public static final int ARROW_DIRECTION_END = 3; // 0x3
+    field public static final int ARROW_DIRECTION_LEFT = 0; // 0x0
+    field public static final int ARROW_DIRECTION_RIGHT = 1; // 0x1
+    field public static final int ARROW_DIRECTION_START = 2; // 0x2
+  }
+
+}
+
+package android.support.v7.media {
+
+  public final class MediaControlIntent {
+    field public static final java.lang.String ACTION_END_SESSION = "android.media.intent.action.END_SESSION";
+    field public static final java.lang.String ACTION_ENQUEUE = "android.media.intent.action.ENQUEUE";
+    field public static final java.lang.String ACTION_GET_SESSION_STATUS = "android.media.intent.action.GET_SESSION_STATUS";
+    field public static final java.lang.String ACTION_GET_STATUS = "android.media.intent.action.GET_STATUS";
+    field public static final java.lang.String ACTION_PAUSE = "android.media.intent.action.PAUSE";
+    field public static final java.lang.String ACTION_PLAY = "android.media.intent.action.PLAY";
+    field public static final java.lang.String ACTION_REMOVE = "android.media.intent.action.REMOVE";
+    field public static final java.lang.String ACTION_RESUME = "android.media.intent.action.RESUME";
+    field public static final java.lang.String ACTION_SEEK = "android.media.intent.action.SEEK";
+    field public static final java.lang.String ACTION_SEND_MESSAGE = "android.media.intent.action.SEND_MESSAGE";
+    field public static final java.lang.String ACTION_START_SESSION = "android.media.intent.action.START_SESSION";
+    field public static final java.lang.String ACTION_STOP = "android.media.intent.action.STOP";
+    field public static final java.lang.String CATEGORY_LIVE_AUDIO = "android.media.intent.category.LIVE_AUDIO";
+    field public static final java.lang.String CATEGORY_LIVE_VIDEO = "android.media.intent.category.LIVE_VIDEO";
+    field public static final java.lang.String CATEGORY_REMOTE_PLAYBACK = "android.media.intent.category.REMOTE_PLAYBACK";
+    field public static final int ERROR_INVALID_ITEM_ID = 3; // 0x3
+    field public static final int ERROR_INVALID_SESSION_ID = 2; // 0x2
+    field public static final int ERROR_UNKNOWN = 0; // 0x0
+    field public static final int ERROR_UNSUPPORTED_OPERATION = 1; // 0x1
+    field public static final java.lang.String EXTRA_ERROR_CODE = "android.media.intent.extra.ERROR_CODE";
+    field public static final java.lang.String EXTRA_ITEM_CONTENT_POSITION = "android.media.intent.extra.ITEM_POSITION";
+    field public static final java.lang.String EXTRA_ITEM_HTTP_HEADERS = "android.media.intent.extra.HTTP_HEADERS";
+    field public static final java.lang.String EXTRA_ITEM_ID = "android.media.intent.extra.ITEM_ID";
+    field public static final java.lang.String EXTRA_ITEM_METADATA = "android.media.intent.extra.ITEM_METADATA";
+    field public static final java.lang.String EXTRA_ITEM_STATUS = "android.media.intent.extra.ITEM_STATUS";
+    field public static final java.lang.String EXTRA_ITEM_STATUS_UPDATE_RECEIVER = "android.media.intent.extra.ITEM_STATUS_UPDATE_RECEIVER";
+    field public static final java.lang.String EXTRA_MESSAGE = "android.media.intent.extra.MESSAGE";
+    field public static final java.lang.String EXTRA_MESSAGE_RECEIVER = "android.media.intent.extra.MESSAGE_RECEIVER";
+    field public static final java.lang.String EXTRA_SESSION_ID = "android.media.intent.extra.SESSION_ID";
+    field public static final java.lang.String EXTRA_SESSION_STATUS = "android.media.intent.extra.SESSION_STATUS";
+    field public static final java.lang.String EXTRA_SESSION_STATUS_UPDATE_RECEIVER = "android.media.intent.extra.SESSION_STATUS_UPDATE_RECEIVER";
+  }
+
+  public final class MediaItemMetadata {
+    field public static final java.lang.String KEY_ALBUM_ARTIST = "android.media.metadata.ALBUM_ARTIST";
+    field public static final java.lang.String KEY_ALBUM_TITLE = "android.media.metadata.ALBUM_TITLE";
+    field public static final java.lang.String KEY_ARTIST = "android.media.metadata.ARTIST";
+    field public static final java.lang.String KEY_ARTWORK_URI = "android.media.metadata.ARTWORK_URI";
+    field public static final java.lang.String KEY_AUTHOR = "android.media.metadata.AUTHOR";
+    field public static final java.lang.String KEY_COMPOSER = "android.media.metadata.COMPOSER";
+    field public static final java.lang.String KEY_DISC_NUMBER = "android.media.metadata.DISC_NUMBER";
+    field public static final java.lang.String KEY_DURATION = "android.media.metadata.DURATION";
+    field public static final java.lang.String KEY_TITLE = "android.media.metadata.TITLE";
+    field public static final java.lang.String KEY_TRACK_NUMBER = "android.media.metadata.TRACK_NUMBER";
+    field public static final java.lang.String KEY_YEAR = "android.media.metadata.YEAR";
+  }
+
+  public final class MediaItemStatus {
+    method public android.os.Bundle asBundle();
+    method public static android.support.v7.media.MediaItemStatus fromBundle(android.os.Bundle);
+    method public long getContentDuration();
+    method public long getContentPosition();
+    method public android.os.Bundle getExtras();
+    method public int getPlaybackState();
+    method public long getTimestamp();
+    field public static final java.lang.String EXTRA_HTTP_RESPONSE_HEADERS = "android.media.status.extra.HTTP_RESPONSE_HEADERS";
+    field public static final java.lang.String EXTRA_HTTP_STATUS_CODE = "android.media.status.extra.HTTP_STATUS_CODE";
+    field public static final int PLAYBACK_STATE_BUFFERING = 3; // 0x3
+    field public static final int PLAYBACK_STATE_CANCELED = 5; // 0x5
+    field public static final int PLAYBACK_STATE_ERROR = 7; // 0x7
+    field public static final int PLAYBACK_STATE_FINISHED = 4; // 0x4
+    field public static final int PLAYBACK_STATE_INVALIDATED = 6; // 0x6
+    field public static final int PLAYBACK_STATE_PAUSED = 2; // 0x2
+    field public static final int PLAYBACK_STATE_PENDING = 0; // 0x0
+    field public static final int PLAYBACK_STATE_PLAYING = 1; // 0x1
+  }
+
+  public static final class MediaItemStatus.Builder {
+    ctor public MediaItemStatus.Builder(int);
+    ctor public MediaItemStatus.Builder(android.support.v7.media.MediaItemStatus);
+    method public android.support.v7.media.MediaItemStatus build();
+    method public android.support.v7.media.MediaItemStatus.Builder setContentDuration(long);
+    method public android.support.v7.media.MediaItemStatus.Builder setContentPosition(long);
+    method public android.support.v7.media.MediaItemStatus.Builder setExtras(android.os.Bundle);
+    method public android.support.v7.media.MediaItemStatus.Builder setPlaybackState(int);
+    method public android.support.v7.media.MediaItemStatus.Builder setTimestamp(long);
+  }
+
+  public final class MediaRouteDescriptor {
+    method public android.os.Bundle asBundle();
+    method public boolean canDisconnectAndKeepPlaying();
+    method public static android.support.v7.media.MediaRouteDescriptor fromBundle(android.os.Bundle);
+    method public int getConnectionState();
+    method public java.util.List<android.content.IntentFilter> getControlFilters();
+    method public java.lang.String getDescription();
+    method public int getDeviceType();
+    method public android.os.Bundle getExtras();
+    method public android.net.Uri getIconUri();
+    method public java.lang.String getId();
+    method public java.lang.String getName();
+    method public int getPlaybackStream();
+    method public int getPlaybackType();
+    method public int getPresentationDisplayId();
+    method public android.content.IntentSender getSettingsActivity();
+    method public int getVolume();
+    method public int getVolumeHandling();
+    method public int getVolumeMax();
+    method public deprecated boolean isConnecting();
+    method public boolean isEnabled();
+    method public boolean isValid();
+  }
+
+  public static final class MediaRouteDescriptor.Builder {
+    ctor public MediaRouteDescriptor.Builder(java.lang.String, java.lang.String);
+    ctor public MediaRouteDescriptor.Builder(android.support.v7.media.MediaRouteDescriptor);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder addControlFilter(android.content.IntentFilter);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder addControlFilters(java.util.Collection<android.content.IntentFilter>);
+    method public android.support.v7.media.MediaRouteDescriptor build();
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setCanDisconnect(boolean);
+    method public deprecated android.support.v7.media.MediaRouteDescriptor.Builder setConnecting(boolean);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setConnectionState(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setDescription(java.lang.String);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setDeviceType(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setEnabled(boolean);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setExtras(android.os.Bundle);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setIconUri(android.net.Uri);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setId(java.lang.String);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setName(java.lang.String);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setPlaybackStream(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setPlaybackType(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setPresentationDisplayId(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setSettingsActivity(android.content.IntentSender);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setVolume(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setVolumeHandling(int);
+    method public android.support.v7.media.MediaRouteDescriptor.Builder setVolumeMax(int);
+  }
+
+  public final class MediaRouteDiscoveryRequest {
+    ctor public MediaRouteDiscoveryRequest(android.support.v7.media.MediaRouteSelector, boolean);
+    method public android.os.Bundle asBundle();
+    method public static android.support.v7.media.MediaRouteDiscoveryRequest fromBundle(android.os.Bundle);
+    method public android.support.v7.media.MediaRouteSelector getSelector();
+    method public boolean isActiveScan();
+    method public boolean isValid();
+  }
+
+  public abstract class MediaRouteProvider {
+    ctor public MediaRouteProvider(android.content.Context);
+    method public final android.content.Context getContext();
+    method public final android.support.v7.media.MediaRouteProviderDescriptor getDescriptor();
+    method public final android.support.v7.media.MediaRouteDiscoveryRequest getDiscoveryRequest();
+    method public final android.os.Handler getHandler();
+    method public final android.support.v7.media.MediaRouteProvider.ProviderMetadata getMetadata();
+    method public android.support.v7.media.MediaRouteProvider.RouteController onCreateRouteController(java.lang.String);
+    method public void onDiscoveryRequestChanged(android.support.v7.media.MediaRouteDiscoveryRequest);
+    method public final void setCallback(android.support.v7.media.MediaRouteProvider.Callback);
+    method public final void setDescriptor(android.support.v7.media.MediaRouteProviderDescriptor);
+    method public final void setDiscoveryRequest(android.support.v7.media.MediaRouteDiscoveryRequest);
+  }
+
+  public static abstract class MediaRouteProvider.Callback {
+    ctor public MediaRouteProvider.Callback();
+    method public void onDescriptorChanged(android.support.v7.media.MediaRouteProvider, android.support.v7.media.MediaRouteProviderDescriptor);
+  }
+
+  public static final class MediaRouteProvider.ProviderMetadata {
+    method public android.content.ComponentName getComponentName();
+    method public java.lang.String getPackageName();
+  }
+
+  public static abstract class MediaRouteProvider.RouteController {
+    ctor public MediaRouteProvider.RouteController();
+    method public boolean onControlRequest(android.content.Intent, android.support.v7.media.MediaRouter.ControlRequestCallback);
+    method public void onRelease();
+    method public void onSelect();
+    method public void onSetVolume(int);
+    method public void onUnselect();
+    method public void onUnselect(int);
+    method public void onUpdateVolume(int);
+  }
+
+  public final class MediaRouteProviderDescriptor {
+    method public android.os.Bundle asBundle();
+    method public static android.support.v7.media.MediaRouteProviderDescriptor fromBundle(android.os.Bundle);
+    method public java.util.List<android.support.v7.media.MediaRouteDescriptor> getRoutes();
+    method public boolean isValid();
+  }
+
+  public static final class MediaRouteProviderDescriptor.Builder {
+    ctor public MediaRouteProviderDescriptor.Builder();
+    ctor public MediaRouteProviderDescriptor.Builder(android.support.v7.media.MediaRouteProviderDescriptor);
+    method public android.support.v7.media.MediaRouteProviderDescriptor.Builder addRoute(android.support.v7.media.MediaRouteDescriptor);
+    method public android.support.v7.media.MediaRouteProviderDescriptor.Builder addRoutes(java.util.Collection<android.support.v7.media.MediaRouteDescriptor>);
+    method public android.support.v7.media.MediaRouteProviderDescriptor build();
+  }
+
+  public abstract class MediaRouteProviderService extends android.app.Service {
+    ctor public MediaRouteProviderService();
+    method public android.support.v7.media.MediaRouteProvider getMediaRouteProvider();
+    method public android.os.IBinder onBind(android.content.Intent);
+    method public abstract android.support.v7.media.MediaRouteProvider onCreateMediaRouteProvider();
+    field public static final java.lang.String SERVICE_INTERFACE = "android.media.MediaRouteProviderService";
+  }
+
+  public final class MediaRouteSelector {
+    method public android.os.Bundle asBundle();
+    method public boolean contains(android.support.v7.media.MediaRouteSelector);
+    method public static android.support.v7.media.MediaRouteSelector fromBundle(android.os.Bundle);
+    method public java.util.List<java.lang.String> getControlCategories();
+    method public boolean hasControlCategory(java.lang.String);
+    method public boolean isEmpty();
+    method public boolean isValid();
+    method public boolean matchesControlFilters(java.util.List<android.content.IntentFilter>);
+    field public static final android.support.v7.media.MediaRouteSelector EMPTY;
+  }
+
+  public static final class MediaRouteSelector.Builder {
+    ctor public MediaRouteSelector.Builder();
+    ctor public MediaRouteSelector.Builder(android.support.v7.media.MediaRouteSelector);
+    method public android.support.v7.media.MediaRouteSelector.Builder addControlCategories(java.util.Collection<java.lang.String>);
+    method public android.support.v7.media.MediaRouteSelector.Builder addControlCategory(java.lang.String);
+    method public android.support.v7.media.MediaRouteSelector.Builder addSelector(android.support.v7.media.MediaRouteSelector);
+    method public android.support.v7.media.MediaRouteSelector build();
+  }
+
+  public final class MediaRouter {
+    method public void addCallback(android.support.v7.media.MediaRouteSelector, android.support.v7.media.MediaRouter.Callback);
+    method public void addCallback(android.support.v7.media.MediaRouteSelector, android.support.v7.media.MediaRouter.Callback, int);
+    method public void addProvider(android.support.v7.media.MediaRouteProvider);
+    method public void addRemoteControlClient(java.lang.Object);
+    method public android.support.v7.media.MediaRouter.RouteInfo getBluetoothRoute();
+    method public android.support.v7.media.MediaRouter.RouteInfo getDefaultRoute();
+    method public static android.support.v7.media.MediaRouter getInstance(android.content.Context);
+    method public android.support.v4.media.session.MediaSessionCompat.Token getMediaSessionToken();
+    method public java.util.List<android.support.v7.media.MediaRouter.ProviderInfo> getProviders();
+    method public java.util.List<android.support.v7.media.MediaRouter.RouteInfo> getRoutes();
+    method public android.support.v7.media.MediaRouter.RouteInfo getSelectedRoute();
+    method public boolean isRouteAvailable(android.support.v7.media.MediaRouteSelector, int);
+    method public void removeCallback(android.support.v7.media.MediaRouter.Callback);
+    method public void removeProvider(android.support.v7.media.MediaRouteProvider);
+    method public void removeRemoteControlClient(java.lang.Object);
+    method public void selectRoute(android.support.v7.media.MediaRouter.RouteInfo);
+    method public void setMediaSession(java.lang.Object);
+    method public void setMediaSessionCompat(android.support.v4.media.session.MediaSessionCompat);
+    method public void unselect(int);
+    method public android.support.v7.media.MediaRouter.RouteInfo updateSelectedRoute(android.support.v7.media.MediaRouteSelector);
+    field public static final int AVAILABILITY_FLAG_IGNORE_DEFAULT_ROUTE = 1; // 0x1
+    field public static final int AVAILABILITY_FLAG_REQUIRE_MATCH = 2; // 0x2
+    field public static final int CALLBACK_FLAG_FORCE_DISCOVERY = 8; // 0x8
+    field public static final int CALLBACK_FLAG_PERFORM_ACTIVE_SCAN = 1; // 0x1
+    field public static final int CALLBACK_FLAG_REQUEST_DISCOVERY = 4; // 0x4
+    field public static final int CALLBACK_FLAG_UNFILTERED_EVENTS = 2; // 0x2
+    field public static final int UNSELECT_REASON_DISCONNECTED = 1; // 0x1
+    field public static final int UNSELECT_REASON_ROUTE_CHANGED = 3; // 0x3
+    field public static final int UNSELECT_REASON_STOPPED = 2; // 0x2
+    field public static final int UNSELECT_REASON_UNKNOWN = 0; // 0x0
+  }
+
+  public static abstract class MediaRouter.Callback {
+    ctor public MediaRouter.Callback();
+    method public void onProviderAdded(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.ProviderInfo);
+    method public void onProviderChanged(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.ProviderInfo);
+    method public void onProviderRemoved(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.ProviderInfo);
+    method public void onRouteAdded(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRouteChanged(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRoutePresentationDisplayChanged(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRouteRemoved(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRouteSelected(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRouteUnselected(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void onRouteUnselected(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo, int);
+    method public void onRouteVolumeChanged(android.support.v7.media.MediaRouter, android.support.v7.media.MediaRouter.RouteInfo);
+  }
+
+  public static abstract class MediaRouter.ControlRequestCallback {
+    ctor public MediaRouter.ControlRequestCallback();
+    method public void onError(java.lang.String, android.os.Bundle);
+    method public void onResult(android.os.Bundle);
+  }
+
+  public static final class MediaRouter.ProviderInfo {
+    method public android.content.ComponentName getComponentName();
+    method public java.lang.String getPackageName();
+    method public android.support.v7.media.MediaRouteProvider getProviderInstance();
+    method public java.util.List<android.support.v7.media.MediaRouter.RouteInfo> getRoutes();
+  }
+
+  public static class MediaRouter.RouteInfo {
+    method public boolean canDisconnect();
+    method public int getConnectionState();
+    method public java.util.List<android.content.IntentFilter> getControlFilters();
+    method public java.lang.String getDescription();
+    method public int getDeviceType();
+    method public android.os.Bundle getExtras();
+    method public android.net.Uri getIconUri();
+    method public java.lang.String getId();
+    method public java.lang.String getName();
+    method public int getPlaybackStream();
+    method public int getPlaybackType();
+    method public android.view.Display getPresentationDisplay();
+    method public android.support.v7.media.MediaRouter.ProviderInfo getProvider();
+    method public android.content.IntentSender getSettingsIntent();
+    method public int getVolume();
+    method public int getVolumeHandling();
+    method public int getVolumeMax();
+    method public boolean isBluetooth();
+    method public boolean isConnecting();
+    method public boolean isDefault();
+    method public boolean isDeviceSpeaker();
+    method public boolean isEnabled();
+    method public boolean isSelected();
+    method public boolean matchesSelector(android.support.v7.media.MediaRouteSelector);
+    method public void requestSetVolume(int);
+    method public void requestUpdateVolume(int);
+    method public void select();
+    method public void sendControlRequest(android.content.Intent, android.support.v7.media.MediaRouter.ControlRequestCallback);
+    method public boolean supportsControlAction(java.lang.String, java.lang.String);
+    method public boolean supportsControlCategory(java.lang.String);
+    method public boolean supportsControlRequest(android.content.Intent);
+    field public static final int CONNECTION_STATE_CONNECTED = 2; // 0x2
+    field public static final int CONNECTION_STATE_CONNECTING = 1; // 0x1
+    field public static final int CONNECTION_STATE_DISCONNECTED = 0; // 0x0
+    field public static final int DEVICE_TYPE_SPEAKER = 2; // 0x2
+    field public static final int DEVICE_TYPE_TV = 1; // 0x1
+    field public static final int PLAYBACK_TYPE_LOCAL = 0; // 0x0
+    field public static final int PLAYBACK_TYPE_REMOTE = 1; // 0x1
+    field public static final int PLAYBACK_VOLUME_FIXED = 0; // 0x0
+    field public static final int PLAYBACK_VOLUME_VARIABLE = 1; // 0x1
+  }
+
+  public final class MediaSessionStatus {
+    method public android.os.Bundle asBundle();
+    method public static android.support.v7.media.MediaSessionStatus fromBundle(android.os.Bundle);
+    method public android.os.Bundle getExtras();
+    method public int getSessionState();
+    method public long getTimestamp();
+    method public boolean isQueuePaused();
+    field public static final int SESSION_STATE_ACTIVE = 0; // 0x0
+    field public static final int SESSION_STATE_ENDED = 1; // 0x1
+    field public static final int SESSION_STATE_INVALIDATED = 2; // 0x2
+  }
+
+  public static final class MediaSessionStatus.Builder {
+    ctor public MediaSessionStatus.Builder(int);
+    ctor public MediaSessionStatus.Builder(android.support.v7.media.MediaSessionStatus);
+    method public android.support.v7.media.MediaSessionStatus build();
+    method public android.support.v7.media.MediaSessionStatus.Builder setExtras(android.os.Bundle);
+    method public android.support.v7.media.MediaSessionStatus.Builder setQueuePaused(boolean);
+    method public android.support.v7.media.MediaSessionStatus.Builder setSessionState(int);
+    method public android.support.v7.media.MediaSessionStatus.Builder setTimestamp(long);
+  }
+
+  public class RemotePlaybackClient {
+    ctor public RemotePlaybackClient(android.content.Context, android.support.v7.media.MediaRouter.RouteInfo);
+    method public void endSession(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void enqueue(android.net.Uri, java.lang.String, android.os.Bundle, long, android.os.Bundle, android.support.v7.media.RemotePlaybackClient.ItemActionCallback);
+    method public java.lang.String getSessionId();
+    method public void getSessionStatus(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void getStatus(java.lang.String, android.os.Bundle, android.support.v7.media.RemotePlaybackClient.ItemActionCallback);
+    method public boolean hasSession();
+    method public boolean isMessagingSupported();
+    method public boolean isQueuingSupported();
+    method public boolean isRemotePlaybackSupported();
+    method public boolean isSessionManagementSupported();
+    method public void pause(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void play(android.net.Uri, java.lang.String, android.os.Bundle, long, android.os.Bundle, android.support.v7.media.RemotePlaybackClient.ItemActionCallback);
+    method public void release();
+    method public void remove(java.lang.String, android.os.Bundle, android.support.v7.media.RemotePlaybackClient.ItemActionCallback);
+    method public void resume(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void seek(java.lang.String, long, android.os.Bundle, android.support.v7.media.RemotePlaybackClient.ItemActionCallback);
+    method public void sendMessage(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void setOnMessageReceivedListener(android.support.v7.media.RemotePlaybackClient.OnMessageReceivedListener);
+    method public void setSessionId(java.lang.String);
+    method public void setStatusCallback(android.support.v7.media.RemotePlaybackClient.StatusCallback);
+    method public void startSession(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+    method public void stop(android.os.Bundle, android.support.v7.media.RemotePlaybackClient.SessionActionCallback);
+  }
+
+  public static abstract class RemotePlaybackClient.ActionCallback {
+    ctor public RemotePlaybackClient.ActionCallback();
+    method public void onError(java.lang.String, int, android.os.Bundle);
+  }
+
+  public static abstract class RemotePlaybackClient.ItemActionCallback extends android.support.v7.media.RemotePlaybackClient.ActionCallback {
+    ctor public RemotePlaybackClient.ItemActionCallback();
+    method public void onResult(android.os.Bundle, java.lang.String, android.support.v7.media.MediaSessionStatus, java.lang.String, android.support.v7.media.MediaItemStatus);
+  }
+
+  public static abstract interface RemotePlaybackClient.OnMessageReceivedListener {
+    method public abstract void onMessageReceived(java.lang.String, android.os.Bundle);
+  }
+
+  public static abstract class RemotePlaybackClient.SessionActionCallback extends android.support.v7.media.RemotePlaybackClient.ActionCallback {
+    ctor public RemotePlaybackClient.SessionActionCallback();
+    method public void onResult(android.os.Bundle, java.lang.String, android.support.v7.media.MediaSessionStatus);
+  }
+
+  public static abstract class RemotePlaybackClient.StatusCallback {
+    ctor public RemotePlaybackClient.StatusCallback();
+    method public void onItemStatusChanged(android.os.Bundle, java.lang.String, android.support.v7.media.MediaSessionStatus, java.lang.String, android.support.v7.media.MediaItemStatus);
+    method public void onSessionChanged(java.lang.String);
+    method public void onSessionStatusChanged(android.os.Bundle, java.lang.String, android.support.v7.media.MediaSessionStatus);
+  }
+
+}
+
+package android.support.v7.preference {
+
+  public class CheckBoxPreference extends android.support.v7.preference.TwoStatePreference {
+    ctor public CheckBoxPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public CheckBoxPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public CheckBoxPreference(android.content.Context, android.util.AttributeSet);
+    ctor public CheckBoxPreference(android.content.Context);
+  }
+
+  public abstract class DialogPreference extends android.support.v7.preference.Preference {
+    ctor public DialogPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public DialogPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public DialogPreference(android.content.Context, android.util.AttributeSet);
+    ctor public DialogPreference(android.content.Context);
+    method public android.graphics.drawable.Drawable getDialogIcon();
+    method public int getDialogLayoutResource();
+    method public java.lang.CharSequence getDialogMessage();
+    method public java.lang.CharSequence getDialogTitle();
+    method public java.lang.CharSequence getNegativeButtonText();
+    method public java.lang.CharSequence getPositiveButtonText();
+    method public void setDialogIcon(android.graphics.drawable.Drawable);
+    method public void setDialogIcon(int);
+    method public void setDialogLayoutResource(int);
+    method public void setDialogMessage(java.lang.CharSequence);
+    method public void setDialogMessage(int);
+    method public void setDialogTitle(java.lang.CharSequence);
+    method public void setDialogTitle(int);
+    method public void setNegativeButtonText(java.lang.CharSequence);
+    method public void setNegativeButtonText(int);
+    method public void setPositiveButtonText(java.lang.CharSequence);
+    method public void setPositiveButtonText(int);
+  }
+
+  public static abstract interface DialogPreference.TargetFragment {
+    method public abstract android.support.v7.preference.Preference findPreference(java.lang.CharSequence);
+  }
+
+  public class DropDownPreference extends android.support.v7.preference.ListPreference {
+    ctor public DropDownPreference(android.content.Context);
+    ctor public DropDownPreference(android.content.Context, android.util.AttributeSet);
+    ctor public DropDownPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public DropDownPreference(android.content.Context, android.util.AttributeSet, int, int);
+    method protected android.widget.ArrayAdapter createAdapter();
+  }
+
+  public class EditTextPreference extends android.support.v7.preference.DialogPreference {
+    ctor public EditTextPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public EditTextPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public EditTextPreference(android.content.Context, android.util.AttributeSet);
+    ctor public EditTextPreference(android.content.Context);
+    method public java.lang.String getText();
+    method public void setText(java.lang.String);
+  }
+
+  public class EditTextPreferenceDialogFragmentCompat extends android.support.v7.preference.PreferenceDialogFragmentCompat {
+    ctor public EditTextPreferenceDialogFragmentCompat();
+    method public static android.support.v7.preference.EditTextPreferenceDialogFragmentCompat newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public class ListPreference extends android.support.v7.preference.DialogPreference {
+    ctor public ListPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public ListPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public ListPreference(android.content.Context, android.util.AttributeSet);
+    ctor public ListPreference(android.content.Context);
+    method public int findIndexOfValue(java.lang.String);
+    method public java.lang.CharSequence[] getEntries();
+    method public java.lang.CharSequence getEntry();
+    method public java.lang.CharSequence[] getEntryValues();
+    method public java.lang.String getValue();
+    method public void setEntries(java.lang.CharSequence[]);
+    method public void setEntries(int);
+    method public void setEntryValues(java.lang.CharSequence[]);
+    method public void setEntryValues(int);
+    method public void setValue(java.lang.String);
+    method public void setValueIndex(int);
+  }
+
+  public class ListPreferenceDialogFragmentCompat extends android.support.v7.preference.PreferenceDialogFragmentCompat {
+    ctor public ListPreferenceDialogFragmentCompat();
+    method public static android.support.v7.preference.ListPreferenceDialogFragmentCompat newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public class MultiSelectListPreferenceDialogFragmentCompat extends android.support.v7.preference.PreferenceDialogFragmentCompat {
+    ctor public MultiSelectListPreferenceDialogFragmentCompat();
+    method public static android.support.v7.preference.MultiSelectListPreferenceDialogFragmentCompat newInstance(java.lang.String);
+    method public void onDialogClosed(boolean);
+  }
+
+  public class Preference implements java.lang.Comparable {
+    ctor public Preference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public Preference(android.content.Context, android.util.AttributeSet, int);
+    ctor public Preference(android.content.Context, android.util.AttributeSet);
+    ctor public Preference(android.content.Context);
+    method public boolean callChangeListener(java.lang.Object);
+    method public int compareTo(android.support.v7.preference.Preference);
+    method protected android.support.v7.preference.Preference findPreferenceInHierarchy(java.lang.String);
+    method public android.content.Context getContext();
+    method public java.lang.String getDependency();
+    method public android.os.Bundle getExtras();
+    method public java.lang.String getFragment();
+    method public android.graphics.drawable.Drawable getIcon();
+    method public android.content.Intent getIntent();
+    method public java.lang.String getKey();
+    method public final int getLayoutResource();
+    method public android.support.v7.preference.Preference.OnPreferenceChangeListener getOnPreferenceChangeListener();
+    method public android.support.v7.preference.Preference.OnPreferenceClickListener getOnPreferenceClickListener();
+    method public int getOrder();
+    method public android.support.v7.preference.PreferenceGroup getParent();
+    method protected boolean getPersistedBoolean(boolean);
+    method protected float getPersistedFloat(float);
+    method protected int getPersistedInt(int);
+    method protected long getPersistedLong(long);
+    method protected java.lang.String getPersistedString(java.lang.String);
+    method public java.util.Set<java.lang.String> getPersistedStringSet(java.util.Set<java.lang.String>);
+    method public android.support.v7.preference.PreferenceDataStore getPreferenceDataStore();
+    method public android.support.v7.preference.PreferenceManager getPreferenceManager();
+    method public android.content.SharedPreferences getSharedPreferences();
+    method public boolean getShouldDisableView();
+    method public java.lang.CharSequence getSummary();
+    method public java.lang.CharSequence getTitle();
+    method public final int getWidgetLayoutResource();
+    method public boolean hasKey();
+    method public boolean isEnabled();
+    method public boolean isIconSpaceReserved();
+    method public boolean isPersistent();
+    method public boolean isSelectable();
+    method public boolean isSingleLineTitle();
+    method public final boolean isVisible();
+    method protected void notifyChanged();
+    method public void notifyDependencyChange(boolean);
+    method protected void notifyHierarchyChanged();
+    method public void onAttached();
+    method protected void onAttachedToHierarchy(android.support.v7.preference.PreferenceManager);
+    method public void onBindViewHolder(android.support.v7.preference.PreferenceViewHolder);
+    method protected void onClick();
+    method public void onDependencyChanged(android.support.v7.preference.Preference, boolean);
+    method public void onDetached();
+    method protected java.lang.Object onGetDefaultValue(android.content.res.TypedArray, int);
+    method public void onInitializeAccessibilityNodeInfo(android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public void onParentChanged(android.support.v7.preference.Preference, boolean);
+    method protected void onPrepareForRemoval();
+    method protected void onRestoreInstanceState(android.os.Parcelable);
+    method protected android.os.Parcelable onSaveInstanceState();
+    method protected void onSetInitialValue(boolean, java.lang.Object);
+    method public android.os.Bundle peekExtras();
+    method protected boolean persistBoolean(boolean);
+    method protected boolean persistFloat(float);
+    method protected boolean persistInt(int);
+    method protected boolean persistLong(long);
+    method protected boolean persistString(java.lang.String);
+    method public boolean persistStringSet(java.util.Set<java.lang.String>);
+    method public void restoreHierarchyState(android.os.Bundle);
+    method public void saveHierarchyState(android.os.Bundle);
+    method public void setDefaultValue(java.lang.Object);
+    method public void setDependency(java.lang.String);
+    method public void setEnabled(boolean);
+    method public void setFragment(java.lang.String);
+    method public void setIcon(android.graphics.drawable.Drawable);
+    method public void setIcon(int);
+    method public void setIconSpaceReserved(boolean);
+    method public void setIntent(android.content.Intent);
+    method public void setKey(java.lang.String);
+    method public void setLayoutResource(int);
+    method public void setOnPreferenceChangeListener(android.support.v7.preference.Preference.OnPreferenceChangeListener);
+    method public void setOnPreferenceClickListener(android.support.v7.preference.Preference.OnPreferenceClickListener);
+    method public void setOrder(int);
+    method public void setPersistent(boolean);
+    method public void setPreferenceDataStore(android.support.v7.preference.PreferenceDataStore);
+    method public void setSelectable(boolean);
+    method public void setShouldDisableView(boolean);
+    method public void setSingleLineTitle(boolean);
+    method public void setSummary(java.lang.CharSequence);
+    method public void setSummary(int);
+    method public void setTitle(java.lang.CharSequence);
+    method public void setTitle(int);
+    method public void setViewId(int);
+    method public final void setVisible(boolean);
+    method public void setWidgetLayoutResource(int);
+    method public boolean shouldDisableDependents();
+    method protected boolean shouldPersist();
+    field public static final int DEFAULT_ORDER = 2147483647; // 0x7fffffff
+  }
+
+  public static class Preference.BaseSavedState extends android.view.AbsSavedState {
+    ctor public Preference.BaseSavedState(android.os.Parcel);
+    ctor public Preference.BaseSavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.v7.preference.Preference.BaseSavedState> CREATOR;
+  }
+
+  public static abstract interface Preference.OnPreferenceChangeListener {
+    method public abstract boolean onPreferenceChange(android.support.v7.preference.Preference, java.lang.Object);
+  }
+
+  public static abstract interface Preference.OnPreferenceClickListener {
+    method public abstract boolean onPreferenceClick(android.support.v7.preference.Preference);
+  }
+
+  public class PreferenceCategory extends android.support.v7.preference.PreferenceGroup {
+    ctor public PreferenceCategory(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public PreferenceCategory(android.content.Context, android.util.AttributeSet, int);
+    ctor public PreferenceCategory(android.content.Context, android.util.AttributeSet);
+    ctor public PreferenceCategory(android.content.Context);
+  }
+
+  public abstract class PreferenceDataStore {
+    ctor public PreferenceDataStore();
+    method public boolean getBoolean(java.lang.String, boolean);
+    method public float getFloat(java.lang.String, float);
+    method public int getInt(java.lang.String, int);
+    method public long getLong(java.lang.String, long);
+    method public java.lang.String getString(java.lang.String, java.lang.String);
+    method public java.util.Set<java.lang.String> getStringSet(java.lang.String, java.util.Set<java.lang.String>);
+    method public void putBoolean(java.lang.String, boolean);
+    method public void putFloat(java.lang.String, float);
+    method public void putInt(java.lang.String, int);
+    method public void putLong(java.lang.String, long);
+    method public void putString(java.lang.String, java.lang.String);
+    method public void putStringSet(java.lang.String, java.util.Set<java.lang.String>);
+  }
+
+  public abstract class PreferenceDialogFragmentCompat extends android.support.v4.app.DialogFragment implements android.content.DialogInterface.OnClickListener {
+    ctor public PreferenceDialogFragmentCompat();
+    method public android.support.v7.preference.DialogPreference getPreference();
+    method protected void onBindDialogView(android.view.View);
+    method public void onClick(android.content.DialogInterface, int);
+    method protected android.view.View onCreateDialogView(android.content.Context);
+    method public abstract void onDialogClosed(boolean);
+    method protected void onPrepareDialogBuilder(android.support.v7.app.AlertDialog.Builder);
+    field protected static final java.lang.String ARG_KEY = "key";
+  }
+
+  public abstract class PreferenceFragmentCompat extends android.support.v4.app.Fragment implements android.support.v7.preference.DialogPreference.TargetFragment android.support.v7.preference.PreferenceManager.OnDisplayPreferenceDialogListener android.support.v7.preference.PreferenceManager.OnNavigateToScreenListener android.support.v7.preference.PreferenceManager.OnPreferenceTreeClickListener {
+    ctor public PreferenceFragmentCompat();
+    method public void addPreferencesFromResource(int);
+    method public android.support.v7.preference.Preference findPreference(java.lang.CharSequence);
+    method public final android.support.v7.widget.RecyclerView getListView();
+    method public android.support.v7.preference.PreferenceManager getPreferenceManager();
+    method public android.support.v7.preference.PreferenceScreen getPreferenceScreen();
+    method protected android.support.v7.widget.RecyclerView.Adapter onCreateAdapter(android.support.v7.preference.PreferenceScreen);
+    method public android.support.v7.widget.RecyclerView.LayoutManager onCreateLayoutManager();
+    method public abstract void onCreatePreferences(android.os.Bundle, java.lang.String);
+    method public android.support.v7.widget.RecyclerView onCreateRecyclerView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle);
+    method public void onDisplayPreferenceDialog(android.support.v7.preference.Preference);
+    method public void onNavigateToScreen(android.support.v7.preference.PreferenceScreen);
+    method public boolean onPreferenceTreeClick(android.support.v7.preference.Preference);
+    method public void scrollToPreference(java.lang.String);
+    method public void scrollToPreference(android.support.v7.preference.Preference);
+    method public void setDivider(android.graphics.drawable.Drawable);
+    method public void setDividerHeight(int);
+    method public void setPreferenceScreen(android.support.v7.preference.PreferenceScreen);
+    method public void setPreferencesFromResource(int, java.lang.String);
+    field public static final java.lang.String ARG_PREFERENCE_ROOT = "android.support.v7.preference.PreferenceFragmentCompat.PREFERENCE_ROOT";
+  }
+
+  public static abstract interface PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback {
+    method public abstract boolean onPreferenceDisplayDialog(android.support.v7.preference.PreferenceFragmentCompat, android.support.v7.preference.Preference);
+  }
+
+  public static abstract interface PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
+    method public abstract boolean onPreferenceStartFragment(android.support.v7.preference.PreferenceFragmentCompat, android.support.v7.preference.Preference);
+  }
+
+  public static abstract interface PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
+    method public abstract boolean onPreferenceStartScreen(android.support.v7.preference.PreferenceFragmentCompat, android.support.v7.preference.PreferenceScreen);
+  }
+
+  public abstract class PreferenceGroup extends android.support.v7.preference.Preference {
+    ctor public PreferenceGroup(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public PreferenceGroup(android.content.Context, android.util.AttributeSet, int);
+    ctor public PreferenceGroup(android.content.Context, android.util.AttributeSet);
+    method public void addItemFromInflater(android.support.v7.preference.Preference);
+    method public boolean addPreference(android.support.v7.preference.Preference);
+    method protected void dispatchRestoreInstanceState(android.os.Bundle);
+    method protected void dispatchSaveInstanceState(android.os.Bundle);
+    method public android.support.v7.preference.Preference findPreference(java.lang.CharSequence);
+    method public android.support.v7.preference.Preference getPreference(int);
+    method public int getPreferenceCount();
+    method protected boolean isOnSameScreenAsChildren();
+    method public boolean isOrderingAsAdded();
+    method protected boolean onPrepareAddPreference(android.support.v7.preference.Preference);
+    method public void removeAll();
+    method public boolean removePreference(android.support.v7.preference.Preference);
+    method public void setOrderingAsAdded(boolean);
+  }
+
+  public static abstract interface PreferenceGroup.PreferencePositionCallback {
+    method public abstract int getPreferenceAdapterPosition(java.lang.String);
+    method public abstract int getPreferenceAdapterPosition(android.support.v7.preference.Preference);
+  }
+
+  public class PreferenceManager {
+    method public android.support.v7.preference.PreferenceScreen createPreferenceScreen(android.content.Context);
+    method public android.support.v7.preference.Preference findPreference(java.lang.CharSequence);
+    method public android.content.Context getContext();
+    method public static android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context);
+    method public android.support.v7.preference.PreferenceManager.OnDisplayPreferenceDialogListener getOnDisplayPreferenceDialogListener();
+    method public android.support.v7.preference.PreferenceManager.OnNavigateToScreenListener getOnNavigateToScreenListener();
+    method public android.support.v7.preference.PreferenceManager.OnPreferenceTreeClickListener getOnPreferenceTreeClickListener();
+    method public android.support.v7.preference.PreferenceManager.PreferenceComparisonCallback getPreferenceComparisonCallback();
+    method public android.support.v7.preference.PreferenceDataStore getPreferenceDataStore();
+    method public android.support.v7.preference.PreferenceScreen getPreferenceScreen();
+    method public android.content.SharedPreferences getSharedPreferences();
+    method public int getSharedPreferencesMode();
+    method public java.lang.String getSharedPreferencesName();
+    method public boolean isStorageDefault();
+    method public boolean isStorageDeviceProtected();
+    method public static void setDefaultValues(android.content.Context, int, boolean);
+    method public static void setDefaultValues(android.content.Context, java.lang.String, int, int, boolean);
+    method public void setOnDisplayPreferenceDialogListener(android.support.v7.preference.PreferenceManager.OnDisplayPreferenceDialogListener);
+    method public void setOnNavigateToScreenListener(android.support.v7.preference.PreferenceManager.OnNavigateToScreenListener);
+    method public void setOnPreferenceTreeClickListener(android.support.v7.preference.PreferenceManager.OnPreferenceTreeClickListener);
+    method public void setPreferenceComparisonCallback(android.support.v7.preference.PreferenceManager.PreferenceComparisonCallback);
+    method public void setPreferenceDataStore(android.support.v7.preference.PreferenceDataStore);
+    method public boolean setPreferences(android.support.v7.preference.PreferenceScreen);
+    method public void setSharedPreferencesMode(int);
+    method public void setSharedPreferencesName(java.lang.String);
+    method public void setStorageDefault();
+    method public void setStorageDeviceProtected();
+    method public void showDialog(android.support.v7.preference.Preference);
+    field public static final java.lang.String KEY_HAS_SET_DEFAULT_VALUES = "_has_set_default_values";
+  }
+
+  public static abstract interface PreferenceManager.OnDisplayPreferenceDialogListener {
+    method public abstract void onDisplayPreferenceDialog(android.support.v7.preference.Preference);
+  }
+
+  public static abstract interface PreferenceManager.OnNavigateToScreenListener {
+    method public abstract void onNavigateToScreen(android.support.v7.preference.PreferenceScreen);
+  }
+
+  public static abstract interface PreferenceManager.OnPreferenceTreeClickListener {
+    method public abstract boolean onPreferenceTreeClick(android.support.v7.preference.Preference);
+  }
+
+  public static abstract class PreferenceManager.PreferenceComparisonCallback {
+    ctor public PreferenceManager.PreferenceComparisonCallback();
+    method public abstract boolean arePreferenceContentsTheSame(android.support.v7.preference.Preference, android.support.v7.preference.Preference);
+    method public abstract boolean arePreferenceItemsTheSame(android.support.v7.preference.Preference, android.support.v7.preference.Preference);
+  }
+
+  public static class PreferenceManager.SimplePreferenceComparisonCallback extends android.support.v7.preference.PreferenceManager.PreferenceComparisonCallback {
+    ctor public PreferenceManager.SimplePreferenceComparisonCallback();
+    method public boolean arePreferenceContentsTheSame(android.support.v7.preference.Preference, android.support.v7.preference.Preference);
+    method public boolean arePreferenceItemsTheSame(android.support.v7.preference.Preference, android.support.v7.preference.Preference);
+  }
+
+  public final class PreferenceScreen extends android.support.v7.preference.PreferenceGroup {
+    method public void setShouldUseGeneratedIds(boolean);
+    method public boolean shouldUseGeneratedIds();
+  }
+
+  public class PreferenceViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
+    method public android.view.View findViewById(int);
+    method public boolean isDividerAllowedAbove();
+    method public boolean isDividerAllowedBelow();
+    method public void setDividerAllowedAbove(boolean);
+    method public void setDividerAllowedBelow(boolean);
+  }
+
+  public class SeekBarPreference extends android.support.v7.preference.Preference {
+    ctor public SeekBarPreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public SeekBarPreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public SeekBarPreference(android.content.Context, android.util.AttributeSet);
+    ctor public SeekBarPreference(android.content.Context);
+    method public int getMax();
+    method public int getMin();
+    method public final int getSeekBarIncrement();
+    method public int getValue();
+    method public boolean isAdjustable();
+    method public void setAdjustable(boolean);
+    method public final void setMax(int);
+    method public void setMin(int);
+    method public final void setSeekBarIncrement(int);
+    method public void setValue(int);
+  }
+
+  public class SwitchPreferenceCompat extends android.support.v7.preference.TwoStatePreference {
+    ctor public SwitchPreferenceCompat(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public SwitchPreferenceCompat(android.content.Context, android.util.AttributeSet, int);
+    ctor public SwitchPreferenceCompat(android.content.Context, android.util.AttributeSet);
+    ctor public SwitchPreferenceCompat(android.content.Context);
+    method public java.lang.CharSequence getSwitchTextOff();
+    method public java.lang.CharSequence getSwitchTextOn();
+    method public void setSwitchTextOff(java.lang.CharSequence);
+    method public void setSwitchTextOff(int);
+    method public void setSwitchTextOn(java.lang.CharSequence);
+    method public void setSwitchTextOn(int);
+  }
+
+  public abstract class TwoStatePreference extends android.support.v7.preference.Preference {
+    ctor public TwoStatePreference(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public TwoStatePreference(android.content.Context, android.util.AttributeSet, int);
+    ctor public TwoStatePreference(android.content.Context, android.util.AttributeSet);
+    ctor public TwoStatePreference(android.content.Context);
+    method public boolean getDisableDependentsState();
+    method public java.lang.CharSequence getSummaryOff();
+    method public java.lang.CharSequence getSummaryOn();
+    method public boolean isChecked();
+    method public void setChecked(boolean);
+    method public void setDisableDependentsState(boolean);
+    method public void setSummaryOff(java.lang.CharSequence);
+    method public void setSummaryOff(int);
+    method public void setSummaryOn(java.lang.CharSequence);
+    method public void setSummaryOn(int);
+    method protected void syncSummaryView(android.support.v7.preference.PreferenceViewHolder);
+    field protected boolean mChecked;
+  }
+
+}
+
+package android.support.v7.util {
+
+  public class AsyncListUtil<T> {
+    ctor public AsyncListUtil(java.lang.Class<T>, int, android.support.v7.util.AsyncListUtil.DataCallback<T>, android.support.v7.util.AsyncListUtil.ViewCallback);
+    method public T getItem(int);
+    method public int getItemCount();
+    method public void onRangeChanged();
+    method public void refresh();
+  }
+
+  public static abstract class AsyncListUtil.DataCallback<T> {
+    ctor public AsyncListUtil.DataCallback();
+    method public abstract void fillData(T[], int, int);
+    method public int getMaxCachedTiles();
+    method public void recycleData(T[], int);
+    method public abstract int refreshData();
+  }
+
+  public static abstract class AsyncListUtil.ViewCallback {
+    ctor public AsyncListUtil.ViewCallback();
+    method public void extendRangeInto(int[], int[], int);
+    method public abstract void getItemRangeInto(int[]);
+    method public abstract void onDataRefresh();
+    method public abstract void onItemLoaded(int);
+    field public static final int HINT_SCROLL_ASC = 2; // 0x2
+    field public static final int HINT_SCROLL_DESC = 1; // 0x1
+    field public static final int HINT_SCROLL_NONE = 0; // 0x0
+  }
+
+  public class BatchingListUpdateCallback implements android.support.v7.util.ListUpdateCallback {
+    ctor public BatchingListUpdateCallback(android.support.v7.util.ListUpdateCallback);
+    method public void dispatchLastEvent();
+    method public void onChanged(int, int, java.lang.Object);
+    method public void onInserted(int, int);
+    method public void onMoved(int, int);
+    method public void onRemoved(int, int);
+  }
+
+  public class DiffUtil {
+    method public static android.support.v7.util.DiffUtil.DiffResult calculateDiff(android.support.v7.util.DiffUtil.Callback);
+    method public static android.support.v7.util.DiffUtil.DiffResult calculateDiff(android.support.v7.util.DiffUtil.Callback, boolean);
+  }
+
+  public static abstract class DiffUtil.Callback {
+    ctor public DiffUtil.Callback();
+    method public abstract boolean areContentsTheSame(int, int);
+    method public abstract boolean areItemsTheSame(int, int);
+    method public java.lang.Object getChangePayload(int, int);
+    method public abstract int getNewListSize();
+    method public abstract int getOldListSize();
+  }
+
+  public static class DiffUtil.DiffResult {
+    method public void dispatchUpdatesTo(android.support.v7.widget.RecyclerView.Adapter);
+    method public void dispatchUpdatesTo(android.support.v7.util.ListUpdateCallback);
+  }
+
+  public abstract interface ListUpdateCallback {
+    method public abstract void onChanged(int, int, java.lang.Object);
+    method public abstract void onInserted(int, int);
+    method public abstract void onMoved(int, int);
+    method public abstract void onRemoved(int, int);
+  }
+
+  public class SortedList<T> {
+    ctor public SortedList(java.lang.Class<T>, android.support.v7.util.SortedList.Callback<T>);
+    ctor public SortedList(java.lang.Class<T>, android.support.v7.util.SortedList.Callback<T>, int);
+    method public int add(T);
+    method public void addAll(T[], boolean);
+    method public void addAll(T...);
+    method public void addAll(java.util.Collection<T>);
+    method public void beginBatchedUpdates();
+    method public void clear();
+    method public void endBatchedUpdates();
+    method public T get(int) throws java.lang.IndexOutOfBoundsException;
+    method public int indexOf(T);
+    method public void recalculatePositionOfItemAt(int);
+    method public boolean remove(T);
+    method public T removeItemAt(int);
+    method public int size();
+    method public void updateItemAt(int, T);
+    field public static final int INVALID_POSITION = -1; // 0xffffffff
+  }
+
+  public static class SortedList.BatchedCallback<T2> extends android.support.v7.util.SortedList.Callback {
+    ctor public SortedList.BatchedCallback(android.support.v7.util.SortedList.Callback<T2>);
+    method public boolean areContentsTheSame(T2, T2);
+    method public boolean areItemsTheSame(T2, T2);
+    method public int compare(T2, T2);
+    method public void dispatchLastEvent();
+    method public void onChanged(int, int);
+    method public void onInserted(int, int);
+    method public void onMoved(int, int);
+    method public void onRemoved(int, int);
+  }
+
+  public static abstract class SortedList.Callback<T2> implements java.util.Comparator android.support.v7.util.ListUpdateCallback {
+    ctor public SortedList.Callback();
+    method public abstract boolean areContentsTheSame(T2, T2);
+    method public abstract boolean areItemsTheSame(T2, T2);
+    method public abstract int compare(T2, T2);
+    method public abstract void onChanged(int, int);
+    method public void onChanged(int, int, java.lang.Object);
+  }
+
+}
+
+package android.support.v7.view {
+
+  public abstract class ActionMode {
+    ctor public ActionMode();
+    method public abstract void finish();
+    method public abstract android.view.View getCustomView();
+    method public abstract android.view.Menu getMenu();
+    method public abstract android.view.MenuInflater getMenuInflater();
+    method public abstract java.lang.CharSequence getSubtitle();
+    method public java.lang.Object getTag();
+    method public abstract java.lang.CharSequence getTitle();
+    method public boolean getTitleOptionalHint();
+    method public abstract void invalidate();
+    method public boolean isTitleOptional();
+    method public abstract void setCustomView(android.view.View);
+    method public abstract void setSubtitle(java.lang.CharSequence);
+    method public abstract void setSubtitle(int);
+    method public void setTag(java.lang.Object);
+    method public abstract void setTitle(java.lang.CharSequence);
+    method public abstract void setTitle(int);
+    method public void setTitleOptionalHint(boolean);
+  }
+
+  public static abstract interface ActionMode.Callback {
+    method public abstract boolean onActionItemClicked(android.support.v7.view.ActionMode, android.view.MenuItem);
+    method public abstract boolean onCreateActionMode(android.support.v7.view.ActionMode, android.view.Menu);
+    method public abstract void onDestroyActionMode(android.support.v7.view.ActionMode);
+    method public abstract boolean onPrepareActionMode(android.support.v7.view.ActionMode, android.view.Menu);
+  }
+
+  public abstract interface CollapsibleActionView {
+    method public abstract void onActionViewCollapsed();
+    method public abstract void onActionViewExpanded();
+  }
+
+}
+
+package android.support.v7.widget {
+
+  public class ActionMenuView extends android.support.v7.widget.LinearLayoutCompat {
+    ctor public ActionMenuView(android.content.Context);
+    ctor public ActionMenuView(android.content.Context, android.util.AttributeSet);
+    method public void dismissPopupMenus();
+    method protected android.support.v7.widget.ActionMenuView.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.ActionMenuView.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.ActionMenuView.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public android.view.Menu getMenu();
+    method public android.graphics.drawable.Drawable getOverflowIcon();
+    method public int getPopupTheme();
+    method public boolean hideOverflowMenu();
+    method public boolean isOverflowMenuShowing();
+    method public void onConfigurationChanged(android.content.res.Configuration);
+    method public void onDetachedFromWindow();
+    method public void setOnMenuItemClickListener(android.support.v7.widget.ActionMenuView.OnMenuItemClickListener);
+    method public void setOverflowIcon(android.graphics.drawable.Drawable);
+    method public void setPopupTheme(int);
+    method public boolean showOverflowMenu();
+  }
+
+  public static class ActionMenuView.LayoutParams extends android.support.v7.widget.LinearLayoutCompat.LayoutParams {
+    ctor public ActionMenuView.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public ActionMenuView.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public ActionMenuView.LayoutParams(android.support.v7.widget.ActionMenuView.LayoutParams);
+    ctor public ActionMenuView.LayoutParams(int, int);
+    field public int cellsUsed;
+    field public boolean expandable;
+    field public int extraPixels;
+    field public boolean isOverflowButton;
+    field public boolean preventEdgeOffset;
+  }
+
+  public static abstract interface ActionMenuView.OnMenuItemClickListener {
+    method public abstract boolean onMenuItemClick(android.view.MenuItem);
+  }
+
+  public class AppCompatAutoCompleteTextView extends android.widget.AutoCompleteTextView implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatAutoCompleteTextView(android.content.Context);
+    ctor public AppCompatAutoCompleteTextView(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatAutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class AppCompatButton extends android.widget.Button implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatButton(android.content.Context);
+    ctor public AppCompatButton(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatButton(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setSupportAllCaps(boolean);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class AppCompatCheckBox extends android.widget.CheckBox implements android.support.v4.widget.TintableCompoundButton {
+    ctor public AppCompatCheckBox(android.content.Context);
+    ctor public AppCompatCheckBox(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatCheckBox(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class AppCompatCheckedTextView extends android.widget.CheckedTextView {
+    ctor public AppCompatCheckedTextView(android.content.Context);
+    ctor public AppCompatCheckedTextView(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatCheckedTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class AppCompatEditText extends android.widget.EditText implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatEditText(android.content.Context);
+    ctor public AppCompatEditText(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatEditText(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class AppCompatImageButton extends android.widget.ImageButton implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatImageButton(android.content.Context);
+    ctor public AppCompatImageButton(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatImageButton(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+  }
+
+  public class AppCompatImageView extends android.widget.ImageView implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatImageView(android.content.Context);
+    ctor public AppCompatImageView(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatImageView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+  }
+
+  public class AppCompatMultiAutoCompleteTextView extends android.widget.MultiAutoCompleteTextView implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatMultiAutoCompleteTextView(android.content.Context);
+    ctor public AppCompatMultiAutoCompleteTextView(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatMultiAutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class AppCompatRadioButton extends android.widget.RadioButton implements android.support.v4.widget.TintableCompoundButton {
+    ctor public AppCompatRadioButton(android.content.Context);
+    ctor public AppCompatRadioButton(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatRadioButton(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class AppCompatRatingBar extends android.widget.RatingBar {
+    ctor public AppCompatRatingBar(android.content.Context);
+    ctor public AppCompatRatingBar(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatRatingBar(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class AppCompatSeekBar extends android.widget.SeekBar {
+    ctor public AppCompatSeekBar(android.content.Context);
+    ctor public AppCompatSeekBar(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatSeekBar(android.content.Context, android.util.AttributeSet, int);
+  }
+
+  public class AppCompatSpinner extends android.widget.Spinner implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatSpinner(android.content.Context);
+    ctor public AppCompatSpinner(android.content.Context, int);
+    ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int);
+    ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public AppCompatSpinner(android.content.Context, android.util.AttributeSet, int, int, android.content.res.Resources.Theme);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+  }
+
+  public class AppCompatTextView extends android.widget.TextView implements android.support.v4.view.TintableBackgroundView {
+    ctor public AppCompatTextView(android.content.Context);
+    ctor public AppCompatTextView(android.content.Context, android.util.AttributeSet);
+    ctor public AppCompatTextView(android.content.Context, android.util.AttributeSet, int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setTextAppearance(android.content.Context, int);
+  }
+
+  public class CardView extends android.widget.FrameLayout {
+    ctor public CardView(android.content.Context);
+    ctor public CardView(android.content.Context, android.util.AttributeSet);
+    ctor public CardView(android.content.Context, android.util.AttributeSet, int);
+    method public android.content.res.ColorStateList getCardBackgroundColor();
+    method public float getCardElevation();
+    method public int getContentPaddingBottom();
+    method public int getContentPaddingLeft();
+    method public int getContentPaddingRight();
+    method public int getContentPaddingTop();
+    method public float getMaxCardElevation();
+    method public boolean getPreventCornerOverlap();
+    method public float getRadius();
+    method public boolean getUseCompatPadding();
+    method public void setCardBackgroundColor(int);
+    method public void setCardBackgroundColor(android.content.res.ColorStateList);
+    method public void setCardElevation(float);
+    method public void setContentPadding(int, int, int, int);
+    method public void setMaxCardElevation(float);
+    method public void setPreventCornerOverlap(boolean);
+    method public void setRadius(float);
+    method public void setUseCompatPadding(boolean);
+  }
+
+  public class DefaultItemAnimator extends android.support.v7.widget.SimpleItemAnimator {
+    ctor public DefaultItemAnimator();
+    method public boolean animateAdd(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public boolean animateChange(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder, int, int, int, int);
+    method public boolean animateMove(android.support.v7.widget.RecyclerView.ViewHolder, int, int, int, int);
+    method public boolean animateRemove(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void endAnimation(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void endAnimations();
+    method public boolean isRunning();
+    method public void runPendingAnimations();
+  }
+
+  public class DividerItemDecoration extends android.support.v7.widget.RecyclerView.ItemDecoration {
+    ctor public DividerItemDecoration(android.content.Context, int);
+    method public void setDrawable(android.graphics.drawable.Drawable);
+    method public void setOrientation(int);
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  public class GridLayout extends android.view.ViewGroup {
+    ctor public GridLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public GridLayout(android.content.Context, android.util.AttributeSet);
+    ctor public GridLayout(android.content.Context);
+    method protected android.support.v7.widget.GridLayout.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.GridLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.GridLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getAlignmentMode();
+    method public int getColumnCount();
+    method public int getOrientation();
+    method public android.util.Printer getPrinter();
+    method public int getRowCount();
+    method public boolean getUseDefaultMargins();
+    method public boolean isColumnOrderPreserved();
+    method public boolean isRowOrderPreserved();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void setAlignmentMode(int);
+    method public void setColumnCount(int);
+    method public void setColumnOrderPreserved(boolean);
+    method public void setOrientation(int);
+    method public void setPrinter(android.util.Printer);
+    method public void setRowCount(int);
+    method public void setRowOrderPreserved(boolean);
+    method public void setUseDefaultMargins(boolean);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, int, android.support.v7.widget.GridLayout.Alignment, float);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, android.support.v7.widget.GridLayout.Alignment, float);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, int, float);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, float);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, int, android.support.v7.widget.GridLayout.Alignment);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, android.support.v7.widget.GridLayout.Alignment);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int, int);
+    method public static android.support.v7.widget.GridLayout.Spec spec(int);
+    field public static final int ALIGN_BOUNDS = 0; // 0x0
+    field public static final int ALIGN_MARGINS = 1; // 0x1
+    field public static final android.support.v7.widget.GridLayout.Alignment BASELINE;
+    field public static final android.support.v7.widget.GridLayout.Alignment BOTTOM;
+    field public static final android.support.v7.widget.GridLayout.Alignment CENTER;
+    field public static final android.support.v7.widget.GridLayout.Alignment END;
+    field public static final android.support.v7.widget.GridLayout.Alignment FILL;
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final android.support.v7.widget.GridLayout.Alignment LEFT;
+    field public static final android.support.v7.widget.GridLayout.Alignment RIGHT;
+    field public static final android.support.v7.widget.GridLayout.Alignment START;
+    field public static final android.support.v7.widget.GridLayout.Alignment TOP;
+    field public static final int UNDEFINED = -2147483648; // 0x80000000
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  public static abstract class GridLayout.Alignment {
+  }
+
+  public static class GridLayout.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public GridLayout.LayoutParams(android.support.v7.widget.GridLayout.Spec, android.support.v7.widget.GridLayout.Spec);
+    ctor public GridLayout.LayoutParams();
+    ctor public GridLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public GridLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public GridLayout.LayoutParams(android.support.v7.widget.GridLayout.LayoutParams);
+    ctor public GridLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    method public void setGravity(int);
+    field public android.support.v7.widget.GridLayout.Spec columnSpec;
+    field public android.support.v7.widget.GridLayout.Spec rowSpec;
+  }
+
+  public static class GridLayout.Spec {
+    method public android.support.v7.widget.GridLayout.Alignment getAbsoluteAlignment(boolean);
+  }
+
+  public class GridLayoutManager extends android.support.v7.widget.LinearLayoutManager {
+    ctor public GridLayoutManager(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public GridLayoutManager(android.content.Context, int);
+    ctor public GridLayoutManager(android.content.Context, int, int, boolean);
+    method public int getSpanCount();
+    method public android.support.v7.widget.GridLayoutManager.SpanSizeLookup getSpanSizeLookup();
+    method public void setSpanCount(int);
+    method public void setSpanSizeLookup(android.support.v7.widget.GridLayoutManager.SpanSizeLookup);
+    field public static final int DEFAULT_SPAN_COUNT = -1; // 0xffffffff
+  }
+
+  public static final class GridLayoutManager.DefaultSpanSizeLookup extends android.support.v7.widget.GridLayoutManager.SpanSizeLookup {
+    ctor public GridLayoutManager.DefaultSpanSizeLookup();
+    method public int getSpanSize(int);
+  }
+
+  public static class GridLayoutManager.LayoutParams extends android.support.v7.widget.RecyclerView.LayoutParams {
+    ctor public GridLayoutManager.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public GridLayoutManager.LayoutParams(int, int);
+    ctor public GridLayoutManager.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public GridLayoutManager.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public GridLayoutManager.LayoutParams(android.support.v7.widget.RecyclerView.LayoutParams);
+    method public int getSpanIndex();
+    method public int getSpanSize();
+    field public static final int INVALID_SPAN_ID = -1; // 0xffffffff
+  }
+
+  public static abstract class GridLayoutManager.SpanSizeLookup {
+    ctor public GridLayoutManager.SpanSizeLookup();
+    method public int getSpanGroupIndex(int, int);
+    method public int getSpanIndex(int, int);
+    method public abstract int getSpanSize(int);
+    method public void invalidateSpanIndexCache();
+    method public boolean isSpanIndexCacheEnabled();
+    method public void setSpanIndexCacheEnabled(boolean);
+  }
+
+  public class LinearLayoutCompat extends android.view.ViewGroup {
+    ctor public LinearLayoutCompat(android.content.Context);
+    ctor public LinearLayoutCompat(android.content.Context, android.util.AttributeSet);
+    ctor public LinearLayoutCompat(android.content.Context, android.util.AttributeSet, int);
+    method protected android.support.v7.widget.LinearLayoutCompat.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.LinearLayoutCompat.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.LinearLayoutCompat.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getBaselineAlignedChildIndex();
+    method public android.graphics.drawable.Drawable getDividerDrawable();
+    method public int getDividerPadding();
+    method public int getGravity();
+    method public int getOrientation();
+    method public int getShowDividers();
+    method public float getWeightSum();
+    method public boolean isBaselineAligned();
+    method public boolean isMeasureWithLargestChildEnabled();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void setBaselineAligned(boolean);
+    method public void setBaselineAlignedChildIndex(int);
+    method public void setDividerDrawable(android.graphics.drawable.Drawable);
+    method public void setDividerPadding(int);
+    method public void setGravity(int);
+    method public void setHorizontalGravity(int);
+    method public void setMeasureWithLargestChildEnabled(boolean);
+    method public void setOrientation(int);
+    method public void setShowDividers(int);
+    method public void setVerticalGravity(int);
+    method public void setWeightSum(float);
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int SHOW_DIVIDER_BEGINNING = 1; // 0x1
+    field public static final int SHOW_DIVIDER_END = 4; // 0x4
+    field public static final int SHOW_DIVIDER_MIDDLE = 2; // 0x2
+    field public static final int SHOW_DIVIDER_NONE = 0; // 0x0
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  public static class LinearLayoutCompat.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public LinearLayoutCompat.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public LinearLayoutCompat.LayoutParams(int, int);
+    ctor public LinearLayoutCompat.LayoutParams(int, int, float);
+    ctor public LinearLayoutCompat.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public LinearLayoutCompat.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public LinearLayoutCompat.LayoutParams(android.support.v7.widget.LinearLayoutCompat.LayoutParams);
+    field public int gravity;
+    field public float weight;
+  }
+
+  public class LinearLayoutManager extends android.support.v7.widget.RecyclerView.LayoutManager implements android.support.v7.widget.helper.ItemTouchHelper.ViewDropHandler android.support.v7.widget.RecyclerView.SmoothScroller.ScrollVectorProvider {
+    ctor public LinearLayoutManager(android.content.Context);
+    ctor public LinearLayoutManager(android.content.Context, int, boolean);
+    ctor public LinearLayoutManager(android.content.Context, android.util.AttributeSet, int, int);
+    method public android.graphics.PointF computeScrollVectorForPosition(int);
+    method public int findFirstCompletelyVisibleItemPosition();
+    method public int findFirstVisibleItemPosition();
+    method public int findLastCompletelyVisibleItemPosition();
+    method public int findLastVisibleItemPosition();
+    method public android.support.v7.widget.RecyclerView.LayoutParams generateDefaultLayoutParams();
+    method protected int getExtraLayoutSpace(android.support.v7.widget.RecyclerView.State);
+    method public int getInitialPrefetchItemCount();
+    method public int getOrientation();
+    method public boolean getRecycleChildrenOnDetach();
+    method public boolean getReverseLayout();
+    method public boolean getStackFromEnd();
+    method protected boolean isLayoutRTL();
+    method public boolean isSmoothScrollbarEnabled();
+    method public void scrollToPositionWithOffset(int, int);
+    method public void setInitialPrefetchItemCount(int);
+    method public void setOrientation(int);
+    method public void setRecycleChildrenOnDetach(boolean);
+    method public void setReverseLayout(boolean);
+    method public void setSmoothScrollbarEnabled(boolean);
+    method public void setStackFromEnd(boolean);
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int INVALID_OFFSET = -2147483648; // 0x80000000
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  protected static class LinearLayoutManager.LayoutChunkResult {
+    ctor protected LinearLayoutManager.LayoutChunkResult();
+    field public int mConsumed;
+    field public boolean mFinished;
+    field public boolean mFocusable;
+    field public boolean mIgnoreConsumed;
+  }
+
+  public class LinearSmoothScroller extends android.support.v7.widget.RecyclerView.SmoothScroller {
+    ctor public LinearSmoothScroller(android.content.Context);
+    method public int calculateDtToFit(int, int, int, int, int);
+    method public int calculateDxToMakeVisible(android.view.View, int);
+    method public int calculateDyToMakeVisible(android.view.View, int);
+    method protected float calculateSpeedPerPixel(android.util.DisplayMetrics);
+    method protected int calculateTimeForDeceleration(int);
+    method protected int calculateTimeForScrolling(int);
+    method public android.graphics.PointF computeScrollVectorForPosition(int);
+    method protected int getHorizontalSnapPreference();
+    method protected int getVerticalSnapPreference();
+    method protected void onSeekTargetStep(int, int, android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.SmoothScroller.Action);
+    method protected void onStart();
+    method protected void onStop();
+    method protected void onTargetFound(android.view.View, android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.SmoothScroller.Action);
+    method protected void updateActionForInterimTarget(android.support.v7.widget.RecyclerView.SmoothScroller.Action);
+    field public static final int SNAP_TO_ANY = 0; // 0x0
+    field public static final int SNAP_TO_END = 1; // 0x1
+    field public static final int SNAP_TO_START = -1; // 0xffffffff
+    field protected final android.view.animation.DecelerateInterpolator mDecelerateInterpolator;
+    field protected int mInterimTargetDx;
+    field protected int mInterimTargetDy;
+    field protected final android.view.animation.LinearInterpolator mLinearInterpolator;
+    field protected android.graphics.PointF mTargetVector;
+  }
+
+  public class LinearSnapHelper extends android.support.v7.widget.SnapHelper {
+    ctor public LinearSnapHelper();
+    method public int[] calculateDistanceToFinalSnap(android.support.v7.widget.RecyclerView.LayoutManager, android.view.View);
+    method public android.view.View findSnapView(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public int findTargetSnapPosition(android.support.v7.widget.RecyclerView.LayoutManager, int, int);
+  }
+
+  public class ListPopupWindow {
+    ctor public ListPopupWindow(android.content.Context);
+    ctor public ListPopupWindow(android.content.Context, android.util.AttributeSet);
+    ctor public ListPopupWindow(android.content.Context, android.util.AttributeSet, int);
+    ctor public ListPopupWindow(android.content.Context, android.util.AttributeSet, int, int);
+    method public void clearListSelection();
+    method public android.view.View.OnTouchListener createDragToOpenListener(android.view.View);
+    method public void dismiss();
+    method public android.view.View getAnchorView();
+    method public int getAnimationStyle();
+    method public android.graphics.drawable.Drawable getBackground();
+    method public int getHeight();
+    method public int getHorizontalOffset();
+    method public int getInputMethodMode();
+    method public android.widget.ListView getListView();
+    method public int getPromptPosition();
+    method public java.lang.Object getSelectedItem();
+    method public long getSelectedItemId();
+    method public int getSelectedItemPosition();
+    method public android.view.View getSelectedView();
+    method public int getSoftInputMode();
+    method public int getVerticalOffset();
+    method public int getWidth();
+    method public boolean isInputMethodNotNeeded();
+    method public boolean isModal();
+    method public boolean isShowing();
+    method public boolean onKeyDown(int, android.view.KeyEvent);
+    method public boolean onKeyPreIme(int, android.view.KeyEvent);
+    method public boolean onKeyUp(int, android.view.KeyEvent);
+    method public boolean performItemClick(int);
+    method public void postShow();
+    method public void setAdapter(android.widget.ListAdapter);
+    method public void setAnchorView(android.view.View);
+    method public void setAnimationStyle(int);
+    method public void setBackgroundDrawable(android.graphics.drawable.Drawable);
+    method public void setContentWidth(int);
+    method public void setDropDownGravity(int);
+    method public void setHeight(int);
+    method public void setHorizontalOffset(int);
+    method public void setInputMethodMode(int);
+    method public void setListSelector(android.graphics.drawable.Drawable);
+    method public void setModal(boolean);
+    method public void setOnDismissListener(android.widget.PopupWindow.OnDismissListener);
+    method public void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener);
+    method public void setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener);
+    method public void setPromptPosition(int);
+    method public void setPromptView(android.view.View);
+    method public void setSelection(int);
+    method public void setSoftInputMode(int);
+    method public void setVerticalOffset(int);
+    method public void setWidth(int);
+    method public void setWindowLayoutType(int);
+    method public void show();
+    field public static final int INPUT_METHOD_FROM_FOCUSABLE = 0; // 0x0
+    field public static final int INPUT_METHOD_NEEDED = 1; // 0x1
+    field public static final int INPUT_METHOD_NOT_NEEDED = 2; // 0x2
+    field public static final int MATCH_PARENT = -1; // 0xffffffff
+    field public static final int POSITION_PROMPT_ABOVE = 0; // 0x0
+    field public static final int POSITION_PROMPT_BELOW = 1; // 0x1
+    field public static final int WRAP_CONTENT = -2; // 0xfffffffe
+  }
+
+  public abstract class OrientationHelper {
+    method public static android.support.v7.widget.OrientationHelper createHorizontalHelper(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public static android.support.v7.widget.OrientationHelper createOrientationHelper(android.support.v7.widget.RecyclerView.LayoutManager, int);
+    method public static android.support.v7.widget.OrientationHelper createVerticalHelper(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public abstract int getDecoratedEnd(android.view.View);
+    method public abstract int getDecoratedMeasurement(android.view.View);
+    method public abstract int getDecoratedMeasurementInOther(android.view.View);
+    method public abstract int getDecoratedStart(android.view.View);
+    method public abstract int getEnd();
+    method public abstract int getEndAfterPadding();
+    method public abstract int getEndPadding();
+    method public abstract int getMode();
+    method public abstract int getModeInOther();
+    method public abstract int getStartAfterPadding();
+    method public abstract int getTotalSpace();
+    method public int getTotalSpaceChange();
+    method public abstract int getTransformedEndWithDecoration(android.view.View);
+    method public abstract int getTransformedStartWithDecoration(android.view.View);
+    method public abstract void offsetChild(android.view.View, int);
+    method public abstract void offsetChildren(int);
+    method public void onLayoutComplete();
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int VERTICAL = 1; // 0x1
+    field protected final android.support.v7.widget.RecyclerView.LayoutManager mLayoutManager;
+  }
+
+  public class PagerSnapHelper extends android.support.v7.widget.SnapHelper {
+    ctor public PagerSnapHelper();
+    method public int[] calculateDistanceToFinalSnap(android.support.v7.widget.RecyclerView.LayoutManager, android.view.View);
+    method protected android.support.v7.widget.LinearSmoothScroller createSnapScroller(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public android.view.View findSnapView(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public int findTargetSnapPosition(android.support.v7.widget.RecyclerView.LayoutManager, int, int);
+  }
+
+  public class PopupMenu {
+    ctor public PopupMenu(android.content.Context, android.view.View);
+    ctor public PopupMenu(android.content.Context, android.view.View, int);
+    ctor public PopupMenu(android.content.Context, android.view.View, int, int, int);
+    method public void dismiss();
+    method public android.view.View.OnTouchListener getDragToOpenListener();
+    method public int getGravity();
+    method public android.view.Menu getMenu();
+    method public android.view.MenuInflater getMenuInflater();
+    method public void inflate(int);
+    method public void setGravity(int);
+    method public void setOnDismissListener(android.support.v7.widget.PopupMenu.OnDismissListener);
+    method public void setOnMenuItemClickListener(android.support.v7.widget.PopupMenu.OnMenuItemClickListener);
+    method public void show();
+  }
+
+  public static abstract interface PopupMenu.OnDismissListener {
+    method public abstract void onDismiss(android.support.v7.widget.PopupMenu);
+  }
+
+  public static abstract interface PopupMenu.OnMenuItemClickListener {
+    method public abstract boolean onMenuItemClick(android.view.MenuItem);
+  }
+
+  public class RecyclerView extends android.view.ViewGroup implements android.support.v4.view.NestedScrollingChild2 android.support.v4.view.ScrollingView {
+    ctor public RecyclerView(android.content.Context);
+    ctor public RecyclerView(android.content.Context, android.util.AttributeSet);
+    ctor public RecyclerView(android.content.Context, android.util.AttributeSet, int);
+    method public void addItemDecoration(android.support.v7.widget.RecyclerView.ItemDecoration, int);
+    method public void addItemDecoration(android.support.v7.widget.RecyclerView.ItemDecoration);
+    method public void addOnChildAttachStateChangeListener(android.support.v7.widget.RecyclerView.OnChildAttachStateChangeListener);
+    method public void addOnItemTouchListener(android.support.v7.widget.RecyclerView.OnItemTouchListener);
+    method public void addOnScrollListener(android.support.v7.widget.RecyclerView.OnScrollListener);
+    method public void clearOnChildAttachStateChangeListeners();
+    method public void clearOnScrollListeners();
+    method public int computeHorizontalScrollExtent();
+    method public int computeHorizontalScrollOffset();
+    method public int computeHorizontalScrollRange();
+    method public int computeVerticalScrollExtent();
+    method public int computeVerticalScrollOffset();
+    method public int computeVerticalScrollRange();
+    method public boolean dispatchNestedPreScroll(int, int, int[], int[], int);
+    method public boolean dispatchNestedScroll(int, int, int, int, int[], int);
+    method public boolean drawChild(android.graphics.Canvas, android.view.View, long);
+    method public android.view.View findChildViewUnder(float, float);
+    method public android.view.View findContainingItemView(android.view.View);
+    method public android.support.v7.widget.RecyclerView.ViewHolder findContainingViewHolder(android.view.View);
+    method public android.support.v7.widget.RecyclerView.ViewHolder findViewHolderForAdapterPosition(int);
+    method public android.support.v7.widget.RecyclerView.ViewHolder findViewHolderForItemId(long);
+    method public android.support.v7.widget.RecyclerView.ViewHolder findViewHolderForLayoutPosition(int);
+    method public deprecated android.support.v7.widget.RecyclerView.ViewHolder findViewHolderForPosition(int);
+    method public boolean fling(int, int);
+    method public android.support.v7.widget.RecyclerView.Adapter getAdapter();
+    method public int getChildAdapterPosition(android.view.View);
+    method public long getChildItemId(android.view.View);
+    method public int getChildLayoutPosition(android.view.View);
+    method public deprecated int getChildPosition(android.view.View);
+    method public android.support.v7.widget.RecyclerView.ViewHolder getChildViewHolder(android.view.View);
+    method public android.support.v7.widget.RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate();
+    method public void getDecoratedBoundsWithMargins(android.view.View, android.graphics.Rect);
+    method public android.support.v7.widget.RecyclerView.ItemAnimator getItemAnimator();
+    method public android.support.v7.widget.RecyclerView.ItemDecoration getItemDecorationAt(int);
+    method public android.support.v7.widget.RecyclerView.LayoutManager getLayoutManager();
+    method public int getMaxFlingVelocity();
+    method public int getMinFlingVelocity();
+    method public android.support.v7.widget.RecyclerView.OnFlingListener getOnFlingListener();
+    method public boolean getPreserveFocusAfterLayout();
+    method public android.support.v7.widget.RecyclerView.RecycledViewPool getRecycledViewPool();
+    method public int getScrollState();
+    method public boolean hasFixedSize();
+    method public boolean hasNestedScrollingParent(int);
+    method public boolean hasPendingAdapterUpdates();
+    method public void invalidateItemDecorations();
+    method public boolean isAnimating();
+    method public boolean isComputingLayout();
+    method public boolean isLayoutFrozen();
+    method public void offsetChildrenHorizontal(int);
+    method public void offsetChildrenVertical(int);
+    method public void onChildAttachedToWindow(android.view.View);
+    method public void onChildDetachedFromWindow(android.view.View);
+    method public void onDraw(android.graphics.Canvas);
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void onScrollStateChanged(int);
+    method public void onScrolled(int, int);
+    method public void removeItemDecoration(android.support.v7.widget.RecyclerView.ItemDecoration);
+    method public void removeOnChildAttachStateChangeListener(android.support.v7.widget.RecyclerView.OnChildAttachStateChangeListener);
+    method public void removeOnItemTouchListener(android.support.v7.widget.RecyclerView.OnItemTouchListener);
+    method public void removeOnScrollListener(android.support.v7.widget.RecyclerView.OnScrollListener);
+    method public void scrollToPosition(int);
+    method public void setAccessibilityDelegateCompat(android.support.v7.widget.RecyclerViewAccessibilityDelegate);
+    method public void setAdapter(android.support.v7.widget.RecyclerView.Adapter);
+    method public void setChildDrawingOrderCallback(android.support.v7.widget.RecyclerView.ChildDrawingOrderCallback);
+    method public void setHasFixedSize(boolean);
+    method public void setItemAnimator(android.support.v7.widget.RecyclerView.ItemAnimator);
+    method public void setItemViewCacheSize(int);
+    method public void setLayoutFrozen(boolean);
+    method public void setLayoutManager(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public void setOnFlingListener(android.support.v7.widget.RecyclerView.OnFlingListener);
+    method public deprecated void setOnScrollListener(android.support.v7.widget.RecyclerView.OnScrollListener);
+    method public void setPreserveFocusAfterLayout(boolean);
+    method public void setRecycledViewPool(android.support.v7.widget.RecyclerView.RecycledViewPool);
+    method public void setRecyclerListener(android.support.v7.widget.RecyclerView.RecyclerListener);
+    method public void setScrollingTouchSlop(int);
+    method public void setViewCacheExtension(android.support.v7.widget.RecyclerView.ViewCacheExtension);
+    method public void smoothScrollBy(int, int);
+    method public void smoothScrollBy(int, int, android.view.animation.Interpolator);
+    method public void smoothScrollToPosition(int);
+    method public boolean startNestedScroll(int, int);
+    method public void stopNestedScroll(int);
+    method public void stopScroll();
+    method public void swapAdapter(android.support.v7.widget.RecyclerView.Adapter, boolean);
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int INVALID_TYPE = -1; // 0xffffffff
+    field public static final long NO_ID = -1L; // 0xffffffffffffffffL
+    field public static final int NO_POSITION = -1; // 0xffffffff
+    field public static final int SCROLL_STATE_DRAGGING = 1; // 0x1
+    field public static final int SCROLL_STATE_IDLE = 0; // 0x0
+    field public static final int SCROLL_STATE_SETTLING = 2; // 0x2
+    field public static final int TOUCH_SLOP_DEFAULT = 0; // 0x0
+    field public static final int TOUCH_SLOP_PAGING = 1; // 0x1
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  public static abstract class RecyclerView.Adapter<VH extends android.support.v7.widget.RecyclerView.ViewHolder> {
+    ctor public RecyclerView.Adapter();
+    method public final void bindViewHolder(VH, int);
+    method public final VH createViewHolder(android.view.ViewGroup, int);
+    method public abstract int getItemCount();
+    method public long getItemId(int);
+    method public int getItemViewType(int);
+    method public final boolean hasObservers();
+    method public final boolean hasStableIds();
+    method public final void notifyDataSetChanged();
+    method public final void notifyItemChanged(int);
+    method public final void notifyItemChanged(int, java.lang.Object);
+    method public final void notifyItemInserted(int);
+    method public final void notifyItemMoved(int, int);
+    method public final void notifyItemRangeChanged(int, int);
+    method public final void notifyItemRangeChanged(int, int, java.lang.Object);
+    method public final void notifyItemRangeInserted(int, int);
+    method public final void notifyItemRangeRemoved(int, int);
+    method public final void notifyItemRemoved(int);
+    method public void onAttachedToRecyclerView(android.support.v7.widget.RecyclerView);
+    method public abstract void onBindViewHolder(VH, int);
+    method public void onBindViewHolder(VH, int, java.util.List<java.lang.Object>);
+    method public abstract VH onCreateViewHolder(android.view.ViewGroup, int);
+    method public void onDetachedFromRecyclerView(android.support.v7.widget.RecyclerView);
+    method public boolean onFailedToRecycleView(VH);
+    method public void onViewAttachedToWindow(VH);
+    method public void onViewDetachedFromWindow(VH);
+    method public void onViewRecycled(VH);
+    method public void registerAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver);
+    method public void setHasStableIds(boolean);
+    method public void unregisterAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver);
+  }
+
+  public static abstract class RecyclerView.AdapterDataObserver {
+    ctor public RecyclerView.AdapterDataObserver();
+    method public void onChanged();
+    method public void onItemRangeChanged(int, int);
+    method public void onItemRangeChanged(int, int, java.lang.Object);
+    method public void onItemRangeInserted(int, int);
+    method public void onItemRangeMoved(int, int, int);
+    method public void onItemRangeRemoved(int, int);
+  }
+
+  public static abstract interface RecyclerView.ChildDrawingOrderCallback {
+    method public abstract int onGetChildDrawingOrder(int, int);
+  }
+
+  public static abstract class RecyclerView.ItemAnimator {
+    ctor public RecyclerView.ItemAnimator();
+    method public abstract boolean animateAppearance(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animateChange(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animateDisappearance(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animatePersistence(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public boolean canReuseUpdatedViewHolder(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public boolean canReuseUpdatedViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, java.util.List<java.lang.Object>);
+    method public final void dispatchAnimationFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchAnimationStarted(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchAnimationsFinished();
+    method public abstract void endAnimation(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public abstract void endAnimations();
+    method public long getAddDuration();
+    method public long getChangeDuration();
+    method public long getMoveDuration();
+    method public long getRemoveDuration();
+    method public abstract boolean isRunning();
+    method public final boolean isRunning(android.support.v7.widget.RecyclerView.ItemAnimator.ItemAnimatorFinishedListener);
+    method public android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo obtainHolderInfo();
+    method public void onAnimationFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onAnimationStarted(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo recordPostLayoutInformation(android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo recordPreLayoutInformation(android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.ViewHolder, int, java.util.List<java.lang.Object>);
+    method public abstract void runPendingAnimations();
+    method public void setAddDuration(long);
+    method public void setChangeDuration(long);
+    method public void setMoveDuration(long);
+    method public void setRemoveDuration(long);
+    field public static final int FLAG_APPEARED_IN_PRE_LAYOUT = 4096; // 0x1000
+    field public static final int FLAG_CHANGED = 2; // 0x2
+    field public static final int FLAG_INVALIDATED = 4; // 0x4
+    field public static final int FLAG_MOVED = 2048; // 0x800
+    field public static final int FLAG_REMOVED = 8; // 0x8
+  }
+
+  public static abstract class RecyclerView.ItemAnimator.AdapterChanges implements java.lang.annotation.Annotation {
+  }
+
+  public static abstract interface RecyclerView.ItemAnimator.ItemAnimatorFinishedListener {
+    method public abstract void onAnimationsFinished();
+  }
+
+  public static class RecyclerView.ItemAnimator.ItemHolderInfo {
+    ctor public RecyclerView.ItemAnimator.ItemHolderInfo();
+    method public android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo setFrom(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo setFrom(android.support.v7.widget.RecyclerView.ViewHolder, int);
+    field public int bottom;
+    field public int changeFlags;
+    field public int left;
+    field public int right;
+    field public int top;
+  }
+
+  public static abstract class RecyclerView.ItemDecoration {
+    ctor public RecyclerView.ItemDecoration();
+    method public deprecated void getItemOffsets(android.graphics.Rect, int, android.support.v7.widget.RecyclerView);
+    method public void getItemOffsets(android.graphics.Rect, android.view.View, android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.State);
+    method public void onDraw(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.State);
+    method public deprecated void onDraw(android.graphics.Canvas, android.support.v7.widget.RecyclerView);
+    method public void onDrawOver(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.State);
+    method public deprecated void onDrawOver(android.graphics.Canvas, android.support.v7.widget.RecyclerView);
+  }
+
+  public static abstract class RecyclerView.LayoutManager {
+    ctor public RecyclerView.LayoutManager();
+    method public void addDisappearingView(android.view.View);
+    method public void addDisappearingView(android.view.View, int);
+    method public void addView(android.view.View);
+    method public void addView(android.view.View, int);
+    method public void assertInLayoutOrScroll(java.lang.String);
+    method public void assertNotInLayoutOrScroll(java.lang.String);
+    method public void attachView(android.view.View, int, android.support.v7.widget.RecyclerView.LayoutParams);
+    method public void attachView(android.view.View, int);
+    method public void attachView(android.view.View);
+    method public void calculateItemDecorationsForChild(android.view.View, android.graphics.Rect);
+    method public boolean canScrollHorizontally();
+    method public boolean canScrollVertically();
+    method public boolean checkLayoutParams(android.support.v7.widget.RecyclerView.LayoutParams);
+    method public static int chooseSize(int, int, int);
+    method public void collectAdjacentPrefetchPositions(int, int, android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.LayoutManager.LayoutPrefetchRegistry);
+    method public void collectInitialPrefetchPositions(int, android.support.v7.widget.RecyclerView.LayoutManager.LayoutPrefetchRegistry);
+    method public int computeHorizontalScrollExtent(android.support.v7.widget.RecyclerView.State);
+    method public int computeHorizontalScrollOffset(android.support.v7.widget.RecyclerView.State);
+    method public int computeHorizontalScrollRange(android.support.v7.widget.RecyclerView.State);
+    method public int computeVerticalScrollExtent(android.support.v7.widget.RecyclerView.State);
+    method public int computeVerticalScrollOffset(android.support.v7.widget.RecyclerView.State);
+    method public int computeVerticalScrollRange(android.support.v7.widget.RecyclerView.State);
+    method public void detachAndScrapAttachedViews(android.support.v7.widget.RecyclerView.Recycler);
+    method public void detachAndScrapView(android.view.View, android.support.v7.widget.RecyclerView.Recycler);
+    method public void detachAndScrapViewAt(int, android.support.v7.widget.RecyclerView.Recycler);
+    method public void detachView(android.view.View);
+    method public void detachViewAt(int);
+    method public void endAnimation(android.view.View);
+    method public android.view.View findContainingItemView(android.view.View);
+    method public android.view.View findViewByPosition(int);
+    method public abstract android.support.v7.widget.RecyclerView.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.RecyclerView.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public android.support.v7.widget.RecyclerView.LayoutParams generateLayoutParams(android.content.Context, android.util.AttributeSet);
+    method public int getBaseline();
+    method public int getBottomDecorationHeight(android.view.View);
+    method public android.view.View getChildAt(int);
+    method public int getChildCount();
+    method public static deprecated int getChildMeasureSpec(int, int, int, boolean);
+    method public static int getChildMeasureSpec(int, int, int, int, boolean);
+    method public boolean getClipToPadding();
+    method public int getColumnCountForAccessibility(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public int getDecoratedBottom(android.view.View);
+    method public void getDecoratedBoundsWithMargins(android.view.View, android.graphics.Rect);
+    method public int getDecoratedLeft(android.view.View);
+    method public int getDecoratedMeasuredHeight(android.view.View);
+    method public int getDecoratedMeasuredWidth(android.view.View);
+    method public int getDecoratedRight(android.view.View);
+    method public int getDecoratedTop(android.view.View);
+    method public android.view.View getFocusedChild();
+    method public int getHeight();
+    method public int getHeightMode();
+    method public int getItemCount();
+    method public int getItemViewType(android.view.View);
+    method public int getLayoutDirection();
+    method public int getLeftDecorationWidth(android.view.View);
+    method public int getMinimumHeight();
+    method public int getMinimumWidth();
+    method public int getPaddingBottom();
+    method public int getPaddingEnd();
+    method public int getPaddingLeft();
+    method public int getPaddingRight();
+    method public int getPaddingStart();
+    method public int getPaddingTop();
+    method public int getPosition(android.view.View);
+    method public static android.support.v7.widget.RecyclerView.LayoutManager.Properties getProperties(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getRightDecorationWidth(android.view.View);
+    method public int getRowCountForAccessibility(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public int getSelectionModeForAccessibility(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public int getTopDecorationHeight(android.view.View);
+    method public void getTransformedBoundingBox(android.view.View, boolean, android.graphics.Rect);
+    method public int getWidth();
+    method public int getWidthMode();
+    method public boolean hasFocus();
+    method public void ignoreView(android.view.View);
+    method public boolean isAttachedToWindow();
+    method public boolean isAutoMeasureEnabled();
+    method public boolean isFocused();
+    method public final boolean isItemPrefetchEnabled();
+    method public boolean isLayoutHierarchical(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public boolean isMeasurementCacheEnabled();
+    method public boolean isSmoothScrolling();
+    method public boolean isViewPartiallyVisible(android.view.View, boolean, boolean);
+    method public void layoutDecorated(android.view.View, int, int, int, int);
+    method public void layoutDecoratedWithMargins(android.view.View, int, int, int, int);
+    method public void measureChild(android.view.View, int, int);
+    method public void measureChildWithMargins(android.view.View, int, int);
+    method public void moveView(int, int);
+    method public void offsetChildrenHorizontal(int);
+    method public void offsetChildrenVertical(int);
+    method public void onAdapterChanged(android.support.v7.widget.RecyclerView.Adapter, android.support.v7.widget.RecyclerView.Adapter);
+    method public boolean onAddFocusables(android.support.v7.widget.RecyclerView, java.util.ArrayList<android.view.View>, int, int);
+    method public void onAttachedToWindow(android.support.v7.widget.RecyclerView);
+    method public deprecated void onDetachedFromWindow(android.support.v7.widget.RecyclerView);
+    method public void onDetachedFromWindow(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.Recycler);
+    method public android.view.View onFocusSearchFailed(android.view.View, int, android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public void onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent);
+    method public void onInitializeAccessibilityEvent(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, android.view.accessibility.AccessibilityEvent);
+    method public void onInitializeAccessibilityNodeInfo(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public void onInitializeAccessibilityNodeInfoForItem(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, android.view.View, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat);
+    method public android.view.View onInterceptFocusSearch(android.view.View, int);
+    method public void onItemsAdded(android.support.v7.widget.RecyclerView, int, int);
+    method public void onItemsChanged(android.support.v7.widget.RecyclerView);
+    method public void onItemsMoved(android.support.v7.widget.RecyclerView, int, int, int);
+    method public void onItemsRemoved(android.support.v7.widget.RecyclerView, int, int);
+    method public void onItemsUpdated(android.support.v7.widget.RecyclerView, int, int);
+    method public void onItemsUpdated(android.support.v7.widget.RecyclerView, int, int, java.lang.Object);
+    method public void onLayoutChildren(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public void onLayoutCompleted(android.support.v7.widget.RecyclerView.State);
+    method public void onMeasure(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, int, int);
+    method public deprecated boolean onRequestChildFocus(android.support.v7.widget.RecyclerView, android.view.View, android.view.View);
+    method public boolean onRequestChildFocus(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.State, android.view.View, android.view.View);
+    method public void onRestoreInstanceState(android.os.Parcelable);
+    method public android.os.Parcelable onSaveInstanceState();
+    method public void onScrollStateChanged(int);
+    method public boolean performAccessibilityAction(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, int, android.os.Bundle);
+    method public boolean performAccessibilityActionForItem(android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State, android.view.View, int, android.os.Bundle);
+    method public void postOnAnimation(java.lang.Runnable);
+    method public void removeAllViews();
+    method public void removeAndRecycleAllViews(android.support.v7.widget.RecyclerView.Recycler);
+    method public void removeAndRecycleView(android.view.View, android.support.v7.widget.RecyclerView.Recycler);
+    method public void removeAndRecycleViewAt(int, android.support.v7.widget.RecyclerView.Recycler);
+    method public boolean removeCallbacks(java.lang.Runnable);
+    method public void removeDetachedView(android.view.View);
+    method public void removeView(android.view.View);
+    method public void removeViewAt(int);
+    method public boolean requestChildRectangleOnScreen(android.support.v7.widget.RecyclerView, android.view.View, android.graphics.Rect, boolean);
+    method public boolean requestChildRectangleOnScreen(android.support.v7.widget.RecyclerView, android.view.View, android.graphics.Rect, boolean, boolean);
+    method public void requestLayout();
+    method public void requestSimpleAnimationsInNextLayout();
+    method public int scrollHorizontallyBy(int, android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public void scrollToPosition(int);
+    method public int scrollVerticallyBy(int, android.support.v7.widget.RecyclerView.Recycler, android.support.v7.widget.RecyclerView.State);
+    method public void setAutoMeasureEnabled(boolean);
+    method public final void setItemPrefetchEnabled(boolean);
+    method public void setMeasuredDimension(android.graphics.Rect, int, int);
+    method public void setMeasuredDimension(int, int);
+    method public void setMeasurementCacheEnabled(boolean);
+    method public void smoothScrollToPosition(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.State, int);
+    method public void startSmoothScroll(android.support.v7.widget.RecyclerView.SmoothScroller);
+    method public void stopIgnoringView(android.view.View);
+    method public boolean supportsPredictiveItemAnimations();
+  }
+
+  public static abstract interface RecyclerView.LayoutManager.LayoutPrefetchRegistry {
+    method public abstract void addPosition(int, int);
+  }
+
+  public static class RecyclerView.LayoutManager.Properties {
+    ctor public RecyclerView.LayoutManager.Properties();
+    field public int orientation;
+    field public boolean reverseLayout;
+    field public int spanCount;
+    field public boolean stackFromEnd;
+  }
+
+  public static class RecyclerView.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
+    ctor public RecyclerView.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public RecyclerView.LayoutParams(int, int);
+    ctor public RecyclerView.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public RecyclerView.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public RecyclerView.LayoutParams(android.support.v7.widget.RecyclerView.LayoutParams);
+    method public int getViewAdapterPosition();
+    method public int getViewLayoutPosition();
+    method public deprecated int getViewPosition();
+    method public boolean isItemChanged();
+    method public boolean isItemRemoved();
+    method public boolean isViewInvalid();
+    method public boolean viewNeedsUpdate();
+  }
+
+  public static abstract interface RecyclerView.OnChildAttachStateChangeListener {
+    method public abstract void onChildViewAttachedToWindow(android.view.View);
+    method public abstract void onChildViewDetachedFromWindow(android.view.View);
+  }
+
+  public static abstract class RecyclerView.OnFlingListener {
+    ctor public RecyclerView.OnFlingListener();
+    method public abstract boolean onFling(int, int);
+  }
+
+  public static abstract interface RecyclerView.OnItemTouchListener {
+    method public abstract boolean onInterceptTouchEvent(android.support.v7.widget.RecyclerView, android.view.MotionEvent);
+    method public abstract void onRequestDisallowInterceptTouchEvent(boolean);
+    method public abstract void onTouchEvent(android.support.v7.widget.RecyclerView, android.view.MotionEvent);
+  }
+
+  public static abstract class RecyclerView.OnScrollListener {
+    ctor public RecyclerView.OnScrollListener();
+    method public void onScrollStateChanged(android.support.v7.widget.RecyclerView, int);
+    method public void onScrolled(android.support.v7.widget.RecyclerView, int, int);
+  }
+
+  public static class RecyclerView.RecycledViewPool {
+    ctor public RecyclerView.RecycledViewPool();
+    method public void clear();
+    method public android.support.v7.widget.RecyclerView.ViewHolder getRecycledView(int);
+    method public int getRecycledViewCount(int);
+    method public void putRecycledView(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void setMaxRecycledViews(int, int);
+  }
+
+  public final class RecyclerView.Recycler {
+    ctor public RecyclerView.Recycler();
+    method public void bindViewToPosition(android.view.View, int);
+    method public void clear();
+    method public int convertPreLayoutPositionToPostLayout(int);
+    method public java.util.List<android.support.v7.widget.RecyclerView.ViewHolder> getScrapList();
+    method public android.view.View getViewForPosition(int);
+    method public void recycleView(android.view.View);
+    method public void setViewCacheSize(int);
+  }
+
+  public static abstract interface RecyclerView.RecyclerListener {
+    method public abstract void onViewRecycled(android.support.v7.widget.RecyclerView.ViewHolder);
+  }
+
+  public static class RecyclerView.SimpleOnItemTouchListener implements android.support.v7.widget.RecyclerView.OnItemTouchListener {
+    ctor public RecyclerView.SimpleOnItemTouchListener();
+    method public boolean onInterceptTouchEvent(android.support.v7.widget.RecyclerView, android.view.MotionEvent);
+    method public void onRequestDisallowInterceptTouchEvent(boolean);
+    method public void onTouchEvent(android.support.v7.widget.RecyclerView, android.view.MotionEvent);
+  }
+
+  public static abstract class RecyclerView.SmoothScroller {
+    ctor public RecyclerView.SmoothScroller();
+    method public android.view.View findViewByPosition(int);
+    method public int getChildCount();
+    method public int getChildPosition(android.view.View);
+    method public android.support.v7.widget.RecyclerView.LayoutManager getLayoutManager();
+    method public int getTargetPosition();
+    method public deprecated void instantScrollToPosition(int);
+    method public boolean isPendingInitialRun();
+    method public boolean isRunning();
+    method protected void normalize(android.graphics.PointF);
+    method protected void onChildAttachedToWindow(android.view.View);
+    method protected abstract void onSeekTargetStep(int, int, android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.SmoothScroller.Action);
+    method protected abstract void onStart();
+    method protected abstract void onStop();
+    method protected abstract void onTargetFound(android.view.View, android.support.v7.widget.RecyclerView.State, android.support.v7.widget.RecyclerView.SmoothScroller.Action);
+    method public void setTargetPosition(int);
+    method protected final void stop();
+  }
+
+  public static class RecyclerView.SmoothScroller.Action {
+    ctor public RecyclerView.SmoothScroller.Action(int, int);
+    ctor public RecyclerView.SmoothScroller.Action(int, int, int);
+    ctor public RecyclerView.SmoothScroller.Action(int, int, int, android.view.animation.Interpolator);
+    method public int getDuration();
+    method public int getDx();
+    method public int getDy();
+    method public android.view.animation.Interpolator getInterpolator();
+    method public void jumpTo(int);
+    method public void setDuration(int);
+    method public void setDx(int);
+    method public void setDy(int);
+    method public void setInterpolator(android.view.animation.Interpolator);
+    method public void update(int, int, int, android.view.animation.Interpolator);
+    field public static final int UNDEFINED_DURATION = -2147483648; // 0x80000000
+  }
+
+  public static abstract interface RecyclerView.SmoothScroller.ScrollVectorProvider {
+    method public abstract android.graphics.PointF computeScrollVectorForPosition(int);
+  }
+
+  public static class RecyclerView.State {
+    ctor public RecyclerView.State();
+    method public boolean didStructureChange();
+    method public <T> T get(int);
+    method public int getItemCount();
+    method public int getRemainingScrollHorizontal();
+    method public int getRemainingScrollVertical();
+    method public int getTargetScrollPosition();
+    method public boolean hasTargetScrollPosition();
+    method public boolean isMeasuring();
+    method public boolean isPreLayout();
+    method public void put(int, java.lang.Object);
+    method public void remove(int);
+    method public boolean willRunPredictiveAnimations();
+    method public boolean willRunSimpleAnimations();
+  }
+
+  public static abstract class RecyclerView.ViewCacheExtension {
+    ctor public RecyclerView.ViewCacheExtension();
+    method public abstract android.view.View getViewForPositionAndType(android.support.v7.widget.RecyclerView.Recycler, int, int);
+  }
+
+  public static abstract class RecyclerView.ViewHolder {
+    ctor public RecyclerView.ViewHolder(android.view.View);
+    method public final int getAdapterPosition();
+    method public final long getItemId();
+    method public final int getItemViewType();
+    method public final int getLayoutPosition();
+    method public final int getOldPosition();
+    method public final deprecated int getPosition();
+    method public final boolean isRecyclable();
+    method public final void setIsRecyclable(boolean);
+    field public final android.view.View itemView;
+  }
+
+  public class RecyclerViewAccessibilityDelegate extends android.support.v4.view.AccessibilityDelegateCompat {
+    ctor public RecyclerViewAccessibilityDelegate(android.support.v7.widget.RecyclerView);
+    method public android.support.v4.view.AccessibilityDelegateCompat getItemDelegate();
+  }
+
+  public static class RecyclerViewAccessibilityDelegate.ItemDelegate extends android.support.v4.view.AccessibilityDelegateCompat {
+    ctor public RecyclerViewAccessibilityDelegate.ItemDelegate(android.support.v7.widget.RecyclerViewAccessibilityDelegate);
+  }
+
+  public class SearchView extends android.support.v7.widget.LinearLayoutCompat implements android.support.v7.view.CollapsibleActionView {
+    ctor public SearchView(android.content.Context);
+    ctor public SearchView(android.content.Context, android.util.AttributeSet);
+    ctor public SearchView(android.content.Context, android.util.AttributeSet, int);
+    method public int getImeOptions();
+    method public int getInputType();
+    method public int getMaxWidth();
+    method public java.lang.CharSequence getQuery();
+    method public java.lang.CharSequence getQueryHint();
+    method public android.support.v4.widget.CursorAdapter getSuggestionsAdapter();
+    method public boolean isIconfiedByDefault();
+    method public boolean isIconified();
+    method public boolean isQueryRefinementEnabled();
+    method public boolean isSubmitButtonEnabled();
+    method public void onActionViewCollapsed();
+    method public void onActionViewExpanded();
+    method public void setIconified(boolean);
+    method public void setIconifiedByDefault(boolean);
+    method public void setImeOptions(int);
+    method public void setInputType(int);
+    method public void setMaxWidth(int);
+    method public void setOnCloseListener(android.support.v7.widget.SearchView.OnCloseListener);
+    method public void setOnQueryTextFocusChangeListener(android.view.View.OnFocusChangeListener);
+    method public void setOnQueryTextListener(android.support.v7.widget.SearchView.OnQueryTextListener);
+    method public void setOnSearchClickListener(android.view.View.OnClickListener);
+    method public void setOnSuggestionListener(android.support.v7.widget.SearchView.OnSuggestionListener);
+    method public void setQuery(java.lang.CharSequence, boolean);
+    method public void setQueryHint(java.lang.CharSequence);
+    method public void setQueryRefinementEnabled(boolean);
+    method public void setSearchableInfo(android.app.SearchableInfo);
+    method public void setSubmitButtonEnabled(boolean);
+    method public void setSuggestionsAdapter(android.support.v4.widget.CursorAdapter);
+  }
+
+  public static abstract interface SearchView.OnCloseListener {
+    method public abstract boolean onClose();
+  }
+
+  public static abstract interface SearchView.OnQueryTextListener {
+    method public abstract boolean onQueryTextChange(java.lang.String);
+    method public abstract boolean onQueryTextSubmit(java.lang.String);
+  }
+
+  public static abstract interface SearchView.OnSuggestionListener {
+    method public abstract boolean onSuggestionClick(int);
+    method public abstract boolean onSuggestionSelect(int);
+  }
+
+  public class ShareActionProvider extends android.support.v4.view.ActionProvider {
+    ctor public ShareActionProvider(android.content.Context);
+    method public android.view.View onCreateActionView();
+    method public void setOnShareTargetSelectedListener(android.support.v7.widget.ShareActionProvider.OnShareTargetSelectedListener);
+    method public void setShareHistoryFileName(java.lang.String);
+    method public void setShareIntent(android.content.Intent);
+    field public static final java.lang.String DEFAULT_SHARE_HISTORY_FILE_NAME = "share_history.xml";
+  }
+
+  public static abstract interface ShareActionProvider.OnShareTargetSelectedListener {
+    method public abstract boolean onShareTargetSelected(android.support.v7.widget.ShareActionProvider, android.content.Intent);
+  }
+
+  public abstract class SimpleItemAnimator extends android.support.v7.widget.RecyclerView.ItemAnimator {
+    ctor public SimpleItemAnimator();
+    method public abstract boolean animateAdd(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public boolean animateAppearance(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public boolean animateChange(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animateChange(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder, int, int, int, int);
+    method public boolean animateDisappearance(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animateMove(android.support.v7.widget.RecyclerView.ViewHolder, int, int, int, int);
+    method public boolean animatePersistence(android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo, android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo);
+    method public abstract boolean animateRemove(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchAddFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchAddStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchChangeFinished(android.support.v7.widget.RecyclerView.ViewHolder, boolean);
+    method public final void dispatchChangeStarting(android.support.v7.widget.RecyclerView.ViewHolder, boolean);
+    method public final void dispatchMoveFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchMoveStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchRemoveFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public final void dispatchRemoveStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public boolean getSupportsChangeAnimations();
+    method public void onAddFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onAddStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onChangeFinished(android.support.v7.widget.RecyclerView.ViewHolder, boolean);
+    method public void onChangeStarting(android.support.v7.widget.RecyclerView.ViewHolder, boolean);
+    method public void onMoveFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onMoveStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onRemoveFinished(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onRemoveStarting(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void setSupportsChangeAnimations(boolean);
+  }
+
+  public abstract class SnapHelper extends android.support.v7.widget.RecyclerView.OnFlingListener {
+    ctor public SnapHelper();
+    method public void attachToRecyclerView(android.support.v7.widget.RecyclerView) throws java.lang.IllegalStateException;
+    method public abstract int[] calculateDistanceToFinalSnap(android.support.v7.widget.RecyclerView.LayoutManager, android.view.View);
+    method public int[] calculateScrollDistance(int, int);
+    method protected android.support.v7.widget.RecyclerView.SmoothScroller createScroller(android.support.v7.widget.RecyclerView.LayoutManager);
+    method protected deprecated android.support.v7.widget.LinearSmoothScroller createSnapScroller(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public abstract android.view.View findSnapView(android.support.v7.widget.RecyclerView.LayoutManager);
+    method public abstract int findTargetSnapPosition(android.support.v7.widget.RecyclerView.LayoutManager, int, int);
+    method public boolean onFling(int, int);
+  }
+
+  public class StaggeredGridLayoutManager extends android.support.v7.widget.RecyclerView.LayoutManager implements android.support.v7.widget.RecyclerView.SmoothScroller.ScrollVectorProvider {
+    ctor public StaggeredGridLayoutManager(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public StaggeredGridLayoutManager(int, int);
+    method public android.graphics.PointF computeScrollVectorForPosition(int);
+    method public int[] findFirstCompletelyVisibleItemPositions(int[]);
+    method public int[] findFirstVisibleItemPositions(int[]);
+    method public int[] findLastCompletelyVisibleItemPositions(int[]);
+    method public int[] findLastVisibleItemPositions(int[]);
+    method public android.support.v7.widget.RecyclerView.LayoutParams generateDefaultLayoutParams();
+    method public int getGapStrategy();
+    method public int getOrientation();
+    method public boolean getReverseLayout();
+    method public int getSpanCount();
+    method public void invalidateSpanAssignments();
+    method public void scrollToPositionWithOffset(int, int);
+    method public void setGapStrategy(int);
+    method public void setOrientation(int);
+    method public void setReverseLayout(boolean);
+    method public void setSpanCount(int);
+    field public static final deprecated int GAP_HANDLING_LAZY = 1; // 0x1
+    field public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS = 2; // 0x2
+    field public static final int GAP_HANDLING_NONE = 0; // 0x0
+    field public static final int HORIZONTAL = 0; // 0x0
+    field public static final int VERTICAL = 1; // 0x1
+  }
+
+  public static class StaggeredGridLayoutManager.LayoutParams extends android.support.v7.widget.RecyclerView.LayoutParams {
+    ctor public StaggeredGridLayoutManager.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public StaggeredGridLayoutManager.LayoutParams(int, int);
+    ctor public StaggeredGridLayoutManager.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public StaggeredGridLayoutManager.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public StaggeredGridLayoutManager.LayoutParams(android.support.v7.widget.RecyclerView.LayoutParams);
+    method public final int getSpanIndex();
+    method public boolean isFullSpan();
+    method public void setFullSpan(boolean);
+    field public static final int INVALID_SPAN_ID = -1; // 0xffffffff
+  }
+
+  public class SwitchCompat extends android.widget.CompoundButton {
+    ctor public SwitchCompat(android.content.Context);
+    ctor public SwitchCompat(android.content.Context, android.util.AttributeSet);
+    ctor public SwitchCompat(android.content.Context, android.util.AttributeSet, int);
+    method public boolean getShowText();
+    method public boolean getSplitTrack();
+    method public int getSwitchMinWidth();
+    method public int getSwitchPadding();
+    method public java.lang.CharSequence getTextOff();
+    method public java.lang.CharSequence getTextOn();
+    method public android.graphics.drawable.Drawable getThumbDrawable();
+    method public int getThumbTextPadding();
+    method public android.content.res.ColorStateList getThumbTintList();
+    method public android.graphics.PorterDuff.Mode getThumbTintMode();
+    method public android.graphics.drawable.Drawable getTrackDrawable();
+    method public android.content.res.ColorStateList getTrackTintList();
+    method public android.graphics.PorterDuff.Mode getTrackTintMode();
+    method public void onMeasure(int, int);
+    method public void setShowText(boolean);
+    method public void setSplitTrack(boolean);
+    method public void setSwitchMinWidth(int);
+    method public void setSwitchPadding(int);
+    method public void setSwitchTextAppearance(android.content.Context, int);
+    method public void setSwitchTypeface(android.graphics.Typeface, int);
+    method public void setSwitchTypeface(android.graphics.Typeface);
+    method public void setTextOff(java.lang.CharSequence);
+    method public void setTextOn(java.lang.CharSequence);
+    method public void setThumbDrawable(android.graphics.drawable.Drawable);
+    method public void setThumbResource(int);
+    method public void setThumbTextPadding(int);
+    method public void setThumbTintList(android.content.res.ColorStateList);
+    method public void setThumbTintMode(android.graphics.PorterDuff.Mode);
+    method public void setTrackDrawable(android.graphics.drawable.Drawable);
+    method public void setTrackResource(int);
+    method public void setTrackTintList(android.content.res.ColorStateList);
+    method public void setTrackTintMode(android.graphics.PorterDuff.Mode);
+  }
+
+  public abstract interface ThemedSpinnerAdapter implements android.widget.SpinnerAdapter {
+    method public abstract android.content.res.Resources.Theme getDropDownViewTheme();
+    method public abstract void setDropDownViewTheme(android.content.res.Resources.Theme);
+  }
+
+  public static final class ThemedSpinnerAdapter.Helper {
+    ctor public ThemedSpinnerAdapter.Helper(android.content.Context);
+    method public android.view.LayoutInflater getDropDownViewInflater();
+    method public android.content.res.Resources.Theme getDropDownViewTheme();
+    method public void setDropDownViewTheme(android.content.res.Resources.Theme);
+  }
+
+  public class Toolbar extends android.view.ViewGroup {
+    ctor public Toolbar(android.content.Context);
+    ctor public Toolbar(android.content.Context, android.util.AttributeSet);
+    ctor public Toolbar(android.content.Context, android.util.AttributeSet, int);
+    method public void collapseActionView();
+    method public void dismissPopupMenus();
+    method protected android.support.v7.widget.Toolbar.LayoutParams generateDefaultLayoutParams();
+    method public android.support.v7.widget.Toolbar.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected android.support.v7.widget.Toolbar.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams);
+    method public int getContentInsetEnd();
+    method public int getContentInsetEndWithActions();
+    method public int getContentInsetLeft();
+    method public int getContentInsetRight();
+    method public int getContentInsetStart();
+    method public int getContentInsetStartWithNavigation();
+    method public int getCurrentContentInsetEnd();
+    method public int getCurrentContentInsetLeft();
+    method public int getCurrentContentInsetRight();
+    method public int getCurrentContentInsetStart();
+    method public android.graphics.drawable.Drawable getLogo();
+    method public java.lang.CharSequence getLogoDescription();
+    method public android.view.Menu getMenu();
+    method public java.lang.CharSequence getNavigationContentDescription();
+    method public android.graphics.drawable.Drawable getNavigationIcon();
+    method public android.graphics.drawable.Drawable getOverflowIcon();
+    method public int getPopupTheme();
+    method public java.lang.CharSequence getSubtitle();
+    method public java.lang.CharSequence getTitle();
+    method public int getTitleMarginBottom();
+    method public int getTitleMarginEnd();
+    method public int getTitleMarginStart();
+    method public int getTitleMarginTop();
+    method public boolean hasExpandedActionView();
+    method public boolean hideOverflowMenu();
+    method public void inflateMenu(int);
+    method public boolean isOverflowMenuShowing();
+    method protected void onLayout(boolean, int, int, int, int);
+    method public void setContentInsetEndWithActions(int);
+    method public void setContentInsetStartWithNavigation(int);
+    method public void setContentInsetsAbsolute(int, int);
+    method public void setContentInsetsRelative(int, int);
+    method public void setLogo(int);
+    method public void setLogo(android.graphics.drawable.Drawable);
+    method public void setLogoDescription(int);
+    method public void setLogoDescription(java.lang.CharSequence);
+    method public void setNavigationContentDescription(int);
+    method public void setNavigationContentDescription(java.lang.CharSequence);
+    method public void setNavigationIcon(int);
+    method public void setNavigationIcon(android.graphics.drawable.Drawable);
+    method public void setNavigationOnClickListener(android.view.View.OnClickListener);
+    method public void setOnMenuItemClickListener(android.support.v7.widget.Toolbar.OnMenuItemClickListener);
+    method public void setOverflowIcon(android.graphics.drawable.Drawable);
+    method public void setPopupTheme(int);
+    method public void setSubtitle(int);
+    method public void setSubtitle(java.lang.CharSequence);
+    method public void setSubtitleTextAppearance(android.content.Context, int);
+    method public void setSubtitleTextColor(int);
+    method public void setTitle(int);
+    method public void setTitle(java.lang.CharSequence);
+    method public void setTitleMargin(int, int, int, int);
+    method public void setTitleMarginBottom(int);
+    method public void setTitleMarginEnd(int);
+    method public void setTitleMarginStart(int);
+    method public void setTitleMarginTop(int);
+    method public void setTitleTextAppearance(android.content.Context, int);
+    method public void setTitleTextColor(int);
+    method public boolean showOverflowMenu();
+  }
+
+  public static class Toolbar.LayoutParams extends android.support.v7.app.ActionBar.LayoutParams {
+    ctor public Toolbar.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public Toolbar.LayoutParams(int, int);
+    ctor public Toolbar.LayoutParams(int, int, int);
+    ctor public Toolbar.LayoutParams(int);
+    ctor public Toolbar.LayoutParams(android.support.v7.widget.Toolbar.LayoutParams);
+    ctor public Toolbar.LayoutParams(android.support.v7.app.ActionBar.LayoutParams);
+    ctor public Toolbar.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public Toolbar.LayoutParams(android.view.ViewGroup.LayoutParams);
+  }
+
+  public static abstract interface Toolbar.OnMenuItemClickListener {
+    method public abstract boolean onMenuItemClick(android.view.MenuItem);
+  }
+
+  public static class Toolbar.SavedState extends android.support.v4.view.AbsSavedState {
+    ctor public Toolbar.SavedState(android.os.Parcel);
+    ctor public Toolbar.SavedState(android.os.Parcel, java.lang.ClassLoader);
+    ctor public Toolbar.SavedState(android.os.Parcelable);
+    field public static final android.os.Parcelable.Creator<android.support.v7.widget.Toolbar.SavedState> CREATOR;
+  }
+
+  public class TooltipCompat {
+    method public static void setTooltipText(android.view.View, java.lang.CharSequence);
+  }
+
+}
+
+package android.support.v7.widget.helper {
+
+  public class ItemTouchHelper extends android.support.v7.widget.RecyclerView.ItemDecoration implements android.support.v7.widget.RecyclerView.OnChildAttachStateChangeListener {
+    ctor public ItemTouchHelper(android.support.v7.widget.helper.ItemTouchHelper.Callback);
+    method public void attachToRecyclerView(android.support.v7.widget.RecyclerView);
+    method public void onChildViewAttachedToWindow(android.view.View);
+    method public void onChildViewDetachedFromWindow(android.view.View);
+    method public void startDrag(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void startSwipe(android.support.v7.widget.RecyclerView.ViewHolder);
+    field public static final int ACTION_STATE_DRAG = 2; // 0x2
+    field public static final int ACTION_STATE_IDLE = 0; // 0x0
+    field public static final int ACTION_STATE_SWIPE = 1; // 0x1
+    field public static final int ANIMATION_TYPE_DRAG = 8; // 0x8
+    field public static final int ANIMATION_TYPE_SWIPE_CANCEL = 4; // 0x4
+    field public static final int ANIMATION_TYPE_SWIPE_SUCCESS = 2; // 0x2
+    field public static final int DOWN = 2; // 0x2
+    field public static final int END = 32; // 0x20
+    field public static final int LEFT = 4; // 0x4
+    field public static final int RIGHT = 8; // 0x8
+    field public static final int START = 16; // 0x10
+    field public static final int UP = 1; // 0x1
+  }
+
+  public static abstract class ItemTouchHelper.Callback {
+    ctor public ItemTouchHelper.Callback();
+    method public boolean canDropOver(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public android.support.v7.widget.RecyclerView.ViewHolder chooseDropTarget(android.support.v7.widget.RecyclerView.ViewHolder, java.util.List<android.support.v7.widget.RecyclerView.ViewHolder>, int, int);
+    method public void clearView(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public int convertToAbsoluteDirection(int, int);
+    method public static int convertToRelativeDirection(int, int);
+    method public long getAnimationDuration(android.support.v7.widget.RecyclerView, int, float, float);
+    method public int getBoundingBoxMargin();
+    method public static android.support.v7.widget.helper.ItemTouchUIUtil getDefaultUIUtil();
+    method public float getMoveThreshold(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public abstract int getMovementFlags(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public float getSwipeEscapeVelocity(float);
+    method public float getSwipeThreshold(android.support.v7.widget.RecyclerView.ViewHolder);
+    method public float getSwipeVelocityThreshold(float);
+    method public int interpolateOutOfBoundsScroll(android.support.v7.widget.RecyclerView, int, int, int, long);
+    method public boolean isItemViewSwipeEnabled();
+    method public boolean isLongPressDragEnabled();
+    method public static int makeFlag(int, int);
+    method public static int makeMovementFlags(int, int);
+    method public void onChildDraw(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, float, float, int, boolean);
+    method public void onChildDrawOver(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, float, float, int, boolean);
+    method public abstract boolean onMove(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void onMoved(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder, int, android.support.v7.widget.RecyclerView.ViewHolder, int, int, int);
+    method public void onSelectedChanged(android.support.v7.widget.RecyclerView.ViewHolder, int);
+    method public abstract void onSwiped(android.support.v7.widget.RecyclerView.ViewHolder, int);
+    field public static final int DEFAULT_DRAG_ANIMATION_DURATION = 200; // 0xc8
+    field public static final int DEFAULT_SWIPE_ANIMATION_DURATION = 250; // 0xfa
+  }
+
+  public static abstract class ItemTouchHelper.SimpleCallback extends android.support.v7.widget.helper.ItemTouchHelper.Callback {
+    ctor public ItemTouchHelper.SimpleCallback(int, int);
+    method public int getDragDirs(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public int getMovementFlags(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public int getSwipeDirs(android.support.v7.widget.RecyclerView, android.support.v7.widget.RecyclerView.ViewHolder);
+    method public void setDefaultDragDirs(int);
+    method public void setDefaultSwipeDirs(int);
+  }
+
+  public static abstract interface ItemTouchHelper.ViewDropHandler {
+    method public abstract void prepareForDrop(android.view.View, android.view.View, int, int);
+  }
+
+  public abstract interface ItemTouchUIUtil {
+    method public abstract void clearView(android.view.View);
+    method public abstract void onDraw(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.view.View, float, float, int, boolean);
+    method public abstract void onDrawOver(android.graphics.Canvas, android.support.v7.widget.RecyclerView, android.view.View, float, float, int, boolean);
+    method public abstract void onSelected(android.view.View);
+  }
+
+}
+
+package android.support.v7.widget.util {
+
+  public abstract class SortedListAdapterCallback<T2> extends android.support.v7.util.SortedList.Callback {
+    ctor public SortedListAdapterCallback(android.support.v7.widget.RecyclerView.Adapter);
+    method public void onChanged(int, int);
+    method public void onInserted(int, int);
+    method public void onMoved(int, int);
+    method public void onRemoved(int, int);
+  }
+
+}
+
+package android.support.wear.widget {
+
+  public class BoxInsetLayout extends android.view.ViewGroup {
+    ctor public BoxInsetLayout(android.content.Context);
+    ctor public BoxInsetLayout(android.content.Context, android.util.AttributeSet);
+    ctor public BoxInsetLayout(android.content.Context, android.util.AttributeSet, int);
+    method public android.support.wear.widget.BoxInsetLayout.LayoutParams generateLayoutParams(android.util.AttributeSet);
+    method protected void onLayout(boolean, int, int, int, int);
+  }
+
+  public static class BoxInsetLayout.LayoutParams extends android.widget.FrameLayout.LayoutParams {
+    ctor public BoxInsetLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
+    ctor public BoxInsetLayout.LayoutParams(int, int);
+    ctor public BoxInsetLayout.LayoutParams(int, int, int);
+    ctor public BoxInsetLayout.LayoutParams(int, int, int, int);
+    ctor public BoxInsetLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
+    ctor public BoxInsetLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
+    ctor public BoxInsetLayout.LayoutParams(android.widget.FrameLayout.LayoutParams);
+    ctor public BoxInsetLayout.LayoutParams(android.support.wear.widget.BoxInsetLayout.LayoutParams);
+    field public static final int BOX_ALL = 15; // 0xf
+    field public static final int BOX_BOTTOM = 8; // 0x8
+    field public static final int BOX_LEFT = 1; // 0x1
+    field public static final int BOX_NONE = 0; // 0x0
+    field public static final int BOX_RIGHT = 4; // 0x4
+    field public static final int BOX_TOP = 2; // 0x2
+    field public int boxedEdges;
+  }
+
+  public class CircularProgressLayout extends android.widget.FrameLayout {
+    ctor public CircularProgressLayout(android.content.Context);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public CircularProgressLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public int getBackgroundColor();
+    method public int[] getColorSchemeColors();
+    method public android.support.wear.widget.CircularProgressLayout.OnTimerFinishedListener getOnTimerFinishedListener();
+    method public android.support.v4.widget.CircularProgressDrawable getProgressDrawable();
+    method public float getStartingRotation();
+    method public float getStrokeWidth();
+    method public long getTotalTime();
+    method public boolean isIndeterminate();
+    method public boolean isTimerRunning();
+    method public void setColorSchemeColors(int...);
+    method public void setIndeterminate(boolean);
+    method public void setOnTimerFinishedListener(android.support.wear.widget.CircularProgressLayout.OnTimerFinishedListener);
+    method public void setStartingRotation(float);
+    method public void setStrokeWidth(float);
+    method public void setTotalTime(long);
+    method public void startTimer();
+    method public void stopTimer();
+  }
+
+  public static abstract interface CircularProgressLayout.OnTimerFinishedListener {
+    method public abstract void onTimerFinished(android.support.wear.widget.CircularProgressLayout);
+  }
+
+  public class CurvingLayoutCallback extends android.support.wear.widget.WearableLinearLayoutManager.LayoutCallback {
+    ctor public CurvingLayoutCallback(android.content.Context);
+    method public void adjustAnchorOffsetXY(android.view.View, float[]);
+    method public void onLayoutFinished(android.view.View, android.support.v7.widget.RecyclerView);
+  }
+
+  public class RoundedDrawable extends android.graphics.drawable.Drawable {
+    ctor public RoundedDrawable();
+    method public void draw(android.graphics.Canvas);
+    method public int getBackgroundColor();
+    method public android.graphics.drawable.Drawable getDrawable();
+    method public int getOpacity();
+    method public int getRadius();
+    method public boolean isClipEnabled();
+    method public void setAlpha(int);
+    method public void setBackgroundColor(int);
+    method public void setClipEnabled(boolean);
+    method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setDrawable(android.graphics.drawable.Drawable);
+    method public void setRadius(int);
+  }
+
+  public class SwipeDismissFrameLayout extends android.widget.FrameLayout {
+    ctor public SwipeDismissFrameLayout(android.content.Context);
+    ctor public SwipeDismissFrameLayout(android.content.Context, android.util.AttributeSet);
+    ctor public SwipeDismissFrameLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public SwipeDismissFrameLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public void addCallback(android.support.wear.widget.SwipeDismissFrameLayout.Callback);
+    method public void removeCallback(android.support.wear.widget.SwipeDismissFrameLayout.Callback);
+  }
+
+  public static abstract class SwipeDismissFrameLayout.Callback {
+    ctor public SwipeDismissFrameLayout.Callback();
+    method public void onDismissed(android.support.wear.widget.SwipeDismissFrameLayout);
+    method public void onSwipeCanceled(android.support.wear.widget.SwipeDismissFrameLayout);
+    method public void onSwipeStarted(android.support.wear.widget.SwipeDismissFrameLayout);
+  }
+
+  public class WearableLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
+    ctor public WearableLinearLayoutManager(android.content.Context, android.support.wear.widget.WearableLinearLayoutManager.LayoutCallback);
+    ctor public WearableLinearLayoutManager(android.content.Context);
+    method public android.support.wear.widget.WearableLinearLayoutManager.LayoutCallback getLayoutCallback();
+    method public void setLayoutCallback(android.support.wear.widget.WearableLinearLayoutManager.LayoutCallback);
+  }
+
+  public static abstract class WearableLinearLayoutManager.LayoutCallback {
+    ctor public WearableLinearLayoutManager.LayoutCallback();
+    method public abstract void onLayoutFinished(android.view.View, android.support.v7.widget.RecyclerView);
+  }
+
+  public class WearableRecyclerView extends android.support.v7.widget.RecyclerView {
+    ctor public WearableRecyclerView(android.content.Context);
+    ctor public WearableRecyclerView(android.content.Context, android.util.AttributeSet);
+    ctor public WearableRecyclerView(android.content.Context, android.util.AttributeSet, int);
+    ctor public WearableRecyclerView(android.content.Context, android.util.AttributeSet, int, int);
+    method public float getBezelFraction();
+    method public float getScrollDegreesPerScreen();
+    method public boolean isCircularScrollingGestureEnabled();
+    method public boolean isEdgeItemsCenteringEnabled();
+    method public void setBezelFraction(float);
+    method public void setCircularScrollingGestureEnabled(boolean);
+    method public void setEdgeItemsCenteringEnabled(boolean);
+    method public void setScrollDegreesPerScreen(float);
+  }
+
+}
+
+package android.support.wear.widget.drawer {
+
+  public class WearableActionDrawerView extends android.support.wear.widget.drawer.WearableDrawerView {
+    ctor public WearableActionDrawerView(android.content.Context);
+    ctor public WearableActionDrawerView(android.content.Context, android.util.AttributeSet);
+    ctor public WearableActionDrawerView(android.content.Context, android.util.AttributeSet, int);
+    ctor public WearableActionDrawerView(android.content.Context, android.util.AttributeSet, int, int);
+    method public android.view.Menu getMenu();
+    method public void setOnMenuItemClickListener(android.view.MenuItem.OnMenuItemClickListener);
+    method public void setTitle(java.lang.CharSequence);
+  }
+
+  public class WearableDrawerController {
+    method public void closeDrawer();
+    method public void openDrawer();
+    method public void peekDrawer();
+  }
+
+  public class WearableDrawerLayout extends android.widget.FrameLayout implements android.support.v4.view.NestedScrollingParent android.view.View.OnLayoutChangeListener {
+    ctor public WearableDrawerLayout(android.content.Context);
+    ctor public WearableDrawerLayout(android.content.Context, android.util.AttributeSet);
+    ctor public WearableDrawerLayout(android.content.Context, android.util.AttributeSet, int);
+    ctor public WearableDrawerLayout(android.content.Context, android.util.AttributeSet, int, int);
+    method public void onFlingComplete(android.view.View);
+    method public void onLayoutChange(android.view.View, int, int, int, int, int, int, int, int);
+    method public void setDrawerStateCallback(android.support.wear.widget.drawer.WearableDrawerLayout.DrawerStateCallback);
+  }
+
+  public static class WearableDrawerLayout.DrawerStateCallback {
+    ctor public WearableDrawerLayout.DrawerStateCallback();
+    method public void onDrawerClosed(android.support.wear.widget.drawer.WearableDrawerLayout, android.support.wear.widget.drawer.WearableDrawerView);
+    method public void onDrawerOpened(android.support.wear.widget.drawer.WearableDrawerLayout, android.support.wear.widget.drawer.WearableDrawerView);
+    method public void onDrawerStateChanged(android.support.wear.widget.drawer.WearableDrawerLayout, int);
+  }
+
+  public class WearableDrawerView extends android.widget.FrameLayout {
+    ctor public WearableDrawerView(android.content.Context);
+    ctor public WearableDrawerView(android.content.Context, android.util.AttributeSet);
+    ctor public WearableDrawerView(android.content.Context, android.util.AttributeSet, int);
+    ctor public WearableDrawerView(android.content.Context, android.util.AttributeSet, int, int);
+    method public android.support.wear.widget.drawer.WearableDrawerController getController();
+    method public android.view.View getDrawerContent();
+    method public int getDrawerState();
+    method public boolean isAutoPeekEnabled();
+    method public boolean isClosed();
+    method public boolean isLocked();
+    method public boolean isLockedWhenClosed();
+    method public boolean isOpenOnlyAtTopEnabled();
+    method public boolean isOpened();
+    method public boolean isPeekOnScrollDownEnabled();
+    method public boolean isPeeking();
+    method public void onDrawerClosed();
+    method public void onDrawerOpened();
+    method public void onDrawerStateChanged(int);
+    method public void onPeekContainerClicked(android.view.View);
+    method public void setDrawerContent(android.view.View);
+    method public void setIsAutoPeekEnabled(boolean);
+    method public void setIsLocked(boolean);
+    method public void setLockedWhenClosed(boolean);
+    method public void setOpenOnlyAtTopEnabled(boolean);
+    method public void setPeekContent(android.view.View);
+    method public void setPeekOnScrollDownEnabled(boolean);
+    field public static final int STATE_DRAGGING = 1; // 0x1
+    field public static final int STATE_IDLE = 0; // 0x0
+    field public static final int STATE_SETTLING = 2; // 0x2
+  }
+
+  public class WearableNavigationDrawerView extends android.support.wear.widget.drawer.WearableDrawerView {
+    ctor public WearableNavigationDrawerView(android.content.Context);
+    ctor public WearableNavigationDrawerView(android.content.Context, android.util.AttributeSet);
+    ctor public WearableNavigationDrawerView(android.content.Context, android.util.AttributeSet, int);
+    ctor public WearableNavigationDrawerView(android.content.Context, android.util.AttributeSet, int, int);
+    method public void addOnItemSelectedListener(android.support.wear.widget.drawer.WearableNavigationDrawerView.OnItemSelectedListener);
+    method public int getNavigationStyle();
+    method public void removeOnItemSelectedListener(android.support.wear.widget.drawer.WearableNavigationDrawerView.OnItemSelectedListener);
+    method public void setAdapter(android.support.wear.widget.drawer.WearableNavigationDrawerView.WearableNavigationDrawerAdapter);
+    method public void setCurrentItem(int, boolean);
+    field public static final int MULTI_PAGE = 1; // 0x1
+    field public static final int SINGLE_PAGE = 0; // 0x0
+  }
+
+  public static abstract interface WearableNavigationDrawerView.OnItemSelectedListener {
+    method public abstract void onItemSelected(int);
+  }
+
+  public static abstract class WearableNavigationDrawerView.WearableNavigationDrawerAdapter {
+    ctor public WearableNavigationDrawerView.WearableNavigationDrawerAdapter();
+    method public abstract int getCount();
+    method public abstract android.graphics.drawable.Drawable getItemDrawable(int);
+    method public abstract java.lang.CharSequence getItemText(int);
+    method public void notifyDataSetChanged();
+  }
+
+}
+
diff --git a/app-toolkit/.gitignore b/app-toolkit/.gitignore
new file mode 100644
index 0000000..be4e6f1
--- /dev/null
+++ b/app-toolkit/.gitignore
@@ -0,0 +1,4 @@
+local.properties
+maven-repo/
+build/
+*.DS_Store
diff --git a/app-toolkit/README.md b/app-toolkit/README.md
new file mode 100644
index 0000000..e36944f
--- /dev/null
+++ b/app-toolkit/README.md
@@ -0,0 +1,3 @@
+This is a wrapper project for flatfoot projects.
+You can use either individual projects or this one.
+Build server uses this project to build flatfoot.
\ No newline at end of file
diff --git a/app-toolkit/build.gradle b/app-toolkit/build.gradle
new file mode 100644
index 0000000..6a9d5a0
--- /dev/null
+++ b/app-toolkit/build.gradle
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+buildscript {
+    ext.supportRootFolder = new File(project.projectDir, "../")
+    apply from: 'buildSrc/repos.gradle'
+    apply from: 'init.gradle'
+    repos.addMavenRepositories(repositories)
+    dependencies {
+        classpath libs.jacoco
+        classpath libs.gradle
+        classpath libs.kotlin.gradle_plugin
+        if (enablePublicRepos) {
+            classpath libs.localize_maven
+        }
+    }
+}
diff --git a/app-toolkit/buildSrc b/app-toolkit/buildSrc
new file mode 120000
index 0000000..053a423
--- /dev/null
+++ b/app-toolkit/buildSrc
@@ -0,0 +1 @@
+../buildSrc
\ No newline at end of file
diff --git a/app-toolkit/common/build.gradle b/app-toolkit/common/build.gradle
new file mode 100644
index 0000000..2f54c2a
--- /dev/null
+++ b/app-toolkit/common/build.gradle
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+apply plugin: 'java'
+apply plugin: 'maven'
+
+sourceCompatibility = 1.7
+
+dependencies {
+    compile libs.support.annotations
+
+    testCompile libs.junit
+    testCompile libs.mockito_core
+}
+
+archivesBaseName = "common"
+
+createAndroidCheckstyle(project)
diff --git a/app-toolkit/common/src/main/java/android/arch/core/internal/FastSafeIterableMap.java b/app-toolkit/common/src/main/java/android/arch/core/internal/FastSafeIterableMap.java
new file mode 100644
index 0000000..dbd4d5f
--- /dev/null
+++ b/app-toolkit/common/src/main/java/android/arch/core/internal/FastSafeIterableMap.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.internal;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Poor's man LinkedHashMap, which supports modifications during iterations.
+ * Takes more memory that {@link SafeIterableMap}
+ * It is NOT thread safe.
+ *
+ * @param <K> Key type
+ * @param <V> Value type
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class FastSafeIterableMap<K, V> extends SafeIterableMap<K, V> {
+
+    private HashMap<K, Entry<K, V>> mHashMap = new HashMap<>();
+
+    @Override
+    protected Entry<K, V> get(K k) {
+        return mHashMap.get(k);
+    }
+
+    @Override
+    public V putIfAbsent(@NonNull K key, @NonNull V v) {
+        Entry<K, V> current = get(key);
+        if (current != null) {
+            return current.mValue;
+        }
+        mHashMap.put(key, put(key, v));
+        return null;
+    }
+
+    @Override
+    public V remove(@NonNull K key) {
+        V removed = super.remove(key);
+        mHashMap.remove(key);
+        return removed;
+    }
+
+    /**
+     * Returns {@code true} if this map contains a mapping for the specified
+     * key.
+     */
+    public boolean contains(K key) {
+        return mHashMap.containsKey(key);
+    }
+
+    /**
+     * Return an entry added to prior to an entry associated with the given key.
+     *
+     * @param k the key
+     */
+    public Map.Entry<K, V> ceil(K k) {
+        if (contains(k)) {
+            return mHashMap.get(k).mPrevious;
+        }
+        return null;
+    }
+}
diff --git a/app-toolkit/common/src/main/java/android/arch/core/internal/SafeIterableMap.java b/app-toolkit/common/src/main/java/android/arch/core/internal/SafeIterableMap.java
new file mode 100644
index 0000000..16a7607
--- /dev/null
+++ b/app-toolkit/common/src/main/java/android/arch/core/internal/SafeIterableMap.java
@@ -0,0 +1,383 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.internal;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.WeakHashMap;
+
+/**
+ * LinkedList, which pretends to be a map and supports modifications during iterations.
+ * It is NOT thread safe.
+ *
+ * @param <K> Key type
+ * @param <V> Value type
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class SafeIterableMap<K, V> implements Iterable<Map.Entry<K, V>> {
+
+    private Entry<K, V> mStart;
+    private Entry<K, V> mEnd;
+    // using WeakHashMap over List<WeakReference>, so we don't have to manually remove
+    // WeakReferences that have null in them.
+    private WeakHashMap<SupportRemove<K, V>, Boolean> mIterators = new WeakHashMap<>();
+    private int mSize = 0;
+
+    protected Entry<K, V> get(K k) {
+        Entry<K, V> currentNode = mStart;
+        while (currentNode != null) {
+            if (currentNode.mKey.equals(k)) {
+                break;
+            }
+            currentNode = currentNode.mNext;
+        }
+        return currentNode;
+    }
+
+    /**
+     * If the specified key is not already associated
+     * with a value, associates it with the given value.
+     *
+     * @param key key with which the specified value is to be associated
+     * @param v   value to be associated with the specified key
+     * @return the previous value associated with the specified key,
+     * or {@code null} if there was no mapping for the key
+     */
+    public V putIfAbsent(@NonNull K key, @NonNull V v) {
+        Entry<K, V> entry = get(key);
+        if (entry != null) {
+            return entry.mValue;
+        }
+        put(key, v);
+        return null;
+    }
+
+    protected Entry<K, V> put(@NonNull K key, @NonNull V v) {
+        Entry<K, V> newEntry = new Entry<>(key, v);
+        mSize++;
+        if (mEnd == null) {
+            mStart = newEntry;
+            mEnd = mStart;
+            return newEntry;
+        }
+
+        mEnd.mNext = newEntry;
+        newEntry.mPrevious = mEnd;
+        mEnd = newEntry;
+        return newEntry;
+
+    }
+
+    /**
+     * Removes the mapping for a key from this map if it is present.
+     *
+     * @param key key whose mapping is to be removed from the map
+     * @return the previous value associated with the specified key,
+     * or {@code null} if there was no mapping for the key
+     */
+    public V remove(@NonNull K key) {
+        Entry<K, V> toRemove = get(key);
+        if (toRemove == null) {
+            return null;
+        }
+        mSize--;
+        if (!mIterators.isEmpty()) {
+            for (SupportRemove<K, V> iter : mIterators.keySet()) {
+                iter.supportRemove(toRemove);
+            }
+        }
+
+        if (toRemove.mPrevious != null) {
+            toRemove.mPrevious.mNext = toRemove.mNext;
+        } else {
+            mStart = toRemove.mNext;
+        }
+
+        if (toRemove.mNext != null) {
+            toRemove.mNext.mPrevious = toRemove.mPrevious;
+        } else {
+            mEnd = toRemove.mPrevious;
+        }
+
+        toRemove.mNext = null;
+        toRemove.mPrevious = null;
+        return toRemove.mValue;
+    }
+
+    /**
+     * @return the number of elements in this map
+     */
+    public int size() {
+        return mSize;
+    }
+
+    /**
+     * @return an ascending iterator, which doesn't include new elements added during an
+     * iteration.
+     */
+    @NonNull
+    @Override
+    public Iterator<Map.Entry<K, V>> iterator() {
+        ListIterator<K, V> iterator = new AscendingIterator<>(mStart, mEnd);
+        mIterators.put(iterator, false);
+        return iterator;
+    }
+
+    /**
+     * @return an descending iterator, which doesn't include new elements added during an
+     * iteration.
+     */
+    public Iterator<Map.Entry<K, V>> descendingIterator() {
+        DescendingIterator<K, V> iterator = new DescendingIterator<>(mEnd, mStart);
+        mIterators.put(iterator, false);
+        return iterator;
+    }
+
+    /**
+     * return an iterator with additions.
+     */
+    public IteratorWithAdditions iteratorWithAdditions() {
+        @SuppressWarnings("unchecked")
+        IteratorWithAdditions iterator = new IteratorWithAdditions();
+        mIterators.put(iterator, false);
+        return iterator;
+    }
+
+    /**
+     * @return eldest added entry or null
+     */
+    public Map.Entry<K, V> eldest() {
+        return mStart;
+    }
+
+    /**
+     * @return newest added entry or null
+     */
+    public Map.Entry<K, V> newest() {
+        return mEnd;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == this) {
+            return true;
+        }
+        if (!(obj instanceof SafeIterableMap)) {
+            return false;
+        }
+        SafeIterableMap map = (SafeIterableMap) obj;
+        if (this.size() != map.size()) {
+            return false;
+        }
+        Iterator<Map.Entry<K, V>> iterator1 = iterator();
+        Iterator iterator2 = map.iterator();
+        while (iterator1.hasNext() && iterator2.hasNext()) {
+            Map.Entry<K, V> next1 = iterator1.next();
+            Object next2 = iterator2.next();
+            if ((next1 == null && next2 != null)
+                    || (next1 != null && !next1.equals(next2))) {
+                return false;
+            }
+        }
+        return !iterator1.hasNext() && !iterator2.hasNext();
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("[");
+        Iterator<Map.Entry<K, V>> iterator = iterator();
+        while (iterator.hasNext()) {
+            builder.append(iterator.next().toString());
+            if (iterator.hasNext()) {
+                builder.append(", ");
+            }
+        }
+        builder.append("]");
+        return builder.toString();
+    }
+
+    private abstract static class ListIterator<K, V> implements Iterator<Map.Entry<K, V>>,
+            SupportRemove<K, V> {
+        Entry<K, V> mExpectedEnd;
+        Entry<K, V> mNext;
+
+        ListIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
+            this.mExpectedEnd = expectedEnd;
+            this.mNext = start;
+        }
+
+        @Override
+        public boolean hasNext() {
+            return mNext != null;
+        }
+
+        @Override
+        public void supportRemove(@NonNull Entry<K, V> entry) {
+            if (mExpectedEnd == entry && entry == mNext) {
+                mNext = null;
+                mExpectedEnd = null;
+            }
+
+            if (mExpectedEnd == entry) {
+                mExpectedEnd = backward(mExpectedEnd);
+            }
+
+            if (mNext == entry) {
+                mNext = nextNode();
+            }
+        }
+
+        private Entry<K, V> nextNode() {
+            if (mNext == mExpectedEnd || mExpectedEnd == null) {
+                return null;
+            }
+            return forward(mNext);
+        }
+
+        @Override
+        public Map.Entry<K, V> next() {
+            Map.Entry<K, V> result = mNext;
+            mNext = nextNode();
+            return result;
+        }
+
+        abstract Entry<K, V> forward(Entry<K, V> entry);
+
+        abstract Entry<K, V> backward(Entry<K, V> entry);
+    }
+
+    static class AscendingIterator<K, V> extends ListIterator<K, V> {
+        AscendingIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
+            super(start, expectedEnd);
+        }
+
+        @Override
+        Entry<K, V> forward(Entry<K, V> entry) {
+            return entry.mNext;
+        }
+
+        @Override
+        Entry<K, V> backward(Entry<K, V> entry) {
+            return entry.mPrevious;
+        }
+    }
+
+    private static class DescendingIterator<K, V> extends ListIterator<K, V> {
+
+        DescendingIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
+            super(start, expectedEnd);
+        }
+
+        @Override
+        Entry<K, V> forward(Entry<K, V> entry) {
+            return entry.mPrevious;
+        }
+
+        @Override
+        Entry<K, V> backward(Entry<K, V> entry) {
+            return entry.mNext;
+        }
+    }
+
+    private class IteratorWithAdditions implements Iterator<Map.Entry<K, V>>, SupportRemove<K, V> {
+        private Entry<K, V> mCurrent;
+        private boolean mFirstStep = true;
+
+        @Override
+        public void supportRemove(@NonNull Entry<K, V> entry) {
+            if (entry == mCurrent) {
+                mCurrent = mCurrent.mPrevious;
+            }
+        }
+
+        @Override
+        public boolean hasNext() {
+            if (mFirstStep) {
+                return mStart != null;
+            }
+            return mCurrent != null && mCurrent.mNext != null;
+        }
+
+        @Override
+        public Map.Entry<K, V> next() {
+            if (mFirstStep) {
+                mFirstStep = false;
+                mCurrent = mStart;
+            } else {
+                mCurrent = mCurrent != null ? mCurrent.mNext : null;
+            }
+            return mCurrent;
+        }
+    }
+
+    interface SupportRemove<K, V> {
+        void supportRemove(@NonNull Entry<K, V> entry);
+    }
+
+    static class Entry<K, V> implements Map.Entry<K, V> {
+        @NonNull
+        final K mKey;
+        @NonNull
+        final V mValue;
+        Entry<K, V> mNext;
+        Entry<K, V> mPrevious;
+
+        Entry(@NonNull K key, @NonNull V value) {
+            mKey = key;
+            this.mValue = value;
+        }
+
+        @NonNull
+        @Override
+        public K getKey() {
+            return mKey;
+        }
+
+        @NonNull
+        @Override
+        public V getValue() {
+            return mValue;
+        }
+
+        @Override
+        public V setValue(V value) {
+            throw new UnsupportedOperationException("An entry modification is not supported");
+        }
+
+        @Override
+        public String toString() {
+            return mKey + "=" + mValue;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (obj == this) {
+                return true;
+            }
+            if (!(obj instanceof Entry)) {
+                return false;
+            }
+            Entry entry = (Entry) obj;
+            return mKey.equals(entry.mKey) && mValue.equals(entry.mValue);
+        }
+    }
+}
diff --git a/app-toolkit/common/src/main/java/android/arch/core/util/Function.java b/app-toolkit/common/src/main/java/android/arch/core/util/Function.java
new file mode 100644
index 0000000..25e7a6b
--- /dev/null
+++ b/app-toolkit/common/src/main/java/android/arch/core/util/Function.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.util;
+
+/**
+ * Represents a function.
+ *
+ * @param <I> the type of the input to the function
+ * @param <O> the type of the output of the function
+ */
+public interface Function<I, O> {
+    /**
+     * Applies this function to the given input.
+     *
+     * @param input the input
+     * @return the function result.
+     */
+    O apply(I input);
+}
diff --git a/app-toolkit/common/src/test/java/android/arch/core/internal/FastSafeIterableMapTest.java b/app-toolkit/common/src/test/java/android/arch/core/internal/FastSafeIterableMapTest.java
new file mode 100644
index 0000000..41b1497
--- /dev/null
+++ b/app-toolkit/common/src/test/java/android/arch/core/internal/FastSafeIterableMapTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.internal;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class FastSafeIterableMapTest {
+    @Test
+    public void testCeil() {
+        FastSafeIterableMap<Integer, Boolean> map = new FastSafeIterableMap<>();
+        assertThat(map.ceil(1), nullValue());
+        map.putIfAbsent(1, false);
+        assertThat(map.ceil(1), nullValue());
+        map.putIfAbsent(2, false);
+        assertThat(map.ceil(2).getKey(), is(1));
+        map.remove(1);
+        assertThat(map.ceil(2), nullValue());
+    }
+
+    @Test
+    public void testPut() {
+        FastSafeIterableMap<Integer, Integer> map = new FastSafeIterableMap<>();
+        map.putIfAbsent(10, 20);
+        map.putIfAbsent(20, 40);
+        map.putIfAbsent(30, 60);
+        assertThat(map.putIfAbsent(5, 10), is((Integer) null));
+        assertThat(map.putIfAbsent(10, 30), is(20));
+    }
+
+    @Test
+    public void testContains() {
+        FastSafeIterableMap<Integer, Integer> map = new FastSafeIterableMap<>();
+        map.putIfAbsent(10, 20);
+        map.putIfAbsent(20, 40);
+        map.putIfAbsent(30, 60);
+        assertThat(map.contains(10), is(true));
+        assertThat(map.contains(11), is(false));
+        assertThat(new FastSafeIterableMap<Integer, Integer>().contains(0), is(false));
+    }
+
+
+    @Test
+    public void testRemove() {
+        FastSafeIterableMap<Integer, Integer> map = new FastSafeIterableMap<>();
+        map.putIfAbsent(10, 20);
+        map.putIfAbsent(20, 40);
+        assertThat(map.contains(10), is(true));
+        assertThat(map.contains(20), is(true));
+        assertThat(map.remove(10), is(20));
+        assertThat(map.contains(10), is(false));
+        assertThat(map.putIfAbsent(10, 30), nullValue());
+        assertThat(map.putIfAbsent(10, 40), is(30));
+    }
+}
diff --git a/app-toolkit/common/src/test/java/android/arch/core/internal/SafeIterableMapTest.java b/app-toolkit/common/src/test/java/android/arch/core/internal/SafeIterableMapTest.java
new file mode 100644
index 0000000..4b25e34
--- /dev/null
+++ b/app-toolkit/common/src/test/java/android/arch/core/internal/SafeIterableMapTest.java
@@ -0,0 +1,475 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.internal;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map.Entry;
+
+@RunWith(JUnit4.class)
+public class SafeIterableMapTest {
+
+    @Test
+    public void testToString() {
+        SafeIterableMap<Integer, String> map = from(1, 2, 3, 4).to("a", "b", "c", "d");
+        assertThat(map.toString(), is("[1=a, 2=b, 3=c, 4=d]"));
+    }
+
+    @Test
+    public void testEmptyToString() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        assertThat(map.toString(), is("[]"));
+    }
+
+    @Test
+    public void testOneElementToString() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1);
+        assertThat(map.toString(), is("[1=true]"));
+    }
+
+
+    @Test
+    public void testEquality1() {
+        SafeIterableMap<Integer, Integer> map1 = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        SafeIterableMap<Integer, Integer> map2 = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        assertThat(map1.equals(map2), is(true));
+    }
+
+    @Test
+    public void testEquality2() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        //noinspection ObjectEqualsNull
+        assertThat(map.equals(null), is(false));
+    }
+
+    @Test
+    public void testEquality3() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        //noinspection EqualsBetweenInconvertibleTypes
+        assertThat(map.equals(new ArrayList<>()), is(false));
+    }
+
+    @Test
+    public void testEquality4() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        assertThat(map.equals(new SafeIterableMap<Integer, Boolean>()), is(false));
+    }
+
+    @Test
+    public void testEquality5() {
+        SafeIterableMap<Integer, Boolean> map1 = mapOf(1, 2, 3, 4);
+        SafeIterableMap<Integer, Boolean> map2 = mapOf(1);
+        assertThat(map1.equals(map2), is(false));
+    }
+
+    @Test
+    public void testEquality6() {
+        SafeIterableMap<Integer, Boolean> map1 = mapOf(1, 2, 3, 4);
+        SafeIterableMap<Integer, Boolean> map2 = mapOf(1, 2, 3, 5);
+        assertThat(map1.equals(map2), is(false));
+    }
+
+    @Test
+    public void testEquality7() {
+        SafeIterableMap<Integer, Integer> map1 = from(1, 2, 3, 4).to(1, 2, 3, 4);
+        SafeIterableMap<Integer, Integer> map2 = from(1, 2, 3, 4).to(1, 2, 3, 5);
+        assertThat(map1.equals(map2), is(false));
+    }
+
+
+    @Test
+    public void testEquality8() {
+        SafeIterableMap<Integer, Boolean> map1 = mapOf();
+        SafeIterableMap<Integer, Boolean> map2 = mapOf();
+        assertThat(map1.equals(map2), is(true));
+    }
+
+    @Test
+    public void testEqualityRespectsOrder() {
+        SafeIterableMap<Integer, Boolean> map1 = mapOf(1, 2, 3, 4);
+        SafeIterableMap<Integer, Boolean> map2 = mapOf(1, 3, 2, 4);
+        assertThat(map1.equals(map2), is(false));
+    }
+
+    @Test
+    public void testPut() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        assertThat(map.putIfAbsent(5, 10), is((Integer) null));
+        assertThat(map, is(from(1, 2, 3, 4, 5).to(10, 20, 30, 40, 10)));
+    }
+
+    @Test
+    public void testAddExisted() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 261, 40);
+        assertThat(map.putIfAbsent(3, 239), is(261));
+        assertThat(map, is(from(1, 2, 3, 4).to(10, 20, 261, 40)));
+    }
+
+    @Test
+    public void testRemoveLast() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        assertThat(map.remove(4), is(40));
+        assertThat(map, is(from(1, 2, 3).to(10, 20, 30)));
+    }
+
+    @Test
+    public void testRemoveFirst() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        assertThat(map.remove(1), is(true));
+        assertThat(map, is(mapOf(2, 3, 4)));
+    }
+
+    @Test
+    public void testRemoveMiddle() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        assertThat(map.remove(2), is(20));
+        assertThat(map.remove(3), is(30));
+        assertThat(map, is(from(1, 4).to(10, 40)));
+    }
+
+    @Test
+    public void testRemoveNotExisted() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        assertThat(map.remove(5), is((Boolean) null));
+        assertThat(map, is(mapOf(1, 2, 3, 4)));
+    }
+
+    @Test
+    public void testRemoveSole() {
+        SafeIterableMap<Integer, Integer> map = from(1).to(261);
+        assertThat(map.remove(1), is(261));
+        assertThat(map, is(new SafeIterableMap<Integer, Integer>()));
+    }
+
+    @Test
+    public void testRemoveDuringIteration1() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        int index = 0;
+        int[] expected = new int[]{1, 4};
+        for (Entry<Integer, Integer> i : map) {
+            assertThat(i.getKey(), is(expected[index++]));
+            if (index == 1) {
+                assertThat(map.remove(2), is(20));
+                assertThat(map.remove(3), is(30));
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveDuringIteration2() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2).to(10, 20);
+        Iterator<Entry<Integer, Integer>> iter = map.iterator();
+        assertThat(map.remove(2), is(20));
+        assertThat(map.remove(1), is(10));
+        assertThat(iter.hasNext(), is(false));
+    }
+
+    @Test
+    public void testRemoveDuringIteration3() {
+        SafeIterableMap<Integer, Integer> map = from(1, 2, 3, 4).to(10, 20, 30, 40);
+        int index = 0;
+        Iterator<Entry<Integer, Integer>> iter = map.iterator();
+        assertThat(map.remove(1), is(10));
+        assertThat(map.remove(2), is(20));
+        int[] expected = new int[]{3, 4};
+        while (iter.hasNext()) {
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+    }
+
+    @Test
+    public void testAdditionDuringIteration() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{1, 2, 3, 4};
+        int index = 0;
+        for (Entry<Integer, Boolean> entry : map) {
+            assertThat(entry.getKey(), is(expected[index++]));
+            if (index == 1) {
+                map.putIfAbsent(5, true);
+            }
+        }
+    }
+
+    @Test
+    public void testReAdditionDuringIteration() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{1, 2, 4};
+        int index = 0;
+        for (Entry<Integer, Boolean> entry : map) {
+            assertThat(entry.getKey(), is(expected[index++]));
+            if (index == 1) {
+                map.remove(3);
+                map.putIfAbsent(3, true);
+            }
+        }
+    }
+
+    @Test
+    public void testSize() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        assertThat(map.size(), is(4));
+        map.putIfAbsent(5, true);
+        map.putIfAbsent(6, true);
+        assertThat(map.size(), is(6));
+        map.remove(5);
+        map.remove(5);
+        assertThat(map.size(), is(5));
+        map.remove(1);
+        map.remove(2);
+        map.remove(4);
+        map.remove(3);
+        map.remove(6);
+        assertThat(map.size(), is(0));
+        map.putIfAbsent(4, true);
+        assertThat(map.size(), is(1));
+        assertThat(mapOf().size(), is(0));
+    }
+
+    @Test
+    public void testIteratorWithAdditions1() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{1, 2, 3, 5};
+        int index = 0;
+        Iterator<Entry<Integer, Boolean>> iterator = map.iteratorWithAdditions();
+        while (iterator.hasNext()) {
+            Entry<Integer, Boolean> entry = iterator.next();
+            assertThat(entry.getKey(), is(expected[index++]));
+            if (index == 3) {
+                map.remove(4);
+                map.putIfAbsent(5, true);
+            }
+        }
+    }
+
+    @Test
+    public void testIteratorWithAdditions2() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1);
+        int[] expected = new int[]{1, 2, 3};
+        int index = 0;
+        Iterator<Entry<Integer, Boolean>> iterator = map.iteratorWithAdditions();
+        while (iterator.hasNext()) {
+            Entry<Integer, Boolean> entry = iterator.next();
+            assertThat(entry.getKey(), is(expected[index++]));
+            if (index == 1) {
+                map.putIfAbsent(2, true);
+                map.putIfAbsent(3, true);
+            }
+        }
+        assertThat(index, is(3));
+    }
+
+
+    @Test
+    public void testIteratorWithAdditions3() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3);
+        int[] expected = new int[]{1};
+        int index = 0;
+        Iterator<Entry<Integer, Boolean>> iterator = map.iteratorWithAdditions();
+        while (iterator.hasNext()) {
+            Entry<Integer, Boolean> entry = iterator.next();
+            assertThat(entry.getKey(), is(expected[index++]));
+            map.remove(2);
+            map.remove(3);
+        }
+        assertThat(index, is(1));
+    }
+
+    @Test
+    public void testIteratorWithAdditions4() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        int[] expected = new int[]{1, 2, 3};
+        int index = 0;
+        Iterator<Entry<Integer, Boolean>> iterator = map.iteratorWithAdditions();
+        map.putIfAbsent(1, true);
+        while (iterator.hasNext()) {
+            Entry<Integer, Boolean> entry = iterator.next();
+            assertThat(entry.getKey(), is(expected[index++]));
+            if (index == 1) {
+                map.putIfAbsent(2, false);
+            }
+            if (index == 2) {
+                map.putIfAbsent(3, false);
+            }
+        }
+        assertThat(index, is(3));
+    }
+
+    @Test
+    public void testDescendingIteration() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{4, 3, 2, 1};
+        int index = 0;
+        for (Iterator<Entry<Integer, Boolean>> iter = map.descendingIterator(); iter.hasNext(); ) {
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+        assertThat(index, is(4));
+    }
+
+    @Test
+    public void testDescendingIterationRemove1() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{4, 3, 2};
+        int index = 0;
+        for (Iterator<Entry<Integer, Boolean>> iter = map.descendingIterator(); iter.hasNext(); ) {
+            if (index == 1) {
+                map.remove(1);
+            }
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+        assertThat(index, is(3));
+        assertThat(map.size(), is(3));
+    }
+
+    @Test
+    public void testDescendingIterationRemove2() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{3, 2, 1};
+        int index = 0;
+        for (Iterator<Entry<Integer, Boolean>> iter = map.descendingIterator(); iter.hasNext(); ) {
+            if (index == 0) {
+                map.remove(4);
+            }
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+        assertThat(index, is(3));
+        assertThat(map.size(), is(3));
+    }
+
+    @Test
+    public void testDescendingIterationRemove3() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{4, 1};
+        int index = 0;
+        for (Iterator<Entry<Integer, Boolean>> iter = map.descendingIterator(); iter.hasNext(); ) {
+            if (index == 1) {
+                map.remove(3);
+                map.remove(2);
+            }
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+        assertThat(index, is(2));
+        assertThat(map.size(), is(2));
+    }
+
+    @Test
+    public void testDescendingIterationAddition() {
+        SafeIterableMap<Integer, Boolean> map = mapOf(1, 2, 3, 4);
+        int[] expected = new int[]{4, 3, 2, 1};
+        int index = 0;
+        for (Iterator<Entry<Integer, Boolean>> iter = map.descendingIterator(); iter.hasNext(); ) {
+            if (index == 0) {
+                map.putIfAbsent(5, false);
+            }
+            assertThat(iter.next().getKey(), is(expected[index++]));
+        }
+        assertThat(index, is(4));
+        assertThat(map.size(), is(5));
+    }
+
+    @Test
+    public void testDescendingIteratorEmpty() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        Iterator<Entry<Integer, Boolean>> iterator = map.descendingIterator();
+        assertThat(iterator.hasNext(), is(false));
+    }
+
+    @Test
+    public void testIteratorEmpty() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        Iterator<Entry<Integer, Boolean>> iterator = map.iterator();
+        assertThat(iterator.hasNext(), is(false));
+    }
+
+    @Test
+    public void testIteratorWithAdditionEmpty() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        Iterator<Entry<Integer, Boolean>> iterator = map.iteratorWithAdditions();
+        assertThat(iterator.hasNext(), is(false));
+    }
+
+    @Test
+    public void testEldest() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        assertThat(map.eldest(), nullValue());
+        map.putIfAbsent(1, false);
+        assertThat(map.eldest().getKey(), is(1));
+        map.putIfAbsent(2, false);
+        assertThat(map.eldest().getKey(), is(1));
+        map.remove(1);
+        assertThat(map.eldest().getKey(), is(2));
+        map.remove(2);
+        assertThat(map.eldest(), nullValue());
+    }
+
+    @Test
+    public void testNewest() {
+        SafeIterableMap<Integer, Boolean> map = mapOf();
+        assertThat(map.newest(), nullValue());
+        map.putIfAbsent(1, false);
+        assertThat(map.newest().getKey(), is(1));
+        map.putIfAbsent(2, false);
+        assertThat(map.newest().getKey(), is(2));
+        map.remove(2);
+        assertThat(map.eldest().getKey(), is(1));
+        map.remove(1);
+        assertThat(map.newest(), nullValue());
+    }
+
+
+    // for most operations we don't care about values, so we create map from key to true
+    @SafeVarargs
+    private static <K> SafeIterableMap<K, Boolean> mapOf(K... keys) {
+        SafeIterableMap<K, Boolean> map = new SafeIterableMap<>();
+        for (K key : keys) {
+            map.putIfAbsent(key, true);
+        }
+        return map;
+    }
+
+    @SafeVarargs
+    private static <K> MapBuilder<K> from(K... keys) {
+        return new MapBuilder<>(keys);
+    }
+
+    private static class MapBuilder<K> {
+        final K[] mKeys;
+
+        MapBuilder(K[] keys) {
+            this.mKeys = keys;
+        }
+
+        @SafeVarargs
+        public final <V> SafeIterableMap<K, V> to(V... values) {
+            assertThat("Failed to build Map", mKeys.length, is(values.length));
+            SafeIterableMap<K, V> map = new SafeIterableMap<>();
+            for (int i = 0; i < mKeys.length; i++) {
+                map.putIfAbsent(mKeys[i], values[i]);
+            }
+            return map;
+        }
+    }
+}
+
+
diff --git a/app-toolkit/core-testing/build.gradle b/app-toolkit/core-testing/build.gradle
new file mode 100644
index 0000000..c757533
--- /dev/null
+++ b/app-toolkit/core-testing/build.gradle
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile project(":arch:runtime")
+    compile libs.support.annotations
+    compile libs.support.core_utils
+    compile(libs.junit) {
+        exclude module: 'hamcrest-core'
+    }
+    compile libs.mockito_core
+
+    testCompile libs.junit
+    testCompile libs.support.annotations
+
+    androidTestCompile libs.junit
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+}
+
+archivesBaseName = "core-testing"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    project.tasks.create(name: "jar${suffix}", type: Jar) {
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/app-toolkit/core-testing/src/androidTest/java/android/arch/core/executor/testing/CountingTaskExecutorRuleTest.java b/app-toolkit/core-testing/src/androidTest/java/android/arch/core/executor/testing/CountingTaskExecutorRuleTest.java
new file mode 100644
index 0000000..ad36b9b
--- /dev/null
+++ b/app-toolkit/core-testing/src/androidTest/java/android/arch/core/executor/testing/CountingTaskExecutorRuleTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor.testing;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+@RunWith(AndroidJUnit4.class)
+@MediumTest
+public class CountingTaskExecutorRuleTest {
+    private final Semaphore mOnIdleCount = new Semaphore(0);
+
+    @Rule
+    public CountingTaskExecutorRule mRule = new CountingTaskExecutorRule() {
+        @Override
+        protected void onIdle() {
+            super.onIdle();
+            mOnIdleCount.release(1);
+        }
+    };
+
+    @Test
+    public void initialIdle() {
+        assertThat(mRule.isIdle(), is(true));
+    }
+
+    @Test
+    public void busyIO() throws InterruptedException {
+        LatchRunnable task = runOnIO();
+        singleTaskTest(task);
+    }
+
+    @Test
+    public void busyMain() throws InterruptedException {
+        LatchRunnable task = runOnMain();
+        singleTaskTest(task);
+    }
+
+    @Test
+    public void multipleTasks() throws InterruptedException {
+        List<LatchRunnable> latches = new ArrayList<>(10);
+        for (int i = 0; i < 5; i++) {
+            latches.add(runOnIO());
+            latches.add(runOnMain());
+        }
+        assertNotIdle();
+        for (int i = 0; i < 9; i++) {
+            latches.get(i).start();
+        }
+        for (int i = 0; i < 9; i++) {
+            latches.get(i).await();
+        }
+        assertNotIdle();
+
+        LatchRunnable another = runOnIO();
+        latches.get(9).startAndFinish();
+        assertNotIdle();
+
+        another.startAndFinish();
+        assertBecomeIdle();
+
+        LatchRunnable oneMore = runOnMain();
+
+        assertNotIdle();
+
+        oneMore.startAndFinish();
+        assertBecomeIdle();
+    }
+
+    private void assertNotIdle() throws InterruptedException {
+        assertThat(mOnIdleCount.tryAcquire(300, TimeUnit.MILLISECONDS), is(false));
+        assertThat(mRule.isIdle(), is(false));
+    }
+
+    private void assertBecomeIdle() throws InterruptedException {
+        assertThat(mOnIdleCount.tryAcquire(1, TimeUnit.SECONDS), is(true));
+        assertThat(mRule.isIdle(), is(true));
+    }
+
+    private void singleTaskTest(LatchRunnable task)
+            throws InterruptedException {
+        assertNotIdle();
+        task.startAndFinish();
+        assertBecomeIdle();
+    }
+
+    private LatchRunnable runOnIO() {
+        LatchRunnable latchRunnable = new LatchRunnable();
+        AppToolkitTaskExecutor.getInstance().executeOnDiskIO(latchRunnable);
+        return latchRunnable;
+    }
+
+    private LatchRunnable runOnMain() {
+        LatchRunnable latchRunnable = new LatchRunnable();
+        AppToolkitTaskExecutor.getInstance().executeOnMainThread(latchRunnable);
+        return latchRunnable;
+    }
+
+    @Test
+    public void drainFailure() throws InterruptedException {
+        runOnIO();
+        try {
+            mRule.drainTasks(300, TimeUnit.MILLISECONDS);
+            throw new AssertionError("drain should fail");
+        } catch (TimeoutException ignored) {
+        }
+    }
+
+    @Test
+    public void drainSuccess() throws TimeoutException, InterruptedException {
+        final LatchRunnable task = runOnIO();
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    Thread.sleep(300);
+                } catch (InterruptedException ignored) {
+                }
+                task.start();
+            }
+        }).start();
+        mRule.drainTasks(1, TimeUnit.SECONDS);
+    }
+
+    private static class LatchRunnable implements Runnable {
+        private final CountDownLatch mStart = new CountDownLatch(1);
+        private final CountDownLatch mEnd = new CountDownLatch(1);
+
+        @Override
+        public void run() {
+            try {
+                mStart.await(10, TimeUnit.SECONDS);
+                mEnd.countDown();
+            } catch (InterruptedException e) {
+                throw new AssertionError(e);
+            }
+        }
+
+        void await() throws InterruptedException {
+            mEnd.await(10, TimeUnit.SECONDS);
+        }
+
+        void start() {
+            mStart.countDown();
+        }
+
+        private void startAndFinish() throws InterruptedException {
+            start();
+            await();
+        }
+    }
+}
diff --git a/app-toolkit/core-testing/src/main/AndroidManifest.xml b/app-toolkit/core-testing/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..83e0d83
--- /dev/null
+++ b/app-toolkit/core-testing/src/main/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest package="android.arch.core.testing">
+</manifest>
diff --git a/app-toolkit/core-testing/src/main/java/android/arch/core/executor/JunitTaskExecutorRule.java b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/JunitTaskExecutorRule.java
new file mode 100644
index 0000000..cd4f8f5
--- /dev/null
+++ b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/JunitTaskExecutorRule.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor;
+
+import android.support.annotation.RestrictTo;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.MultipleFailureException;
+import org.junit.runners.model.Statement;
+import org.mockito.Mockito;
+
+import java.util.List;
+
+/**
+ * A JUnit rule that swaps the task executor with a more controllable one.
+ * Once we have the TaskExecutor API, we should consider making this public (via some test package).
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class JunitTaskExecutorRule implements TestRule {
+    private final TaskExecutorWithFakeMainThread mTaskExecutor;
+
+    public JunitTaskExecutorRule(int ioThreadCount, boolean spyOnExecutor) {
+        if (spyOnExecutor) {
+            mTaskExecutor = Mockito.spy(new TaskExecutorWithFakeMainThread(ioThreadCount));
+        } else {
+            mTaskExecutor = new TaskExecutorWithFakeMainThread(ioThreadCount);
+        }
+
+    }
+
+    private void beforeStart() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(mTaskExecutor);
+    }
+
+    private void afterFinished() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    public TaskExecutor getTaskExecutor() {
+        return mTaskExecutor;
+    }
+
+    /**
+     * Awaits while all currently posted tasks will be finished
+     *
+     * @param seconds timeout in seconds
+     */
+    public void drainTasks(int seconds) throws InterruptedException {
+        mTaskExecutor.drainTasks(seconds);
+    }
+
+    @Override
+    public Statement apply(final Statement base, Description description) {
+        return new Statement() {
+            @Override
+            public void evaluate() throws Throwable {
+                beforeStart();
+                try {
+                    base.evaluate();
+                    finishExecutors();
+                } catch (Throwable t) {
+                    throw new RuntimeException(t);
+                } finally {
+                    afterFinished();
+                }
+            }
+        };
+    }
+
+    private void finishExecutors() throws InterruptedException, MultipleFailureException {
+        mTaskExecutor.shutdown(10);
+        final List<Throwable> errors = mTaskExecutor.getErrors();
+        if (!errors.isEmpty()) {
+            throw new MultipleFailureException(errors);
+        }
+    }
+}
diff --git a/app-toolkit/core-testing/src/main/java/android/arch/core/executor/TaskExecutorWithFakeMainThread.java b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/TaskExecutorWithFakeMainThread.java
new file mode 100644
index 0000000..af0aca4
--- /dev/null
+++ b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/TaskExecutorWithFakeMainThread.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A TaskExecutor that has a real thread for main thread operations and can wait for execution etc.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class TaskExecutorWithFakeMainThread extends TaskExecutor {
+    private List<Throwable> mCaughtExceptions = Collections.synchronizedList(new ArrayList
+            <Throwable>());
+
+    private ExecutorService mIOService;
+
+    private Thread mMainThread;
+    private final int mIOThreadCount;
+
+    private ExecutorService mMainThreadService =
+            Executors.newSingleThreadExecutor(new ThreadFactory() {
+                @Override
+                public Thread newThread(@NonNull final Runnable r) {
+                    mMainThread = new LoggingThread(r);
+                    return mMainThread;
+                }
+            });
+
+    public TaskExecutorWithFakeMainThread(int ioThreadCount) {
+        mIOThreadCount = ioThreadCount;
+        mIOService = Executors.newFixedThreadPool(ioThreadCount, new ThreadFactory() {
+            @Override
+            public Thread newThread(@NonNull Runnable r) {
+                return new LoggingThread(r);
+            }
+        });
+    }
+
+    @Override
+    public void executeOnDiskIO(Runnable runnable) {
+        mIOService.execute(runnable);
+    }
+
+    @Override
+    public void postToMainThread(Runnable runnable) {
+        // Tasks in SingleThreadExecutor are guaranteed to execute sequentially,
+        // and no more than one task will be active at any given time.
+        // So if we call this method from the main thread, new task will be scheduled,
+        // which is equivalent to post.
+        mMainThreadService.execute(runnable);
+    }
+
+    @Override
+    public boolean isMainThread() {
+        return Thread.currentThread() == mMainThread;
+    }
+
+    List<Throwable> getErrors() {
+        return mCaughtExceptions;
+    }
+
+    @SuppressWarnings("SameParameterValue")
+    void shutdown(int timeoutInSeconds) throws InterruptedException {
+        mMainThreadService.shutdown();
+        mIOService.shutdown();
+        mMainThreadService.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS);
+        mIOService.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS);
+    }
+
+    /**
+     * Drains tasks at the given time limit
+     * @param seconds Number of seconds to wait
+     * @throws InterruptedException
+     */
+    public void drainTasks(int seconds) throws InterruptedException {
+        if (isMainThread()) {
+            throw new IllegalStateException();
+        }
+        final CountDownLatch enterLatch = new CountDownLatch(mIOThreadCount);
+        final CountDownLatch exitLatch = new CountDownLatch(1);
+        for (int i = 0; i < mIOThreadCount; i++) {
+            executeOnDiskIO(new Runnable() {
+                @Override
+                public void run() {
+                    enterLatch.countDown();
+                    try {
+                        exitLatch.await();
+                    } catch (InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            });
+        }
+
+        final CountDownLatch mainLatch = new CountDownLatch(1);
+        postToMainThread(new Runnable() {
+            @Override
+            public void run() {
+                mainLatch.countDown();
+            }
+        });
+        if (!enterLatch.await(seconds, TimeUnit.SECONDS)) {
+            throw new AssertionError("Could not drain IO tasks in " + seconds
+                    + " seconds");
+        }
+        exitLatch.countDown();
+        if (!mainLatch.await(seconds, TimeUnit.SECONDS)) {
+            throw new AssertionError("Could not drain UI tasks in " + seconds
+                    + " seconds");
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    class LoggingThread extends Thread {
+        LoggingThread(final Runnable target) {
+            super(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        target.run();
+                    } catch (Throwable t) {
+                        mCaughtExceptions.add(t);
+                    }
+                }
+            });
+        }
+    }
+}
diff --git a/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/CountingTaskExecutorRule.java b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/CountingTaskExecutorRule.java
new file mode 100644
index 0000000..ad930aa
--- /dev/null
+++ b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/CountingTaskExecutorRule.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor.testing;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.DefaultTaskExecutor;
+import android.os.SystemClock;
+
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * A JUnit Test Rule that swaps the background executor used by the Architecture Components with a
+ * different one which counts the tasks as they are start and finish.
+ * <p>
+ * You can use this rule for your host side tests that use Architecture Components.
+ */
+public class CountingTaskExecutorRule extends TestWatcher {
+    private final Object mCountLock = new Object();
+    private int mTaskCount = 0;
+
+    @Override
+    protected void starting(Description description) {
+        super.starting(description);
+        AppToolkitTaskExecutor.getInstance().setDelegate(new DefaultTaskExecutor() {
+            @Override
+            public void executeOnDiskIO(Runnable runnable) {
+                super.executeOnDiskIO(new CountingRunnable(runnable));
+            }
+
+            @Override
+            public void postToMainThread(Runnable runnable) {
+                super.postToMainThread(new CountingRunnable(runnable));
+            }
+        });
+    }
+
+    @Override
+    protected void finished(Description description) {
+        super.finished(description);
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    private void increment() {
+        synchronized (mCountLock) {
+            mTaskCount++;
+        }
+    }
+
+    private void decrement() {
+        synchronized (mCountLock) {
+            mTaskCount--;
+            if (mTaskCount == 0) {
+                onIdle();
+                mCountLock.notifyAll();
+            }
+        }
+    }
+
+    /**
+     * Called when the number of awaiting tasks reaches to 0.
+     *
+     * @see #isIdle()
+     */
+    protected void onIdle() {
+
+    }
+
+    /**
+     * Returns false if there are tasks waiting to be executed, true otherwise.
+     *
+     * @return False if there are tasks waiting to be executed, true otherwise.
+     *
+     * @see #onIdle()
+     */
+    public boolean isIdle() {
+        synchronized (mCountLock) {
+            return mTaskCount == 0;
+        }
+    }
+
+    /**
+     * Waits until all active tasks are finished.
+     *
+     * @param time The duration to wait
+     * @param timeUnit The time unit for the {@code time} parameter
+     *
+     * @throws InterruptedException If thread is interrupted while waiting
+     * @throws TimeoutException If tasks cannot be drained at the given time
+     */
+    public void drainTasks(int time, TimeUnit timeUnit)
+            throws InterruptedException, TimeoutException {
+        long end = SystemClock.uptimeMillis() + timeUnit.toMillis(time);
+        synchronized (mCountLock) {
+            while (mTaskCount != 0) {
+                long now = SystemClock.uptimeMillis();
+                long remaining = end - now;
+                if (remaining > 0) {
+                    mCountLock.wait(remaining);
+                } else {
+                    throw new TimeoutException("could not drain tasks");
+                }
+            }
+        }
+    }
+
+    class CountingRunnable implements Runnable {
+        final Runnable mWrapped;
+
+        CountingRunnable(Runnable wrapped) {
+            mWrapped = wrapped;
+            increment();
+        }
+
+        @Override
+        public void run() {
+            try {
+                mWrapped.run();
+            } finally {
+                decrement();
+            }
+        }
+    }
+}
diff --git a/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/InstantTaskExecutorRule.java b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/InstantTaskExecutorRule.java
new file mode 100644
index 0000000..07dcf1f
--- /dev/null
+++ b/app-toolkit/core-testing/src/main/java/android/arch/core/executor/testing/InstantTaskExecutorRule.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor.testing;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.TaskExecutor;
+
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+/**
+ * A JUnit Test Rule that swaps the background executor used by the Architecture Components with a
+ * different one which executes each task synchronously.
+ * <p>
+ * You can use this rule for your host side tests that use Architecture Components.
+ */
+public class InstantTaskExecutorRule extends TestWatcher {
+    @Override
+    protected void starting(Description description) {
+        super.starting(description);
+        AppToolkitTaskExecutor.getInstance().setDelegate(new TaskExecutor() {
+            @Override
+            public void executeOnDiskIO(Runnable runnable) {
+                runnable.run();
+            }
+
+            @Override
+            public void postToMainThread(Runnable runnable) {
+                runnable.run();
+            }
+
+            @Override
+            public boolean isMainThread() {
+                return true;
+            }
+        });
+    }
+
+    @Override
+    protected void finished(Description description) {
+        super.finished(description);
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+}
diff --git a/app-toolkit/core-testing/src/test/java/android/arch/core/executor/testing/InstantTaskExecutorRuleTest.java b/app-toolkit/core-testing/src/test/java/android/arch/core/executor/testing/InstantTaskExecutorRuleTest.java
new file mode 100644
index 0000000..4345fd1
--- /dev/null
+++ b/app-toolkit/core-testing/src/test/java/android/arch/core/executor/testing/InstantTaskExecutorRuleTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor.testing;
+
+import static org.junit.Assert.assertTrue;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+@RunWith(JUnit4.class)
+public class InstantTaskExecutorRuleTest {
+    @Rule
+    public InstantTaskExecutorRule mInstantTaskExecutorRule = new InstantTaskExecutorRule();
+
+    @Test
+    public void executeOnMain() throws ExecutionException, InterruptedException, TimeoutException {
+        final Thread current = Thread.currentThread();
+        FutureTask<Void> check = new FutureTask<>(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                assertTrue(Thread.currentThread() == current);
+                return null;
+            }
+        });
+        AppToolkitTaskExecutor.getInstance().executeOnMainThread(check);
+        check.get(1, TimeUnit.SECONDS);
+    }
+
+    @Test
+    public void executeOnIO() throws ExecutionException, InterruptedException, TimeoutException {
+        final Thread current = Thread.currentThread();
+        FutureTask<Void> check = new FutureTask<>(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                assertTrue(Thread.currentThread() == current);
+                return null;
+            }
+        });
+        AppToolkitTaskExecutor.getInstance().executeOnDiskIO(check);
+        check.get(1, TimeUnit.SECONDS);
+    }
+}
diff --git a/app-toolkit/dependencies.gradle b/app-toolkit/dependencies.gradle
new file mode 100644
index 0000000..bec804a
--- /dev/null
+++ b/app-toolkit/dependencies.gradle
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+def ffLibs
+if (hasProperty("libs")) {
+    ffLibs = libs
+} else {
+    apply from: "${ext.supportRootFolder}/buildSrc/dependencies.gradle"
+    ffLibs = libs
+}
+def ffVersions = [:]
+ffVersions.kotlin = "1.1.3"
+ffVersions.auto_common = "0.6"
+ffVersions.javapoet = "1.8.0"
+ffVersions.compile_testing = "0.11"
+ffVersions.localize_maven = "1.2"
+ffVersions.support_lib = "26.0.0"
+ffVersions.intellij_annotations = "12.0"
+ffVersions.rxjava2 = "2.0.6"
+ffVersions.reactivestreams = "1.0.0"
+// this Xerial version is newer than we want but we need it to fix
+// https://github.com/xerial/sqlite-jdbc/issues/97
+ffVersions.xerial = "3.16.1"
+ffVersions.antlr = "4.5.3"
+ffVersions.commons_codec = "1.10"
+ffVersions.gson = "2.8.0"
+ffVersions.guava = "21.0"
+
+ffLibs.kotlin = [
+        stdlib : "org.jetbrains.kotlin:kotlin-stdlib:$ffVersions.kotlin",
+        gradle_plugin : "org.jetbrains.kotlin:kotlin-gradle-plugin:$ffVersions.kotlin"
+]
+ffLibs.auto_common = "com.google.auto:auto-common:$ffVersions.auto_common"
+ffLibs.apache = [
+    commons : [
+            codec : "commons-codec:commons-codec:$ffVersions.commons_codec"
+    ]
+]
+
+def getSupportLib(String name, String version, String artifactName = null) {
+    def sourceProject = findProject(name)
+    if (sourceProject != null) {
+        return sourceProject
+    }
+    if (artifactName == null) {
+        artifactName = name
+    }
+    return "com.android.support$artifactName:$version"
+}
+ffLibs.support = [
+        annotations : getSupportLib(":support-annotations", ffVersions.support_lib),
+        core_utils : getSupportLib(':support-core-utils', ffVersions.support_lib),
+        fragments : getSupportLib(':support-fragment', ffVersions.support_lib),
+        app_compat : getSupportLib(':support-appcompat-v7', ffVersions.support_lib, ":appcompat-v7"),
+        design : getSupportLib(':support-design', ffVersions.support_lib, ":design"),
+        recyclerview : getSupportLib(':support-recyclerview-v7', ffVersions.support_lib, ":recyclerview-v7")
+]
+
+ffLibs.localize_maven = "com.android.databinding:localizemaven:$ffVersions.localize_maven"
+ffLibs.javapoet = "com.squareup:javapoet:$ffVersions.javapoet"
+ffLibs.antlr = "org.antlr:antlr4:$ffVersions.antlr"
+ffLibs.xerial = "org.xerial:sqlite-jdbc:$ffVersions.xerial"
+ffLibs.google_compile_testing = "com.google.testing.compile:compile-testing:$ffVersions.compile_testing"
+ffLibs.ij_annotations = "com.intellij:annotations:$ffVersions.intellij_annotations"
+ffLibs.reactive_streams = "org.reactivestreams:reactive-streams:$ffVersions.reactivestreams"
+ffLibs.rx_java = "io.reactivex.rxjava2:rxjava:$ffVersions.rxjava2"
+ffLibs.gson = "com.google.code.gson:gson:$ffVersions.gson"
+ffLibs.guava= "com.google.guava:guava:$ffVersions.guava"
+
+ext.tools = [:]
+ext.tools.current_sdk = gradle.ext.currentSdk
+ext.tools.build_tools_version = rootProject.ext.buildToolsVersion
+ext.flatfoot = [:]
+ext.flatfoot.release_version = "1.0.0-alpha8"
+ext.flatfoot.min_sdk = 14
diff --git a/app-toolkit/gradle.properties b/app-toolkit/gradle.properties
new file mode 100644
index 0000000..3e1a1a6
--- /dev/null
+++ b/app-toolkit/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx3000M
+org.gradle.daemon=true
+org.gradle.configureondemand=false
+org.gradle.parallel=false
\ No newline at end of file
diff --git a/app-toolkit/gradle/wrapper/gradle-wrapper.jar b/app-toolkit/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..d6e2637
--- /dev/null
+++ b/app-toolkit/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/app-toolkit/gradle/wrapper/gradle-wrapper.properties b/app-toolkit/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..1b987ef
--- /dev/null
+++ b/app-toolkit/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Tue Aug 16 10:43:36 PDT 2016
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=../../../../../tools/external/gradle/gradle-4.1-milestone-1-bin.zip
diff --git a/app-toolkit/gradlew b/app-toolkit/gradlew
new file mode 100755
index 0000000..4ef3a87
--- /dev/null
+++ b/app-toolkit/gradlew
@@ -0,0 +1,171 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+  NONSTOP* )
+    nonstop=true
+    ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Escape application args
+for s in "${@}" ; do
+    s=\"$s\"
+    APP_ARGS=$APP_ARGS" "$s
+done
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- "$DEFAULT_JVM_OPTS" "$JAVA_OPTS" "$GRADLE_OPTS" "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+  cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/app-toolkit/gradlew.bat b/app-toolkit/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/app-toolkit/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windows variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/app-toolkit/init.gradle b/app-toolkit/init.gradle
new file mode 100644
index 0000000..70e518a
--- /dev/null
+++ b/app-toolkit/init.gradle
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+import org.gradle.internal.os.OperatingSystem
+
+def root = ext.supportRootFolder
+ext.usePrebuilts = "true" // for doclava
+ext.inAppToolkitProject = rootProject.name == "app-toolkit"
+
+if (ext.inAppToolkitProject) {
+    apply from: "${ext.supportRootFolder}/buildSrc/init.gradle"
+    init.loadDefaultVersions()
+    init.setSdkInLocalPropertiesFile()
+}
+
+def checkoutRoot = "${root}/../.."
+ext.checkoutRoot = checkoutRoot
+ext.prebuiltsRoot = "$checkoutRoot/prebuilts"
+ext.prebuiltsRootUri = "file://${prebuiltsRoot}"
+
+final String platform = OperatingSystem.current().isMacOsX() ? 'darwin' : 'linux'
+final String fullSdkPath = new File("${checkoutRoot}/prebuilts/fullsdk-${platform}").getCanonicalPath()
+System.setProperty('android.home', fullSdkPath)
+File props = file("local.properties")
+props.write "sdk.dir=${fullSdkPath}"
+
+def buildDir
+def distDir
+def supportLibBuildDir
+
+if (ext.runningInBuildServer) {
+    supportLibBuildDir = new File(System.env.OUT_DIR + '/gradle/frameworks/support/build').getCanonicalFile();
+    buildDir = new File(System.env.OUT_DIR + '/gradle/frameworks/app-toolkit/build').getCanonicalFile()
+    distDir = new File(System.env.DIST_DIR).getCanonicalFile()
+} else {
+    supportLibBuildDir = file("${checkoutRoot}/out/host/gradle/frameworks/support/build")
+    buildDir = file("${checkoutRoot}/out/host/gradle/frameworks/app-toolkit/build")
+    distDir = file("${checkoutRoot}/out/dist")
+}
+
+def localMavenRepo = "file://${new File(buildDir, "flatfoot_repo").absolutePath}"
+ext.testApkDistOut = distDir
+ext.testResultsDistDir = new File(distDir, "host-test-reports")
+ext.localMavenRepo = localMavenRepo
+file(localMavenRepo).delete()
+file(localMavenRepo).mkdirs()
+
+ext.repoNames = ["$prebuiltsRootUri/maven_repo",
+                 "$prebuiltsRootUri/gradle-plugin",
+                 "$prebuiltsRootUri/tools/common/m2/repository",
+                 "$prebuiltsRootUri/tools/common/m2/internal",
+                 "$prebuiltsRootUri/tools/common/offline-m2",
+                 "$prebuiltsRootUri/maven_repo/android",
+                 "file://$fullSdkPath/extras/android/m2repository",
+                 "file://${new File(supportLibBuildDir, "support_repo").absolutePath}"]
+
+apply from: "${ext.supportRootFolder}/app-toolkit/dependencies.gradle"
+ext.enablePublicRepos = System.getenv("ALLOW_PUBLIC_REPOS")
+
+// repository creation task
+def buildServerAnchorTask = rootProject.tasks.create(name : "runBuildServerCompilationTasks",
+    description: "Anchor task for everything we want to run in build server.")
+
+if (ext.inAppToolkitProject) {
+    // always build offline docs for flatfoot specific builds.
+    ext.docs.dac = [
+            libraryroot: "android/arch",
+            dataname: "ARCH_DATA"
+    ]
+    repos.addMavenRepositories(repositories)
+    init.setupRepoOutAndBuildNumber()
+    init.configureSubProjects()
+    init.setupRelease()
+    init.enableDoclavaAndJDiff(this)
+    rootProject.tasks["generateDocs"].exclude '**/R.java'
+}
+
+
+// flatfoot docs
+def zipFlatfootDocsTask = rootProject.tasks.create(name : "createFlatfootDocsArchive", type : Zip) {
+    from rootProject.docsDir
+    destinationDir distDir
+    baseName = String.format("flatfoot-docs-%s", rootProject.ext.flatfoot.release_version)
+}
+
+buildServerAnchorTask.dependsOn zipFlatfootDocsTask
+zipFlatfootDocsTask.dependsOn rootProject.tasks["generateDocs"]
+
+// Disable API checks for now.
+checkApiRelease.enabled = false
+checkApi.enabled = false
+generateApi.enabled = false
+
+buildServerAnchorTask.dependsOn createArchive
+
+rootProject.ext.flatfootProjectGroups = [
+        "room" : "android.arch.persistence.room",
+        "lifecycle" : "android.arch.lifecycle",
+        "arch" : "android.arch.core",
+        "paging" : "android.arch.paging",
+        "navigation" : "android.arch.navigation"]
+
+subprojects {
+    repos.addMavenRepositories(project.repositories)
+    if (project.name == 'doclava' || project.name == 'jdiff') {
+        project.tasks.whenTaskAdded { task ->
+            if (task instanceof org.gradle.api.tasks.testing.Test) {
+                task.enabled = false
+            }
+        }
+        return
+    }
+
+    def mavenGroup = project.getPath().split(":")[1]
+    def finalGroup = rootProject.flatfootProjectGroups[mavenGroup]
+
+    if (finalGroup == null) {
+        return
+    }
+    project.group = finalGroup
+    project.version = flatfoot.release_version
+
+    if (project.getPath().contains("integration-tests")) {
+        // disable upload tasks
+        project.tasks.whenTaskAdded { task ->
+            if (task instanceof Upload || task.name == "generateSourceProps") {
+                task.enabled = false
+            }
+        }
+    } else {
+        // add license to pom
+        project.tasks.whenTaskAdded { task ->
+            if (task instanceof Upload) {
+                task.repositories {
+                    mavenDeployer {
+                        repository(url: project.uri(project.rootProject.supportRepoOut))
+                        pom.project {
+                            url "https://developer.android.com/topic/libraries/architecture/index.html"
+                            inceptionYear 2017
+                            licenses {
+                                license {
+                                    name 'The Apache Software License, Version 2.0'
+                                    url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
+                                    distribution 'repo'
+                                }
+                            }
+                            scm {
+                                url "http://source.android.com"
+                                connection "scm:git:https://android.googlesource.com/platform/frameworks/support"
+                            }
+                            developers {
+                                developer {
+                                    name 'The Android Open Source Project'
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+
+    project.plugins.whenPluginAdded { plugin ->
+        def isAndroidLibrary = "com.android.build.gradle.LibraryPlugin"
+                .equals(plugin.class.name)
+        def isJavaLibrary = "org.gradle.api.plugins.JavaPlugin".equals(plugin.class.name)
+        if (isAndroidLibrary) {
+            // it is an android lib, enable sources.
+            def sourcesTask = project.tasks.create(name: "sourcesJar", type : Jar) {
+                classifier = 'sources'
+                from android.sourceSets.main.getJava().getSrcDirs()
+            }
+            project.artifacts {
+                archives sourcesTask
+            }
+        } else if(isJavaLibrary && project.name == "common") {
+            // it is a shared lib, enable sources.
+            def sourcesTask = project.tasks.create(name: "sourcesJar", type : Jar) {
+                classifier = 'sources'
+                from sourceSets.main.allSource
+            }
+            project.artifacts {
+                archives sourcesTask
+            }
+        }
+    }
+
+    project.tasks.whenTaskAdded { task ->
+        if (task.name.startsWith("assembleAndroidTest")) {
+            buildServerAnchorTask.dependsOn task
+        }
+        if (task.name.startsWith("assembleDebug")) {
+            buildServerAnchorTask.dependsOn task
+        }
+    }
+
+    if (enablePublicRepos) {
+        project.afterEvaluate {
+            apply plugin: 'com.android.databinding.localizemaven'
+            project.localizeMaven {
+                localRepoDir = file("$prebuiltsRoot/tools/common/m2/repository")
+                otherRepoDirs = repoNames
+                licenseInformation = [
+                        [
+                                libraries: ["org.jetbrains:annotations",
+                                            "org.jetbrains.kotlin:kotlin-compiler-runner"],
+                                licenses : ["http://www.apache.org/licenses/LICENSE-2.0.txt"]
+                        ],
+                        [
+                                libraries: ["com.google.code.gson:gson"],
+                                licenses : ["http://www.apache.org/licenses/LICENSE-2.0.txt"]
+                        ]
+
+                ]
+            }
+        }
+    }
+}
+
+def createKotlinCheckstyle(Project project) {
+    def fs = files();
+    if (project.sourceSets.hasProperty('main')) {
+        fs += files(project.sourceSets.main.allJava.srcDirs.collect { fileTree(it) })
+    }
+    if (project.sourceSets.hasProperty('test')) {
+        fs += files(project.sourceSets.test.allJava.srcDirs.collect { fileTree(it) })
+    }
+    if (project.hasProperty('android')) {
+        fs += files(project.android.sourceSets.main.java.getSrcDirs().collect {fileTree(it)})
+        fs += files(project.android.sourceSets.test.java.getSrcDirs().collect {fileTree(it)})
+        fs += files(project.android.sourceSets.androidTest.java.getSrcDirs().collect {fileTree(it)})
+    }
+    fs = fs.filter{file -> file.name.endsWith(".kt")}
+    def kotlinCheckstyle = createCheckstyleTask(project, 'checkstyleKotlin',
+            "${project.rootProject.ext.supportRootFolder}/app-toolkit/kotlin-checkstyle.xml",
+            fs.files)
+
+    project.tasks.findByName("check").dependsOn(kotlinCheckstyle)
+    // poor man's line length check
+    def lineCheck = project.tasks.create(name : "lineLengthCheck") {
+        fs.each { sourceDir ->
+                  fileTree(dir : sourceDir, include : "**/*.kt").each{ file ->
+                      file.readLines().eachWithIndex { line, index ->
+                          if (line.size() > 100) {
+                              project.logger.error("line too long: file: $file" +
+                                      " index:$index line: $line")
+                          }
+                      }
+                  }
+        }
+    }
+    kotlinCheckstyle.dependsOn(lineCheck)
+}
+
+def createAndroidCheckstyle(Project project) {
+    def fs = files()
+    if (project.hasProperty('android')) {
+        fs += files(project.android.sourceSets.main.java.getSrcDirs().collect {fileTree(it)})
+    }
+    if (project.sourceSets.hasProperty('main')) {
+        fs += files(project.sourceSets.main.allJava)
+    }
+    fs = fs.filter{file -> file.name.endsWith(".java")}
+
+    def checkStyle = createCheckstyleTask(project, 'checkstyleAndroid',
+            "${project.rootProject.ext.checkoutRoot}/prebuilts/checkstyle/android-style.xml",
+            fs.files)
+    project.tasks.findByName("check").dependsOn(checkStyle)
+}
+
+def createCheckstyleTask(project, taskName, configFile, inputFiles) {
+    def arguments = ['-c', configFile]
+    arguments.addAll(inputFiles)
+    def checkStyle = project.tasks.create(name : taskName, type: JavaExec) {
+        inputs.files(inputFiles).skipWhenEmpty()
+        main = "com.puppycrawl.tools.checkstyle.Main"
+        args = arguments
+        classpath = files(file("${project.rootProject.ext.checkoutRoot}/prebuilts/checkstyle/checkstyle.jar").path)
+    }
+    return checkStyle;
+}
+
+ext.createKotlinCheckstyle = this.&createKotlinCheckstyle
+ext.createAndroidCheckstyle = this.&createAndroidCheckstyle
diff --git a/app-toolkit/kotlin-checkstyle.xml b/app-toolkit/kotlin-checkstyle.xml
new file mode 100644
index 0000000..5cdad0a
--- /dev/null
+++ b/app-toolkit/kotlin-checkstyle.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
+    "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
+<!-- this is a very limited set of checkstyle rules mainly because TreeWalker rules are not
+supported for kt files yet.-->
+<module name="Checker">
+    <property name="severity" value="warning"/>
+    <property name="charset" value="UTF-8"/>
+    <module name="SuppressionCommentFilter">
+        <property name="offCommentFormat" value="CHECKSTYLE:OFF IndentationCheck"/>
+        <property name="onCommentFormat" value="CHECKSTYLE:ON IndentationCheck"/>
+        <property name="checkFormat" value="IndentationCheck"/>
+    </module>
+    <module name="SuppressionCommentFilter">
+        <property name="offCommentFormat" value="CHECKSTYLE:OFF Generated code"/>
+        <property name="onCommentFormat" value="CHECKSTYLE:ON Generated code"/>
+    </module>
+    <module name="FileTabCharacter">
+        <property name="severity" value="error"/>
+    </module>
+    <module name="NewlineAtEndOfFile">
+        <property name="severity" value="error"/>
+    </module>
+    <module name="RegexpSingleline">
+        <property name="severity" value="error"/>
+        <property name="format" value="[ \t]+$"/>
+        <property name="message" value="Trailing whitespace"/>
+    </module>
+    <module name="RegexpHeader">
+        <property name="severity" value="error"/>
+        <message key="header.mismatch"
+                 value="Android Copyright header seems to be incorrect. Expected ''{0}'' on this line."/>
+        <property name="header" value="^/\*\n \* Copyright \([Cc]\) [0-9]{4} The Android Open Source Project\n \*\n \* Licensed under the Apache License, Version 2\.0 \(the \&quot;License\&quot;\);\n \* you may not use this file except in compliance with the License.\n \* You may obtain a copy of the License at\n \*\n \*      http:\/\/www\.apache\.org\/licenses\/LICENSE-2\.0\n \*\n \* Unless required by applicable law or agreed to in writing, software\n \* distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n \* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied\.\n \* See the License for the specific language governing permissions and\n \* limitations under the License\.\n \*\/" />
+    </module>
+</module>
diff --git a/app-toolkit/localize.sh b/app-toolkit/localize.sh
new file mode 100755
index 0000000..3b7cb99
--- /dev/null
+++ b/app-toolkit/localize.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+ALLOW_PUBLIC_REPOS=true ./gradlew localizeDependencies :room:compiler:buildLicenseNotice :lifecycle:compiler:buildLicenseNotice
\ No newline at end of file
diff --git a/app-toolkit/runtime/build.gradle b/app-toolkit/runtime/build.gradle
new file mode 100644
index 0000000..5e2fe46
--- /dev/null
+++ b/app-toolkit/runtime/build.gradle
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile libs.support.annotations
+    compile project(":arch:common")
+    testCompile libs.junit
+    testCompile libs.mockito_core
+    testCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+}
+
+archivesBaseName = "runtime"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    def jarTask = project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/app-toolkit/runtime/src/main/AndroidManifest.xml b/app-toolkit/runtime/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..3f40068
--- /dev/null
+++ b/app-toolkit/runtime/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.core">
+</manifest>
diff --git a/app-toolkit/runtime/src/main/java/android/arch/core/executor/AppToolkitTaskExecutor.java b/app-toolkit/runtime/src/main/java/android/arch/core/executor/AppToolkitTaskExecutor.java
new file mode 100644
index 0000000..7337f74
--- /dev/null
+++ b/app-toolkit/runtime/src/main/java/android/arch/core/executor/AppToolkitTaskExecutor.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.concurrent.Executor;
+
+/**
+ * A static class that serves as a central point to execute common tasks.
+ * <p>
+ *
+ * @hide This API is not final.
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class AppToolkitTaskExecutor extends TaskExecutor {
+    private static volatile AppToolkitTaskExecutor sInstance;
+
+    @NonNull
+    private TaskExecutor mDelegate;
+
+    @NonNull
+    private TaskExecutor mDefaultTaskExecutor;
+
+    @NonNull
+    private static final Executor sMainThreadExecutor = new Executor() {
+        @Override
+        public void execute(Runnable command) {
+            getInstance().postToMainThread(command);
+        }
+    };
+
+    @NonNull
+    private static final Executor sIOThreadExecutor = new Executor() {
+        @Override
+        public void execute(Runnable command) {
+            getInstance().executeOnDiskIO(command);
+        }
+    };
+
+    private AppToolkitTaskExecutor() {
+        mDefaultTaskExecutor = new DefaultTaskExecutor();
+        mDelegate = mDefaultTaskExecutor;
+    }
+
+    /**
+     * Returns an instance of the task executor.
+     *
+     * @return The singleton AppToolkitTaskExecutor.
+     */
+    public static AppToolkitTaskExecutor getInstance() {
+        if (sInstance != null) {
+            return sInstance;
+        }
+        synchronized (AppToolkitTaskExecutor.class) {
+            if (sInstance == null) {
+                sInstance = new AppToolkitTaskExecutor();
+            }
+        }
+        return sInstance;
+    }
+
+    /**
+     * Sets a delegate to handle task execution requests.
+     * <p>
+     * If you have a common executor, you can set it as the delegate and App Toolkit components will
+     * use your executors. You may also want to use this for your tests.
+     * <p>
+     * Calling this method with {@code null} sets it to the default TaskExecutor.
+     *
+     * @param taskExecutor The task executor to handle task requests.
+     */
+    public void setDelegate(@Nullable TaskExecutor taskExecutor) {
+        mDelegate = taskExecutor == null ? mDefaultTaskExecutor : taskExecutor;
+    }
+
+    @Override
+    public void executeOnDiskIO(Runnable runnable) {
+        mDelegate.executeOnDiskIO(runnable);
+    }
+
+    @Override
+    public void postToMainThread(Runnable runnable) {
+        mDelegate.postToMainThread(runnable);
+    }
+
+    @NonNull
+    public static Executor getMainThreadExecutor() {
+        return sMainThreadExecutor;
+    }
+
+    @NonNull
+    public static Executor getIOThreadExecutor() {
+        return sIOThreadExecutor;
+    }
+
+    @Override
+    public boolean isMainThread() {
+        return mDelegate.isMainThread();
+    }
+}
diff --git a/app-toolkit/runtime/src/main/java/android/arch/core/executor/DefaultTaskExecutor.java b/app-toolkit/runtime/src/main/java/android/arch/core/executor/DefaultTaskExecutor.java
new file mode 100644
index 0000000..dbb1054
--- /dev/null
+++ b/app-toolkit/runtime/src/main/java/android/arch/core/executor/DefaultTaskExecutor.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class DefaultTaskExecutor extends TaskExecutor {
+    private final Object mLock = new Object();
+    private ExecutorService mDiskIO = Executors.newFixedThreadPool(2);
+
+    @Nullable
+    private volatile Handler mMainHandler;
+
+    @Override
+    public void executeOnDiskIO(Runnable runnable) {
+        mDiskIO.execute(runnable);
+    }
+
+    @Override
+    public void postToMainThread(Runnable runnable) {
+        if (mMainHandler == null) {
+            synchronized (mLock) {
+                if (mMainHandler == null) {
+                    mMainHandler = new Handler(Looper.getMainLooper());
+                }
+            }
+        }
+        //noinspection ConstantConditions
+        mMainHandler.post(runnable);
+    }
+
+    @Override
+    public boolean isMainThread() {
+        return Looper.getMainLooper().getThread() == Thread.currentThread();
+    }
+}
diff --git a/app-toolkit/runtime/src/main/java/android/arch/core/executor/TaskExecutor.java b/app-toolkit/runtime/src/main/java/android/arch/core/executor/TaskExecutor.java
new file mode 100644
index 0000000..055b476
--- /dev/null
+++ b/app-toolkit/runtime/src/main/java/android/arch/core/executor/TaskExecutor.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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 android.arch.core.executor;
+
+import android.support.annotation.RestrictTo;
+
+/**
+ * A task executor that can divide tasks into logical groups.
+ * <p>
+ * It holds a collection a executors for each group of task.
+ * <p>
+ * TODO: Don't use this from outside, we don't know what the API will look like yet.
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class TaskExecutor {
+    /**
+     * Executes the given task in the disk IO thread pool.
+     *
+     * @param runnable The runnable to run in the disk IO thread pool.
+     */
+    public abstract void executeOnDiskIO(Runnable runnable);
+
+    /**
+     * Posts the given task to the main thread.
+     *
+     * @param runnable The runnable to run on the main thread.
+     */
+    public abstract void postToMainThread(Runnable runnable);
+
+    /**
+     * Executes the given task on the main thread.
+     * <p>
+     * If the current thread is a main thread, immediately runs the given runnable.
+     *
+     * @param runnable The runnable to run on the main thread.
+     */
+    public void executeOnMainThread(Runnable runnable) {
+        if (isMainThread()) {
+            runnable.run();
+        } else {
+            postToMainThread(runnable);
+        }
+    }
+
+    /**
+     * Returns true if the current thread is the main thread, false otherwise.
+     *
+     * @return true if we are on the main thread, false otherwise.
+     */
+    public abstract boolean isMainThread();
+}
diff --git a/app-toolkit/settings.gradle b/app-toolkit/settings.gradle
new file mode 100644
index 0000000..0977dc6
--- /dev/null
+++ b/app-toolkit/settings.gradle
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+// If you change this file, you should also change the settings gradle inside
+// the sub project.
+
+def inAppToolkitProject = rootProject.name == "app-toolkit"
+def supportRoot
+if (inAppToolkitProject) {
+    supportRoot = new File(rootProject.projectDir, "..").getCanonicalFile()
+} else {
+    supportRoot = rootProject.projectDir
+}
+
+println "support root:${supportRoot}"
+
+include ':arch:runtime'
+project(':arch:runtime').projectDir = new File(supportRoot, "app-toolkit/runtime")
+
+include ':arch:common'
+project(':arch:common').projectDir = new File(supportRoot, "app-toolkit/common")
+
+include ':paging:common'
+project(':paging:common').projectDir = new File(supportRoot, "paging/common")
+
+include ":paging:runtime"
+project(':paging:runtime').projectDir = new File(supportRoot, "paging/runtime")
+
+include ':paging:integration-tests:testapp'
+project(':paging:integration-tests:testapp').projectDir = new File(supportRoot, "paging/integration-tests/testapp")
+
+include ':arch:core-testing'
+project(':arch:core-testing').projectDir = new File(supportRoot, "app-toolkit/core-testing")
+
+include ':lifecycle:extensions'
+project(':lifecycle:extensions').projectDir = new File(supportRoot, "lifecycle/extensions")
+
+include ':lifecycle:reactivestreams'
+project(':lifecycle:reactivestreams').projectDir = new File(supportRoot, "lifecycle/reactivestreams")
+
+include ':lifecycle:runtime'
+project(':lifecycle:runtime').projectDir = new File(supportRoot, "lifecycle/runtime")
+
+include ':lifecycle:common'
+project(':lifecycle:common').projectDir = new File(supportRoot, "lifecycle/common")
+
+include ':lifecycle:compiler'
+project(':lifecycle:compiler').projectDir = new File(supportRoot, "lifecycle/compiler")
+
+include ':lifecycle:integration-tests:testapp'
+project(':lifecycle:integration-tests:testapp').projectDir = new File(supportRoot, "lifecycle/integration-tests/testapp")
+
+include ':room:common'
+project(':room:common').projectDir = new File(supportRoot, "room/common")
+
+include ':room:runtime'
+project(':room:runtime').projectDir = new File(supportRoot, "room/runtime")
+
+include ':room:compiler'
+project(':room:compiler').projectDir = new File(supportRoot, "room/compiler")
+
+include ':room:migration'
+project(':room:migration').projectDir = new File(supportRoot, "room/migration")
+
+include ':room:db'
+project(':room:db').projectDir = new File(supportRoot, "room/db")
+
+include ":room:db-impl"
+project(':room:db-impl').projectDir = new File(supportRoot, "room/db-impl")
+
+include ":room:testing"
+project(':room:testing').projectDir = new File(supportRoot, "room/testing")
+
+include ":room:rxjava2"
+project(':room:rxjava2').projectDir = new File(supportRoot, "room/rxjava2")
+
+include ':room:integration-tests:testapp'
+project(':room:integration-tests:testapp').projectDir = new File(supportRoot, "room/integration-tests/testapp")
+
+include ':room:integration-tests:kotlintestapp'
+project(':room:integration-tests:kotlintestapp').projectDir = new File(supportRoot, "room/integration-tests/kotlintestapp")
+
+/////////////////////////////
+//
+// SupportLib
+//
+/////////////////////////////
+if (inAppToolkitProject && System.getenv("USE_SUPPORT_LIB_SOURCE")) {
+    apply from: "${supportRoot.absolutePath}/app-toolkit/settings_support_lib.gradle"
+}
+
+/////////////////////////////
+//
+// External
+//
+/////////////////////////////
+if (inAppToolkitProject) {
+    File externalRoot = new File(supportRoot, '../../external')
+
+    include ':doclava'
+    project(':doclava').projectDir = new File(externalRoot, 'doclava')
+
+    include ':jdiff'
+    project(':jdiff').projectDir = new File(externalRoot, 'jdiff')
+}
diff --git a/app-toolkit/settings_support_lib.gradle b/app-toolkit/settings_support_lib.gradle
new file mode 100644
index 0000000..c6f56f1
--- /dev/null
+++ b/app-toolkit/settings_support_lib.gradle
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// settings file to include support lib sources.
+def supportRootDir = new File("../.")
+
+include ':support-core-utils'
+project(':support-core-utils').projectDir = new File(supportRootDir, 'core-utils')
+
+include ':support-fragment'
+project(':support-fragment').projectDir = new File(supportRootDir, 'fragment')
+
+include ':support-compat'
+project(':support-compat').projectDir = new File(supportRootDir, 'compat')
+
+include ':support-annotations'
+project(':support-annotations').projectDir = new File(supportRootDir, 'annotations')
+
+include ':support-core-ui'
+project(':support-core-ui').projectDir = new File(supportRootDir, 'core-ui')
+
+include ':support-appcompat-v7'
+project(':support-appcompat-v7').projectDir = new File(rootDir, 'v7/appcompat')
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index 5bd5d13..360ec02 100644
--- a/build.gradle
+++ b/build.gradle
@@ -35,6 +35,8 @@
 
 init.configureSubProjects()
 
+init.configureBuildOnServer()
+
 init.setupRelease()
 
 init.enableDoclavaAndJDiff(this)
diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle
index bd5e6a6..d63de24 100644
--- a/buildSrc/build.gradle
+++ b/buildSrc/build.gradle
@@ -1,4 +1,5 @@
 apply plugin: 'groovy'
+apply plugin: 'java'
 
 apply from: "dependencies.gradle"
 
diff --git a/buildSrc/dependencies.gradle b/buildSrc/dependencies.gradle
index 91315c1..8a7d69a 100644
--- a/buildSrc/dependencies.gradle
+++ b/buildSrc/dependencies.gradle
@@ -17,14 +17,14 @@
 def libs = [:]
 
 // Testing dependencies
-libs.mockito_core = 'org.mockito:mockito-core:1.9.5'
-libs.dexmaker = 'com.google.dexmaker:dexmaker:1.2'
-libs.dexmaker_mockito = 'com.google.dexmaker:dexmaker-mockito:1.2'
+libs.mockito_core = 'org.mockito:mockito-core:2.7.6'
+libs.dexmaker_mockito = 'com.linkedin.dexmaker:dexmaker-mockito:2.2.0'
 libs.junit = 'junit:junit:4.12'
 libs.test_runner = 'com.android.support.test:runner:0.6-alpha'
 libs.espresso_core = 'com.android.support.test.espresso:espresso-core:2.3-alpha'
 libs.espresso_contrib = 'com.android.support.test.espresso:espresso-contrib:2.3-alpha'
 libs.jacoco = 'org.jacoco:org.jacoco.core:0.7.8'
+libs.test_rules = 'com.android.support.test:rules:0.6-alpha'
 
 def androidPluginVersionOverride = System.getenv("GRADLE_PLUGIN_VERSION")
 
@@ -32,7 +32,7 @@
     libs.gradle = 'com.android.tools.build:gradle:' + androidPluginVersionOverride
 } else {
     // Keep gradle plugin version in sync with ub_supportlib-master manifest.
-    libs.gradle = 'com.android.tools.build:gradle:2.4.0-alpha6'
+    libs.gradle = 'com.android.tools.build:gradle:3.0.0-alpha7'
 }
 
 // Other dependencies
diff --git a/buildSrc/diff_and_docs.gradle b/buildSrc/diff_and_docs.gradle
index 47fcefc..1f012d1 100644
--- a/buildSrc/diff_and_docs.gradle
+++ b/buildSrc/diff_and_docs.gradle
@@ -254,8 +254,8 @@
 
     if (!previous) {
         // If this is a patch or release version, ignore the extra.
-        return new File(apiDir, "$refMajor.$refMinor.0" +
-                (refPatch || release ? "" : refExtra) + ".txt")
+        return new File(apiDir, "$refMajor.$refMinor.0"
+                + (!refExtra || refPatch || release ? "" : refExtra) + ".txt")
     }
 
     File lastFile = null
@@ -271,8 +271,8 @@
         if (lastFile == null || major > lastMajor || (major == lastMajor && minor > lastMinor)) {
             if (refMajor > major || (refMajor == major && refMinor > minor)) {
                 lastFile = file
-                lastMajor = major;
-                lastMinor = minor;
+                lastMajor = major
+                lastMinor = minor
             }
         }
     }
@@ -440,7 +440,8 @@
                 fileTree(releaseVariant.aidlCompile.sourceOutputDir) +
                 fileTree(releaseVariant.outputs[0].processResources.sourceOutputDir)
     }
-    task.classpath += files{releaseVariant.javaCompile.classpath.files} +
+
+    task.classpath += releaseVariant.getCompileClasspath(null) +
             files(releaseVariant.javaCompile.destinationDir)
 }
 
diff --git a/buildSrc/init.gradle b/buildSrc/init.gradle
index 5c61cc2..a483337 100644
--- a/buildSrc/init.gradle
+++ b/buildSrc/init.gradle
@@ -17,9 +17,6 @@
 import com.android.build.gradle.internal.coverage.JacocoPlugin
 import com.android.build.gradle.internal.coverage.JacocoReportTask
 import com.android.build.gradle.internal.tasks.DeviceProviderInstrumentTestTask
-import com.google.common.base.Charsets
-import com.google.common.io.Files
-
 import org.gradle.api.logging.configuration.ShowStacktrace
 
 def supportRoot = ext.supportRootFolder
@@ -60,14 +57,17 @@
     apply from: "${ext.supportRootFolder}/buildSrc/diff_and_docs.gradle"
 }
 
-def setSdkInLocalPropertiesFile() {
+def getFullSdkPath() {
     final String osName = System.getProperty("os.name").toLowerCase();
     final boolean isMacOsX =
             osName.contains("mac os x") || osName.contains("darwin") || osName.contains("osx");
     final String platform = isMacOsX ? 'darwin' : 'linux'
-    System.setProperty('android.dir', "${supportRootFolder}/../../")
+    return "${repos.prebuiltsRoot}/fullsdk-${platform}"
+}
+
+def setSdkInLocalPropertiesFile() {
     ext.buildToolsVersion = '26.0.0'
-    final String fullSdkPath = "${repos.prebuiltsRoot}/fullsdk-${platform}"
+    final String fullSdkPath = getFullSdkPath();
     if (file(fullSdkPath).exists()) {
         gradle.ext.currentSdk = 26
         project.ext.androidJar =
@@ -75,7 +75,6 @@
         project.ext.androidSrcJar =
                 file("${fullSdkPath}/platforms/android-${gradle.currentSdk}/android-stubs-src.jar")
         project.ext.androidApiTxt = null
-        System.setProperty('android.home', "${repos.prebuiltsRoot}/fullsdk-${platform}")
         File props = file("local.properties")
         props.write "sdk.dir=${fullSdkPath}"
         ext.usingFullSdk = true
@@ -84,6 +83,7 @@
         project.ext.androidJar = files("${repos.prebuiltsRoot}/sdk/current/android.jar")
         project.ext.androidSrcJar = null
         project.ext.androidApiTxt = file("${repos.prebuiltsRoot}/sdk/api/26.txt")
+        System.setProperty('android.dir', "${supportRootFolder}/../../")
         File props = file("local.properties")
         props.write "android.dir=../../"
         ext.usingFullSdk = false
@@ -126,6 +126,23 @@
     ext.docsDir = new File(buildDir, 'javadoc')
 }
 
+def configureBuildOnServer() {
+    def buildOnServerTask = rootProject.tasks.create("buildOnServer")
+    rootProject.tasks.whenTaskAdded { task ->
+        if ("createArchive".equals(task.name)) {
+            buildOnServerTask.dependsOn task
+        }
+    }
+
+    subprojects {
+        project.tasks.whenTaskAdded { task ->
+            if ("assembleErrorProne".equals(task.name) || "assembleAndroidTest".equals(task.name)) {
+                buildOnServerTask.dependsOn task
+            }
+        }
+    }
+}
+
 def configureSubProjects() {
     // lint every library
     def lintTask = project.tasks.create("lint")
@@ -184,31 +201,30 @@
                             destinationDir file(project.distDir)
                             archiveName "${project.archivesBaseName}-${v.baseName}-allclasses.jar"
                         }
-                        def jacocoAntConfig =
-                                project.configurations[JacocoPlugin.ANT_CONFIGURATION_NAME]
-                        def jacocoAntArtifacts = jacocoAntConfig.resolvedConfiguration
-                                .resolvedArtifacts
-                        def version = jacocoAntArtifacts.find { "org.jacoco.ant".equals(it.name) }
-                                .moduleVersion.id.version
+
                         def collectJacocoAntPackages = project.tasks.create(
                                 name: "collectJacocoAntPackages",
                                 type: Jar) {
-                            from(jacocoAntArtifacts.collect { zipTree(it.getFile()) }) {
-                                // exclude all the signatures the jar might have
-                                exclude "META-INF/*.SF"
-                                exclude "META-INF/*.DSA"
-                                exclude "META-INF/*.RSA"
-                            }
+                            inputs.files project.configurations[JacocoPlugin.ANT_CONFIGURATION_NAME]
+                            from {
+                                project.configurations[JacocoPlugin.ANT_CONFIGURATION_NAME]
+                                        .resolvedConfiguration
+                                        .resolvedArtifacts.collect{ zipTree(it.getFile()) }} {
+                                    // exclude all the signatures the jar might have
+                                    exclude "META-INF/*.SF"
+                                    exclude "META-INF/*.DSA"
+                                    exclude "META-INF/*.RSA"
+                                }
                             destinationDir file(project.distDir)
-                            archiveName "jacocoant-" + version + ".jar"
+                            archiveName "jacocoant.jar"
                         }
+
                         jarifyTask.dependsOn v.getJavaCompiler()
-                        v.assemble.dependsOn jarifyTask, collectJacocoAntPackages
+                        v.assemble.dependsOn jarifyTask , collectJacocoAntPackages
                     }
                 }
 
                 // Enforce NewApi lint check as fatal.
-                project.android.lintOptions.check 'NewApi'
                 project.android.lintOptions.fatal 'NewApi'
                 lintTask.dependsOn project.lint
             }
@@ -239,13 +255,6 @@
                         }
                     }
 
-                    uploadTask.repositories.mavenDeployer.pom*.whenConfigured { pom ->
-                        pom.dependencies.findAll { dep ->
-                            dep.groupId == 'com.android.support' &&
-                                    dep.artifactId != 'support-annotations'
-                        }*.type = 'aar'
-                    }
-
                     // Before the upload, make sure the repo is ready.
                     uploadTask.dependsOn rootProject.tasks.prepareRepo
 
@@ -265,9 +274,10 @@
                 task.doLast {
                     def source = testApk ? project.android.sourceSets.androidTest
                             : project.android.sourceSets.main
-                    if (task.hasProperty("outputFile") && !source.java.sourceFiles.isEmpty()) {
+                    if (task.hasProperty("outputDirectory") && !source.java.sourceFiles.isEmpty()) {
                         copy {
-                            from(task.outputFile)
+                            from(task.outputDirectory)
+                            include '*.apk'
                             into(rootProject.ext.testApkDistOut)
                             rename { String fileName ->
                                 // multiple modules may have the same name so prefix the name with
@@ -343,4 +353,5 @@
 ext.init.setupRepoOutAndBuildNumber = this.&setupRepoOutAndBuildNumber
 ext.init.setupRelease = this.&setupRelease
 ext.init.loadDefaultVersions = this.&loadDefaultVersions
-ext.init.configureSubProjects = this.&configureSubProjects
\ No newline at end of file
+ext.init.configureSubProjects = this.&configureSubProjects
+ext.init.configureBuildOnServer = this.&configureBuildOnServer
diff --git a/buildSrc/repos.gradle b/buildSrc/repos.gradle
index 6ee60e1..caedf3a 100644
--- a/buildSrc/repos.gradle
+++ b/buildSrc/repos.gradle
@@ -44,6 +44,7 @@
     if (System.getenv("ALLOW_PUBLIC_REPOS") != null) {
         handler.mavenCentral()
         handler.jcenter()
+        handler.google()
     }
     def androidPluginRepoOverride = System.getenv("GRADLE_PLUGIN_REPO")
     if (androidPluginRepoOverride != null) {
diff --git a/buildSrc/src/main/groovy/android/support/SupportLibraryPlugin.groovy b/buildSrc/src/main/groovy/android/support/SupportLibraryPlugin.groovy
index f598e82..1d07f51 100644
--- a/buildSrc/src/main/groovy/android/support/SupportLibraryPlugin.groovy
+++ b/buildSrc/src/main/groovy/android/support/SupportLibraryPlugin.groovy
@@ -52,7 +52,8 @@
 
         library.defaultConfig {
             // Update the version meta-data in each Manifest.
-            addManifestPlaceholders(["support-version": project.rootProject.supportVersion])
+            addManifestPlaceholders(["support-version": project.rootProject.supportVersion,
+                                     "target-sdk-version": project.currentSdk])
 
             // Set test related options.
             testInstrumentationRunner INSTRUMENTATION_RUNNER
@@ -89,7 +90,7 @@
             textOutput 'stderr'
             textReport true
             htmlReport false
-            xmlReport false
+            //xmlReport false
 
             // Format output for convenience.
             explainIssues true
@@ -98,6 +99,12 @@
 
             // Always fail on NewApi.
             error 'NewApi'
+
+            // TODO(aurimas): figure out the issue with missing translation check
+            disable 'MissingTranslation', 'ExtraTranslation'
+
+            // Set baseline file for all legacy lint warnings.
+            baseline new File(project.projectDir, "/lint-baseline.xml")
         }
 
         // Java 8 is only fully supported on API 24+ and not all Java 8 features are binary
@@ -168,11 +175,11 @@
                     }
                 }
             });
-        }
 
-        if (project.rootProject.usingFullSdk) {
-            // Library projects don't run lint by default, so set up dependency.
-            uploadTask.dependsOn project.tasks.lint
+            if (project.rootProject.usingFullSdk) {
+                // Library projects don't run lint by default, so set up dependency.
+                uploadTask.dependsOn project.getTasks().getByName("lintRelease")
+            }
         }
 
         final ErrorProneToolChain toolChain = ErrorProneToolChain.create(project);
@@ -188,7 +195,10 @@
 
                             // Enforce the following checks.
                             '-Xep:MissingOverride:ERROR',
+                            '-Xep:NarrowingCompoundAssignment:ERROR',
                             '-Xep:ClassNewInstance:ERROR',
+                            '-Xep:ClassCanBeStatic:ERROR',
+                            '-Xep:SynchronizeOnNonFinalField:ERROR'
                     ]
                 }
             }
diff --git a/buildSrc/src/main/groovy/android/support/checkapi/ApiXmlConversionTask.groovy b/buildSrc/src/main/groovy/android/support/checkapi/ApiXmlConversionTask.groovy
index 61e84d4..bd4bda7 100644
--- a/buildSrc/src/main/groovy/android/support/checkapi/ApiXmlConversionTask.groovy
+++ b/buildSrc/src/main/groovy/android/support/checkapi/ApiXmlConversionTask.groovy
@@ -16,12 +16,10 @@
 
 package android.support.checkapi
 
-import org.gradle.api.tasks.JavaExec
 import org.gradle.api.tasks.InputFile
-import org.gradle.api.tasks.ParallelizableTask
+import org.gradle.api.tasks.JavaExec
 import org.gradle.api.tasks.OutputFile
 
-@ParallelizableTask
 public class ApiXmlConversionTask extends JavaExec {
 
     @InputFile
diff --git a/buildSrc/src/main/groovy/android/support/checkapi/CheckApiTask.groovy b/buildSrc/src/main/groovy/android/support/checkapi/CheckApiTask.groovy
index 15b4594..2aa9d21 100644
--- a/buildSrc/src/main/groovy/android/support/checkapi/CheckApiTask.groovy
+++ b/buildSrc/src/main/groovy/android/support/checkapi/CheckApiTask.groovy
@@ -14,20 +14,18 @@
  * limitations under the License.
  */
 
-package android.support.checkapi;
+package android.support.checkapi
 
 import org.gradle.api.DefaultTask
-import org.gradle.api.Nullable
 import org.gradle.api.GradleException
 import org.gradle.api.InvalidUserDataException
+import org.gradle.api.Nullable
 import org.gradle.api.tasks.Input
 import org.gradle.api.tasks.InputFile
 import org.gradle.api.tasks.InputFiles
-import org.gradle.api.tasks.ParallelizableTask
 import org.gradle.api.tasks.TaskAction
 import org.gradle.api.tasks.Optional
 import org.gradle.api.tasks.OutputFile
-import org.gradle.process.ExecResult
 
 import java.security.MessageDigest
 
@@ -41,7 +39,6 @@
  * Specific failures may be ignored by specifying a list of SHAs in {@link #whitelistErrors}. Each
  * SHA is unique to a specific API change and is logged to the error output on failure.
  */
-@ParallelizableTask
 public class CheckApiTask extends DefaultTask {
     /** Character that resets console output color. */
     private static final String ANSI_RESET = "\u001B[0m";
diff --git a/buildSrc/src/main/groovy/android/support/doclava/DoclavaTask.groovy b/buildSrc/src/main/groovy/android/support/doclava/DoclavaTask.groovy
index ff5c968..b82ccc8 100644
--- a/buildSrc/src/main/groovy/android/support/doclava/DoclavaTask.groovy
+++ b/buildSrc/src/main/groovy/android/support/doclava/DoclavaTask.groovy
@@ -24,9 +24,7 @@
 import org.gradle.api.tasks.Optional
 import org.gradle.api.tasks.OutputDirectory
 import org.gradle.api.tasks.OutputFile
-import org.gradle.api.tasks.ParallelizableTask
 
-@ParallelizableTask
 public class DoclavaTask extends Javadoc {
 
     // external/doclava/src/com/google/doclava/Errors.java
diff --git a/buildSrc/src/main/groovy/android/support/jdiff/JDiffTask.groovy b/buildSrc/src/main/groovy/android/support/jdiff/JDiffTask.groovy
deleted file mode 100644
index 7bb9435..0000000
--- a/buildSrc/src/main/groovy/android/support/jdiff/JDiffTask.groovy
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.jdiff;
-
-import org.gradle.api.tasks.Input
-import org.gradle.api.tasks.InputFile
-import org.gradle.api.tasks.InputFiles
-import org.gradle.api.tasks.javadoc.Javadoc
-import org.gradle.api.tasks.Optional
-import org.gradle.api.tasks.ParallelizableTask
-
-@ParallelizableTask
-public class JDiffTask extends Javadoc {
-
-    @InputFiles
-    Collection<File> docletpath
-
-    @InputFile
-    File oldApiXmlFile
-
-    @InputFile
-    File newApiXmlFile
-
-    /**
-     * Relative path to the Javadoc corresponding to the old API, relative to
-     * "${destinationDir}/changes". Should end with the directory separator (usually '/').
-     */
-    @Input
-    @Optional
-    String oldJavadocPrefix
-
-    /**
-     * Relative path to the Javadoc corresponding to the new API, relative to
-     * "${destinationDir}/changes". Should end with the directory separator (usually '/').
-     */
-    @Input
-    String newJavadocPrefix
-
-    // HTML diff files will be placed in destinationDir, which is defined by the superclass.
-
-    @Input
-    boolean stats = true
-
-    public JDiffTask() {
-        failOnError = true
-        options.doclet = "jdiff.JDiff"
-        options.encoding("UTF-8")
-        maxMemory = "1280m"
-    }
-
-    /**
-     * Sets the doclet path which has the {@code com.gogole.doclava.Doclava} class.
-     * <p>
-     * This option will override any doclet path set in this instance's
-     * {@link #getOptions() JavadocOptions}.
-     *
-     * @see MinimalJavadocOptions#setDocletpath(java.util.List)
-     */
-    public void setDocletpath(Collection<File> docletpath) {
-        this.docletpath = docletpath
-
-        // Go ahead and keep the docletpath in our JavadocOptions object in sync.
-        options.docletpath = docletpath as List
-    }
-
-    /**
-     * "Configures" this JDiffTask with parameters that might not be at their final values
-     * until this task is run.
-     */
-    private void configureJDiffTask() {
-        options.docletpath = getDocletpath() as List
-
-        if (getStats()) {
-            options.addStringOption('stats')
-        }
-
-        File oldApiXmlFile = getOldApiXmlFile()
-        File newApiXmlFile = getNewApiXmlFile()
-
-        File oldApiXmlFileDir = oldApiXmlFile.parentFile
-        File newApiXmlFileDir = newApiXmlFile.parentFile
-
-        if (oldApiXmlFileDir) {
-            options.addStringOption('oldapidir', oldApiXmlFileDir.absolutePath)
-        }
-        // For whatever reason, jdiff appends .xml to the file name on its own.
-        // Strip the .xml off the end of the file name
-        options.addStringOption('oldapi',
-                oldApiXmlFile.name.substring(0, oldApiXmlFile.name.length() - 4))
-        if (newApiXmlFileDir) {
-            options.addStringOption('newapidir', newApiXmlFileDir.absolutePath)
-        }
-        options.addStringOption('newapi',
-                newApiXmlFile.name.substring(0, newApiXmlFile.name.length() - 4))
-
-        String oldJavadocPrefix = getOldJavadocPrefix()
-        String newJavadocPrefix = getNewJavadocPrefix()
-
-        if (oldJavadocPrefix) {
-            options.addStringOption('javadocold', oldJavadocPrefix)
-        }
-        if (newJavadocPrefix) {
-            options.addStringOption('javadocnew', newJavadocPrefix)
-        }
-    }
-
-    @Override
-    public void generate() {
-        configureJDiffTask();
-        super.generate();
-    }
-}
diff --git a/buildSrc/src/main/java/android/support/jdiff/JDiffTask.java b/buildSrc/src/main/java/android/support/jdiff/JDiffTask.java
new file mode 100644
index 0000000..f89a375
--- /dev/null
+++ b/buildSrc/src/main/java/android/support/jdiff/JDiffTask.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2016 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 android.support.jdiff;
+
+import org.gradle.api.tasks.Input;
+import org.gradle.api.tasks.InputFile;
+import org.gradle.api.tasks.InputFiles;
+import org.gradle.api.tasks.Optional;
+import org.gradle.api.tasks.javadoc.Javadoc;
+import org.gradle.external.javadoc.CoreJavadocOptions;
+import org.gradle.external.javadoc.MinimalJavadocOptions;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * JDiff task to compare API changes.
+ */
+public class JDiffTask extends Javadoc {
+
+    private Collection<File> mDocletpath;
+
+    private File mOldApiXmlFile;
+
+    private File mNewApiXmlFile;
+
+    /**
+     * Relative path to the Javadoc corresponding to the old API, relative to
+     * "${destinationDir}/changes". Should end with the directory separator (usually '/').
+     */
+    private String mOldJavadocPrefix;
+
+    /**
+     * Relative path to the Javadoc corresponding to the new API, relative to
+     * "${destinationDir}/changes". Should end with the directory separator (usually '/').
+     */
+    private String mNewJavadocPrefix;
+
+    // HTML diff files will be placed in destinationDir, which is defined by the superclass.
+
+    private boolean mStats = true;
+
+    public JDiffTask() {
+        setFailOnError(true);
+        getOptions().setDoclet("jdiff.JDiff");
+        getOptions().setEncoding("UTF-8");
+        setMaxMemory("1280m");
+    }
+
+    public void setOldApiXmlFile(File file) {
+        mOldApiXmlFile = file;
+    }
+
+    @InputFile
+    public File getOldApiXmlFile() {
+        return mOldApiXmlFile;
+    }
+
+    public void setNewApiXmlFile(File file) {
+        mNewApiXmlFile = file;
+    }
+
+    @InputFile
+    public File getNewApiXmlFile() {
+        return mNewApiXmlFile;
+    }
+
+    @Optional
+    public void setOldJavadocPrefix(String prefix) {
+        mOldJavadocPrefix = prefix;
+    }
+
+    @Optional
+    @Input
+    public String getOldJavadocPrefix() {
+        return mOldJavadocPrefix;
+    }
+
+    public void setNewJavadocPrefix(String prefix) {
+        mNewJavadocPrefix = prefix;
+    }
+
+    @Input
+    public String getNewJavadocPrefix() {
+        return mNewJavadocPrefix;
+    }
+
+    public void setStats(boolean enabled) {
+        mStats = enabled;
+    }
+
+    @Input
+    public boolean getStats() {
+        return mStats;
+    }
+
+    /**
+     * Sets the doclet path which has the {@code com.gogole.doclava.Doclava} class.
+     * <p>
+     * This option will override any doclet path set in this instance's
+     * {@link #getOptions() JavadocOptions}.
+     *
+     * @see MinimalJavadocOptions#setDocletpath(java.util.List)
+     */
+    public void setDocletpath(Collection<File> docletpath) {
+        mDocletpath = docletpath;
+
+        // Go ahead and keep the mDocletpath in our JavadocOptions object in sync.
+        getOptions().setDocletpath(new ArrayList<>(docletpath));
+    }
+
+    @InputFiles
+    public Collection<File> getDocletpath() {
+        return mDocletpath;
+    }
+
+    /**
+     * "Configures" this JDiffTask with parameters that might not be at their final values
+     * until this task is run.
+     */
+    private void configureJDiffTask() {
+        CoreJavadocOptions options = (CoreJavadocOptions) getOptions();
+
+        options.setDocletpath(new ArrayList<>(mDocletpath));
+
+        if (getStats()) {
+            options.addStringOption("stats");
+        }
+
+        File oldApiXmlFile = getOldApiXmlFile();
+        File newApiXmlFile = getNewApiXmlFile();
+
+        File oldApiXmlFileDir = oldApiXmlFile.getParentFile();
+        File newApiXmlFileDir = newApiXmlFile.getParentFile();
+
+        if (oldApiXmlFileDir.exists()) {
+            options.addStringOption("oldapidir", oldApiXmlFileDir.getAbsolutePath());
+        }
+        // For whatever reason, jdiff appends .xml to the file name on its own.
+        // Strip the .xml off the end of the file name
+        options.addStringOption("oldapi",
+                oldApiXmlFile.getName().substring(0, oldApiXmlFile.getName().length() - 4));
+        if (newApiXmlFileDir.exists()) {
+            options.addStringOption("newapidir", newApiXmlFileDir.getAbsolutePath());
+        }
+        options.addStringOption("newapi",
+                newApiXmlFile.getName().substring(0, newApiXmlFile.getName().length() - 4));
+
+        String oldJavadocPrefix = getOldJavadocPrefix();
+        String newJavadocPrefix = getNewJavadocPrefix();
+
+        if (oldJavadocPrefix != null) {
+            options.addStringOption("javadocold", oldJavadocPrefix);
+        }
+        if (newJavadocPrefix != null) {
+            options.addStringOption("javadocnew", newJavadocPrefix);
+        }
+    }
+
+    @Override
+    public void generate() {
+        configureJDiffTask();
+        super.generate();
+    }
+}
diff --git a/buildSrc/versions.gradle b/buildSrc/versions.gradle
index 5814016..02a1e20 100644
--- a/buildSrc/versions.gradle
+++ b/buildSrc/versions.gradle
@@ -17,11 +17,7 @@
 ext['android.builder.sdkDownload'] = false
 
 // Version code of the support library components.
-ext.supportVersion = "26.0.0-SNAPSHOT"
+ext.supportVersion = "26.0.0"
 
 // This number gets incremented for each public release.
 ext.extraVersion = 46
-
-// Enforce the use of prebuilt dependencies in all sub-projects. This is
-// required for the doclava dependency.
-ext.usePrebuilts = "true"
diff --git a/compat/api21/android/support/v4/app/NotificationCompatApi21.java b/compat/api21/android/support/v4/app/NotificationCompatApi21.java
index 44237f3..d56d87e 100644
--- a/compat/api21/android/support/v4/app/NotificationCompatApi21.java
+++ b/compat/api21/android/support/v4/app/NotificationCompatApi21.java
@@ -36,22 +36,6 @@
 
 @RequiresApi(21)
 class NotificationCompatApi21 {
-
-    public static final String CATEGORY_CALL = Notification.CATEGORY_CALL;
-    public static final String CATEGORY_MESSAGE = Notification.CATEGORY_MESSAGE;
-    public static final String CATEGORY_EMAIL = Notification.CATEGORY_EMAIL;
-    public static final String CATEGORY_EVENT = Notification.CATEGORY_EVENT;
-    public static final String CATEGORY_PROMO = Notification.CATEGORY_PROMO;
-    public static final String CATEGORY_ALARM = Notification.CATEGORY_ALARM;
-    public static final String CATEGORY_PROGRESS = Notification.CATEGORY_PROGRESS;
-    public static final String CATEGORY_SOCIAL = Notification.CATEGORY_SOCIAL;
-    public static final String CATEGORY_ERROR = Notification.CATEGORY_ERROR;
-    public static final String CATEGORY_TRANSPORT = Notification.CATEGORY_TRANSPORT;
-    public static final String CATEGORY_SYSTEM = Notification.CATEGORY_SYSTEM;
-    public static final String CATEGORY_SERVICE = Notification.CATEGORY_SERVICE;
-    public static final String CATEGORY_RECOMMENDATION = Notification.CATEGORY_RECOMMENDATION;
-    public static final String CATEGORY_STATUS = Notification.CATEGORY_STATUS;
-
     private static final String KEY_AUTHOR = "author";
     private static final String KEY_TEXT = "text";
     private static final String KEY_MESSAGES = "messages";
diff --git a/compat/api21/android/support/v4/graphics/drawable/DrawableWrapperApi21.java b/compat/api21/android/support/v4/graphics/drawable/DrawableWrapperApi21.java
index 6c7f74b..5195cc9 100644
--- a/compat/api21/android/support/v4/graphics/drawable/DrawableWrapperApi21.java
+++ b/compat/api21/android/support/v4/graphics/drawable/DrawableWrapperApi21.java
@@ -16,6 +16,8 @@
 
 package android.support.v4.graphics.drawable;
 
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
 import android.content.res.ColorStateList;
 import android.content.res.Resources;
 import android.graphics.Outline;
@@ -25,20 +27,29 @@
 import android.graphics.drawable.DrawableContainer;
 import android.graphics.drawable.GradientDrawable;
 import android.graphics.drawable.InsetDrawable;
+import android.graphics.drawable.RippleDrawable;
 import android.os.Build;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
+import android.util.Log;
+
+import java.lang.reflect.Method;
 
 @RequiresApi(21)
 class DrawableWrapperApi21 extends DrawableWrapperApi19 {
+    private static final String TAG = "DrawableWrapperApi21";
+    private static Method sIsProjectedDrawableMethod;
 
     DrawableWrapperApi21(Drawable drawable) {
         super(drawable);
+        findAndCacheIsProjectedDrawableMethod();
     }
 
     DrawableWrapperApi21(DrawableWrapperState state, Resources resources) {
         super(state, resources);
+        findAndCacheIsProjectedDrawableMethod();
     }
 
     @Override
@@ -103,12 +114,30 @@
     protected boolean isCompatTintEnabled() {
         if (Build.VERSION.SDK_INT == 21) {
             final Drawable drawable = mDrawable;
-            return drawable instanceof GradientDrawable || drawable instanceof DrawableContainer
-                    || drawable instanceof InsetDrawable;
+            return drawable instanceof GradientDrawable
+                    || drawable instanceof DrawableContainer
+                    || drawable instanceof InsetDrawable
+                    || drawable instanceof RippleDrawable;
         }
         return false;
     }
 
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    public boolean isProjected() {
+        if (mDrawable != null && sIsProjectedDrawableMethod != null) {
+            try {
+                return (Boolean) sIsProjectedDrawableMethod.invoke(mDrawable);
+            } catch (Exception ex) {
+                Log.w(TAG, "Error calling Drawable#isProjected() method", ex);
+            }
+        }
+
+        return false;
+    }
+
     @NonNull
     @Override
     DrawableWrapperState mutateConstantState() {
@@ -126,4 +155,14 @@
             return new DrawableWrapperApi21(this, res);
         }
     }
+
+    private void findAndCacheIsProjectedDrawableMethod() {
+        if (sIsProjectedDrawableMethod == null) {
+            try {
+                sIsProjectedDrawableMethod = Drawable.class.getDeclaredMethod("isProjected");
+            } catch (Exception ex) {
+                Log.w(TAG, "Failed to retrieve Drawable#isProjected() method", ex);
+            }
+        }
+    }
 }
diff --git a/compat/api23/android/support/v4/app/NotificationCompatApi23.java b/compat/api23/android/support/v4/app/NotificationCompatApi23.java
deleted file mode 100644
index 2f8216c..0000000
--- a/compat/api23/android/support/v4/app/NotificationCompatApi23.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v4.app;
-
-import android.app.Notification;
-import android.support.annotation.RequiresApi;
-
-@RequiresApi(23)
-class NotificationCompatApi23 {
-
-    public static final String CATEGORY_REMINDER = Notification.CATEGORY_REMINDER;
-}
diff --git a/compat/api24/android/support/v4/app/NotificationCompatApi24.java b/compat/api24/android/support/v4/app/NotificationCompatApi24.java
index 17e5cad..67ea5dc 100644
--- a/compat/api24/android/support/v4/app/NotificationCompatApi24.java
+++ b/compat/api24/android/support/v4/app/NotificationCompatApi24.java
@@ -30,6 +30,7 @@
 import android.graphics.Bitmap;
 import android.net.Uri;
 import android.os.Bundle;
+import android.os.Parcelable;
 import android.support.annotation.RequiresApi;
 import android.widget.RemoteViews;
 
@@ -181,8 +182,89 @@
         }
         actionExtras.putBoolean(NotificationCompatJellybean.EXTRA_ALLOW_GENERATED_REPLIES,
                 action.getAllowGeneratedReplies());
-        actionBuilder.addExtras(actionExtras);
         actionBuilder.setAllowGeneratedReplies(action.getAllowGeneratedReplies());
+        actionBuilder.addExtras(actionExtras);
         b.addAction(actionBuilder.build());
     }
+
+    public static NotificationCompatBase.Action getAction(Notification notif,
+            int actionIndex, NotificationCompatBase.Action.Factory actionFactory,
+            RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
+        return getActionCompatFromAction(notif.actions[actionIndex], actionFactory,
+                remoteInputFactory);
+    }
+
+    private static NotificationCompatBase.Action getActionCompatFromAction(
+            Notification.Action action, NotificationCompatBase.Action.Factory actionFactory,
+            RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
+        RemoteInputCompatBase.RemoteInput[] remoteInputs = RemoteInputCompatApi20.toCompat(
+                action.getRemoteInputs(), remoteInputFactory);
+        boolean allowGeneratedReplies = action.getExtras().getBoolean(
+                NotificationCompatJellybean.EXTRA_ALLOW_GENERATED_REPLIES)
+                || action.getAllowGeneratedReplies();
+        return actionFactory.build(action.icon, action.title, action.actionIntent,
+                action.getExtras(), remoteInputs, null, allowGeneratedReplies);
+    }
+
+    private static Notification.Action getActionFromActionCompat(
+            NotificationCompatBase.Action actionCompat) {
+        Notification.Action.Builder actionBuilder = new Notification.Action.Builder(
+                actionCompat.getIcon(), actionCompat.getTitle(), actionCompat.getActionIntent());
+        Bundle actionExtras;
+        if (actionCompat.getExtras() != null) {
+            actionExtras = new Bundle(actionCompat.getExtras());
+        } else {
+            actionExtras = new Bundle();
+        }
+        actionExtras.putBoolean(NotificationCompatJellybean.EXTRA_ALLOW_GENERATED_REPLIES,
+                actionCompat.getAllowGeneratedReplies());
+        actionBuilder.setAllowGeneratedReplies(actionCompat.getAllowGeneratedReplies());
+        actionBuilder.addExtras(actionExtras);
+        RemoteInputCompatBase.RemoteInput[] remoteInputCompats = actionCompat.getRemoteInputs();
+        if (remoteInputCompats != null) {
+            RemoteInput[] remoteInputs = RemoteInputCompatApi20.fromCompat(remoteInputCompats);
+            for (RemoteInput remoteInput : remoteInputs) {
+                actionBuilder.addRemoteInput(remoteInput);
+            }
+        }
+        return actionBuilder.build();
+    }
+
+    /**
+     * Get a list of notification compat actions by parsing actions stored within a list of
+     * parcelables using the {@link Bundle#getParcelableArrayList} function in the same
+     * manner that framework code would do so. In API20, Using Action parcelable directly
+     * is correct.
+     */
+    public static NotificationCompatBase.Action[] getActionsFromParcelableArrayList(
+            ArrayList<Parcelable> parcelables,
+            NotificationCompatBase.Action.Factory actionFactory,
+            RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
+        if (parcelables == null) {
+            return null;
+        }
+        NotificationCompatBase.Action[] actions = actionFactory.newArray(parcelables.size());
+        for (int i = 0; i < actions.length; i++) {
+            Notification.Action action = (Notification.Action) parcelables.get(i);
+            actions[i] = getActionCompatFromAction(action, actionFactory, remoteInputFactory);
+        }
+        return actions;
+    }
+
+    /**
+     * Get an array list of parcelables, suitable for {@link Bundle#putParcelableArrayList},
+     * that matches what framework code would do to store an actions list in this way. In API20,
+     * action parcelables were directly placed as entries in the array list.
+     */
+    public static ArrayList<Parcelable> getParcelableArrayListForActions(
+            NotificationCompatBase.Action[] actions) {
+        if (actions == null) {
+            return null;
+        }
+        ArrayList<Parcelable> parcelables = new ArrayList<Parcelable>(actions.length);
+        for (NotificationCompatBase.Action action : actions) {
+            parcelables.add(getActionFromActionCompat(action));
+        }
+        return parcelables;
+    }
 }
diff --git a/compat/build.gradle b/compat/build.gradle
index fc61134..5f9e079 100644
--- a/compat/build.gradle
+++ b/compat/build.gradle
@@ -2,18 +2,17 @@
 archivesBaseName = 'support-compat'
 
 dependencies {
-    compile project(':support-annotations')
+    api project(':support-annotations')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
diff --git a/compat/ics/android/support/v4/graphics/PaintCompatApi14.java b/compat/ics/android/support/v4/graphics/PaintCompatApi14.java
index 86e87d8..7a7de7c 100644
--- a/compat/ics/android/support/v4/graphics/PaintCompatApi14.java
+++ b/compat/ics/android/support/v4/graphics/PaintCompatApi14.java
@@ -24,6 +24,7 @@
 class PaintCompatApi14 {
     // U+DFFFD which is very end of unassigned plane.
     private static final String TOFU_STRING = "\uDB3F\uDFFD";
+    private static final String EM_STRING = "m";
 
     private static final ThreadLocal<Pair<Rect, Rect>> sRectThreadLocal = new ThreadLocal<>();
 
@@ -36,6 +37,8 @@
         }
 
         final float missingGlyphWidth = paint.measureText(TOFU_STRING);
+        final float emGlyphWidth = paint.measureText(EM_STRING);
+
         final float width = paint.measureText(string);
 
         if (width == 0f) {
@@ -46,7 +49,7 @@
         if (string.codePointCount(0, string.length()) > 1) {
             // Heuristic to detect fallback glyphs for ligatures like flags and ZWJ sequences
             // Return false if string is rendered too widely
-            if (width > 2 * missingGlyphWidth) {
+            if (width > 2 * emGlyphWidth) {
                 return false;
             }
 
diff --git a/compat/java/android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat.java b/compat/java/android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat.java
index e2ea863..3c17fda 100644
--- a/compat/java/android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat.java
+++ b/compat/java/android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat.java
@@ -18,15 +18,14 @@
 
 import android.accessibilityservice.AccessibilityService;
 import android.accessibilityservice.AccessibilityServiceInfo;
-import android.support.annotation.RequiresApi;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.view.View;
 
 /**
- * Helper for accessing features in {@link android.accessibilityservice.AccessibilityService}
- * in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.accessibilityservice.AccessibilityService}.
  */
 public final class AccessibilityServiceInfoCompat {
 
diff --git a/compat/java/android/support/v4/app/ActivityCompat.java b/compat/java/android/support/v4/app/ActivityCompat.java
index e3e2516..f260508 100644
--- a/compat/java/android/support/v4/app/ActivityCompat.java
+++ b/compat/java/android/support/v4/app/ActivityCompat.java
@@ -41,8 +41,7 @@
 import java.util.Map;
 
 /**
- * Helper for accessing features in {@link android.app.Activity}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.app.Activity}.
  */
 public class ActivityCompat extends ContextCompat {
 
diff --git a/compat/java/android/support/v4/app/AppOpsManagerCompat.java b/compat/java/android/support/v4/app/AppOpsManagerCompat.java
index 5b8fdd9..ce2d2c6 100644
--- a/compat/java/android/support/v4/app/AppOpsManagerCompat.java
+++ b/compat/java/android/support/v4/app/AppOpsManagerCompat.java
@@ -23,8 +23,7 @@
 import android.support.annotation.NonNull;
 
 /**
- * Helper for accessing features in android.app.AppOpsManager
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.app.AppOpsManager}.
  */
 public final class AppOpsManagerCompat {
 
diff --git a/compat/java/android/support/v4/app/BundleCompat.java b/compat/java/android/support/v4/app/BundleCompat.java
index eb8a4c8..e5fc302 100644
--- a/compat/java/android/support/v4/app/BundleCompat.java
+++ b/compat/java/android/support/v4/app/BundleCompat.java
@@ -25,7 +25,7 @@
 import java.lang.reflect.Method;
 
 /**
- * Helper for accessing features in {@link Bundle} in a backwards compatible fashion.
+ * Helper for accessing features in {@link Bundle}.
  */
 public final class BundleCompat {
 
diff --git a/compat/java/android/support/v4/app/JobIntentService.java b/compat/java/android/support/v4/app/JobIntentService.java
index a5417e6..4c83eb9 100644
--- a/compat/java/android/support/v4/app/JobIntentService.java
+++ b/compat/java/android/support/v4/app/JobIntentService.java
@@ -32,7 +32,6 @@
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
-import android.support.v4.os.BuildCompat;
 import android.util.Log;
 
 import java.util.ArrayList;
@@ -96,11 +95,13 @@
     CompatJobEngine mJobImpl;
     WorkEnqueuer mCompatWorkEnqueuer;
     CommandProcessor mCurProcessor;
+    boolean mInterruptIfStopped = false;
+    boolean mStopped = false;
 
     final ArrayList<CompatWorkItem> mCompatQueue;
 
     static final Object sLock = new Object();
-    static final HashMap<Class, WorkEnqueuer> sClassWorkEnqueuer = new HashMap<>();
+    static final HashMap<ComponentName, WorkEnqueuer> sClassWorkEnqueuer = new HashMap<>();
 
     /**
      * Base class for the target service we can deliver work to and the implementation of
@@ -112,8 +113,8 @@
         boolean mHasJobId;
         int mJobId;
 
-        WorkEnqueuer(Context context, Class cls) {
-            mComponentName = new ComponentName(context, cls);
+        WorkEnqueuer(Context context, ComponentName cn) {
+            mComponentName = cn;
         }
 
         void ensureJobId(int jobId) {
@@ -156,16 +157,18 @@
         boolean mLaunchingService;
         boolean mServiceRunning;
 
-        CompatWorkEnqueuer(Context context, Class cls) {
-            super(context, cls);
+        CompatWorkEnqueuer(Context context, ComponentName cn) {
+            super(context, cn);
             mContext = context.getApplicationContext();
             // Make wake locks.  We need two, because the launch wake lock wants to have
             // a timeout, and the system does not do the right thing if you mix timeout and
             // non timeout (or even changing the timeout duration) in one wake lock.
             PowerManager pm = ((PowerManager) context.getSystemService(Context.POWER_SERVICE));
-            mLaunchWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, cls.getName());
+            mLaunchWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
+                    cn.getClassName() + ":launch");
             mLaunchWakeLock.setReferenceCounted(false);
-            mRunWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, cls.getName());
+            mRunWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
+                    cn.getClassName() + ":run");
             mRunWakeLock.setReferenceCounted(false);
         }
 
@@ -237,6 +240,7 @@
         static final boolean DEBUG = false;
 
         final JobIntentService mService;
+        final Object mLock = new Object();
         JobParameters mParams;
 
         final class WrapperWorkItem implements JobIntentService.GenericWorkItem {
@@ -253,7 +257,11 @@
 
             @Override
             public void complete() {
-                mParams.completeWork(mJobWork);
+                synchronized (mLock) {
+                    if (mParams != null) {
+                        mParams.completeWork(mJobWork);
+                    }
+                }
             }
         }
 
@@ -279,7 +287,13 @@
         @Override
         public boolean onStopJob(JobParameters params) {
             if (DEBUG) Log.d(TAG, "onStartJob: " + params);
-            return mService.onStopCurrentWork();
+            boolean result = mService.doStopCurrentWork();
+            synchronized (mLock) {
+                // Once we return, the job is stopped, so its JobParameters are no
+                // longer valid and we should not be doing anything with them.
+                mParams = null;
+            }
+            return result;
         }
 
         /**
@@ -287,8 +301,15 @@
          */
         @Override
         public JobIntentService.GenericWorkItem dequeueWork() {
-            JobWorkItem work = mParams.dequeueWork();
+            JobWorkItem work;
+            synchronized (mLock) {
+                if (mParams == null) {
+                    return null;
+                }
+                work = mParams.dequeueWork();
+            }
             if (work != null) {
+                work.getIntent().setExtrasClassLoader(mService.getClassLoader());
                 return new WrapperWorkItem(work);
             } else {
                 return null;
@@ -301,8 +322,8 @@
         private final JobInfo mJobInfo;
         private final JobScheduler mJobScheduler;
 
-        JobWorkEnqueuer(Context context, Class cls, int jobId) {
-            super(context, cls);
+        JobWorkEnqueuer(Context context, ComponentName cn, int jobId) {
+            super(context, cn);
             ensureJobId(jobId);
             JobInfo.Builder b = new JobInfo.Builder(jobId, mComponentName);
             mJobInfo = b.setOverrideDeadline(0).build();
@@ -373,13 +394,13 @@
         }
 
         @Override
+        protected void onCancelled(Void aVoid) {
+            processorFinished();
+        }
+
+        @Override
         protected void onPostExecute(Void aVoid) {
-            if (mCompatQueue != null) {
-                synchronized (mCompatQueue) {
-                    mCurProcessor = null;
-                    checkForMoreCompatWorkLocked();
-                }
-            }
+            processorFinished();
         }
     }
 
@@ -403,7 +424,8 @@
             mCompatWorkEnqueuer = null;
         } else {
             mJobImpl = null;
-            mCompatWorkEnqueuer = getWorkEnqueuer(this, this.getClass(), false, 0);
+            ComponentName cn = new ComponentName(this, this.getClass());
+            mCompatWorkEnqueuer = getWorkEnqueuer(this, cn, false, 0);
             mCompatWorkEnqueuer.serviceCreated();
         }
     }
@@ -468,28 +490,45 @@
      */
     public static void enqueueWork(@NonNull Context context, @NonNull Class cls, int jobId,
             @NonNull Intent work) {
+        enqueueWork(context, new ComponentName(context, cls), jobId, work);
+    }
+
+    /**
+     * Like {@link #enqueueWork(Context, Class, int, Intent)}, but supplies a ComponentName
+     * for the service to interact with instead of its class.
+     *
+     * @param context Context this is being called from.
+     * @param component The published ComponentName of the class this work should be
+     * dispatched to.
+     * @param jobId A unique job ID for scheduling; must be the same value for all work
+     * enqueued for the same class.
+     * @param work The Intent of work to enqueue.
+     */
+    public static void enqueueWork(@NonNull Context context, @NonNull ComponentName component,
+            int jobId, @NonNull Intent work) {
         if (work == null) {
             throw new IllegalArgumentException("work must not be null");
         }
         synchronized (sLock) {
-            WorkEnqueuer we = getWorkEnqueuer(context, cls, true, jobId);
+            WorkEnqueuer we = getWorkEnqueuer(context, component, true, jobId);
             we.ensureJobId(jobId);
             we.enqueueWork(work);
         }
     }
 
-    static WorkEnqueuer getWorkEnqueuer(Context context, Class cls, boolean hasJobId, int jobId) {
-        WorkEnqueuer we = sClassWorkEnqueuer.get(cls);
+    static WorkEnqueuer getWorkEnqueuer(Context context, ComponentName cn, boolean hasJobId,
+            int jobId) {
+        WorkEnqueuer we = sClassWorkEnqueuer.get(cn);
         if (we == null) {
-            if (BuildCompat.isAtLeastO()) {
+            if (Build.VERSION.SDK_INT >= 26) {
                 if (!hasJobId) {
                     throw new IllegalArgumentException("Can't be here without a job id");
                 }
-                we = new JobWorkEnqueuer(context, cls, jobId);
+                we = new JobWorkEnqueuer(context, cn, jobId);
             } else {
-                we = new CompatWorkEnqueuer(context, cls);
+                we = new CompatWorkEnqueuer(context, cn);
             }
-            sClassWorkEnqueuer.put(cls, we);
+            sClassWorkEnqueuer.put(cn, we);
         }
         return we;
     }
@@ -512,6 +551,28 @@
     protected abstract void onHandleWork(@NonNull Intent intent);
 
     /**
+     * Control whether code executing in {@link #onHandleWork(Intent)} will be interrupted
+     * if the job is stopped.  By default this is false.  If called and set to true, any
+     * time {@link #onStopCurrentWork()} is called, the class will first call
+     * {@link AsyncTask#cancel(boolean) AsyncTask.cancel(true)} to interrupt the running
+     * task.
+     *
+     * @param interruptIfStopped Set to true to allow the system to interrupt actively
+     * running work.
+     */
+    public void setInterruptIfStopped(boolean interruptIfStopped) {
+        mInterruptIfStopped = interruptIfStopped;
+    }
+
+    /**
+     * Returns true if {@link #onStopCurrentWork()} has been called.  You can use this,
+     * while executing your work, to see if it should be stopped.
+     */
+    public boolean isStopped() {
+        return mStopped;
+    }
+
+    /**
      * This will be called if the JobScheduler has decided to stop this job.  The job for
      * this service does not have any constraints specified, so this will only generally happen
      * if the service exceeds the job's maximum execution time.
@@ -526,6 +587,14 @@
         return true;
     }
 
+    boolean doStopCurrentWork() {
+        if (mCurProcessor != null) {
+            mCurProcessor.cancel(mInterruptIfStopped);
+        }
+        mStopped = true;
+        return onStopCurrentWork();
+    }
+
     void ensureProcessorRunningLocked() {
         if (mCurProcessor == null) {
             mCurProcessor = new CommandProcessor();
@@ -534,11 +603,22 @@
         }
     }
 
-    void checkForMoreCompatWorkLocked() {
-        // The async task has finished, but we may have gotten more work scheduled in the
-        // meantime.  If so,
-        if (mCompatQueue != null && mCompatQueue.size() > 0) {
-            ensureProcessorRunningLocked();
+    void processorFinished() {
+        if (mCompatQueue != null) {
+            synchronized (mCompatQueue) {
+                mCurProcessor = null;
+                // The async task has finished, but we may have gotten more work scheduled in the
+                // meantime.  If so, we need to restart the new processor to execute it.  If there
+                // is no more work at this point, either the service is in the process of being
+                // destroyed (because we called stopSelf on the last intent started for it), or
+                // someone has already called startService with a new Intent that will be
+                // arriving shortly.  In either case, we want to just leave the service
+                // waiting -- either to get destroyed, or get a new onStartCommand() callback
+                // which will then kick off a new processor.
+                if (mCompatQueue != null && mCompatQueue.size() > 0) {
+                    ensureProcessorRunningLocked();
+                }
+            }
         }
     }
 
diff --git a/compat/java/android/support/v4/app/NotificationCompat.java b/compat/java/android/support/v4/app/NotificationCompat.java
index ec46c55..8d370ab 100644
--- a/compat/java/android/support/v4/app/NotificationCompat.java
+++ b/compat/java/android/support/v4/app/NotificationCompat.java
@@ -24,33 +24,48 @@
 import android.app.Notification;
 import android.app.PendingIntent;
 import android.content.Context;
+import android.content.res.ColorStateList;
+import android.content.res.Resources;
 import android.graphics.Bitmap;
+import android.graphics.Canvas;
 import android.graphics.Color;
+import android.graphics.PorterDuff;
+import android.graphics.PorterDuffColorFilter;
+import android.graphics.drawable.Drawable;
 import android.media.AudioManager;
 import android.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Parcelable;
+import android.os.SystemClock;
 import android.support.annotation.ColorInt;
 import android.support.annotation.IntDef;
 import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
-import android.support.v4.os.BuildCompat;
+import android.support.compat.R;
+import android.support.v4.text.BidiFormatter;
 import android.support.v4.view.GravityCompat;
+import android.text.SpannableStringBuilder;
+import android.text.Spanned;
+import android.text.TextUtils;
+import android.text.style.TextAppearanceSpan;
+import android.util.TypedValue;
 import android.view.Gravity;
+import android.view.View;
 import android.widget.RemoteViews;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 
 /**
- * Helper for accessing features in {@link android.app.Notification}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.app.Notification}.
  */
 public class NotificationCompat {
 
@@ -451,67 +466,67 @@
     /**
      * Notification category: incoming call (voice or video) or similar synchronous communication request.
      */
-    public static final String CATEGORY_CALL = NotificationCompatApi21.CATEGORY_CALL;
+    public static final String CATEGORY_CALL = Notification.CATEGORY_CALL;
 
     /**
      * Notification category: incoming direct message (SMS, instant message, etc.).
      */
-    public static final String CATEGORY_MESSAGE = NotificationCompatApi21.CATEGORY_MESSAGE;
+    public static final String CATEGORY_MESSAGE = Notification.CATEGORY_MESSAGE;
 
     /**
      * Notification category: asynchronous bulk message (email).
      */
-    public static final String CATEGORY_EMAIL = NotificationCompatApi21.CATEGORY_EMAIL;
+    public static final String CATEGORY_EMAIL = Notification.CATEGORY_EMAIL;
 
     /**
      * Notification category: calendar event.
      */
-    public static final String CATEGORY_EVENT = NotificationCompatApi21.CATEGORY_EVENT;
+    public static final String CATEGORY_EVENT = Notification.CATEGORY_EVENT;
 
     /**
      * Notification category: promotion or advertisement.
      */
-    public static final String CATEGORY_PROMO = NotificationCompatApi21.CATEGORY_PROMO;
+    public static final String CATEGORY_PROMO = Notification.CATEGORY_PROMO;
 
     /**
      * Notification category: alarm or timer.
      */
-    public static final String CATEGORY_ALARM = NotificationCompatApi21.CATEGORY_ALARM;
+    public static final String CATEGORY_ALARM = Notification.CATEGORY_ALARM;
 
     /**
      * Notification category: progress of a long-running background operation.
      */
-    public static final String CATEGORY_PROGRESS = NotificationCompatApi21.CATEGORY_PROGRESS;
+    public static final String CATEGORY_PROGRESS = Notification.CATEGORY_PROGRESS;
 
     /**
      * Notification category: social network or sharing update.
      */
-    public static final String CATEGORY_SOCIAL = NotificationCompatApi21.CATEGORY_SOCIAL;
+    public static final String CATEGORY_SOCIAL = Notification.CATEGORY_SOCIAL;
 
     /**
      * Notification category: error in background operation or authentication status.
      */
-    public static final String CATEGORY_ERROR = NotificationCompatApi21.CATEGORY_ERROR;
+    public static final String CATEGORY_ERROR = Notification.CATEGORY_ERROR;
 
     /**
      * Notification category: media transport control for playback.
      */
-    public static final String CATEGORY_TRANSPORT = NotificationCompatApi21.CATEGORY_TRANSPORT;
+    public static final String CATEGORY_TRANSPORT = Notification.CATEGORY_TRANSPORT;
 
     /**
      * Notification category: system or device status update.  Reserved for system use.
      */
-    public static final String CATEGORY_SYSTEM = NotificationCompatApi21.CATEGORY_SYSTEM;
+    public static final String CATEGORY_SYSTEM = Notification.CATEGORY_SYSTEM;
 
     /**
      * Notification category: indication of running background service.
      */
-    public static final String CATEGORY_SERVICE = NotificationCompatApi21.CATEGORY_SERVICE;
+    public static final String CATEGORY_SERVICE = Notification.CATEGORY_SERVICE;
 
     /**
      * Notification category: user-scheduled reminder.
      */
-    public static final String CATEGORY_REMINDER = NotificationCompatApi23.CATEGORY_REMINDER;
+    public static final String CATEGORY_REMINDER = Notification.CATEGORY_REMINDER;
 
     /**
      * Notification category: a specific, timely recommendation for a single thing.
@@ -519,12 +534,12 @@
      * want to read next.
      */
     public static final String CATEGORY_RECOMMENDATION =
-            NotificationCompatApi21.CATEGORY_RECOMMENDATION;
+            Notification.CATEGORY_RECOMMENDATION;
 
     /**
      * Notification category: ongoing information about device or contextual status.
      */
-    public static final String CATEGORY_STATUS = NotificationCompatApi21.CATEGORY_STATUS;
+    public static final String CATEGORY_STATUS = Notification.CATEGORY_STATUS;
 
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
@@ -592,17 +607,34 @@
     }
 
     /**
-     * Interface for appcompat to extend v4 builder with media style.
+     * Interface for appcompat to extend compat builder with media style.
      *
      * @hide
      */
     @RestrictTo(LIBRARY_GROUP)
     protected static class BuilderExtender {
         public Notification build(Builder b, NotificationBuilderWithBuilderAccessor builder) {
+            RemoteViews styleContentView = b.mStyle != null
+                    ? b.mStyle.makeContentView(builder)
+                    : null;
             Notification n = builder.build();
-            if (b.mContentView != null) {
+            if (styleContentView != null) {
+                n.contentView = styleContentView;
+            } else if (b.mContentView != null) {
                 n.contentView = b.mContentView;
             }
+            if (Build.VERSION.SDK_INT >= 16 && b.mStyle != null) {
+                RemoteViews styleBigContentView = b.mStyle.makeBigContentView(builder);
+                if (styleBigContentView != null) {
+                    n.bigContentView = styleBigContentView;
+                }
+            }
+            if (Build.VERSION.SDK_INT >= 21 && b.mStyle != null) {
+                RemoteViews styleHeadsUpContentView = b.mStyle.makeHeadsUpContentView(builder);
+                if (styleHeadsUpContentView != null) {
+                    n.headsUpContentView = styleHeadsUpContentView;
+                }
+            }
             return n;
         }
     }
@@ -657,7 +689,7 @@
         public Notification build(Builder b, BuilderExtender extender) {
             BuilderBase builder =
                     new BuilderBase(b.mContext, b.mNotification,
-                            b.resolveTitle(), b.resolveText(), b.mContentInfo, b.mTickerView,
+                            b.mContentTitle, b.mContentText, b.mContentInfo, b.mTickerView,
                             b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
                             b.mProgressMax, b.mProgress, b.mProgressIndeterminate);
             return extender.build(b, builder);
@@ -696,13 +728,15 @@
         @Override
         public Notification build(Builder b, BuilderExtender extender) {
             NotificationCompatJellybean.Builder builder = new NotificationCompatJellybean.Builder(
-                    b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
+                    b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
                     b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
                     b.mProgressMax, b.mProgress, b.mProgressIndeterminate,
                     b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
                     b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderJellybean(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             Notification notification = extender.build(b, builder);
             if (b.mStyle != null) {
                 Bundle extras = getExtras(notification);
@@ -738,14 +772,16 @@
         @Override
         public Notification build(Builder b, BuilderExtender extender) {
             NotificationCompatKitKat.Builder builder = new NotificationCompatKitKat.Builder(
-                    b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
+                    b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
                     b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
                     b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
                     b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly,
                     b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey,
                     b.mContentView, b.mBigContentView);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderJellybean(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             return extender.build(b, builder);
         }
 
@@ -761,14 +797,16 @@
         @Override
         public Notification build(Builder b, BuilderExtender extender) {
             NotificationCompatApi20.Builder builder = new NotificationCompatApi20.Builder(
-                    b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
+                    b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
                     b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
                     b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
                     b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mPeople, b.mExtras,
                     b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
                     b.mGroupAlertBehavior);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderJellybean(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             Notification notification = extender.build(b, builder);
             if (b.mStyle != null) {
                 b.mStyle.addCompatExtras(getExtras(notification));
@@ -801,7 +839,7 @@
         @Override
         public Notification build(Builder b, BuilderExtender extender) {
             NotificationCompatApi21.Builder builder = new NotificationCompatApi21.Builder(
-                    b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
+                    b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
                     b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
                     b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
                     b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
@@ -809,7 +847,9 @@
                     b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
                     b.mHeadsUpContentView, b.mGroupAlertBehavior);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderJellybean(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             Notification notification = extender.build(b, builder);
             if (b.mStyle != null) {
                 b.mStyle.addCompatExtras(getExtras(notification));
@@ -845,13 +885,34 @@
                     b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
                     b.mBigContentView, b.mHeadsUpContentView, b.mGroupAlertBehavior);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderApi24(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             Notification notification = extender.build(b, builder);
             if (b.mStyle != null) {
                 b.mStyle.addCompatExtras(getExtras(notification));
             }
             return notification;
         }
+
+        @Override
+        public Action getAction(Notification n, int actionIndex) {
+            return (Action) NotificationCompatApi24.getAction(n, actionIndex, Action.FACTORY,
+                    RemoteInput.FACTORY);
+        }
+
+        @Override
+        public Action[] getActionsFromParcelableArrayList(
+                ArrayList<Parcelable> parcelables) {
+            return (Action[]) NotificationCompatApi24.getActionsFromParcelableArrayList(
+                    parcelables, Action.FACTORY, RemoteInput.FACTORY);
+        }
+
+        @Override
+        public ArrayList<Parcelable> getParcelableArrayListForActions(
+                Action[] actions) {
+            return NotificationCompatApi24.getParcelableArrayListForActions(actions);
+        }
     }
 
     @RequiresApi(26)
@@ -870,7 +931,9 @@
                     b.mShortcutId, b.mTimeout, b.mColorized, b.mColorizedSet,
                     b.mGroupAlertBehavior);
             addActionsToBuilder(builder, b.mActions);
-            addStyleToBuilderApi24(builder, b.mStyle);
+            if (b.mStyle != null) {
+                b.mStyle.apply(builder);
+            }
             Notification notification = extender.build(b, builder);
             if (b.mStyle != null) {
                 b.mStyle.addCompatExtras(getExtras(notification));
@@ -886,67 +949,8 @@
         }
     }
 
-    @RequiresApi(16)
-    static void addStyleToBuilderJellybean(NotificationBuilderWithBuilderAccessor builder,
-            Style style) {
-        if (style != null) {
-            if (style instanceof BigTextStyle) {
-                BigTextStyle bigTextStyle = (BigTextStyle) style;
-                NotificationCompatJellybean.addBigTextStyle(builder,
-                        bigTextStyle.mBigContentTitle,
-                        bigTextStyle.mSummaryTextSet,
-                        bigTextStyle.mSummaryText,
-                        bigTextStyle.mBigText);
-            } else if (style instanceof InboxStyle) {
-                InboxStyle inboxStyle = (InboxStyle) style;
-                NotificationCompatJellybean.addInboxStyle(builder,
-                        inboxStyle.mBigContentTitle,
-                        inboxStyle.mSummaryTextSet,
-                        inboxStyle.mSummaryText,
-                        inboxStyle.mTexts);
-            } else if (style instanceof BigPictureStyle) {
-                BigPictureStyle bigPictureStyle = (BigPictureStyle) style;
-                NotificationCompatJellybean.addBigPictureStyle(builder,
-                        bigPictureStyle.mBigContentTitle,
-                        bigPictureStyle.mSummaryTextSet,
-                        bigPictureStyle.mSummaryText,
-                        bigPictureStyle.mPicture,
-                        bigPictureStyle.mBigLargeIcon,
-                        bigPictureStyle.mBigLargeIconSet);
-            }
-        }
-    }
-
-    @RequiresApi(24)
-    static void addStyleToBuilderApi24(NotificationBuilderWithBuilderAccessor builder,
-            Style style) {
-        if (style != null) {
-            if (style instanceof MessagingStyle) {
-                MessagingStyle messagingStyle = (MessagingStyle) style;
-                List<CharSequence> texts = new ArrayList<>();
-                List<Long> timestamps = new ArrayList<>();
-                List<CharSequence> senders = new ArrayList<>();
-                List<String> dataMimeTypes = new ArrayList<>();
-                List<Uri> dataUris = new ArrayList<>();
-
-                for (MessagingStyle.Message message : messagingStyle.mMessages) {
-                    texts.add(message.getText());
-                    timestamps.add(message.getTimestamp());
-                    senders.add(message.getSender());
-                    dataMimeTypes.add(message.getDataMimeType());
-                    dataUris.add(message.getDataUri());
-                }
-                NotificationCompatApi24.addMessagingStyle(builder, messagingStyle.mUserDisplayName,
-                        messagingStyle.mConversationTitle, texts, timestamps, senders,
-                        dataMimeTypes, dataUris);
-            } else {
-                addStyleToBuilderJellybean(builder, style);
-            }
-        }
-    }
-
     static {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             IMPL = new NotificationCompatApi26Impl();
         } else if (Build.VERSION.SDK_INT >= 24) {
             IMPL = new NotificationCompatApi24Impl();
@@ -1780,12 +1784,6 @@
             return this;
         }
 
-        /** @deprecated removed from API 26 */
-        @Deprecated
-        public Builder setChannel(@NonNull String channelId) {
-            return setChannelId(channelId);
-        }
-
         /**
          * Specifies the time at which this notification should be canceled, if it is not already
          * canceled.
@@ -1795,12 +1793,6 @@
             return this;
         }
 
-        /** @deprecated removed from API 26 */
-        @Deprecated
-        public Builder setTimeout(long durationMs) {
-            return setTimeoutAfter(durationMs);
-        }
-
         /**
          * If this notification is duplicative of a Launcher shortcut, sets the
          * {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id} of the shortcut, in
@@ -1938,27 +1930,6 @@
         public int getColor() {
             return mColor;
         }
-
-
-        /**
-         * @return the text of the notification
-         *
-         * @hide
-         */
-        @RestrictTo(LIBRARY_GROUP)
-        protected CharSequence resolveText() {
-            return mContentText;
-        }
-
-        /**
-         * @return the title of the notification
-         *
-         * @hide
-         */
-        @RestrictTo(LIBRARY_GROUP)
-        protected CharSequence resolveTitle() {
-            return mContentTitle;
-        }
     }
 
     /**
@@ -1969,7 +1940,11 @@
      * effect.
      */
     public static abstract class Style {
-        Builder mBuilder;
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        protected Builder mBuilder;
         CharSequence mBigContentTitle;
         CharSequence mSummaryText;
         boolean mSummaryTextSet = false;
@@ -1996,6 +1971,38 @@
          */
         @RestrictTo(LIBRARY_GROUP)
         // TODO: implement for all styles
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public RemoteViews makeContentView(NotificationBuilderWithBuilderAccessor builder) {
+            return null;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public RemoteViews makeBigContentView(NotificationBuilderWithBuilderAccessor builder) {
+            return null;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public RemoteViews makeHeadsUpContentView(NotificationBuilderWithBuilderAccessor builder) {
+            return null;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        // TODO: implement for all styles
         public void addCompatExtras(Bundle extras) {
         }
 
@@ -2006,6 +2013,233 @@
         // TODO: implement for all styles
         protected void restoreFromCompatExtras(Bundle extras) {
         }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public RemoteViews applyStandardTemplate(boolean showSmallIcon,
+                int resId, boolean fitIn1U) {
+            Resources res = mBuilder.mContext.getResources();
+            RemoteViews contentView = new RemoteViews(mBuilder.mContext.getPackageName(), resId);
+            boolean showLine3 = false;
+            boolean showLine2 = false;
+
+            boolean minPriority = mBuilder.getPriority() < NotificationCompat.PRIORITY_LOW;
+            if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 21) {
+                // lets color the backgrounds
+                if (minPriority) {
+                    contentView.setInt(R.id.notification_background,
+                            "setBackgroundResource", R.drawable.notification_bg_low);
+                    contentView.setInt(R.id.icon,
+                            "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
+                } else {
+                    contentView.setInt(R.id.notification_background,
+                            "setBackgroundResource", R.drawable.notification_bg);
+                    contentView.setInt(R.id.icon,
+                            "setBackgroundResource", R.drawable.notification_template_icon_bg);
+                }
+            }
+
+            if (mBuilder.mLargeIcon != null) {
+                // On versions before Jellybean, the large icon was shown by SystemUI, so we need
+                // to hide it here.
+                if (Build.VERSION.SDK_INT >= 16) {
+                    contentView.setViewVisibility(R.id.icon, View.VISIBLE);
+                    contentView.setImageViewBitmap(R.id.icon, mBuilder.mLargeIcon);
+                } else {
+                    contentView.setViewVisibility(R.id.icon, View.GONE);
+                }
+                if (showSmallIcon && mBuilder.mNotification.icon != 0) {
+                    int backgroundSize = res.getDimensionPixelSize(
+                            R.dimen.notification_right_icon_size);
+                    int iconSize = backgroundSize - res.getDimensionPixelSize(
+                            R.dimen.notification_small_icon_background_padding) * 2;
+                    if (Build.VERSION.SDK_INT >= 21) {
+                        Bitmap smallBit = createIconWithBackground(
+                                mBuilder.mNotification.icon,
+                                backgroundSize,
+                                iconSize,
+                                mBuilder.getColor());
+                        contentView.setImageViewBitmap(R.id.right_icon, smallBit);
+                    } else {
+                        contentView.setImageViewBitmap(R.id.right_icon, createColoredBitmap(
+                                mBuilder.mNotification.icon, Color.WHITE));
+                    }
+                    contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
+                }
+            } else if (showSmallIcon && mBuilder.mNotification.icon != 0) { // small icon at left
+                contentView.setViewVisibility(R.id.icon, View.VISIBLE);
+                if (Build.VERSION.SDK_INT >= 21) {
+                    int backgroundSize = res.getDimensionPixelSize(
+                            R.dimen.notification_large_icon_width)
+                            - res.getDimensionPixelSize(R.dimen.notification_big_circle_margin);
+                    int iconSize = res.getDimensionPixelSize(
+                            R.dimen.notification_small_icon_size_as_large);
+                    Bitmap smallBit = createIconWithBackground(
+                            mBuilder.mNotification.icon,
+                            backgroundSize,
+                            iconSize,
+                            mBuilder.getColor());
+                    contentView.setImageViewBitmap(R.id.icon, smallBit);
+                } else {
+                    contentView.setImageViewBitmap(R.id.icon, createColoredBitmap(
+                            mBuilder.mNotification.icon, Color.WHITE));
+                }
+            }
+            if (mBuilder.mContentTitle != null) {
+                contentView.setTextViewText(R.id.title, mBuilder.mContentTitle);
+            }
+            if (mBuilder.mContentText != null) {
+                contentView.setTextViewText(R.id.text, mBuilder.mContentText);
+                showLine3 = true;
+            }
+            // If there is a large icon we have a right side
+            boolean hasRightSide = !(Build.VERSION.SDK_INT >= 21) && mBuilder.mLargeIcon != null;
+            if (mBuilder.mContentInfo != null) {
+                contentView.setTextViewText(R.id.info, mBuilder.mContentInfo);
+                contentView.setViewVisibility(R.id.info, View.VISIBLE);
+                showLine3 = true;
+                hasRightSide = true;
+            } else if (mBuilder.mNumber > 0) {
+                final int tooBig = res.getInteger(
+                        R.integer.status_bar_notification_info_maxnum);
+                if (mBuilder.mNumber > tooBig) {
+                    contentView.setTextViewText(R.id.info, ((Resources) res).getString(
+                            R.string.status_bar_notification_info_overflow));
+                } else {
+                    NumberFormat f = NumberFormat.getIntegerInstance();
+                    contentView.setTextViewText(R.id.info, f.format(mBuilder.mNumber));
+                }
+                contentView.setViewVisibility(R.id.info, View.VISIBLE);
+                showLine3 = true;
+                hasRightSide = true;
+            } else {
+                contentView.setViewVisibility(R.id.info, View.GONE);
+            }
+
+            // Need to show three lines? Only allow on Jellybean+
+            if (mBuilder.mSubText != null && Build.VERSION.SDK_INT >= 16) {
+                contentView.setTextViewText(R.id.text, mBuilder.mSubText);
+                if (mBuilder.mContentText != null) {
+                    contentView.setTextViewText(R.id.text2, mBuilder.mContentText);
+                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
+                    showLine2 = true;
+                } else {
+                    contentView.setViewVisibility(R.id.text2, View.GONE);
+                }
+            }
+
+            // RemoteViews.setViewPadding and RemoteViews.setTextViewTextSize is not available on
+            // ICS-
+            if (showLine2 && Build.VERSION.SDK_INT >= 16) {
+                if (fitIn1U) {
+                    // need to shrink all the type to make sure everything fits
+                    final float subTextSize = res.getDimensionPixelSize(
+                            R.dimen.notification_subtext_size);
+                    contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX,
+                            subTextSize);
+                }
+                // vertical centering
+                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
+            }
+
+            if (mBuilder.getWhenIfShowing() != 0) {
+                if (mBuilder.mUseChronometer && Build.VERSION.SDK_INT >= 16) {
+                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
+                    contentView.setLong(R.id.chronometer, "setBase",
+                            mBuilder.getWhenIfShowing()
+                                    + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
+                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
+                } else {
+                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
+                    contentView.setLong(R.id.time, "setTime", mBuilder.getWhenIfShowing());
+                }
+                hasRightSide = true;
+            }
+            contentView.setViewVisibility(R.id.right_side, hasRightSide ? View.VISIBLE : View.GONE);
+            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
+            return contentView;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public Bitmap createColoredBitmap(int iconId, int color) {
+            return createColoredBitmap(iconId, color, 0);
+        }
+
+        private Bitmap createColoredBitmap(int iconId, int color, int size) {
+            Drawable drawable = mBuilder.mContext.getResources().getDrawable(iconId);
+            int width = size == 0 ? drawable.getIntrinsicWidth() : size;
+            int height = size == 0 ? drawable.getIntrinsicHeight() : size;
+            Bitmap resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
+            drawable.setBounds(0, 0, width, height);
+            if (color != 0) {
+                drawable.mutate().setColorFilter(
+                        new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
+            }
+            Canvas canvas = new Canvas(resultBitmap);
+            drawable.draw(canvas);
+            return resultBitmap;
+        }
+
+        private Bitmap createIconWithBackground(int iconId, int size,
+                int iconSize, int color) {
+            Bitmap coloredBitmap = createColoredBitmap(R.drawable.notification_icon_background,
+                    color == NotificationCompat.COLOR_DEFAULT ? 0 : color, size);
+            Canvas canvas = new Canvas(coloredBitmap);
+            Drawable icon = mBuilder.mContext.getResources().getDrawable(iconId).mutate();
+            icon.setFilterBitmap(true);
+            int inset = (size - iconSize) / 2;
+            icon.setBounds(inset, inset, iconSize + inset, iconSize + inset);
+            icon.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP));
+            icon.draw(canvas);
+            return coloredBitmap;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        public void buildIntoRemoteViews(RemoteViews outerView,
+                RemoteViews innerView) {
+            // this needs to be done fore the other calls, since otherwise we might hide the wrong
+            // things if our ids collide.
+            hideNormalContent(outerView);
+            outerView.removeAllViews(R.id.notification_main_column);
+            outerView.addView(R.id.notification_main_column, innerView.clone());
+            outerView.setViewVisibility(R.id.notification_main_column, View.VISIBLE);
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+                // Adjust padding depending on font size.
+                outerView.setViewPadding(R.id.notification_main_column_container,
+                        0, calculateTopPadding(), 0, 0);
+            }
+        }
+
+        private void hideNormalContent(RemoteViews outerView) {
+            outerView.setViewVisibility(R.id.title, View.GONE);
+            outerView.setViewVisibility(R.id.text2, View.GONE);
+            outerView.setViewVisibility(R.id.text, View.GONE);
+        }
+
+        private int calculateTopPadding() {
+            Resources resources = mBuilder.mContext.getResources();
+            int padding = resources.getDimensionPixelSize(R.dimen.notification_top_pad);
+            int largePadding = resources.getDimensionPixelSize(
+                    R.dimen.notification_top_pad_large_text);
+            float fontScale = resources.getConfiguration().fontScale;
+            float largeFactor = (constrain(fontScale, 1.0f, 1.3f) - 1f) / (1.3f - 1f);
+
+            // Linearly interpolate the padding between large and normal with the font scale ranging
+            // from 1f to LARGE_TEXT_SCALE
+            return Math.round((1 - largeFactor) * padding + largeFactor * largePadding);
+        }
+
+        private static float constrain(float amount, float low, float high) {
+            return amount < low ? low : (amount > high ? high : amount);
+        }
     }
 
     /**
@@ -2029,9 +2263,9 @@
      * @see Notification#bigContentView
      */
     public static class BigPictureStyle extends Style {
-        Bitmap mPicture;
-        Bitmap mBigLargeIcon;
-        boolean mBigLargeIconSet;
+        private Bitmap mPicture;
+        private Bitmap mBigLargeIcon;
+        private boolean mBigLargeIconSet;
 
         public BigPictureStyle() {
         }
@@ -2074,6 +2308,23 @@
             mBigLargeIconSet = true;
             return this;
         }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 16) {
+                NotificationCompatJellybean.addBigPictureStyle(builder,
+                        mBigContentTitle,
+                        mSummaryTextSet,
+                        mSummaryText,
+                        mPicture,
+                        mBigLargeIcon,
+                        mBigLargeIconSet);
+            }
+        }
     }
 
     /**
@@ -2098,7 +2349,7 @@
      * @see Notification#bigContentView
      */
     public static class BigTextStyle extends Style {
-        CharSequence mBigText;
+        private CharSequence mBigText;
 
         public BigTextStyle() {
         }
@@ -2133,6 +2384,21 @@
             mBigText = Builder.limitCharSequenceLength(cs);
             return this;
         }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 16) {
+                NotificationCompatJellybean.addBigTextStyle(builder,
+                        mBigContentTitle,
+                        mSummaryTextSet,
+                        mSummaryText,
+                        mBigText);
+            }
+        }
     }
 
     /**
@@ -2222,7 +2488,7 @@
          * Adds a message for display by this notification. Convenience call for a simple
          * {@link Message} in {@link #addMessage(Message)}
          * @param text A {@link CharSequence} to be displayed as the message content
-         * @param timestamp Time at which the message arrived
+         * @param timestamp Time at which the message arrived in ms since Unix epoch
          * @param sender A {@link CharSequence} to be used for displaying the name of the
          * sender. Should be <code>null</code> for messages by the current user, in which case
          * the platform will insert {@link #getUserDisplayName()}.
@@ -2285,6 +2551,121 @@
             return style;
         }
 
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                List<CharSequence> texts = new ArrayList<>();
+                List<Long> timestamps = new ArrayList<>();
+                List<CharSequence> senders = new ArrayList<>();
+                List<String> dataMimeTypes = new ArrayList<>();
+                List<Uri> dataUris = new ArrayList<>();
+
+                for (MessagingStyle.Message message : mMessages) {
+                    texts.add(message.getText());
+                    timestamps.add(message.getTimestamp());
+                    senders.add(message.getSender());
+                    dataMimeTypes.add(message.getDataMimeType());
+                    dataUris.add(message.getDataUri());
+                }
+                NotificationCompatApi24.addMessagingStyle(builder, mUserDisplayName,
+                        mConversationTitle, texts, timestamps, senders,
+                        dataMimeTypes, dataUris);
+            } else {
+                MessagingStyle.Message latestIncomingMessage = findLatestIncomingMessage();
+                // Set the title
+                if (mConversationTitle != null) {
+                    builder.getBuilder().setContentTitle(mConversationTitle);
+                } else if (latestIncomingMessage != null) {
+                    builder.getBuilder().setContentTitle(latestIncomingMessage.getSender());
+                }
+                // Set the text
+                if (latestIncomingMessage != null) {
+                    builder.getBuilder().setContentText(mConversationTitle != null
+                            ? makeMessageLine(latestIncomingMessage)
+                            : latestIncomingMessage.getText());
+                }
+                // Build a fallback BigTextStyle for API 16-23 devices
+                if (Build.VERSION.SDK_INT >= 16) {
+                    SpannableStringBuilder completeMessage = new SpannableStringBuilder();
+                    boolean showNames = mConversationTitle != null
+                            || hasMessagesWithoutSender();
+                    for (int i = mMessages.size() - 1; i >= 0; i--) {
+                        MessagingStyle.Message message = mMessages.get(i);
+                        CharSequence line;
+                        line = showNames ? makeMessageLine(message) : message.getText();
+                        if (i != mMessages.size() - 1) {
+                            completeMessage.insert(0, "\n");
+                        }
+                        completeMessage.insert(0, line);
+                    }
+                    NotificationCompatJellybean.addBigTextStyle(builder,
+                            null,
+                            false,
+                            null,
+                            completeMessage);
+                }
+            }
+        }
+
+        @Nullable
+        private MessagingStyle.Message findLatestIncomingMessage() {
+            for (int i = mMessages.size() - 1; i >= 0; i--) {
+                MessagingStyle.Message message = mMessages.get(i);
+                // Incoming messages have a non-empty sender.
+                if (!TextUtils.isEmpty(message.getSender())) {
+                    return message;
+                }
+            }
+            if (!mMessages.isEmpty()) {
+                // No incoming messages, fall back to outgoing message
+                return mMessages.get(mMessages.size() - 1);
+            }
+            return null;
+        }
+
+        private boolean hasMessagesWithoutSender() {
+            for (int i = mMessages.size() - 1; i >= 0; i--) {
+                MessagingStyle.Message message = mMessages.get(i);
+                if (message.getSender() == null) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        private CharSequence makeMessageLine(MessagingStyle.Message message) {
+            BidiFormatter bidi = BidiFormatter.getInstance();
+            SpannableStringBuilder sb = new SpannableStringBuilder();
+            final boolean afterLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
+            int color = afterLollipop ? Color.BLACK : Color.WHITE;
+            CharSequence replyName = message.getSender();
+            if (TextUtils.isEmpty(message.getSender())) {
+                replyName = mUserDisplayName == null
+                        ? "" : mUserDisplayName;
+                color = afterLollipop && mBuilder.getColor() != NotificationCompat.COLOR_DEFAULT
+                        ? mBuilder.getColor()
+                        : color;
+            }
+            CharSequence senderText = bidi.unicodeWrap(replyName);
+            sb.append(senderText);
+            sb.setSpan(makeFontColorSpan(color),
+                    sb.length() - senderText.length(),
+                    sb.length(),
+                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE /* flags */);
+            CharSequence text = message.getText() == null ? "" : message.getText();
+            sb.append("  ").append(bidi.unicodeWrap(text));
+            return sb;
+        }
+
+        @NonNull
+        private TextAppearanceSpan makeFontColorSpan(int color) {
+            return new TextAppearanceSpan(null, 0, 0, ColorStateList.valueOf(color), null);
+        }
+
         @Override
         public void addCompatExtras(Bundle extras) {
             super.addCompatExtras(extras);
@@ -2334,7 +2715,7 @@
             /**
              * Constructor
              * @param text A {@link CharSequence} to be displayed as the message content
-             * @param timestamp Time at which the message arrived
+             * @param timestamp Time at which the message arrived in ms since Unix epoch
              * @param sender A {@link CharSequence} to be used for displaying the name of the
              * sender. Should be <code>null</code> for messages by the current user, in which case
              * the platform will insert {@link MessagingStyle#getUserDisplayName()}.
@@ -2389,7 +2770,7 @@
             }
 
             /**
-             * Get the time at which this message arrived
+             * Get the time at which this message arrived in ms since Unix epoch
              */
             public long getTimestamp() {
                 return mTimestamp;
@@ -2516,7 +2897,7 @@
      * @see Notification#bigContentView
      */
     public static class InboxStyle extends Style {
-        ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
+        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
 
         public InboxStyle() {
         }
@@ -2550,6 +2931,165 @@
             mTexts.add(Builder.limitCharSequenceLength(cs));
             return this;
         }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 16) {
+                NotificationCompatJellybean.addInboxStyle(builder,
+                        mBigContentTitle,
+                        mSummaryTextSet,
+                        mSummaryText,
+                        mTexts);
+            }
+        }
+    }
+
+    /**
+     * Notification style for custom views that are decorated by the system.
+     *
+     * <p>Instead of providing a notification that is completely custom, a developer can set this
+     * style and still obtain system decorations like the notification header with the expand
+     * affordance and actions.
+     *
+     * <p>Use {@link NotificationCompat.Builder#setCustomContentView(RemoteViews)},
+     * {@link NotificationCompat.Builder#setCustomBigContentView(RemoteViews)} and
+     * {@link NotificationCompat.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
+     * corresponding custom views to display.
+     *
+     * <p>To use this style with your Notification, feed it to
+     * {@link NotificationCompat.Builder#setStyle(Style)} like so:
+     * <pre class="prettyprint">
+     * Notification noti = new NotificationCompat.Builder()
+     *     .setSmallIcon(R.drawable.ic_stat_player)
+     *     .setLargeIcon(albumArtBitmap))
+     *     .setCustomContentView(contentView)
+     *     .setStyle(<b>new NotificationCompat.DecoratedCustomViewStyle()</b>)
+     *     .build();
+     * </pre>
+     *
+     * <p>If you are using this style, consider using the corresponding styles like
+     * {@link android.support.compat.R.style#TextAppearance_Compat_Notification} or
+     * {@link android.support.compat.R.style#TextAppearance_Compat_Notification_Title} in
+     * your custom views in order to get the correct styling on each platform version.
+     */
+    public static class DecoratedCustomViewStyle extends Style {
+
+        private static final int MAX_ACTION_BUTTONS = 3;
+
+        public DecoratedCustomViewStyle() {
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                builder.getBuilder().setStyle(new Notification.DecoratedCustomViewStyle());
+            }
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom content view required
+                return null;
+            }
+            if (mBuilder.getContentView() == null) {
+                // No special content view
+                return null;
+            }
+            return createRemoteViews(mBuilder.getContentView(), false);
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeBigContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom big content view required
+                return null;
+            }
+            RemoteViews bigContentView = mBuilder.getBigContentView();
+            RemoteViews innerView = bigContentView != null
+                    ? bigContentView
+                    : mBuilder.getContentView();
+            if (innerView == null) {
+                // No expandable notification
+                return null;
+            }
+            return createRemoteViews(innerView, true);
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeHeadsUpContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom heads up content view required
+                return null;
+            }
+            RemoteViews headsUp = mBuilder.getHeadsUpContentView();
+            RemoteViews innerView = headsUp != null ? headsUp : mBuilder.getContentView();
+            if (headsUp == null) {
+                // No expandable notification
+                return null;
+            }
+            return createRemoteViews(innerView, true);
+        }
+
+        private RemoteViews createRemoteViews(RemoteViews innerView, boolean showActions) {
+            RemoteViews remoteViews = applyStandardTemplate(true /* showSmallIcon */,
+                    R.layout.notification_template_custom_big, false /* fitIn1U */);
+            remoteViews.removeAllViews(R.id.actions);
+            boolean actionsVisible = false;
+            if (showActions && mBuilder.mActions != null) {
+                int numActions = Math.min(mBuilder.mActions.size(), MAX_ACTION_BUTTONS);
+                if (numActions > 0) {
+                    actionsVisible = true;
+                    for (int i = 0; i < numActions; i++) {
+                        final RemoteViews button = generateActionButton(mBuilder.mActions.get(i));
+                        remoteViews.addView(R.id.actions, button);
+                    }
+                }
+            }
+            int actionVisibility = actionsVisible ? View.VISIBLE : View.GONE;
+            remoteViews.setViewVisibility(R.id.actions, actionVisibility);
+            remoteViews.setViewVisibility(R.id.action_divider, actionVisibility);
+            buildIntoRemoteViews(remoteViews, innerView);
+            return remoteViews;
+        }
+
+        private RemoteViews generateActionButton(NotificationCompat.Action action) {
+            final boolean tombstone = (action.actionIntent == null);
+            RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(),
+                    tombstone ? R.layout.notification_action_tombstone
+                            : R.layout.notification_action);
+            button.setImageViewBitmap(R.id.action_image,
+                    createColoredBitmap(action.getIcon(), mBuilder.mContext.getResources()
+                            .getColor(R.color.notification_action_color_filter)));
+            button.setTextViewText(R.id.action_text, action.title);
+            if (!tombstone) {
+                button.setOnClickPendingIntent(R.id.action_container, action.actionIntent);
+            }
+            if (Build.VERSION.SDK_INT >= 15) {
+                button.setContentDescription(R.id.action_container, action.title);
+            }
+            return button;
+        }
     }
 
     /**
@@ -4336,10 +4876,10 @@
         if (Build.VERSION.SDK_INT >= 20) {
             return (notification.flags & Notification.FLAG_LOCAL_ONLY) != 0;
         } else if (Build.VERSION.SDK_INT >= 19) {
-            return notification.extras.getBoolean(NotificationCompatJellybean.EXTRA_LOCAL_ONLY);
+            return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_LOCAL_ONLY);
         } else if (Build.VERSION.SDK_INT >= 16) {
             return NotificationCompatJellybean.getExtras(notification).getBoolean(
-                    NotificationCompatJellybean.EXTRA_LOCAL_ONLY);
+                    NotificationCompatExtras.EXTRA_LOCAL_ONLY);
         } else {
             return false;
         }
@@ -4353,10 +4893,10 @@
         if (Build.VERSION.SDK_INT >= 20) {
             return notification.getGroup();
         } else if (Build.VERSION.SDK_INT >= 19) {
-            return notification.extras.getString(NotificationCompatJellybean.EXTRA_GROUP_KEY);
+            return notification.extras.getString(NotificationCompatExtras.EXTRA_GROUP_KEY);
         } else if (Build.VERSION.SDK_INT >= 16) {
             return NotificationCompatJellybean.getExtras(notification).getString(
-                    NotificationCompatJellybean.EXTRA_GROUP_KEY);
+                    NotificationCompatExtras.EXTRA_GROUP_KEY);
         } else {
             return null;
         }
@@ -4372,10 +4912,10 @@
         if (Build.VERSION.SDK_INT >= 20) {
             return (notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0;
         } else if (Build.VERSION.SDK_INT >= 19) {
-            return notification.extras.getBoolean(NotificationCompatJellybean.EXTRA_GROUP_SUMMARY);
+            return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
         } else if (Build.VERSION.SDK_INT >= 16) {
             return NotificationCompatJellybean.getExtras(notification).getBoolean(
-                    NotificationCompatJellybean.EXTRA_GROUP_SUMMARY);
+                    NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
         } else {
             return false;
         }
@@ -4397,10 +4937,10 @@
         if (Build.VERSION.SDK_INT >= 20) {
             return notification.getSortKey();
         } else if (Build.VERSION.SDK_INT >= 19) {
-            return notification.extras.getString(NotificationCompatJellybean.EXTRA_SORT_KEY);
+            return notification.extras.getString(NotificationCompatExtras.EXTRA_SORT_KEY);
         } else if (Build.VERSION.SDK_INT >= 16) {
             return NotificationCompatJellybean.getExtras(notification).getString(
-                    NotificationCompatJellybean.EXTRA_SORT_KEY);
+                    NotificationCompatExtras.EXTRA_SORT_KEY);
         } else {
             return null;
         }
@@ -4410,44 +4950,32 @@
      * @return the ID of the channel this notification posts to.
      */
     public static String getChannelId(Notification notification) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return notification.getChannelId();
         } else {
             return null;
         }
     }
 
-    /** @deprecated removed from API 26 */
-    @Deprecated
-    public static String getChannel(Notification notification) {
-        return getChannelId(notification);
-    }
-
     /**
      * Returns the time at which this notification should be canceled by the system, if it's not
      * canceled already.
      */
     public static long getTimeoutAfter(Notification notification) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return notification.getTimeoutAfter();
         } else {
             return 0;
         }
     }
 
-    /** @deprecated removed from API 26 */
-    @Deprecated
-    public static long getTimeout(Notification notification) {
-        return getTimeoutAfter(notification);
-    }
-
     /**
      * Returns what icon should be shown for this notification if it is being displayed in a
      * Launcher that supports badging. Will be one of {@link #BADGE_ICON_NONE},
      * {@link #BADGE_ICON_SMALL}, or {@link #BADGE_ICON_LARGE}.
      */
     public static int getBadgeIconType(Notification notification) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return notification.getBadgeIconType();
         } else {
             return BADGE_ICON_NONE;
@@ -4459,7 +4987,7 @@
      * notification supersedes, if any.
      */
     public static String getShortcutId(Notification notification) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return notification.getShortcutId();
         } else {
             return null;
@@ -4472,7 +5000,7 @@
      * {@link #GROUP_ALERT_SUMMARY}.
      */
     public static int getGroupAlertBehavior(Notification notification) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return notification.getGroupAlertBehavior();
         } else {
             return GROUP_ALERT_ALL;
diff --git a/compat/java/android/support/v4/app/NotificationCompatExtras.java b/compat/java/android/support/v4/app/NotificationCompatExtras.java
index bf9ba0f..33bdd06 100644
--- a/compat/java/android/support/v4/app/NotificationCompatExtras.java
+++ b/compat/java/android/support/v4/app/NotificationCompatExtras.java
@@ -25,37 +25,35 @@
      * the {@link android.app.Notification#FLAG_LOCAL_ONLY} field before it was available.
      * If possible, use {@link NotificationCompat#getLocalOnly} to access this field.
      */
-    public static final String EXTRA_LOCAL_ONLY = NotificationCompatJellybean.EXTRA_LOCAL_ONLY;
+    public static final String EXTRA_LOCAL_ONLY = "android.support.localOnly";
 
     /**
      * Extras key used internally by {@link NotificationCompat} to store the value set
      * by {@link android.app.Notification.Builder#setGroup} before it was available.
      * If possible, use {@link NotificationCompat#getGroup} to access this value.
      */
-    public static final String EXTRA_GROUP_KEY = NotificationCompatJellybean.EXTRA_GROUP_KEY;
+    public static final String EXTRA_GROUP_KEY = "android.support.groupKey";
 
     /**
      * Extras key used internally by {@link NotificationCompat} to store the value set
      * by {@link android.app.Notification.Builder#setGroupSummary} before it was available.
      * If possible, use {@link NotificationCompat#isGroupSummary} to access this value.
      */
-    public static final String EXTRA_GROUP_SUMMARY =
-            NotificationCompatJellybean.EXTRA_GROUP_SUMMARY;
+    public static final String EXTRA_GROUP_SUMMARY = "android.support.isGroupSummary";
 
     /**
      * Extras key used internally by {@link NotificationCompat} to store the value set
      * by {@link android.app.Notification.Builder#setSortKey} before it was available.
      * If possible, use {@link NotificationCompat#getSortKey} to access this value.
      */
-    public static final String EXTRA_SORT_KEY = NotificationCompatJellybean.EXTRA_SORT_KEY;
+    public static final String EXTRA_SORT_KEY = "android.support.sortKey";
 
     /**
      * Extras key used internally by {@link NotificationCompat} to store the value of
      * the {@link android.app.Notification.Action#extras} field before it was available.
      * If possible, use {@link NotificationCompat#getAction} to access this field.
      */
-    public static final String EXTRA_ACTION_EXTRAS =
-            NotificationCompatJellybean.EXTRA_ACTION_EXTRAS;
+    public static final String EXTRA_ACTION_EXTRAS = "android.support.actionExtras";
 
     /**
      * Extras key used internally by {@link NotificationCompat} to store the value of
@@ -63,8 +61,7 @@
      * was available.
      * If possible, use {@link NotificationCompat.Action#getRemoteInputs} to access this field.
      */
-    public static final String EXTRA_REMOTE_INPUTS =
-            NotificationCompatJellybean.EXTRA_REMOTE_INPUTS;
+    public static final String EXTRA_REMOTE_INPUTS = "android.support.remoteInputs";
 
     private NotificationCompatExtras() {}
 }
diff --git a/compat/java/android/support/v4/app/NotificationManagerCompat.java b/compat/java/android/support/v4/app/NotificationManagerCompat.java
index 582c570..93775ec 100644
--- a/compat/java/android/support/v4/app/NotificationManagerCompat.java
+++ b/compat/java/android/support/v4/app/NotificationManagerCompat.java
@@ -25,7 +25,6 @@
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.os.Build;
 import android.os.Bundle;
@@ -66,8 +65,7 @@
      * Notification extras key: if set to true, the posted notification should use
      * the side channel for delivery instead of using notification manager.
      */
-    public static final String EXTRA_USE_SIDE_CHANNEL =
-            NotificationCompatJellybean.EXTRA_USE_SIDE_CHANNEL;
+    public static final String EXTRA_USE_SIDE_CHANNEL = "android.support.useSideChannel";
 
     /**
      * Intent action to register for on a service to receive side channel
@@ -411,7 +409,7 @@
             }
             mCachedEnabledPackages = enabledPackages;
             List<ResolveInfo> resolveInfos = mContext.getPackageManager().queryIntentServices(
-                    new Intent().setAction(ACTION_BIND_SIDE_CHANNEL), PackageManager.GET_SERVICES);
+                    new Intent().setAction(ACTION_BIND_SIDE_CHANNEL), 0);
             Set<ComponentName> enabledComponents = new HashSet<ComponentName>();
             for (ResolveInfo resolveInfo : resolveInfos) {
                 if (!enabledPackages.contains(resolveInfo.serviceInfo.packageName)) {
diff --git a/compat/java/android/support/v4/app/RemoteInput.java b/compat/java/android/support/v4/app/RemoteInput.java
index 73eb388..48f7744 100644
--- a/compat/java/android/support/v4/app/RemoteInput.java
+++ b/compat/java/android/support/v4/app/RemoteInput.java
@@ -31,13 +31,13 @@
 import java.util.Set;
 
 /**
- * Helper for using the {@link android.app.RemoteInput} API in a backwards compatible fashion.
+ * Helper for using the {@link android.app.RemoteInput}.
  */
 public final class RemoteInput extends RemoteInputCompatBase.RemoteInput {
     private static final String TAG = "RemoteInput";
 
     /** Label used to denote the clip data type used for remote input transport */
-    public static final String RESULTS_CLIP_LABEL = RemoteInputCompatJellybean.RESULTS_CLIP_LABEL;
+    public static final String RESULTS_CLIP_LABEL = "android.remoteinput.results";
 
     /** Extra added to a clip data intent object to hold the text results bundle. */
     public static final String EXTRA_RESULTS_DATA = "android.remoteinput.resultsData";
diff --git a/compat/java/android/support/v4/app/ServiceCompat.java b/compat/java/android/support/v4/app/ServiceCompat.java
index e4d7cdf..1676ee8 100644
--- a/compat/java/android/support/v4/app/ServiceCompat.java
+++ b/compat/java/android/support/v4/app/ServiceCompat.java
@@ -28,7 +28,7 @@
 import java.lang.annotation.RetentionPolicy;
 
 /**
- * Helper for accessing features in {@link android.app.Service} in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.app.Service}.
  */
 public final class ServiceCompat {
 
diff --git a/compat/java/android/support/v4/content/ContextCompat.java b/compat/java/android/support/v4/content/ContextCompat.java
index 2790234..fdbe32f 100644
--- a/compat/java/android/support/v4/content/ContextCompat.java
+++ b/compat/java/android/support/v4/content/ContextCompat.java
@@ -30,7 +30,6 @@
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.v4.app.ActivityOptionsCompat;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.os.EnvironmentCompat;
 import android.util.Log;
 import android.util.TypedValue;
@@ -38,8 +37,7 @@
 import java.io.File;
 
 /**
- * Helper for accessing features in {@link android.content.Context}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.Context}.
  */
 public class ContextCompat {
     private static final String TAG = "ContextCompat";
@@ -557,7 +555,7 @@
      * @see Context#startService()
      */
     public static void startForegroundService(Context context, Intent intent) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             context.startForegroundService(intent);
         } else {
             // Pre-O behavior.
diff --git a/compat/java/android/support/v4/content/IntentCompat.java b/compat/java/android/support/v4/content/IntentCompat.java
index 387274e..cf6b012 100644
--- a/compat/java/android/support/v4/content/IntentCompat.java
+++ b/compat/java/android/support/v4/content/IntentCompat.java
@@ -23,8 +23,7 @@
 import android.support.annotation.RequiresApi;
 
 /**
- * Helper for accessing features in {@link android.content.Intent}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.Intent}.
  */
 public final class IntentCompat {
 
diff --git a/compat/java/android/support/v4/content/ParallelExecutorCompat.java b/compat/java/android/support/v4/content/ParallelExecutorCompat.java
index 19a6988..4dc4168 100644
--- a/compat/java/android/support/v4/content/ParallelExecutorCompat.java
+++ b/compat/java/android/support/v4/content/ParallelExecutorCompat.java
@@ -21,8 +21,7 @@
 import java.util.concurrent.Executor;
 
 /**
- * Helper for accessing a shared parallel Executor instance
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing a shared parallel Executor instance.
  *
  * @deprecated Use {@link AsyncTask} directly.
  */
diff --git a/compat/java/android/support/v4/content/pm/ActivityInfoCompat.java b/compat/java/android/support/v4/content/pm/ActivityInfoCompat.java
index 4014404..61bed07 100644
--- a/compat/java/android/support/v4/content/pm/ActivityInfoCompat.java
+++ b/compat/java/android/support/v4/content/pm/ActivityInfoCompat.java
@@ -17,8 +17,7 @@
 package android.support.v4.content.pm;
 
 /**
- * Helper for accessing features in {@link android.content.pm.ActivityInfo}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.pm.ActivityInfo}.
  */
 public final class ActivityInfoCompat {
 
diff --git a/compat/java/android/support/v4/content/pm/ShortcutInfoCompat.java b/compat/java/android/support/v4/content/pm/ShortcutInfoCompat.java
index f761339..eb892c6 100644
--- a/compat/java/android/support/v4/content/pm/ShortcutInfoCompat.java
+++ b/compat/java/android/support/v4/content/pm/ShortcutInfoCompat.java
@@ -30,8 +30,7 @@
 import java.util.Arrays;
 
 /**
- * Helper for accessing features in {@link android.content.pm.ShortcutInfo}
- * introduced after API level 25 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.pm.ShortcutInfo}.
  */
 public class ShortcutInfoCompat {
 
diff --git a/compat/java/android/support/v4/content/pm/ShortcutManagerCompat.java b/compat/java/android/support/v4/content/pm/ShortcutManagerCompat.java
index ecc9344..189e51d 100644
--- a/compat/java/android/support/v4/content/pm/ShortcutManagerCompat.java
+++ b/compat/java/android/support/v4/content/pm/ShortcutManagerCompat.java
@@ -24,16 +24,15 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.pm.ShortcutManager;
+import android.os.Build;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.VisibleForTesting;
 import android.support.v4.content.ContextCompat;
-import android.support.v4.os.BuildCompat;
 import android.text.TextUtils;
 
 /**
- * Helper for accessing features in {@link android.content.pm.ShortcutManager}
- * in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.pm.ShortcutManager}.
  */
 public class ShortcutManagerCompat {
 
@@ -51,7 +50,7 @@
      * {@code false} otherwise
      */
     public static boolean isRequestPinShortcutSupported(@NonNull Context context) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return context.getSystemService(ShortcutManager.class).isRequestPinShortcutSupported();
         }
 
@@ -88,7 +87,7 @@
      */
     public static boolean requestPinShortcut(@NonNull final Context context,
             @NonNull ShortcutInfoCompat shortcut, @Nullable final IntentSender callback) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return context.getSystemService(ShortcutManager.class).requestPinShortcut(
                     shortcut.toShortcutInfo(), callback);
         }
@@ -132,7 +131,7 @@
     public static Intent createShortcutResultIntent(@NonNull Context context,
             @NonNull ShortcutInfoCompat shortcut) {
         Intent result = null;
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             result = context.getSystemService(ShortcutManager.class)
                     .createShortcutResultIntent(shortcut.toShortcutInfo());
         }
diff --git a/compat/java/android/support/v4/content/res/FontResourcesParserCompat.java b/compat/java/android/support/v4/content/res/FontResourcesParserCompat.java
index 8f12146..7fe86ad 100644
--- a/compat/java/android/support/v4/content/res/FontResourcesParserCompat.java
+++ b/compat/java/android/support/v4/content/res/FontResourcesParserCompat.java
@@ -99,16 +99,23 @@
      * A class that represents a font element in an xml file which points to a file in resources.
      */
     public static final class FontFileResourceEntry {
+        private final @NonNull String mFileName;
         private int mWeight;
         private boolean mItalic;
         private int mResourceId;
 
-        public FontFileResourceEntry(int weight, boolean italic, int resourceId) {
+        public FontFileResourceEntry(@NonNull String fileName, int weight, boolean italic,
+                int resourceId) {
+            mFileName = fileName;
             mWeight = weight;
             mItalic = italic;
             mResourceId = resourceId;
         }
 
+        public @NonNull String getFileName() {
+            return mFileName;
+        }
+
         public int getWeight() {
             return mWeight;
         }
@@ -228,6 +235,7 @@
                     certs.add(certsList);
                 }
             }
+            typedArray.recycle();
         }
         return certs != null ?  certs : Collections.<List<byte[]>>emptyList();
     }
@@ -247,11 +255,12 @@
         int weight = array.getInt(R.styleable.FontFamilyFont_fontWeight, NORMAL_WEIGHT);
         boolean isItalic = ITALIC == array.getInt(R.styleable.FontFamilyFont_fontStyle, 0);
         int resourceId = array.getResourceId(R.styleable.FontFamilyFont_font, 0);
+        String filename = array.getString(R.styleable.FontFamilyFont_font);
         array.recycle();
         while (parser.next() != XmlPullParser.END_TAG) {
             skip(parser);
         }
-        return new FontFileResourceEntry(weight, isItalic, resourceId);
+        return new FontFileResourceEntry(filename, weight, isItalic, resourceId);
     }
 
     private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
diff --git a/compat/java/android/support/v4/content/res/ResourcesCompat.java b/compat/java/android/support/v4/content/res/ResourcesCompat.java
index 526b79b..43d78d0 100644
--- a/compat/java/android/support/v4/content/res/ResourcesCompat.java
+++ b/compat/java/android/support/v4/content/res/ResourcesCompat.java
@@ -27,7 +27,6 @@
 import android.content.res.XmlResourceParser;
 import android.graphics.Typeface;
 import android.graphics.drawable.Drawable;
-import android.os.Build;
 import android.support.annotation.ColorInt;
 import android.support.annotation.ColorRes;
 import android.support.annotation.DrawableRes;
@@ -46,8 +45,7 @@
 import java.io.IOException;
 
 /**
- * Helper for accessing features in {@link android.content.res.Resources}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.content.res.Resources}.
  */
 public final class ResourcesCompat {
     private static final String TAG = "ResourcesCompat";
@@ -195,10 +193,6 @@
         if (context.isRestricted()) {
             return null;
         }
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
-            // Use framework support.
-            return context.getResources().getFont(id);
-        }
         return loadFont(context, id, new TypedValue(), Typeface.NORMAL, null);
     }
 
@@ -255,7 +249,7 @@
                 return TypefaceCompat.createFromResourcesFamilyXml(
                         context, familyEntry, wrapper, id, style, targetView);
             }
-            return TypefaceCompat.createFromResourcesFontFile(context, wrapper, id, style);
+            return TypefaceCompat.createFromResourcesFontFile(context, wrapper, id, file, style);
         } catch (XmlPullParserException e) {
             Log.e(TAG, "Failed to parse xml resource " + file, e);
         } catch (IOException e) {
diff --git a/compat/java/android/support/v4/database/DatabaseUtilsCompat.java b/compat/java/android/support/v4/database/DatabaseUtilsCompat.java
index dd53ced..f3d3077 100644
--- a/compat/java/android/support/v4/database/DatabaseUtilsCompat.java
+++ b/compat/java/android/support/v4/database/DatabaseUtilsCompat.java
@@ -19,8 +19,7 @@
 import android.text.TextUtils;
 
 /**
- * Helper for accessing features in {@link android.database.DatabaseUtils}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.database.DatabaseUtils}.
  */
 public final class DatabaseUtilsCompat {
 
diff --git a/compat/java/android/support/v4/graphics/BitmapCompat.java b/compat/java/android/support/v4/graphics/BitmapCompat.java
index f417938..20caf80 100644
--- a/compat/java/android/support/v4/graphics/BitmapCompat.java
+++ b/compat/java/android/support/v4/graphics/BitmapCompat.java
@@ -15,13 +15,12 @@
  */
 package android.support.v4.graphics;
 
-import android.support.annotation.RequiresApi;
 import android.graphics.Bitmap;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 
 /**
- * Helper for accessing features in {@link android.graphics.Bitmap}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.graphics.Bitmap}.
  */
 public final class BitmapCompat {
     static class BitmapCompatBaseImpl {
diff --git a/compat/java/android/support/v4/graphics/PaintCompat.java b/compat/java/android/support/v4/graphics/PaintCompat.java
index 2bc676c..95eee0c 100644
--- a/compat/java/android/support/v4/graphics/PaintCompat.java
+++ b/compat/java/android/support/v4/graphics/PaintCompat.java
@@ -21,7 +21,7 @@
 import android.support.annotation.NonNull;
 
 /**
- * Helper for accessing features in {@link Paint} in a backwards compatible fashion.
+ * Helper for accessing features in {@link Paint}.
  */
 public final class PaintCompat {
 
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompat.java b/compat/java/android/support/v4/graphics/TypefaceCompat.java
index f65d585..6d114b6 100644
--- a/compat/java/android/support/v4/graphics/TypefaceCompat.java
+++ b/compat/java/android/support/v4/graphics/TypefaceCompat.java
@@ -21,8 +21,8 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Typeface;
-import android.net.Uri;
 import android.os.Build;
+import android.os.CancellationSignal;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RestrictTo;
@@ -32,15 +32,10 @@
 import android.support.v4.provider.FontsContractCompat;
 import android.support.v4.provider.FontsContractCompat.FontInfo;
 import android.support.v4.util.LruCache;
-import android.util.Log;
 import android.widget.TextView;
 
-import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.Map;
-
 /**
- * Helper for accessing features in {@link Typeface} in a backwards compatible fashion.
+ * Helper for accessing features in {@link Typeface}.
  * @hide
  */
 @RestrictTo(LIBRARY_GROUP)
@@ -49,16 +44,15 @@
 
     private static final TypefaceCompatImpl sTypefaceCompatImpl;
     static {
-        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
-            sTypefaceCompatImpl = new TypefaceCompatBaseImpl();
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            sTypefaceCompatImpl = new TypefaceCompatApi26Impl();
+        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
+                && TypefaceCompatApi24Impl.isUsable()) {
+            sTypefaceCompatImpl = new TypefaceCompatApi24Impl();
+        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+            sTypefaceCompatImpl = new TypefaceCompatApi21Impl();
         } else {
-            if (!TypefaceCompatApi24Impl.isUsable()) {
-                Log.w(TAG, "Unable to collect necessary private methods."
-                        + "Fallback to legacy implementation.");
-                sTypefaceCompatImpl = new TypefaceCompatBaseImpl();
-            } else {
-                sTypefaceCompatImpl = new TypefaceCompatApi24Impl();
-            }
+            sTypefaceCompatImpl = new TypefaceCompatBaseImpl();
         }
     }
 
@@ -73,8 +67,12 @@
                 Context context, FontFamilyFilesResourceEntry entry, Resources resources,
                 int style);
 
-        Typeface createTypeface(Context context, @NonNull FontInfo[] fonts,
-                Map<Uri, ByteBuffer> uriBuffer);
+        Typeface createFromFontInfo(Context context,
+                @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts,
+                int style);
+
+        Typeface createFromResourcesFontFile(
+                Context context, Resources resources, int id, String path, int style);
     }
 
     private TypefaceCompat() {}
@@ -93,7 +91,7 @@
      *
      * @param resources Resources instance
      * @param id a resource id
-     * @param a style to be used for this resource, -1 if not availbale.
+     * @param style style to be used for this resource, -1 if not available.
      * @return Unique id for a given resource and id.
      */
     private static String createResourceUid(final Resources resources, int id, int style) {
@@ -129,35 +127,20 @@
      */
     @Nullable
     public static Typeface createFromResourcesFontFile(
-            Context context, Resources resources, int id, int style) {
-        final File tmpFile = TypefaceCompatUtil.getTempFile(context);
-        if (tmpFile == null) {
-            return null;
+            Context context, Resources resources, int id, String path, int style) {
+        Typeface typeface = sTypefaceCompatImpl.createFromResourcesFontFile(
+                context, resources, id, path, style);
+        if (typeface != null) {
+            sTypefaceCache.put(createResourceUid(resources, id, style), typeface);
         }
-        try {
-            if (!TypefaceCompatUtil.copyToFile(tmpFile, resources, id)) {
-                return null;
-            }
-            Typeface typeface = Typeface.createFromFile(tmpFile.getPath());
-            if (typeface != null) {
-                sTypefaceCache.put(createResourceUid(resources, id, style), typeface);
-            }
-            return typeface;
-        } catch (RuntimeException e) {
-            // This was thrown from Typeface.createFromFile when a Typeface could not be loaded.
-            // such as due to an invalid ttf or unreadable file. We don't want to throw that
-            // exception anymore.
-            return null;
-        } finally {
-            tmpFile.delete();
-        }
+        return typeface;
     }
 
     /**
      * Create a Typeface from a given FontInfo list and a map that matches them to ByteBuffers.
      */
-    public static Typeface createTypeface(Context context, @NonNull FontInfo[] fonts,
-            Map<Uri, ByteBuffer> uriBuffer) {
-        return sTypefaceCompatImpl.createTypeface(context, fonts, uriBuffer);
+    public static Typeface createFromFontInfo(Context context,
+            @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts, int style) {
+        return sTypefaceCompatImpl.createFromFontInfo(context, cancellationSignal, fonts, style);
     }
 }
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompatApi21Impl.java b/compat/java/android/support/v4/graphics/TypefaceCompatApi21Impl.java
new file mode 100644
index 0000000..a742004
--- /dev/null
+++ b/compat/java/android/support/v4/graphics/TypefaceCompatApi21Impl.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.graphics;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.graphics.Typeface;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
+import android.support.annotation.NonNull;
+import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
+import android.support.v4.provider.FontsContractCompat.FontInfo;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+
+/**
+ * Implementation of the Typeface compat methods for API 21 and above.
+ * @hide
+ */
+@RestrictTo(LIBRARY_GROUP)
+@RequiresApi(21)
+class TypefaceCompatApi21Impl extends TypefaceCompatBaseImpl {
+    private static final String TAG = "TypefaceCompatApi21Impl";
+
+    private File getFile(ParcelFileDescriptor fd) {
+        try {
+            final String path = Os.readlink("/proc/self/fd/" + fd.getFd());
+            // Check if the symbolic link points the regular file.
+            if (OsConstants.S_ISREG(Os.stat(path).st_mode)) {
+                return new File(path);
+            } else {
+                return null;
+            }
+        } catch (ErrnoException e) {
+            return null;  // Mostly permission error.
+        }
+    }
+
+    @Override
+    public Typeface createFromFontInfo(Context context, CancellationSignal cancellationSignal,
+            @NonNull FontInfo[] fonts, int style) {
+        if (fonts.length < 1) {
+            return null;
+        }
+        final FontInfo bestFont = findBestInfo(fonts, style);
+        final ContentResolver resolver = context.getContentResolver();
+        try (ParcelFileDescriptor pfd =
+                     resolver.openFileDescriptor(bestFont.getUri(), "r", cancellationSignal)) {
+            final File file = getFile(pfd);
+            if (file == null || !file.canRead()) {
+                // Unable to use the real file for creating Typeface. Fallback to copying
+                // implementation.
+                try (FileInputStream fis = new FileInputStream(pfd.getFileDescriptor())) {
+                    return super.createFromInputStream(context, fis);
+                }
+            }
+            return Typeface.createFromFile(file);
+        } catch (IOException e) {
+            return null;
+        }
+    }
+}
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompatApi24Impl.java b/compat/java/android/support/v4/graphics/TypefaceCompatApi24Impl.java
index 9bf0858..c64e0c3 100644
--- a/compat/java/android/support/v4/graphics/TypefaceCompatApi24Impl.java
+++ b/compat/java/android/support/v4/graphics/TypefaceCompatApi24Impl.java
@@ -22,12 +22,15 @@
 import android.content.res.Resources;
 import android.graphics.Typeface;
 import android.net.Uri;
+import android.os.CancellationSignal;
 import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.support.v4.content.res.FontResourcesParserCompat.FontFamilyFilesResourceEntry;
 import android.support.v4.content.res.FontResourcesParserCompat.FontFileResourceEntry;
 import android.support.v4.provider.FontsContractCompat.FontInfo;
+import android.support.v4.util.SimpleArrayMap;
 import android.util.Log;
 
 import java.lang.reflect.Array;
@@ -36,7 +39,6 @@
 import java.lang.reflect.Method;
 import java.nio.ByteBuffer;
 import java.util.List;
-import java.util.Map;
 
 
 /**
@@ -45,7 +47,7 @@
  */
 @RestrictTo(LIBRARY_GROUP)
 @RequiresApi(24)
-class TypefaceCompatApi24Impl implements TypefaceCompat.TypefaceCompatImpl {
+class TypefaceCompatApi24Impl extends TypefaceCompatBaseImpl {
     private static final String TAG = "TypefaceCompatApi24Impl";
 
     private static final String FONT_FAMILY_CLASS = "android.graphics.FontFamily";
@@ -88,6 +90,10 @@
      * Returns true if API24 implementation is usable.
      */
     public static boolean isUsable() {
+        if (sAddFontWeightStyle == null) {
+            Log.w(TAG, "Unable to collect necessary private methods."
+                    + "Fallback to legacy implementation.");
+        }
         return sAddFontWeightStyle != null;
     }
 
@@ -122,12 +128,20 @@
     }
 
     @Override
-    public Typeface createTypeface(Context context, @NonNull FontInfo[] fonts,
-            Map<Uri, ByteBuffer> uriBuffer) {
+    public Typeface createFromFontInfo(Context context,
+            @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts, int style) {
         Object family = newFamily();
+        SimpleArrayMap<Uri, ByteBuffer> bufferCache = new SimpleArrayMap<>();
+
         for (final FontInfo font : fonts) {
-            if (!addFontWeightStyle(family, uriBuffer.get(font.getUri()), font.getTtcIndex(),
-                    font.getWeight(), font.isItalic())) {
+            final Uri uri = font.getUri();
+            ByteBuffer buffer = bufferCache.get(uri);
+            if (buffer == null) {
+                buffer = TypefaceCompatUtil.mmap(context, cancellationSignal, uri);
+                bufferCache.put(uri, buffer);
+            }
+            if (!addFontWeightStyle(family, buffer, font.getTtcIndex(), font.getWeight(),
+                    font.isItalic())) {
                 return null;
             }
         }
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompatApi26Impl.java b/compat/java/android/support/v4/graphics/TypefaceCompatApi26Impl.java
new file mode 100644
index 0000000..b217c00
--- /dev/null
+++ b/compat/java/android/support/v4/graphics/TypefaceCompatApi26Impl.java
@@ -0,0 +1,301 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.graphics;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.AssetManager;
+import android.content.res.Resources;
+import android.graphics.Typeface;
+import android.graphics.fonts.FontVariationAxis;
+import android.net.Uri;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
+import android.support.v4.content.res.FontResourcesParserCompat;
+import android.support.v4.content.res.FontResourcesParserCompat.FontFileResourceEntry;
+import android.support.v4.provider.FontsContractCompat;
+import android.util.Log;
+
+import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
+import java.util.Map;
+
+/**
+ * Implementation of the Typeface compat methods for API 26 and above.
+ * @hide
+ */
+@RestrictTo(LIBRARY_GROUP)
+@RequiresApi(26)
+public class TypefaceCompatApi26Impl extends TypefaceCompatApi21Impl {
+    private static final String TAG = "TypefaceCompatApi26Impl";
+
+    private static final String FONT_FAMILY_CLASS = "android.graphics.FontFamily";
+    private static final String ADD_FONT_FROM_ASSET_MANAGER_METHOD = "addFontFromAssetManager";
+    private static final String ADD_FONT_FROM_BUFFER_METHOD = "addFontFromBuffer";
+    private static final String CREATE_FROM_FAMILIES_WITH_DEFAULT_METHOD =
+            "createFromFamiliesWithDefault";
+    private static final String FREEZE_METHOD = "freeze";
+    private static final String ABORT_CREATION_METHOD = "abortCreation";
+    private static final Class sFontFamily;
+    private static final Constructor sFontFamilyCtor;
+    private static final Method sAddFontFromAssetManager;
+    private static final Method sAddFontFromBuffer;
+    private static final Method sFreeze;
+    private static final Method sAbortCreation;
+    private static final Method sCreateFromFamiliesWithDefault;
+    private static final int RESOLVE_BY_FONT_TABLE = -1;
+
+    static {
+        Class fontFamilyClass;
+        Constructor fontFamilyCtor;
+        Method addFontMethod;
+        Method addFromBufferMethod;
+        Method freezeMethod;
+        Method abortCreationMethod;
+        Method createFromFamiliesWithDefaultMethod;
+        try {
+            fontFamilyClass = Class.forName(FONT_FAMILY_CLASS);
+            fontFamilyCtor = fontFamilyClass.getConstructor();
+            addFontMethod = fontFamilyClass.getMethod(ADD_FONT_FROM_ASSET_MANAGER_METHOD,
+                    AssetManager.class, String.class, Integer.TYPE, Boolean.TYPE, Integer.TYPE,
+                    Integer.TYPE, Integer.TYPE, FontVariationAxis[].class);
+            addFromBufferMethod = fontFamilyClass.getMethod(ADD_FONT_FROM_BUFFER_METHOD,
+                    ByteBuffer.class, Integer.TYPE, FontVariationAxis[].class, Integer.TYPE,
+                    Integer.TYPE);
+            freezeMethod = fontFamilyClass.getMethod(FREEZE_METHOD);
+            abortCreationMethod = fontFamilyClass.getMethod(ABORT_CREATION_METHOD);
+            Object familyArray = Array.newInstance(fontFamilyClass, 1);
+            createFromFamiliesWithDefaultMethod =
+                    Typeface.class.getDeclaredMethod(CREATE_FROM_FAMILIES_WITH_DEFAULT_METHOD,
+                            familyArray.getClass(), Integer.TYPE, Integer.TYPE);
+            createFromFamiliesWithDefaultMethod.setAccessible(true);
+        } catch (ClassNotFoundException | NoSuchMethodException e) {
+            Log.e(TAG, "Unable to collect necessary methods for class " + e.getClass().getName(),
+                    e);
+            fontFamilyClass = null;
+            fontFamilyCtor = null;
+            addFontMethod = null;
+            addFromBufferMethod = null;
+            freezeMethod = null;
+            abortCreationMethod = null;
+            createFromFamiliesWithDefaultMethod = null;
+        }
+        sFontFamilyCtor = fontFamilyCtor;
+        sFontFamily = fontFamilyClass;
+        sAddFontFromAssetManager = addFontMethod;
+        sAddFontFromBuffer = addFromBufferMethod;
+        sFreeze = freezeMethod;
+        sAbortCreation = abortCreationMethod;
+        sCreateFromFamiliesWithDefault = createFromFamiliesWithDefaultMethod;
+    }
+
+    /**
+     * Returns true if API26 implementation is usable.
+     */
+    private static boolean isFontFamilyPrivateAPIAvailable() {
+        if (sAddFontFromAssetManager == null) {
+            Log.w(TAG, "Unable to collect necessary private methods."
+                    + "Fallback to legacy implementation.");
+        }
+        return sAddFontFromAssetManager != null;
+    }
+
+    /**
+     * Create a new FontFamily instance
+     */
+    private static Object newFamily() {
+        try {
+            return sFontFamilyCtor.newInstance();
+        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Call FontFamily#addFontFromAssetManager(AssetManager mgr, String path, int cookie,
+     *      boolean isAsset, int ttcIndex, int weight, int isItalic, FontVariationAxis[] axes)
+     */
+    private static boolean addFontFromAssetManager(Context context, Object family, String fileName,
+            int ttcIndex, int weight, int style) {
+        try {
+            final Boolean result = (Boolean) sAddFontFromAssetManager.invoke(family,
+                    context.getAssets(), fileName, 0 /* cookie */, false /* isAsset */, ttcIndex,
+                    weight, style, null /* axes */);
+            return result.booleanValue();
+        } catch (IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Call FontFamily#addFontFromBuffer(ByteBuffer font, int ttcIndex, FontVariationAxis[] axes,
+     *      int weight, int italic)
+     */
+    private static boolean addFontFromBuffer(Object family, ByteBuffer buffer,
+            int ttcIndex, int weight, int style) {
+        try {
+            final Boolean result = (Boolean) sAddFontFromBuffer.invoke(family,
+                    buffer, ttcIndex, null /* axes */, weight, style);
+            return result.booleanValue();
+        } catch (IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Call static method Typeface#createFromFamiliesWithDefault(
+     *      FontFamily[] families, int weight, int italic)
+     */
+    private static Typeface createFromFamiliesWithDefault(Object family) {
+        try {
+            Object familyArray = Array.newInstance(sFontFamily, 1);
+            Array.set(familyArray, 0, family);
+            return (Typeface) sCreateFromFamiliesWithDefault.invoke(null /* static method */,
+                    familyArray, RESOLVE_BY_FONT_TABLE, RESOLVE_BY_FONT_TABLE);
+        } catch (IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Call FontFamily#freeze()
+     */
+    private static boolean freeze(Object family) {
+        try {
+            Boolean result = (Boolean) sFreeze.invoke(family);
+            return result.booleanValue();
+        } catch (IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Call FontFamily#abortCreation()
+     */
+    private static boolean abortCreation(Object family) {
+        try {
+            Boolean result = (Boolean) sAbortCreation.invoke(family);
+            return result.booleanValue();
+        } catch (IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public Typeface createFromFontFamilyFilesResourceEntry(Context context,
+            FontResourcesParserCompat.FontFamilyFilesResourceEntry entry, Resources resources,
+            int style) {
+        if (!isFontFamilyPrivateAPIAvailable()) {
+            return super.createFromFontFamilyFilesResourceEntry(context, entry, resources, style);
+        }
+        Object fontFamily = newFamily();
+        for (final FontFileResourceEntry fontFile : entry.getEntries()) {
+            // TODO: Add ttc and variation font support. (b/37853920)
+            if (!addFontFromAssetManager(context, fontFamily, fontFile.getFileName(),
+                    0 /* ttcIndex */, fontFile.getWeight(), fontFile.isItalic() ? 1 : 0)) {
+                abortCreation(fontFamily);
+                return null;
+            }
+        }
+        if (!freeze(fontFamily)) {
+            return null;
+        }
+        return createFromFamiliesWithDefault(fontFamily);
+    }
+
+    @Override
+    public Typeface createFromFontInfo(Context context,
+            @Nullable CancellationSignal cancellationSignal,
+            @NonNull FontsContractCompat.FontInfo[] fonts, int style) {
+        if (fonts.length < 1) {
+            return null;
+        }
+        if (!isFontFamilyPrivateAPIAvailable()) {
+            // Even if the private API is not avaiable, don't use API 21 implemenation and use
+            // public API to create Typeface from file descriptor.
+            final FontsContractCompat.FontInfo bestFont = findBestInfo(fonts, style);
+            final ContentResolver resolver = context.getContentResolver();
+            try (ParcelFileDescriptor pfd =
+                    resolver.openFileDescriptor(bestFont.getUri(), "r", cancellationSignal)) {
+                return new Typeface.Builder(pfd.getFileDescriptor())
+                        .setWeight(bestFont.getWeight())
+                        .setItalic(bestFont.isItalic())
+                        .build();
+            } catch (IOException e) {
+                return null;
+            }
+        }
+        Map<Uri, ByteBuffer> uriBuffer = FontsContractCompat.prepareFontData(
+                context, fonts, cancellationSignal);
+        final Object fontFamily = newFamily();
+        boolean atLeastOneFont = false;
+        for (FontsContractCompat.FontInfo font : fonts) {
+            final ByteBuffer fontBuffer = uriBuffer.get(font.getUri());
+            if (fontBuffer == null) {
+                continue;  // skip
+            }
+            final boolean success = addFontFromBuffer(fontFamily, fontBuffer,
+                    font.getTtcIndex(), font.getWeight(), font.isItalic() ? 1 : 0);
+            if (!success) {
+                abortCreation(fontFamily);
+                return null;
+            }
+            atLeastOneFont = true;
+        }
+        if (!atLeastOneFont) {
+            abortCreation(fontFamily);
+            return null;
+        }
+        if (!freeze(fontFamily)) {
+            return null;
+        }
+        return createFromFamiliesWithDefault(fontFamily);
+    }
+
+    /**
+     * Used by Resources to load a font resource of type font file.
+     */
+    @Nullable
+    @Override
+    public Typeface createFromResourcesFontFile(
+            Context context, Resources resources, int id, String path, int style) {
+        if (!isFontFamilyPrivateAPIAvailable()) {
+            super.createFromResourcesFontFile(context, resources, id, path, style);
+        }
+        Object fontFamily = newFamily();
+        if (!addFontFromAssetManager(context, fontFamily, path,
+                0 /* ttcIndex */, RESOLVE_BY_FONT_TABLE /* weight */,
+                RESOLVE_BY_FONT_TABLE /* italic */)) {
+            abortCreation(fontFamily);
+            return null;
+        }
+        if (!freeze(fontFamily)) {
+            return null;
+        }
+        return createFromFamiliesWithDefault(fontFamily);
+    }
+}
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompatBaseImpl.java b/compat/java/android/support/v4/graphics/TypefaceCompatBaseImpl.java
index 0dad80a..8cfbd5d 100644
--- a/compat/java/android/support/v4/graphics/TypefaceCompatBaseImpl.java
+++ b/compat/java/android/support/v4/graphics/TypefaceCompatBaseImpl.java
@@ -21,7 +21,7 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Typeface;
-import android.net.Uri;
+import android.os.CancellationSignal;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
@@ -31,8 +31,8 @@
 import android.support.v4.provider.FontsContractCompat.FontInfo;
 
 import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.Map;
+import java.io.IOException;
+import java.io.InputStream;
 
 /**
  * Implementation of the Typeface compat methods for API 14 and above.
@@ -44,22 +44,52 @@
     private static final String TAG = "TypefaceCompatBaseImpl";
     private static final String CACHE_FILE_PREFIX = "cached_font_";
 
-    @Override
-    public Typeface createTypeface(Context context, @NonNull FontInfo[] fonts,
-            Map<Uri, ByteBuffer> uriBuffer) {
-        // When we load from file, we can only load one font so just take the first one.
-        if (fonts.length < 1) {
-            return null;
+    private interface StyleExtractor<T> {
+        int getWeight(T t);
+        boolean isItalic(T t);
+    }
+
+    private static <T> T findBestFont(T[] fonts, int style, StyleExtractor<T> extractor) {
+        final int targetWeight = (style & Typeface.BOLD) == 0 ? 400 : 700;
+        final boolean isTargetItalic = (style & Typeface.ITALIC) != 0;
+
+        T best = null;
+        int bestScore = Integer.MAX_VALUE;  // smaller is better
+
+        for (final T font : fonts) {
+            final int score = (Math.abs(extractor.getWeight(font) - targetWeight) * 2)
+                    + (extractor.isItalic(font) == isTargetItalic ? 0 : 1);
+
+            if (best == null || bestScore > score) {
+                best = font;
+                bestScore = score;
+            }
         }
-        Typeface typeface = null;
-        FontInfo font = fonts[0];
-        ByteBuffer buffer = uriBuffer.get(font.getUri());
+        return best;
+    }
+
+    protected FontInfo findBestInfo(FontInfo[] fonts, int style) {
+        return findBestFont(fonts, style, new StyleExtractor<FontInfo>() {
+            @Override
+            public int getWeight(FontInfo info) {
+                return info.getWeight();
+            }
+
+            @Override
+            public boolean isItalic(FontInfo info) {
+                return info.isItalic();
+            }
+        });
+    }
+
+    // Caller must close the stream.
+    protected Typeface createFromInputStream(Context context, InputStream is) {
         final File tmpFile = TypefaceCompatUtil.getTempFile(context);
         if (tmpFile == null) {
             return null;
         }
         try {
-            if (!TypefaceCompatUtil.copyToFile(tmpFile, buffer)) {
+            if (!TypefaceCompatUtil.copyToFile(tmpFile, is)) {
                 return null;
             }
             return Typeface.createFromFile(tmpFile.getPath());
@@ -73,33 +103,74 @@
         }
     }
 
-    private FontFileResourceEntry findBestEntry(FontFamilyFilesResourceEntry entry,
-            int targetWeight, boolean isTargetItalic) {
-        FontFileResourceEntry bestEntry = null;
-        int bestScore = Integer.MAX_VALUE;  // smaller is better
-
-        for (final FontFileResourceEntry e : entry.getEntries()) {
-            final int score = (Math.abs(e.getWeight() - targetWeight) * 2)
-                    + (isTargetItalic == e.isItalic() ? 0 : 1);
-
-            if (bestEntry == null || bestScore > score) {
-                bestEntry = e;
-                bestScore = score;
-            }
+    @Override
+    public Typeface createFromFontInfo(Context context,
+            @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts, int style) {
+        // When we load from file, we can only load one font so just take the first one.
+        if (fonts.length < 1) {
+            return null;
         }
-        return bestEntry;
+        FontInfo font = findBestInfo(fonts, style);
+        InputStream is = null;
+        try {
+            is = context.getContentResolver().openInputStream(font.getUri());
+            return createFromInputStream(context, is);
+        } catch (IOException e) {
+            return null;
+        } finally {
+            TypefaceCompatUtil.closeQuietly(is);
+        }
+    }
+
+    private FontFileResourceEntry findBestEntry(FontFamilyFilesResourceEntry entry, int style) {
+        return findBestFont(entry.getEntries(), style, new StyleExtractor<FontFileResourceEntry>() {
+            @Override
+            public int getWeight(FontFileResourceEntry entry) {
+                return entry.getWeight();
+            }
+
+            @Override
+            public boolean isItalic(FontFileResourceEntry entry) {
+                return entry.isItalic();
+            }
+        });
     }
 
     @Nullable
     @Override
     public Typeface createFromFontFamilyFilesResourceEntry(Context context,
             FontFamilyFilesResourceEntry entry, Resources resources, int style) {
-        FontFileResourceEntry best = findBestEntry(
-                entry, ((style & Typeface.BOLD) == 0) ? 400 : 700, (style & Typeface.ITALIC) != 0);
+        FontFileResourceEntry best = findBestEntry(entry, style);
         if (best == null) {
             return null;
         }
         return TypefaceCompat.createFromResourcesFontFile(
-                context, resources, best.getResourceId(), style);
+                context, resources, best.getResourceId(), best.getFileName(), style);
+    }
+
+    /**
+     * Used by Resources to load a font resource of type font file.
+     */
+    @Nullable
+    @Override
+    public Typeface createFromResourcesFontFile(
+            Context context, Resources resources, int id, String path, int style) {
+        final File tmpFile = TypefaceCompatUtil.getTempFile(context);
+        if (tmpFile == null) {
+            return null;
+        }
+        try {
+            if (!TypefaceCompatUtil.copyToFile(tmpFile, resources, id)) {
+                return null;
+            }
+            return Typeface.createFromFile(tmpFile.getPath());
+        } catch (RuntimeException e) {
+            // This was thrown from Typeface.createFromFile when a Typeface could not be loaded.
+            // such as due to an invalid ttf or unreadable file. We don't want to throw that
+            // exception anymore.
+            return null;
+        } finally {
+            tmpFile.delete();
+        }
     }
 }
diff --git a/compat/java/android/support/v4/graphics/TypefaceCompatUtil.java b/compat/java/android/support/v4/graphics/TypefaceCompatUtil.java
index 5539c35..b7d4707 100644
--- a/compat/java/android/support/v4/graphics/TypefaceCompatUtil.java
+++ b/compat/java/android/support/v4/graphics/TypefaceCompatUtil.java
@@ -18,8 +18,12 @@
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
 
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.res.Resources;
+import android.net.Uri;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
@@ -39,7 +43,7 @@
  * @hide
  */
 @RestrictTo(LIBRARY_GROUP)
-class TypefaceCompatUtil {
+public class TypefaceCompatUtil {
     private static final String TAG = "TypefaceCompatUtil";
 
     private TypefaceCompatUtil() {}  // Do not instantiate.
@@ -81,6 +85,22 @@
     }
 
     /**
+     * Copy the file contents to the direct byte buffer.
+     */
+    @RequiresApi(19)
+    public static ByteBuffer mmap(Context context, CancellationSignal cancellationSignal, Uri uri) {
+        final ContentResolver resolver = context.getContentResolver();
+        try (ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r", cancellationSignal);
+                FileInputStream fis = new FileInputStream(pfd.getFileDescriptor())) {
+            FileChannel channel = fis.getChannel();
+            final long size = channel.size();
+            return channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
+        } catch (IOException e) {
+            return null;
+        }
+    }
+
+    /**
      * Copy the resource contents to the direct byte buffer.
      */
     @RequiresApi(19)
@@ -100,42 +120,6 @@
     }
 
     /**
-     * Helper class for reading ByteBuffer as InputStream.
-     */
-    private static class ByteBufferInputStream extends InputStream {
-        private ByteBuffer mBuf;
-
-        ByteBufferInputStream(ByteBuffer buf) {
-            mBuf = buf;
-        }
-
-        @Override
-        public int read() {
-            if (!mBuf.hasRemaining()) {
-                return -1;
-            }
-            return mBuf.get() & 0xFF;
-        }
-
-        @Override
-        public int read(byte[] bytes, int off, int len) {
-            if (!mBuf.hasRemaining()) {
-                return -1;
-            }
-            len = Math.min(len, mBuf.remaining());
-            mBuf.get(bytes, off, len);
-            return len;
-        }
-    }
-
-    /**
-     * Copy the buffer contents to file.
-     */
-    public static boolean copyToFile(File file, ByteBuffer buffer) {
-        return copyToFile(file, new ByteBufferInputStream(buffer));
-    }
-
-    /**
      * Copy the input stream contents to file.
      */
     public static boolean copyToFile(File file, InputStream is) {
diff --git a/compat/java/android/support/v4/graphics/drawable/DrawableCompat.java b/compat/java/android/support/v4/graphics/drawable/DrawableCompat.java
index d6ee9bc..79fb9c6 100644
--- a/compat/java/android/support/v4/graphics/drawable/DrawableCompat.java
+++ b/compat/java/android/support/v4/graphics/drawable/DrawableCompat.java
@@ -39,12 +39,11 @@
 import java.lang.reflect.Method;
 
 /**
- * Helper for accessing features in {@link android.graphics.drawable.Drawable}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.graphics.drawable.Drawable}.
  */
 public final class DrawableCompat {
     /**
-     * Interface implementation that doesn't use anything about v4 APIs.
+     * Interface implementation that doesn't use anything about platform-specific APIs.
      */
     static class DrawableCompatBaseImpl {
         public void jumpToCurrentState(Drawable drawable) {
diff --git a/compat/java/android/support/v4/graphics/drawable/IconCompat.java b/compat/java/android/support/v4/graphics/drawable/IconCompat.java
index c820366..d6ef5de 100644
--- a/compat/java/android/support/v4/graphics/drawable/IconCompat.java
+++ b/compat/java/android/support/v4/graphics/drawable/IconCompat.java
@@ -34,11 +34,9 @@
 import android.support.annotation.DrawableRes;
 import android.support.annotation.RestrictTo;
 import android.support.annotation.VisibleForTesting;
-import android.support.v4.os.BuildCompat;
 
 /**
- * Helper for accessing features in {@link android.graphics.drawable.Icon}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.graphics.drawable.Icon}.
  */
 public class IconCompat {
 
@@ -178,7 +176,6 @@
     /**
      * @hide
      */
-    @VisibleForTesting
     @RestrictTo(LIBRARY_GROUP)
     @TargetApi(Build.VERSION_CODES.O)
     public Icon toIcon() {
@@ -186,7 +183,7 @@
             case TYPE_BITMAP:
                 return Icon.createWithBitmap((Bitmap) mObj1);
             case TYPE_ADAPTIVE_BITMAP:
-                if (BuildCompat.isAtLeastO()) {
+                if (Build.VERSION.SDK_INT >= 26) {
                     return Icon.createWithAdaptiveBitmap((Bitmap) mObj1);
                 } else {
                     return Icon.createWithBitmap(createLegacyIconFromAdaptiveIcon((Bitmap) mObj1));
diff --git a/compat/java/android/support/v4/hardware/display/DisplayManagerCompat.java b/compat/java/android/support/v4/hardware/display/DisplayManagerCompat.java
index 17907ae..50d246b 100644
--- a/compat/java/android/support/v4/hardware/display/DisplayManagerCompat.java
+++ b/compat/java/android/support/v4/hardware/display/DisplayManagerCompat.java
@@ -26,8 +26,7 @@
 import java.util.WeakHashMap;
 
 /**
- * Helper for accessing features in {@link android.hardware.display.DisplayManager}
- * in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.hardware.display.DisplayManager}.
  */
 public abstract class DisplayManagerCompat {
     private static final WeakHashMap<Context, DisplayManagerCompat> sInstances =
diff --git a/compat/java/android/support/v4/net/ConnectivityManagerCompat.java b/compat/java/android/support/v4/net/ConnectivityManagerCompat.java
index 5c61193..5a39586 100644
--- a/compat/java/android/support/v4/net/ConnectivityManagerCompat.java
+++ b/compat/java/android/support/v4/net/ConnectivityManagerCompat.java
@@ -33,14 +33,14 @@
 import android.os.Build;
 import android.support.annotation.IntDef;
 import android.support.annotation.RequiresApi;
+import android.support.annotation.RequiresPermission;
 import android.support.annotation.RestrictTo;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
 /**
- * Helper for accessing features in {@link ConnectivityManager} introduced after
- * API level 16 in a backwards compatible fashion.
+ * Helper for accessing features in {@link ConnectivityManager}.
  */
 public final class ConnectivityManagerCompat {
 
@@ -162,6 +162,7 @@
      * @return {@code true} if large transfers should be avoided, otherwise
      *        {@code false}.
      */
+    @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
     public static boolean isActiveNetworkMetered(ConnectivityManager cm) {
         return IMPL.isActiveNetworkMetered(cm);
     }
diff --git a/compat/java/android/support/v4/net/TrafficStatsCompat.java b/compat/java/android/support/v4/net/TrafficStatsCompat.java
index a9cb423..1b62101 100644
--- a/compat/java/android/support/v4/net/TrafficStatsCompat.java
+++ b/compat/java/android/support/v4/net/TrafficStatsCompat.java
@@ -16,18 +16,17 @@
 
 package android.support.v4.net;
 
-import android.support.annotation.RequiresApi;
 import android.net.TrafficStats;
 import android.os.Build;
 import android.os.ParcelFileDescriptor;
+import android.support.annotation.RequiresApi;
 
 import java.net.DatagramSocket;
 import java.net.Socket;
 import java.net.SocketException;
 
 /**
- * Helper for accessing features in {@link TrafficStats} introduced after API level 14
- * in a backwards compatible fashion.
+ * Helper for accessing features in {@link TrafficStats}.
  */
 public final class TrafficStatsCompat {
     static class TrafficStatsCompatBaseImpl {
diff --git a/compat/java/android/support/v4/os/AsyncTaskCompat.java b/compat/java/android/support/v4/os/AsyncTaskCompat.java
index 0fb3c84..ebad879 100644
--- a/compat/java/android/support/v4/os/AsyncTaskCompat.java
+++ b/compat/java/android/support/v4/os/AsyncTaskCompat.java
@@ -21,8 +21,7 @@
 import java.util.concurrent.Executor;
 
 /**
- * Helper for accessing features in {@link android.os.AsyncTask}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.os.AsyncTask}.
  *
  * @deprecated Use {@link android.os.AsyncTask} directly.
  */
diff --git a/compat/java/android/support/v4/os/EnvironmentCompat.java b/compat/java/android/support/v4/os/EnvironmentCompat.java
index 90c8e15..3e9e7f9 100644
--- a/compat/java/android/support/v4/os/EnvironmentCompat.java
+++ b/compat/java/android/support/v4/os/EnvironmentCompat.java
@@ -24,7 +24,7 @@
 import java.io.IOException;
 
 /**
- * Helper for accessing features in {@link Environment} in a backwards compatible fashion.
+ * Helper for accessing features in {@link Environment}.
  */
 public final class EnvironmentCompat {
     private static final String TAG = "EnvironmentCompat";
diff --git a/compat/java/android/support/v4/os/LocaleHelper.java b/compat/java/android/support/v4/os/LocaleHelper.java
index 539106c..8b933b9 100644
--- a/compat/java/android/support/v4/os/LocaleHelper.java
+++ b/compat/java/android/support/v4/os/LocaleHelper.java
@@ -23,7 +23,7 @@
 import java.util.Locale;
 
 /**
- * Helper to deal with new {@link Locale} APIs in a backwards compatible fashion.
+ * Helper to deal with new {@link Locale} APIs.
  *
  * @hide
  */
@@ -62,7 +62,7 @@
         StringBuilder buf = new StringBuilder();
         buf.append(locale.getLanguage());
         final String country = locale.getCountry();
-        if (country != null && !country.equals("")) {
+        if (country != null && !country.isEmpty()) {
             buf.append("-");
             buf.append(locale.getCountry());
         }
diff --git a/compat/java/android/support/v4/os/LocaleListCompat.java b/compat/java/android/support/v4/os/LocaleListCompat.java
index 1185e98..9ccc35b 100644
--- a/compat/java/android/support/v4/os/LocaleListCompat.java
+++ b/compat/java/android/support/v4/os/LocaleListCompat.java
@@ -27,7 +27,7 @@
 import java.util.Locale;
 
 /**
- * Helper for accessing features in LocaleList in a backwards compatible fashion.
+ * Helper for accessing features in {@link LocaleList}.
  */
 public final class LocaleListCompat {
     static final LocaleListInterface IMPL;
@@ -285,7 +285,7 @@
      */
     @NonNull
     public static LocaleListCompat forLanguageTags(@Nullable String list) {
-        if (list == null || list.equals("")) {
+        if (list == null || list.isEmpty()) {
             return getEmptyLocaleList();
         } else {
             final String[] tags = list.split(",");
diff --git a/compat/java/android/support/v4/os/LocaleListHelper.java b/compat/java/android/support/v4/os/LocaleListHelper.java
index 133ecfe..cfb24fb 100644
--- a/compat/java/android/support/v4/os/LocaleListHelper.java
+++ b/compat/java/android/support/v4/os/LocaleListHelper.java
@@ -271,7 +271,7 @@
     @RestrictTo(LIBRARY_GROUP)
     @NonNull
     static LocaleListHelper forLanguageTags(@Nullable String list) {
-        if (list == null || list.equals("")) {
+        if (list == null || list.isEmpty()) {
             return getEmptyLocaleList();
         } else {
             final String[] tags = list.split(",");
diff --git a/compat/java/android/support/v4/os/ParcelableCompat.java b/compat/java/android/support/v4/os/ParcelableCompat.java
index 663da56..ee83122 100644
--- a/compat/java/android/support/v4/os/ParcelableCompat.java
+++ b/compat/java/android/support/v4/os/ParcelableCompat.java
@@ -20,7 +20,7 @@
 import android.os.Parcelable;
 
 /**
- * Helper for accessing features in {@link android.os.Parcelable} in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.os.Parcelable}.
  *
  * @deprecated Use {@link android.os.Parcelable.ClassLoaderCreator} directly.
  */
diff --git a/compat/java/android/support/v4/provider/FontsContractCompat.java b/compat/java/android/support/v4/provider/FontsContractCompat.java
index ba44019..6ad46a1 100644
--- a/compat/java/android/support/v4/provider/FontsContractCompat.java
+++ b/compat/java/android/support/v4/provider/FontsContractCompat.java
@@ -19,6 +19,7 @@
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
 import static android.support.v4.content.res.FontResourcesParserCompat.FetchStrategy;
 
+import android.annotation.SuppressLint;
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.Context;
@@ -41,22 +42,22 @@
 import android.support.annotation.IntRange;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.support.annotation.VisibleForTesting;
 import android.support.v4.content.res.FontResourcesParserCompat;
 import android.support.v4.graphics.TypefaceCompat;
+import android.support.v4.graphics.TypefaceCompatUtil;
 import android.support.v4.provider.SelfDestructiveThread.ReplyCallback;
 import android.support.v4.util.LruCache;
 import android.support.v4.util.Preconditions;
 import android.support.v4.util.SimpleArrayMap;
 import android.widget.TextView;
 
-import java.io.FileInputStream;
-import java.io.IOException;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.lang.ref.WeakReference;
 import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -178,7 +179,8 @@
             new SelfDestructiveThread("fonts", Process.THREAD_PRIORITY_BACKGROUND,
                     BACKGROUND_THREAD_KEEP_ALIVE_DURATION_MS);
 
-    private static Typeface getFontInternal(final Context context, final FontRequest request) {
+    private static Typeface getFontInternal(final Context context, final FontRequest request,
+            int style) {
         FontFamilyResult result;
         try {
             result = fetchFonts(context, null /* CancellationSignal */, request);
@@ -186,7 +188,8 @@
             return null;
         }
         if (result.getStatusCode() == FontFamilyResult.STATUS_OK) {
-            return buildTypeface(context, null /* CancellationSignal */, result.getFonts());
+            return TypefaceCompat.createFromFontInfo(context, null /* CancellationSignal */,
+                    result.getFonts(), style);
         }
         return null;
     }
@@ -199,8 +202,9 @@
     /** @hide */
     @RestrictTo(LIBRARY_GROUP)
     public static Typeface getFontSync(final Context context, final FontRequest request,
-            final TextView targetView, @FetchStrategy int strategy, int timeout, final int style) {
-        final String id = request.getIdentifier();
+            final @Nullable TextView targetView, @FetchStrategy int strategy, int timeout,
+            final int style) {
+        final String id = request.getIdentifier() + "-" + style;
         Typeface cached = sTypefaceCache.get(id);
         if (cached != null) {
             return cached;
@@ -211,13 +215,13 @@
 
         if (isBlockingFetch && timeout == FontResourcesParserCompat.INFINITE_TIMEOUT_VALUE) {
             // Wait forever. No need to post to the thread.
-            return getFontInternal(context, request);
+            return getFontInternal(context, request, style);
         }
 
         final Callable<Typeface> fetcher = new Callable<Typeface>() {
             @Override
             public Typeface call() throws Exception {
-                Typeface typeface = getFontInternal(context, request);
+                Typeface typeface = getFontInternal(context, request, style);
                 if (typeface != null) {
                     sTypefaceCache.put(id, typeface);
                 }
@@ -232,10 +236,14 @@
                 return null;
             }
         } else {
+            final WeakReference<TextView> textViewWeak = new WeakReference<TextView>(targetView);
             final ReplyCallback<Typeface> reply = new ReplyCallback<Typeface>() {
                 @Override
                 public void onReply(final Typeface typeface) {
-                    targetView.setTypeface(typeface, style);
+                    final TextView textView = textViewWeak.get();
+                    if (textView != null) {
+                        targetView.setTypeface(typeface, style);
+                    }
                 }
             };
 
@@ -581,55 +589,6 @@
     }
 
     /**
-     * A helper function to create a mapping from {@link Uri} to {@link ByteBuffer}.
-     *
-     * Skip if the file contents is not ready to be read.
-     *
-     * @param context A {@link Context} to be used for resolving content URI in
-     *                {@link FontInfo}.
-     * @param fonts An array of {@link FontInfo}.
-     * @return A map from {@link Uri} to {@link ByteBuffer}.
-     */
-    private static Map<Uri, ByteBuffer> prepareFontData(Context context, FontInfo[] fonts,
-            CancellationSignal cancellationSignal) {
-        final HashMap<Uri, ByteBuffer> out = new HashMap<>();
-        final ContentResolver resolver = context.getContentResolver();
-
-        for (FontInfo font : fonts) {
-            if (font.getResultCode() != Columns.RESULT_CODE_OK) {
-                continue;
-            }
-
-            final Uri uri = font.getUri();
-            if (out.containsKey(uri)) {
-                continue;
-            }
-
-            ByteBuffer buffer = null;
-            ParcelFileDescriptor pfd = null;
-            FileInputStream fis = null;
-            try {
-                if (Build.VERSION.SDK_INT > 19) {
-                    pfd = resolver.openFileDescriptor(uri, "r", cancellationSignal);
-                } else {
-                    pfd = resolver.openFileDescriptor(uri, "r");
-                }
-                fis = new FileInputStream(pfd.getFileDescriptor());
-                final FileChannel fileChannel = fis.getChannel();
-                final long size = fileChannel.size();
-                buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
-            } catch (IOException e) {
-                // ignore
-            }
-
-            // TODO: try other approach?, e.g. read all contents instead of mmap.
-
-            out.put(uri, buffer);
-        }
-        return Collections.unmodifiableMap(out);
-    }
-
-    /**
      * Build a Typeface from an array of {@link FontInfo}
      *
      * Results that are marked as not ready will be skipped.
@@ -643,9 +602,41 @@
      */
     public static Typeface buildTypeface(@NonNull Context context,
             @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts) {
-        final Map<Uri, ByteBuffer> uriBuffer =
-                prepareFontData(context, fonts, cancellationSignal);
-        return TypefaceCompat.createTypeface(context, fonts, uriBuffer);
+        return TypefaceCompat.createFromFontInfo(context, cancellationSignal, fonts,
+                Typeface.NORMAL);
+    }
+
+    /**
+     * A helper function to create a mapping from {@link Uri} to {@link ByteBuffer}.
+     *
+     * Skip if the file contents is not ready to be read.
+     *
+     * @param context A {@link Context} to be used for resolving content URI in
+     *                {@link FontInfo}.
+     * @param fonts An array of {@link FontInfo}.
+     * @return A map from {@link Uri} to {@link ByteBuffer}.
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @RequiresApi(19)
+    public static Map<Uri, ByteBuffer> prepareFontData(Context context, FontInfo[] fonts,
+            CancellationSignal cancellationSignal) {
+        final HashMap<Uri, ByteBuffer> out = new HashMap<>();
+
+        for (FontInfo font : fonts) {
+            if (font.getResultCode() != Columns.RESULT_CODE_OK) {
+                continue;
+            }
+
+            final Uri uri = font.getUri();
+            if (out.containsKey(uri)) {
+                continue;
+            }
+
+            ByteBuffer buffer = TypefaceCompatUtil.mmap(context, cancellationSignal, uri);
+            out.put(uri, buffer);
+        }
+        return Collections.unmodifiableMap(out);
     }
 
     /**
@@ -699,6 +690,8 @@
         }
 
         List<byte[]> signatures;
+        // We correctly check all signatures returned, as advised in the lint error.
+        @SuppressLint("PackageManagerGetSignatures")
         PackageInfo packageInfo = packageManager.getPackageInfo(info.packageName,
                 PackageManager.GET_SIGNATURES);
         signatures = convertToByteArrayList(packageInfo.signatures);
diff --git a/core-utils/java/android/support/v4/text/BidiFormatter.java b/compat/java/android/support/v4/text/BidiFormatter.java
similarity index 100%
rename from core-utils/java/android/support/v4/text/BidiFormatter.java
rename to compat/java/android/support/v4/text/BidiFormatter.java
diff --git a/compat/java/android/support/v4/text/util/LinkifyCompat.java b/compat/java/android/support/v4/text/util/LinkifyCompat.java
index d242780..23b3e49 100644
--- a/compat/java/android/support/v4/text/util/LinkifyCompat.java
+++ b/compat/java/android/support/v4/text/util/LinkifyCompat.java
@@ -18,6 +18,7 @@
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
 
+import android.os.Build;
 import android.support.annotation.IntDef;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
@@ -96,6 +97,9 @@
      *  @return True if at least one link is found and applied.
      */
     public static final boolean addLinks(@NonNull Spannable text, @LinkifyMask int mask) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return Linkify.addLinks(text, mask);
+        }
         if (mask == 0) {
             return false;
         }
@@ -157,6 +161,9 @@
      *  @return True if at least one link is found and applied.
      */
     public static final boolean addLinks(@NonNull TextView text, @LinkifyMask int mask) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return Linkify.addLinks(text, mask);
+        }
         if (mask == 0) {
             return false;
         }
@@ -197,6 +204,10 @@
      */
     public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
             @Nullable String scheme) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            Linkify.addLinks(text, pattern, scheme);
+            return;
+        }
         addLinks(text, pattern, scheme, null, null, null);
     }
 
@@ -217,6 +228,10 @@
     public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
             @Nullable String scheme, @Nullable MatchFilter matchFilter,
             @Nullable TransformFilter transformFilter) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            Linkify.addLinks(text, pattern, scheme, matchFilter, transformFilter);
+            return;
+        }
         addLinks(text, pattern, scheme, null, matchFilter, transformFilter);
     }
 
@@ -238,8 +253,12 @@
      *  @param transformFilter Filter to allow the client code to update the link found.
      */
     public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
-            @Nullable  String defaultScheme, @Nullable String[] schemes,
+            @Nullable String defaultScheme, @Nullable String[] schemes,
             @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            Linkify.addLinks(text, pattern, defaultScheme, schemes, matchFilter, transformFilter);
+            return;
+        }
         SpannableString spannable = SpannableString.valueOf(text.getText());
 
         boolean linksAdded = addLinks(spannable, pattern, defaultScheme, schemes, matchFilter,
@@ -261,6 +280,9 @@
      */
     public static final boolean addLinks(@NonNull Spannable text, @NonNull Pattern pattern,
             @Nullable String scheme) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return Linkify.addLinks(text, pattern, scheme);
+        }
         return addLinks(text, pattern, scheme, null, null, null);
     }
 
@@ -282,6 +304,9 @@
     public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern,
             @Nullable String scheme, @Nullable MatchFilter matchFilter,
             @Nullable TransformFilter transformFilter) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return Linkify.addLinks(spannable, pattern, scheme, matchFilter, transformFilter);
+        }
         return addLinks(spannable, pattern, scheme, null, matchFilter,
                 transformFilter);
     }
@@ -305,6 +330,10 @@
     public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern,
             @Nullable  String defaultScheme, @Nullable String[] schemes,
             @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return Linkify.addLinks(spannable, pattern, defaultScheme, schemes, matchFilter,
+                    transformFilter);
+        }
         final String[] schemesCopy;
         if (defaultScheme == null) defaultScheme = "";
         if (schemes == null || schemes.length < 1) {
diff --git a/compat/java/android/support/v4/util/DebugUtils.java b/compat/java/android/support/v4/util/DebugUtils.java
index 8937b7e..7e35afa 100644
--- a/compat/java/android/support/v4/util/DebugUtils.java
+++ b/compat/java/android/support/v4/util/DebugUtils.java
@@ -21,8 +21,7 @@
 import android.support.annotation.RestrictTo;
 
 /**
- * Helper for accessing features in {@link android.util.DebugUtils}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.util.DebugUtils}.
  *
  * @hide
  */
diff --git a/compat/java/android/support/v4/util/LogWriter.java b/compat/java/android/support/v4/util/LogWriter.java
index 2889f4d..0ab3298 100644
--- a/compat/java/android/support/v4/util/LogWriter.java
+++ b/compat/java/android/support/v4/util/LogWriter.java
@@ -24,8 +24,7 @@
 import java.io.Writer;
 
 /**
- * Helper for accessing features in {@link android.util.LogWriter}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.util.LogWriter}.
  *
  * @hide
  */
diff --git a/compat/java/android/support/v4/util/LruCache.java b/compat/java/android/support/v4/util/LruCache.java
index 524e985..944b354 100644
--- a/compat/java/android/support/v4/util/LruCache.java
+++ b/compat/java/android/support/v4/util/LruCache.java
@@ -17,6 +17,7 @@
 package android.support.v4.util;
 
 import java.util.LinkedHashMap;
+import java.util.Locale;
 import java.util.Map;
 
 /**
@@ -337,7 +338,7 @@
     @Override public synchronized final String toString() {
         int accesses = hitCount + missCount;
         int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;
-        return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
+        return String.format(Locale.US, "LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
                 maxSize, hitCount, missCount, hitPercent);
     }
 }
diff --git a/compat/java/android/support/v4/util/ObjectsCompat.java b/compat/java/android/support/v4/util/ObjectsCompat.java
new file mode 100644
index 0000000..4a4c844
--- /dev/null
+++ b/compat/java/android/support/v4/util/ObjectsCompat.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.util;
+
+import android.os.Build;
+import android.support.annotation.RequiresApi;
+
+import java.util.Objects;
+
+/**
+ * This class consists of static utility methods for operating on objects.
+ */
+public class ObjectsCompat {
+    private static final ImplBase IMPL;
+
+    static {
+        if (Build.VERSION.SDK_INT >= 19) {
+            IMPL = new ImplApi19();
+        } else {
+            IMPL = new ImplBase();
+        }
+    }
+
+    private ObjectsCompat() {
+        // Non-instantiable.
+    }
+
+    /**
+     * Returns {@code true} if the arguments are equal to each other
+     * and {@code false} otherwise.
+     * <p>
+     * Consequently, if both arguments are {@code null}, {@code true}
+     * is returned and if exactly one argument is {@code null}, {@code
+     * false} is returned. Otherwise, equality is determined by using
+     * the {@link Object#equals equals} method of the first
+     * argument.
+     *
+     * @param a an object
+     * @param b an object to be compared with {@code a} for equality
+     * @return {@code true} if the arguments are equal to each other
+     *         and {@code false} otherwise
+     * @see Object#equals(Object)
+     */
+    public static boolean equals(Object a, Object b) {
+        return IMPL.equals(a, b);
+    }
+
+    private static class ImplBase {
+        public boolean equals(Object a, Object b) {
+            return (a == b) || (a != null && a.equals(b));
+        }
+    }
+
+    @RequiresApi(19)
+    private static class ImplApi19 extends ImplBase {
+        @Override
+        public boolean equals(Object a, Object b) {
+            return Objects.equals(a, b);
+        }
+    }
+}
diff --git a/compat/java/android/support/v4/util/Preconditions.java b/compat/java/android/support/v4/util/Preconditions.java
index 9fbbbc3..711566a 100644
--- a/compat/java/android/support/v4/util/Preconditions.java
+++ b/compat/java/android/support/v4/util/Preconditions.java
@@ -22,6 +22,7 @@
 import android.text.TextUtils;
 
 import java.util.Collection;
+import java.util.Locale;
 
 /**
  * Simple static methods to be called at the start of your own methods to verify
@@ -281,11 +282,11 @@
             throw new IllegalArgumentException(valueName + " must not be NaN");
         } else if (value < lower) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%f, %f] (too low)", valueName, lower, upper));
         } else if (value > upper) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%f, %f] (too high)", valueName, lower, upper));
         }
 
@@ -308,11 +309,11 @@
             String valueName) {
         if (value < lower) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%d, %d] (too low)", valueName, lower, upper));
         } else if (value > upper) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%d, %d] (too high)", valueName, lower, upper));
         }
 
@@ -335,11 +336,11 @@
             String valueName) {
         if (value < lower) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%d, %d] (too low)", valueName, lower, upper));
         } else if (value > upper) {
             throw new IllegalArgumentException(
-                    String.format(
+                    String.format(Locale.US,
                             "%s is out of range of [%d, %d] (too high)", valueName, lower, upper));
         }
 
@@ -364,7 +365,7 @@
         for (int i = 0; i < value.length; ++i) {
             if (value[i] == null) {
                 throw new NullPointerException(
-                        String.format("%s[%d] must not be null", valueName, i));
+                        String.format(Locale.US, "%s[%d] must not be null", valueName, i));
             }
         }
 
@@ -392,7 +393,7 @@
         for (T elem : value) {
             if (elem == null) {
                 throw new NullPointerException(
-                        String.format("%s[%d] must not be null", valueName, ctr));
+                        String.format(Locale.US, "%s[%d] must not be null", valueName, ctr));
             }
             ++ctr;
         }
@@ -449,11 +450,11 @@
                 throw new IllegalArgumentException(valueName + "[" + i + "] must not be NaN");
             } else if (v < lower) {
                 throw new IllegalArgumentException(
-                        String.format("%s[%d] is out of range of [%f, %f] (too low)",
+                        String.format(Locale.US, "%s[%d] is out of range of [%f, %f] (too low)",
                                 valueName, i, lower, upper));
             } else if (v > upper) {
                 throw new IllegalArgumentException(
-                        String.format("%s[%d] is out of range of [%f, %f] (too high)",
+                        String.format(Locale.US, "%s[%d] is out of range of [%f, %f] (too high)",
                                 valueName, i, lower, upper));
             }
         }
diff --git a/compat/java/android/support/v4/util/TimeUtils.java b/compat/java/android/support/v4/util/TimeUtils.java
index 0174e3a..2d1ce53 100644
--- a/compat/java/android/support/v4/util/TimeUtils.java
+++ b/compat/java/android/support/v4/util/TimeUtils.java
@@ -23,8 +23,7 @@
 import java.io.PrintWriter;
 
 /**
- * Helper for accessing features in {@link android.util.TimeUtils}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.util.TimeUtils}.
  *
  * @hide
  */
diff --git a/compat/java/android/support/v4/view/AccessibilityDelegateCompat.java b/compat/java/android/support/v4/view/AccessibilityDelegateCompat.java
index 22c2590..66b2cef 100644
--- a/compat/java/android/support/v4/view/AccessibilityDelegateCompat.java
+++ b/compat/java/android/support/v4/view/AccessibilityDelegateCompat.java
@@ -29,8 +29,7 @@
 import android.view.accessibility.AccessibilityNodeProvider;
 
 /**
- * Helper for accessing {@link AccessibilityDelegate} introduced after
- * API level 4 in a backwards compatible fashion.
+ * Helper for accessing {@link AccessibilityDelegate}.
  * <p>
  * <strong>Note:</strong> On platform versions prior to
  * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
diff --git a/compat/java/android/support/v4/view/KeyEventCompat.java b/compat/java/android/support/v4/view/KeyEventCompat.java
index 03c668d..85fe686 100644
--- a/compat/java/android/support/v4/view/KeyEventCompat.java
+++ b/compat/java/android/support/v4/view/KeyEventCompat.java
@@ -20,8 +20,7 @@
 import android.view.View;
 
 /**
- * Helper for accessing features in {@link KeyEvent} introduced after
- * API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link KeyEvent}.
  *
  * @deprecated Use {@link KeyEvent} directly.
  */
diff --git a/compat/java/android/support/v4/view/LayoutInflaterCompat.java b/compat/java/android/support/v4/view/LayoutInflaterCompat.java
index 50f494b..0cb2969 100644
--- a/compat/java/android/support/v4/view/LayoutInflaterCompat.java
+++ b/compat/java/android/support/v4/view/LayoutInflaterCompat.java
@@ -28,8 +28,7 @@
 import java.lang.reflect.Field;
 
 /**
- * Helper for accessing features in {@link LayoutInflater}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link LayoutInflater}.
  */
 public final class LayoutInflaterCompat {
     private static final String TAG = "LayoutInflaterCompatHC";
diff --git a/compat/java/android/support/v4/view/MenuCompat.java b/compat/java/android/support/v4/view/MenuCompat.java
index 4f0890a..bbac379 100644
--- a/compat/java/android/support/v4/view/MenuCompat.java
+++ b/compat/java/android/support/v4/view/MenuCompat.java
@@ -19,8 +19,7 @@
 import android.view.MenuItem;
 
 /**
- * Helper for accessing features in {@link android.view.Menu}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.view.Menu}.
  */
 public final class MenuCompat {
     /**
diff --git a/compat/java/android/support/v4/view/MenuItemCompat.java b/compat/java/android/support/v4/view/MenuItemCompat.java
index 649c413..bbbc2e5 100644
--- a/compat/java/android/support/v4/view/MenuItemCompat.java
+++ b/compat/java/android/support/v4/view/MenuItemCompat.java
@@ -19,9 +19,9 @@
 import android.content.res.ColorStateList;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.Drawable;
+import android.os.Build;
 import android.support.annotation.RequiresApi;
 import android.support.v4.internal.view.SupportMenuItem;
-import android.support.v4.os.BuildCompat;
 import android.util.Log;
 import android.view.KeyEvent;
 import android.view.Menu;
@@ -29,8 +29,7 @@
 import android.view.View;
 
 /**
- * Helper for accessing features in {@link android.view.MenuItem}
- * introduced after API level 14 in a backwards compatible fashion.
+ * Helper for accessing features in {@link android.view.MenuItem}.
  * <p class="note"><strong>Note:</strong> You cannot get an instance of this class. Instead,
  * it provides <em>static</em> methods that correspond to the methods in {@link
  * android.view.MenuItem}, but take a {@link android.view.MenuItem} object as an additional
@@ -274,7 +273,7 @@
      */
     static final MenuVersionImpl IMPL;
     static {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             IMPL = new MenuItemCompatApi26Impl();
         } else {
             IMPL = new MenuItemCompatBaseImpl();
diff --git a/compat/java/android/support/v4/view/MotionEventCompat.java b/compat/java/android/support/v4/view/MotionEventCompat.java
index 0e43ae0..367eda2 100644
--- a/compat/java/android/support/v4/view/MotionEventCompat.java
+++ b/compat/java/android/support/v4/view/MotionEventCompat.java
@@ -19,8 +19,7 @@
 import android.view.MotionEvent;
 
 /**
- * Helper for accessing features in {@link MotionEvent} introduced
- * after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link MotionEvent}.
  */
 public final class MotionEventCompat {
     /**
diff --git a/compat/java/android/support/v4/view/ScaleGestureDetectorCompat.java b/compat/java/android/support/v4/view/ScaleGestureDetectorCompat.java
index afe7a53..6233dff 100644
--- a/compat/java/android/support/v4/view/ScaleGestureDetectorCompat.java
+++ b/compat/java/android/support/v4/view/ScaleGestureDetectorCompat.java
@@ -20,7 +20,7 @@
 import android.view.ScaleGestureDetector;
 
 /**
- * Helper for accessing features in {@link ScaleGestureDetector} in a backwards compatible fashion.
+ * Helper for accessing features in {@link ScaleGestureDetector}.
  */
 public final class ScaleGestureDetectorCompat {
     private ScaleGestureDetectorCompat() {}
diff --git a/compat/java/android/support/v4/view/VelocityTrackerCompat.java b/compat/java/android/support/v4/view/VelocityTrackerCompat.java
index 327f21a..d536085 100644
--- a/compat/java/android/support/v4/view/VelocityTrackerCompat.java
+++ b/compat/java/android/support/v4/view/VelocityTrackerCompat.java
@@ -19,8 +19,7 @@
 import android.view.VelocityTracker;
 
 /**
- * Helper for accessing features in {@link VelocityTracker}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link VelocityTracker}.
  *
  * @deprecated Use {@link VelocityTracker} directly.
  */
diff --git a/compat/java/android/support/v4/view/ViewCompat.java b/compat/java/android/support/v4/view/ViewCompat.java
index efbf848..9a66cec 100644
--- a/compat/java/android/support/v4/view/ViewCompat.java
+++ b/compat/java/android/support/v4/view/ViewCompat.java
@@ -36,7 +36,6 @@
 import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
 import android.support.v4.view.accessibility.AccessibilityNodeProviderCompat;
 import android.util.Log;
@@ -62,8 +61,7 @@
 import java.util.WeakHashMap;
 
 /**
- * Helper for accessing features in {@link View} introduced after API
- * level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link View}.
  */
 public class ViewCompat {
     private static final String TAG = "ViewCompat";
@@ -989,6 +987,10 @@
         public boolean restoreDefaultFocus(@NonNull View view) {
             return view.requestFocus();
         }
+
+        public boolean hasExplicitFocusable(@NonNull View view) {
+            return view.hasFocusable();
+        }
     }
 
     @RequiresApi(15)
@@ -1572,11 +1574,16 @@
         public boolean restoreDefaultFocus(@NonNull View view) {
             return view.restoreDefaultFocus();
         }
+
+        @Override
+        public boolean hasExplicitFocusable(@NonNull View view) {
+            return view.hasExplicitFocusable();
+        }
     }
 
     static final ViewCompatBaseImpl IMPL;
     static {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             IMPL = new ViewCompatApi26Impl();
         } else if (Build.VERSION.SDK_INT >= 24) {
             IMPL = new ViewCompatApi24Impl();
@@ -3693,5 +3700,24 @@
         return IMPL.restoreDefaultFocus(view);
     }
 
+    /**
+     * Returns true if this view is focusable or if it contains a reachable View
+     * for which {@link View#hasExplicitFocusable()} returns {@code true}.
+     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
+     * Only {@link View#VISIBLE} views for which {@link View#getFocusable()} would return
+     * {@link View#FOCUSABLE} are considered focusable.
+     *
+     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
+     * {@link View#hasFocusable()} in that only views explicitly set focusable will cause
+     * this method to return true. A view set to {@link View#FOCUSABLE_AUTO} that resolves
+     * to focusable will not.</p>
+     *
+     * @return {@code true} if the view is focusable or if the view contains a focusable
+     *         view, {@code false} otherwise
+     */
+    public static boolean hasExplicitFocusable(@NonNull View view) {
+        return IMPL.hasExplicitFocusable(view);
+    }
+
     protected ViewCompat() {}
 }
diff --git a/compat/java/android/support/v4/view/ViewConfigurationCompat.java b/compat/java/android/support/v4/view/ViewConfigurationCompat.java
index 683a380..f14b806 100644
--- a/compat/java/android/support/v4/view/ViewConfigurationCompat.java
+++ b/compat/java/android/support/v4/view/ViewConfigurationCompat.java
@@ -17,8 +17,8 @@
 package android.support.v4.view;
 
 import android.content.Context;
+import android.os.Build;
 import android.support.annotation.NonNull;
-import android.support.v4.os.BuildCompat;
 import android.util.Log;
 import android.util.TypedValue;
 import android.view.ViewConfiguration;
@@ -26,7 +26,7 @@
 import java.lang.reflect.Method;
 
 /**
- * Helper for accessing features in {@link ViewConfiguration} in a backwards compatible fashion.
+ * Helper for accessing features in {@link ViewConfiguration}.
  *
  * @deprecated Use {@link ViewConfiguration} directly.
  */
@@ -37,7 +37,7 @@
     private static Method sGetScaledScrollFactorMethod;
 
     static {
-        if (android.os.Build.VERSION.SDK_INT >= 25 && !BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT == 25) {
             try {
                 sGetScaledScrollFactorMethod =
                         ViewConfiguration.class.getDeclaredMethod("getScaledScrollFactor");
@@ -79,7 +79,7 @@
      */
     public static float getScaledHorizontalScrollFactor(@NonNull ViewConfiguration config,
             @NonNull Context context) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return config.getScaledHorizontalScrollFactor();
         } else {
             return getLegacyScrollFactor(config, context);
@@ -96,7 +96,7 @@
      */
     public static float getScaledVerticalScrollFactor(@NonNull ViewConfiguration config,
             @NonNull Context context) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return config.getScaledVerticalScrollFactor();
         } else {
             return getLegacyScrollFactor(config, context);
diff --git a/compat/java/android/support/v4/view/ViewGroupCompat.java b/compat/java/android/support/v4/view/ViewGroupCompat.java
index c6f72f1..528d70e 100644
--- a/compat/java/android/support/v4/view/ViewGroupCompat.java
+++ b/compat/java/android/support/v4/view/ViewGroupCompat.java
@@ -25,8 +25,7 @@
 import android.view.accessibility.AccessibilityEvent;
 
 /**
- * Helper for accessing features in {@link ViewGroup}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link ViewGroup}.
  */
 public final class ViewGroupCompat {
 
diff --git a/compat/java/android/support/v4/view/ViewParentCompat.java b/compat/java/android/support/v4/view/ViewParentCompat.java
index d51c9b4..bb1587e 100644
--- a/compat/java/android/support/v4/view/ViewParentCompat.java
+++ b/compat/java/android/support/v4/view/ViewParentCompat.java
@@ -27,8 +27,7 @@
 import android.view.accessibility.AccessibilityEvent;
 
 /**
- * Helper for accessing features in {@link ViewParent}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link ViewParent}.
  */
 public final class ViewParentCompat {
 
diff --git a/compat/java/android/support/v4/view/WindowCompat.java b/compat/java/android/support/v4/view/WindowCompat.java
index 9a0773e..cdf4789 100644
--- a/compat/java/android/support/v4/view/WindowCompat.java
+++ b/compat/java/android/support/v4/view/WindowCompat.java
@@ -20,8 +20,7 @@
 import android.view.Window;
 
 /**
- * Helper for accessing features in {@link Window} introduced after API
- * level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link Window}.
  */
 public final class WindowCompat {
     /**
diff --git a/compat/java/android/support/v4/view/accessibility/AccessibilityEventCompat.java b/compat/java/android/support/v4/view/accessibility/AccessibilityEventCompat.java
index 61eff1c..924b482 100644
--- a/compat/java/android/support/v4/view/accessibility/AccessibilityEventCompat.java
+++ b/compat/java/android/support/v4/view/accessibility/AccessibilityEventCompat.java
@@ -22,7 +22,7 @@
 import android.view.accessibility.AccessibilityRecord;
 
 /**
- * Helper for accessing features in {@link AccessibilityEvent} in a backwards compatible fashion.
+ * Helper for accessing features in {@link AccessibilityEvent}.
  */
 public final class AccessibilityEventCompat {
 
diff --git a/compat/java/android/support/v4/view/accessibility/AccessibilityManagerCompat.java b/compat/java/android/support/v4/view/accessibility/AccessibilityManagerCompat.java
index 112d809..5767f74 100644
--- a/compat/java/android/support/v4/view/accessibility/AccessibilityManagerCompat.java
+++ b/compat/java/android/support/v4/view/accessibility/AccessibilityManagerCompat.java
@@ -25,7 +25,7 @@
 import java.util.List;
 
 /**
- * Helper for accessing features in {@link AccessibilityManager} in a backwards compatible fashion.
+ * Helper for accessing features in {@link AccessibilityManager}.
  */
 public final class AccessibilityManagerCompat {
     /**
diff --git a/compat/java/android/support/v4/view/accessibility/AccessibilityNodeProviderCompat.java b/compat/java/android/support/v4/view/accessibility/AccessibilityNodeProviderCompat.java
index c336585..211a0bc 100644
--- a/compat/java/android/support/v4/view/accessibility/AccessibilityNodeProviderCompat.java
+++ b/compat/java/android/support/v4/view/accessibility/AccessibilityNodeProviderCompat.java
@@ -16,17 +16,16 @@
 
 package android.support.v4.view.accessibility;
 
-import android.support.annotation.RequiresApi;
 import android.os.Build;
 import android.os.Bundle;
 import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
 
 import java.util.ArrayList;
 import java.util.List;
 
 /**
- * Helper for accessing {@link android.view.accessibility.AccessibilityNodeProvider}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing {@link android.view.accessibility.AccessibilityNodeProvider}.
  */
 public class AccessibilityNodeProviderCompat {
 
diff --git a/compat/java/android/support/v4/view/accessibility/AccessibilityRecordCompat.java b/compat/java/android/support/v4/view/accessibility/AccessibilityRecordCompat.java
index ca29ef3..395af49 100644
--- a/compat/java/android/support/v4/view/accessibility/AccessibilityRecordCompat.java
+++ b/compat/java/android/support/v4/view/accessibility/AccessibilityRecordCompat.java
@@ -27,7 +27,7 @@
 import java.util.List;
 
 /**
- * Helper for accessing {@link AccessibilityRecord} in a backwards compatible fashion.
+ * Helper for accessing {@link AccessibilityRecord}.
  */
 public class AccessibilityRecordCompat {
 
diff --git a/compat/java/android/support/v4/view/accessibility/AccessibilityWindowInfoCompat.java b/compat/java/android/support/v4/view/accessibility/AccessibilityWindowInfoCompat.java
index d95ea27..be5d29f 100644
--- a/compat/java/android/support/v4/view/accessibility/AccessibilityWindowInfoCompat.java
+++ b/compat/java/android/support/v4/view/accessibility/AccessibilityWindowInfoCompat.java
@@ -22,8 +22,7 @@
 import android.view.accessibility.AccessibilityWindowInfo;
 
 /**
- * Helper for accessing {@link android.view.accessibility.AccessibilityWindowInfo}
- * in a backwards compatible fashion.
+ * Helper for accessing {@link android.view.accessibility.AccessibilityWindowInfo}.
  */
 public class AccessibilityWindowInfoCompat {
     private Object mInfo;
diff --git a/compat/java/android/support/v4/widget/CompoundButtonCompat.java b/compat/java/android/support/v4/widget/CompoundButtonCompat.java
index 25d876e..a858b09 100644
--- a/compat/java/android/support/v4/widget/CompoundButtonCompat.java
+++ b/compat/java/android/support/v4/widget/CompoundButtonCompat.java
@@ -16,13 +16,13 @@
 
 package android.support.v4.widget;
 
-import android.support.annotation.RequiresApi;
 import android.content.res.ColorStateList;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.Drawable;
 import android.os.Build;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
 import android.support.v4.graphics.drawable.DrawableCompat;
 import android.util.Log;
 import android.widget.CompoundButton;
@@ -30,8 +30,7 @@
 import java.lang.reflect.Field;
 
 /**
- * Helper for accessing {@link android.widget.CompoundButton} methods introduced after
- * API level 4 in a backwards compatible fashion.
+ * Helper for accessing {@link android.widget.CompoundButton}.
  */
 public final class CompoundButtonCompat {
 
diff --git a/compat/java/android/support/v4/widget/EdgeEffectCompat.java b/compat/java/android/support/v4/widget/EdgeEffectCompat.java
index 8be2d9f..9293e60 100644
--- a/compat/java/android/support/v4/widget/EdgeEffectCompat.java
+++ b/compat/java/android/support/v4/widget/EdgeEffectCompat.java
@@ -22,7 +22,7 @@
 import android.widget.EdgeEffect;
 
 /**
- * Helper for accessing {@link android.widget.EdgeEffect} in a backwards compatible fashion.
+ * Helper for accessing {@link android.widget.EdgeEffect}.
  *
  * This class is used to access {@link android.widget.EdgeEffect} on platform versions
  * that support it. When running on older platforms it will result in no-ops. It should
diff --git a/compat/java/android/support/v4/widget/ImageViewCompat.java b/compat/java/android/support/v4/widget/ImageViewCompat.java
index df3ace5..acaaf63 100644
--- a/compat/java/android/support/v4/widget/ImageViewCompat.java
+++ b/compat/java/android/support/v4/widget/ImageViewCompat.java
@@ -24,8 +24,7 @@
 import android.widget.ImageView;
 
 /**
- * Helper for accessing features in {@link ImageView} introduced in later platform releases
- * in a backwards compatible fashion.
+ * Helper for accessing features in {@link ImageView}.
  */
 public class ImageViewCompat {
     interface ImageViewCompatImpl {
diff --git a/compat/java/android/support/v4/widget/ListPopupWindowCompat.java b/compat/java/android/support/v4/widget/ListPopupWindowCompat.java
index 691d5b6..ab86e58 100644
--- a/compat/java/android/support/v4/widget/ListPopupWindowCompat.java
+++ b/compat/java/android/support/v4/widget/ListPopupWindowCompat.java
@@ -22,7 +22,7 @@
 import android.widget.ListPopupWindow;
 
 /**
- * Helper for accessing features in {@link ListPopupWindow} in a backwards compatible fashion.
+ * Helper for accessing features in {@link ListPopupWindow}.
  */
 public final class ListPopupWindowCompat {
     private ListPopupWindowCompat() {
diff --git a/compat/java/android/support/v4/widget/PopupMenuCompat.java b/compat/java/android/support/v4/widget/PopupMenuCompat.java
index d8b65b5..639a84b 100644
--- a/compat/java/android/support/v4/widget/PopupMenuCompat.java
+++ b/compat/java/android/support/v4/widget/PopupMenuCompat.java
@@ -21,7 +21,7 @@
 import android.widget.PopupMenu;
 
 /**
- * Helper for accessing features in {@link PopupMenu} in a backwards compatible fashion.
+ * Helper for accessing features in {@link PopupMenu}.
  */
 public final class PopupMenuCompat {
     private PopupMenuCompat() {
diff --git a/compat/java/android/support/v4/widget/PopupWindowCompat.java b/compat/java/android/support/v4/widget/PopupWindowCompat.java
index 5018e04..d846b40 100644
--- a/compat/java/android/support/v4/widget/PopupWindowCompat.java
+++ b/compat/java/android/support/v4/widget/PopupWindowCompat.java
@@ -29,7 +29,7 @@
 import java.lang.reflect.Method;
 
 /**
- * Helper for accessing features in PopupWindow in a backwards compatible fashion.
+ * Helper for accessing features in {@link PopupWindow}.
  */
 public final class PopupWindowCompat {
 
diff --git a/compat/java/android/support/v4/widget/SearchViewCompat.java b/compat/java/android/support/v4/widget/SearchViewCompat.java
index 83cb0fc..b176467 100644
--- a/compat/java/android/support/v4/widget/SearchViewCompat.java
+++ b/compat/java/android/support/v4/widget/SearchViewCompat.java
@@ -25,8 +25,7 @@
 import android.widget.TextView;
 
 /**
- * Helper for accessing features in {@link SearchView}
- * introduced after API level 4 in a backwards compatible fashion.
+ * Helper for accessing features in {@link SearchView}.
  *
  * @deprecated Use {@link SearchView} directly.
  */
diff --git a/compat/java/android/support/v4/widget/TextViewCompat.java b/compat/java/android/support/v4/widget/TextViewCompat.java
index b163c73..d7ca21e 100644
--- a/compat/java/android/support/v4/widget/TextViewCompat.java
+++ b/compat/java/android/support/v4/widget/TextViewCompat.java
@@ -37,7 +37,7 @@
 import java.lang.reflect.Field;
 
 /**
- * Helper for accessing features in {@link TextView} in a backwards compatible fashion.
+ * Helper for accessing features in {@link TextView}.
  */
 public final class TextViewCompat {
 
diff --git a/compat/jellybean/android/support/v4/app/NotificationCompatJellybean.java b/compat/jellybean/android/support/v4/app/NotificationCompatJellybean.java
index bf313a0..426dad9 100644
--- a/compat/jellybean/android/support/v4/app/NotificationCompatJellybean.java
+++ b/compat/jellybean/android/support/v4/app/NotificationCompatJellybean.java
@@ -36,14 +36,7 @@
     public static final String TAG = "NotificationCompat";
 
     // Extras keys used for Jellybean SDK and above.
-    static final String EXTRA_LOCAL_ONLY = "android.support.localOnly";
-    static final String EXTRA_ACTION_EXTRAS = "android.support.actionExtras";
-    static final String EXTRA_REMOTE_INPUTS = "android.support.remoteInputs";
     static final String EXTRA_DATA_ONLY_REMOTE_INPUTS = "android.support.dataRemoteInputs";
-    static final String EXTRA_GROUP_KEY = "android.support.groupKey";
-    static final String EXTRA_GROUP_SUMMARY = "android.support.isGroupSummary";
-    static final String EXTRA_SORT_KEY = "android.support.sortKey";
-    static final String EXTRA_USE_SIDE_CHANNEL = "android.support.useSideChannel";
     static final String EXTRA_ALLOW_GENERATED_REPLIES = "android.support.allowGeneratedReplies";
 
     // Bundle keys for storing action fields in a bundle
@@ -112,18 +105,18 @@
                 mExtras.putAll(extras);
             }
             if (localOnly) {
-                mExtras.putBoolean(EXTRA_LOCAL_ONLY, true);
+                mExtras.putBoolean(NotificationCompatExtras.EXTRA_LOCAL_ONLY, true);
             }
             if (groupKey != null) {
-                mExtras.putString(EXTRA_GROUP_KEY, groupKey);
+                mExtras.putString(NotificationCompatExtras.EXTRA_GROUP_KEY, groupKey);
                 if (groupSummary) {
-                    mExtras.putBoolean(EXTRA_GROUP_SUMMARY, true);
+                    mExtras.putBoolean(NotificationCompatExtras.EXTRA_GROUP_SUMMARY, true);
                 } else {
-                    mExtras.putBoolean(EXTRA_USE_SIDE_CHANNEL, true);
+                    mExtras.putBoolean(NotificationManagerCompat.EXTRA_USE_SIDE_CHANNEL, true);
                 }
             }
             if (sortKey != null) {
-                mExtras.putString(EXTRA_SORT_KEY, sortKey);
+                mExtras.putString(NotificationCompatExtras.EXTRA_SORT_KEY, sortKey);
             }
             mContentView = contentView;
             mBigContentView = bigContentView;
@@ -155,7 +148,8 @@
             SparseArray<Bundle> actionExtrasMap = buildActionExtrasMap(mActionExtrasList);
             if (actionExtrasMap != null) {
                 // Add the action extras sparse array if any action was added with extras.
-                getExtras(notif).putSparseParcelableArray(EXTRA_ACTION_EXTRAS, actionExtrasMap);
+                getExtras(notif).putSparseParcelableArray(
+                        NotificationCompatExtras.EXTRA_ACTION_EXTRAS, actionExtrasMap);
             }
             if (mContentView != null) {
                 notif.contentView = mContentView;
@@ -266,7 +260,8 @@
         boolean allowGeneratedReplies = false;
         if (extras != null) {
             remoteInputs = RemoteInputCompatJellybean.fromBundleArray(
-                    BundleUtil.getBundleArrayFromBundle(extras, EXTRA_REMOTE_INPUTS),
+                    BundleUtil.getBundleArrayFromBundle(extras,
+                            NotificationCompatExtras.EXTRA_REMOTE_INPUTS),
                     remoteInputFactory);
             dataOnlyRemoteInputs = RemoteInputCompatJellybean.fromBundleArray(
                     BundleUtil.getBundleArrayFromBundle(extras, EXTRA_DATA_ONLY_REMOTE_INPUTS),
@@ -282,7 +277,7 @@
         builder.addAction(action.getIcon(), action.getTitle(), action.getActionIntent());
         Bundle actionExtras = new Bundle(action.getExtras());
         if (action.getRemoteInputs() != null) {
-            actionExtras.putParcelableArray(EXTRA_REMOTE_INPUTS,
+            actionExtras.putParcelableArray(NotificationCompatExtras.EXTRA_REMOTE_INPUTS,
                     RemoteInputCompatJellybean.toBundleArray(action.getRemoteInputs()));
         }
         if (action.getDataOnlyRemoteInputs() != null) {
@@ -313,7 +308,7 @@
                     Bundle extras = getExtras(notif);
                     if (extras != null) {
                         SparseArray<Bundle> actionExtrasMap = extras.getSparseParcelableArray(
-                                EXTRA_ACTION_EXTRAS);
+                                NotificationCompatExtras.EXTRA_ACTION_EXTRAS);
                         if (actionExtrasMap != null) {
                             actionExtras = actionExtrasMap.get(actionIndex);
                         }
diff --git a/compat/jellybean/android/support/v4/app/RemoteInputCompatJellybean.java b/compat/jellybean/android/support/v4/app/RemoteInputCompatJellybean.java
index 558a42b..0402a91 100644
--- a/compat/jellybean/android/support/v4/app/RemoteInputCompatJellybean.java
+++ b/compat/jellybean/android/support/v4/app/RemoteInputCompatJellybean.java
@@ -31,12 +31,6 @@
 
 @RequiresApi(16)
 class RemoteInputCompatJellybean {
-    /** Label used to denote the clip data type used for remote input transport */
-    public static final String RESULTS_CLIP_LABEL = "android.remoteinput.results";
-
-    /** Extra added to a clip data intent object to hold the results bundle. */
-    public static final String EXTRA_RESULTS_DATA = "android.remoteinput.resultsData";
-
     /** Extra added to a clip data intent object to hold the data results bundle. */
     private static final String EXTRA_DATA_TYPE_RESULTS_DATA =
             "android.remoteinput.dataTypeResultsData";
@@ -112,7 +106,7 @@
         if (clipDataIntent == null) {
             return null;
         }
-        return clipDataIntent.getExtras().getParcelable(EXTRA_RESULTS_DATA);
+        return clipDataIntent.getExtras().getParcelable(RemoteInput.EXTRA_RESULTS_DATA);
     }
 
     static Map<String, Uri> getDataResultsFromIntent(Intent intent, String remoteInputResultKey) {
@@ -145,7 +139,7 @@
         if (clipDataIntent == null) {
             clipDataIntent = new Intent();  // First time we've added a result.
         }
-        Bundle resultsBundle = clipDataIntent.getBundleExtra(EXTRA_RESULTS_DATA);
+        Bundle resultsBundle = clipDataIntent.getBundleExtra(RemoteInput.EXTRA_RESULTS_DATA);
         if (resultsBundle == null) {
             resultsBundle = new Bundle();
         }
@@ -155,8 +149,8 @@
                 resultsBundle.putCharSequence(remoteInput.getResultKey(), (CharSequence) result);
             }
         }
-        clipDataIntent.putExtra(EXTRA_RESULTS_DATA, resultsBundle);
-        intent.setClipData(ClipData.newIntent(RESULTS_CLIP_LABEL, clipDataIntent));
+        clipDataIntent.putExtra(RemoteInput.EXTRA_RESULTS_DATA, resultsBundle);
+        intent.setClipData(ClipData.newIntent(RemoteInput.RESULTS_CLIP_LABEL, clipDataIntent));
     }
 
     /**
@@ -186,7 +180,7 @@
             resultsBundle.putString(remoteInput.getResultKey(), uri.toString());
             clipDataIntent.putExtra(getExtraResultsKeyForData(mimeType), resultsBundle);
         }
-        intent.setClipData(ClipData.newIntent(RESULTS_CLIP_LABEL, clipDataIntent));
+        intent.setClipData(ClipData.newIntent(RemoteInput.RESULTS_CLIP_LABEL, clipDataIntent));
     }
 
     private static String getExtraResultsKeyForData(String mimeType) {
@@ -202,7 +196,7 @@
         if (!clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_INTENT)) {
             return null;
         }
-        if (!clipDescription.getLabel().equals(RESULTS_CLIP_LABEL)) {
+        if (!clipDescription.getLabel().equals(RemoteInput.RESULTS_CLIP_LABEL)) {
             return null;
         }
         return clipData.getItemAt(0).getIntent();
diff --git a/compat/kitkat/android/support/v4/app/NotificationCompatKitKat.java b/compat/kitkat/android/support/v4/app/NotificationCompatKitKat.java
index 34de842..f40fd1b 100644
--- a/compat/kitkat/android/support/v4/app/NotificationCompatKitKat.java
+++ b/compat/kitkat/android/support/v4/app/NotificationCompatKitKat.java
@@ -81,18 +81,18 @@
                         people.toArray(new String[people.size()]));
             }
             if (localOnly) {
-                mExtras.putBoolean(NotificationCompatJellybean.EXTRA_LOCAL_ONLY, true);
+                mExtras.putBoolean(NotificationCompatExtras.EXTRA_LOCAL_ONLY, true);
             }
             if (groupKey != null) {
-                mExtras.putString(NotificationCompatJellybean.EXTRA_GROUP_KEY, groupKey);
+                mExtras.putString(NotificationCompatExtras.EXTRA_GROUP_KEY, groupKey);
                 if (groupSummary) {
-                    mExtras.putBoolean(NotificationCompatJellybean.EXTRA_GROUP_SUMMARY, true);
+                    mExtras.putBoolean(NotificationCompatExtras.EXTRA_GROUP_SUMMARY, true);
                 } else {
-                    mExtras.putBoolean(NotificationCompatJellybean.EXTRA_USE_SIDE_CHANNEL, true);
+                    mExtras.putBoolean(NotificationManagerCompat.EXTRA_USE_SIDE_CHANNEL, true);
                 }
             }
             if (sortKey != null) {
-                mExtras.putString(NotificationCompatJellybean.EXTRA_SORT_KEY, sortKey);
+                mExtras.putString(NotificationCompatExtras.EXTRA_SORT_KEY, sortKey);
             }
             mContentView = contentView;
             mBigContentView = bigContentView;
@@ -115,7 +115,7 @@
             if (actionExtrasMap != null) {
                 // Add the action extras sparse array if any action was added with extras.
                 mExtras.putSparseParcelableArray(
-                        NotificationCompatJellybean.EXTRA_ACTION_EXTRAS, actionExtrasMap);
+                        NotificationCompatExtras.EXTRA_ACTION_EXTRAS, actionExtrasMap);
             }
             b.setExtras(mExtras);
             Notification notification = b.build();
@@ -135,7 +135,7 @@
         Notification.Action action = notif.actions[actionIndex];
         Bundle actionExtras = null;
         SparseArray<Bundle> actionExtrasMap = notif.extras.getSparseParcelableArray(
-                NotificationCompatJellybean.EXTRA_ACTION_EXTRAS);
+                NotificationCompatExtras.EXTRA_ACTION_EXTRAS);
         if (actionExtrasMap != null) {
             actionExtras = actionExtrasMap.get(actionIndex);
         }
diff --git a/compat/lint-baseline.xml b/compat/lint-baseline.xml
new file mode 100644
index 0000000..3919eba
--- /dev/null
+++ b/compat/lint-baseline.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="MissingPermission"
+        message="Missing permissions required by ConnectivityManager.getActiveNetworkInfo: android.permission.ACCESS_NETWORK_STATE"
+        errorLine1="            final NetworkInfo info = cm.getActiveNetworkInfo();"
+        errorLine2="                                     ~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="java/android/support/v4/net/ConnectivityManagerCompat.java"
+            line="92"
+            column="38"/>
+    </issue>
+
+    <issue
+        id="MissingPermission"
+        message="Missing permissions required by ConnectivityManager.isActiveNetworkMetered: android.permission.ACCESS_NETWORK_STATE"
+        errorLine1="            return cm.isActiveNetworkMetered();"
+        errorLine2="                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="java/android/support/v4/net/ConnectivityManagerCompat.java"
+            line="127"
+            column="20"/>
+    </issue>
+
+    <issue
+        id="MissingPermission"
+        message="Missing permissions required by ConnectivityManager.getNetworkInfo: android.permission.ACCESS_NETWORK_STATE"
+        errorLine1="            return cm.getNetworkInfo(info.getType());"
+        errorLine2="                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="java/android/support/v4/net/ConnectivityManagerCompat.java"
+            line="180"
+            column="20"/>
+    </issue>
+
+</issues>
diff --git a/compat/res-public/values/public_styles.xml b/compat/res-public/values/public_styles.xml
new file mode 100644
index 0000000..ee726c7
--- /dev/null
+++ b/compat/res-public/values/public_styles.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Definitions of styles to be exposed as public -->
+<resources>
+    <public type="style" name="TextAppearance.Compat.Notification"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Title"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Info"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Line2"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Time"/>
+</resources>
diff --git a/v7/appcompat/res/drawable-hdpi/notification_bg_low_normal.9.png b/compat/res/drawable-hdpi/notification_bg_low_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-hdpi/notification_bg_low_normal.9.png
rename to compat/res/drawable-hdpi/notification_bg_low_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-hdpi/notification_bg_low_pressed.9.png b/compat/res/drawable-hdpi/notification_bg_low_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-hdpi/notification_bg_low_pressed.9.png
rename to compat/res/drawable-hdpi/notification_bg_low_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-hdpi/notification_bg_normal.9.png b/compat/res/drawable-hdpi/notification_bg_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-hdpi/notification_bg_normal.9.png
rename to compat/res/drawable-hdpi/notification_bg_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-hdpi/notification_bg_normal_pressed.9.png b/compat/res/drawable-hdpi/notification_bg_normal_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-hdpi/notification_bg_normal_pressed.9.png
rename to compat/res/drawable-hdpi/notification_bg_normal_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-hdpi/notify_panel_notification_icon_bg.png b/compat/res/drawable-hdpi/notify_panel_notification_icon_bg.png
similarity index 100%
rename from v7/appcompat/res/drawable-hdpi/notify_panel_notification_icon_bg.png
rename to compat/res/drawable-hdpi/notify_panel_notification_icon_bg.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-mdpi/notification_bg_low_normal.9.png b/compat/res/drawable-mdpi/notification_bg_low_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-mdpi/notification_bg_low_normal.9.png
rename to compat/res/drawable-mdpi/notification_bg_low_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-mdpi/notification_bg_low_pressed.9.png b/compat/res/drawable-mdpi/notification_bg_low_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-mdpi/notification_bg_low_pressed.9.png
rename to compat/res/drawable-mdpi/notification_bg_low_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-mdpi/notification_bg_normal.9.png b/compat/res/drawable-mdpi/notification_bg_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-mdpi/notification_bg_normal.9.png
rename to compat/res/drawable-mdpi/notification_bg_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-mdpi/notification_bg_normal_pressed.9.png b/compat/res/drawable-mdpi/notification_bg_normal_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-mdpi/notification_bg_normal_pressed.9.png
rename to compat/res/drawable-mdpi/notification_bg_normal_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-mdpi/notify_panel_notification_icon_bg.png b/compat/res/drawable-mdpi/notify_panel_notification_icon_bg.png
similarity index 100%
rename from v7/appcompat/res/drawable-mdpi/notify_panel_notification_icon_bg.png
rename to compat/res/drawable-mdpi/notify_panel_notification_icon_bg.png
Binary files differ
diff --git a/compat/res/drawable-v21/notification_action_background.xml b/compat/res/drawable-v21/notification_action_background.xml
new file mode 100644
index 0000000..f3b47cb
--- /dev/null
+++ b/compat/res/drawable-v21/notification_action_background.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<ripple xmlns:android="http://schemas.android.com/apk/res/android"
+    android:color="@color/ripple_material_light">
+    <item android:id="@android:id/mask">
+        <inset xmlns:android="http://schemas.android.com/apk/res/android"
+               android:insetLeft="@dimen/compat_button_inset_horizontal_material"
+               android:insetTop="@dimen/compat_button_inset_vertical_material"
+               android:insetRight="@dimen/compat_button_inset_horizontal_material"
+               android:insetBottom="@dimen/compat_button_inset_vertical_material">
+            <shape android:shape="rectangle">
+                <corners android:radius="@dimen/compat_control_corner_material" />
+                <solid android:color="@android:color/white" />
+                <padding android:left="@dimen/compat_button_padding_horizontal_material"
+                         android:top="@dimen/compat_button_padding_vertical_material"
+                         android:right="@dimen/compat_button_padding_horizontal_material"
+                         android:bottom="@dimen/compat_button_padding_vertical_material" />
+            </shape>
+        </inset>
+    </item>
+</ripple>
\ No newline at end of file
diff --git a/v7/appcompat/res/drawable-xhdpi/notification_bg_low_normal.9.png b/compat/res/drawable-xhdpi/notification_bg_low_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-xhdpi/notification_bg_low_normal.9.png
rename to compat/res/drawable-xhdpi/notification_bg_low_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-xhdpi/notification_bg_low_pressed.9.png b/compat/res/drawable-xhdpi/notification_bg_low_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-xhdpi/notification_bg_low_pressed.9.png
rename to compat/res/drawable-xhdpi/notification_bg_low_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-xhdpi/notification_bg_normal.9.png b/compat/res/drawable-xhdpi/notification_bg_normal.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-xhdpi/notification_bg_normal.9.png
rename to compat/res/drawable-xhdpi/notification_bg_normal.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-xhdpi/notification_bg_normal_pressed.9.png b/compat/res/drawable-xhdpi/notification_bg_normal_pressed.9.png
similarity index 100%
rename from v7/appcompat/res/drawable-xhdpi/notification_bg_normal_pressed.9.png
rename to compat/res/drawable-xhdpi/notification_bg_normal_pressed.9.png
Binary files differ
diff --git a/v7/appcompat/res/drawable-xhdpi/notify_panel_notification_icon_bg.png b/compat/res/drawable-xhdpi/notify_panel_notification_icon_bg.png
similarity index 100%
rename from v7/appcompat/res/drawable-xhdpi/notify_panel_notification_icon_bg.png
rename to compat/res/drawable-xhdpi/notify_panel_notification_icon_bg.png
Binary files differ
diff --git a/v7/appcompat/res/drawable/notification_bg.xml b/compat/res/drawable/notification_bg.xml
similarity index 100%
rename from v7/appcompat/res/drawable/notification_bg.xml
rename to compat/res/drawable/notification_bg.xml
diff --git a/v7/appcompat/res/drawable/notification_bg_low.xml b/compat/res/drawable/notification_bg_low.xml
similarity index 100%
rename from v7/appcompat/res/drawable/notification_bg_low.xml
rename to compat/res/drawable/notification_bg_low.xml
diff --git a/v7/appcompat/res/drawable/notification_icon_background.xml b/compat/res/drawable/notification_icon_background.xml
similarity index 100%
rename from v7/appcompat/res/drawable/notification_icon_background.xml
rename to compat/res/drawable/notification_icon_background.xml
diff --git a/v7/appcompat/res/drawable/notification_tile_bg.xml b/compat/res/drawable/notification_tile_bg.xml
similarity index 100%
rename from v7/appcompat/res/drawable/notification_tile_bg.xml
rename to compat/res/drawable/notification_tile_bg.xml
diff --git a/compat/res/layout-v16/notification_template_custom_big.xml b/compat/res/layout-v16/notification_template_custom_big.xml
new file mode 100644
index 0000000..d0519dc
--- /dev/null
+++ b/compat/res/layout-v16/notification_template_custom_big.xml
@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/notification_background"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content" >
+    <ImageView android:id="@+id/icon"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+        android:scaleType="center"
+    />
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_gravity="top"
+        android:orientation="vertical" >
+        <LinearLayout
+            android:id="@+id/notification_main_column_container"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginLeft="@dimen/notification_large_icon_width"
+            android:layout_marginStart="@dimen/notification_large_icon_width"
+            android:paddingTop="@dimen/notification_main_column_padding_top"
+            android:minHeight="@dimen/notification_large_icon_height"
+            android:orientation="horizontal">
+            <FrameLayout
+                android:id="@+id/notification_main_column"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_weight="1"
+                android:layout_marginLeft="@dimen/notification_content_margin_start"
+                android:layout_marginStart="@dimen/notification_content_margin_start"
+                android:layout_marginBottom="8dp"
+                android:layout_marginRight="8dp"
+                android:layout_marginEnd="8dp" />
+            <FrameLayout
+                android:id="@+id/right_side"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginRight="8dp"
+                android:layout_marginEnd="8dp"
+                android:paddingTop="@dimen/notification_right_side_padding_top">
+                <ViewStub android:id="@+id/time"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="end|top"
+                    android:visibility="gone"
+                    android:layout="@layout/notification_template_part_time" />
+                <ViewStub android:id="@+id/chronometer"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="end|top"
+                    android:visibility="gone"
+                    android:layout="@layout/notification_template_part_chronometer" />
+                <LinearLayout
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:orientation="horizontal"
+                    android:layout_gravity="end|bottom"
+                    android:layout_marginTop="20dp">
+                    <TextView android:id="@+id/info"
+                        android:textAppearance="@style/TextAppearance.Compat.Notification.Info"
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:singleLine="true"
+                    />
+                    <ImageView android:id="@+id/right_icon"
+                        android:layout_width="16dp"
+                        android:layout_height="16dp"
+                        android:layout_gravity="center"
+                        android:layout_marginLeft="8dp"
+                        android:layout_marginStart="8dp"
+                        android:scaleType="centerInside"
+                        android:visibility="gone"
+                        android:alpha="0.6"
+                    />
+                </LinearLayout>
+            </FrameLayout>
+        </LinearLayout>
+        <ImageView
+            android:layout_width="match_parent"
+            android:layout_height="1px"
+            android:id="@+id/action_divider"
+            android:visibility="gone"
+            android:layout_marginLeft="@dimen/notification_large_icon_width"
+            android:layout_marginStart="@dimen/notification_large_icon_width"
+            android:background="?android:attr/dividerHorizontal" />
+        <LinearLayout
+            android:id="@+id/actions"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal"
+            android:visibility="gone"
+            android:showDividers="middle"
+            android:divider="?android:attr/listDivider"
+            android:dividerPadding="12dp"
+            android:layout_marginLeft="@dimen/notification_large_icon_width"
+            android:layout_marginStart="@dimen/notification_large_icon_width" >
+            <!-- actions will be added here -->
+        </LinearLayout>
+    </LinearLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/compat/res/layout-v21/notification_action.xml b/compat/res/layout-v21/notification_action.xml
new file mode 100644
index 0000000..7199c25
--- /dev/null
+++ b/compat/res/layout-v21/notification_action.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/Widget.Compat.NotificationActionContainer"
+    android:id="@+id/action_container"
+    android:layout_width="0dp"
+    android:layout_weight="1"
+    android:layout_height="48dp"
+    android:paddingStart="4dp"
+    android:orientation="horizontal">
+    <ImageView
+        android:id="@+id/action_image"
+        android:layout_width="@dimen/notification_action_icon_size"
+        android:layout_height="@dimen/notification_action_icon_size"
+        android:layout_gravity="center|start"
+        android:scaleType="centerInside"/>
+    <TextView
+        style="@style/Widget.Compat.NotificationActionText"
+        android:id="@+id/action_text"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center|start"
+        android:paddingStart="4dp"
+        android:singleLine="true"
+        android:ellipsize="end"
+        android:clickable="false"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/compat/res/layout-v21/notification_action_tombstone.xml b/compat/res/layout-v21/notification_action_tombstone.xml
new file mode 100644
index 0000000..7ef38fa
--- /dev/null
+++ b/compat/res/layout-v21/notification_action_tombstone.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/Widget.Compat.NotificationActionContainer"
+    android:id="@+id/action_container"
+    android:layout_width="0dp"
+    android:layout_weight="1"
+    android:layout_height="48dp"
+    android:paddingStart="4dp"
+    android:orientation="horizontal"
+    android:enabled="false"
+    android:background="@null">
+    <ImageView
+        android:id="@+id/action_image"
+        android:layout_width="@dimen/notification_action_icon_size"
+        android:layout_height="@dimen/notification_action_icon_size"
+        android:layout_gravity="center|start"
+        android:scaleType="centerInside"
+        android:enabled="false"
+        android:alpha="0.5"/>
+    <TextView
+        style="@style/Widget.Compat.NotificationActionText"
+        android:id="@+id/action_text"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center|start"
+        android:paddingStart="4dp"
+        android:singleLine="true"
+        android:ellipsize="end"
+        android:clickable="false"
+        android:enabled="false"
+        android:alpha="0.5"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/compat/res/layout-v21/notification_template_custom_big.xml b/compat/res/layout-v21/notification_template_custom_big.xml
new file mode 100644
index 0000000..9e3666e
--- /dev/null
+++ b/compat/res/layout-v21/notification_template_custom_big.xml
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/notification_background"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content" >
+    <include layout="@layout/notification_template_icon_group"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+    />
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_gravity="top"
+        android:layout_marginStart="@dimen/notification_large_icon_width"
+        android:orientation="vertical" >
+        <LinearLayout
+            android:id="@+id/notification_main_column_container"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:minHeight="@dimen/notification_large_icon_height"
+            android:orientation="horizontal">
+            <FrameLayout
+                android:id="@+id/notification_main_column"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_weight="1"
+                android:layout_marginEnd="8dp"
+                android:layout_marginBottom="8dp"/>
+            <FrameLayout
+                android:id="@+id/right_side"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginEnd="8dp"
+                android:paddingTop="@dimen/notification_right_side_padding_top">
+                <ViewStub android:id="@+id/time"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="end|top"
+                    android:visibility="gone"
+                    android:layout="@layout/notification_template_part_time" />
+                <ViewStub android:id="@+id/chronometer"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="end|top"
+                    android:visibility="gone"
+                    android:layout="@layout/notification_template_part_chronometer" />
+                <TextView android:id="@+id/info"
+                    android:textAppearance="@style/TextAppearance.Compat.Notification.Info"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_marginTop="20dp"
+                    android:layout_gravity="end|bottom"
+                    android:singleLine="true"
+                />
+            </FrameLayout>
+        </LinearLayout>
+        <ImageView
+            android:layout_width="match_parent"
+            android:layout_height="1dp"
+            android:id="@+id/action_divider"
+            android:visibility="gone"
+            android:background="#29000000" />
+        <LinearLayout
+            android:id="@+id/actions"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginStart="-8dp"
+            android:orientation="horizontal"
+            android:visibility="gone"
+        >
+            <!-- actions will be added here -->
+        </LinearLayout>
+    </LinearLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/compat/res/layout-v21/notification_template_icon_group.xml b/compat/res/layout-v21/notification_template_icon_group.xml
new file mode 100644
index 0000000..8fadd67
--- /dev/null
+++ b/compat/res/layout-v21/notification_template_icon_group.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="@dimen/notification_large_icon_width"
+    android:layout_height="@dimen/notification_large_icon_height"
+    android:id="@+id/icon_group"
+>
+    <ImageView android:id="@+id/icon"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_marginTop="@dimen/notification_big_circle_margin"
+        android:layout_marginBottom="@dimen/notification_big_circle_margin"
+        android:layout_marginStart="@dimen/notification_big_circle_margin"
+        android:layout_marginEnd="@dimen/notification_big_circle_margin"
+        android:scaleType="centerInside"
+    />
+    <ImageView android:id="@+id/right_icon"
+        android:layout_width="@dimen/notification_right_icon_size"
+        android:layout_height="@dimen/notification_right_icon_size"
+        android:layout_gravity="end|bottom"
+        android:scaleType="centerInside"
+        android:visibility="gone"
+        android:layout_marginEnd="8dp"
+        android:layout_marginBottom="8dp"
+    />
+</FrameLayout>
diff --git a/compat/res/layout/notification_action.xml b/compat/res/layout/notification_action.xml
new file mode 100644
index 0000000..3ffd9a1
--- /dev/null
+++ b/compat/res/layout/notification_action.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/Widget.Compat.NotificationActionContainer"
+    android:id="@+id/action_container"
+    android:layout_width="0dp"
+    android:layout_weight="1"
+    android:layout_height="48dp"
+    android:paddingLeft="4dp"
+    android:paddingStart="4dp"
+    android:orientation="horizontal">
+    <ImageView
+        android:id="@+id/action_image"
+        android:layout_width="@dimen/notification_action_icon_size"
+        android:layout_height="@dimen/notification_action_icon_size"
+        android:layout_gravity="center|start"
+        android:scaleType="centerInside"/>
+    <TextView
+        style="@style/Widget.Compat.NotificationActionText"
+        android:id="@+id/action_text"
+        android:textColor="#ccc"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center|start"
+        android:paddingLeft="4dp"
+        android:paddingStart="4dp"
+        android:singleLine="true"
+        android:ellipsize="end"
+        android:clickable="false"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/compat/res/layout/notification_action_tombstone.xml b/compat/res/layout/notification_action_tombstone.xml
new file mode 100644
index 0000000..e9d4e37
--- /dev/null
+++ b/compat/res/layout/notification_action_tombstone.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/Widget.Compat.NotificationActionContainer"
+    android:id="@+id/action_container"
+    android:layout_width="0dp"
+    android:layout_weight="1"
+    android:layout_height="48dp"
+    android:paddingLeft="4dp"
+    android:paddingStart="4dp"
+    android:orientation="horizontal"
+    android:enabled="false"
+    android:background="@null">
+    <ImageView
+        android:id="@+id/action_image"
+        android:layout_width="@dimen/notification_action_icon_size"
+        android:layout_height="@dimen/notification_action_icon_size"
+        android:layout_gravity="center|start"
+        android:scaleType="centerInside"
+        android:enabled="false"
+        android:alpha="0.5"/>
+    <TextView
+        style="@style/Widget.Compat.NotificationActionText"
+        android:id="@+id/action_text"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center|start"
+        android:textColor="#ccc"
+        android:paddingLeft="4dp"
+        android:paddingStart="4dp"
+        android:singleLine="true"
+        android:ellipsize="end"
+        android:clickable="false"
+        android:enabled="false"
+        android:alpha="0.5"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/compat/res/layout/notification_template_custom_big.xml b/compat/res/layout/notification_template_custom_big.xml
new file mode 100644
index 0000000..8aaf9d5
--- /dev/null
+++ b/compat/res/layout/notification_template_custom_big.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<LinearLayout android:id="@+id/notification_main_column_container"
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:minHeight="@dimen/notification_large_icon_height"
+    android:orientation="horizontal"
+    android:paddingRight="12dp"
+    android:paddingEnd="12dp">
+    <ImageView android:id="@+id/icon"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+        android:background="@drawable/notification_tile_bg"
+        android:scaleType="center"
+    />
+    <FrameLayout
+        android:id="@+id/notification_main_column"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:paddingLeft="12dp"
+        android:paddingStart="12dp"
+        android:paddingTop="@dimen/notification_main_column_padding_top"
+        android:layout_weight="1"/>
+    <FrameLayout
+        android:id="@+id/right_side"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:paddingTop="12dp"
+        android:paddingLeft="12dp">
+        <include
+            layout="@layout/notification_template_part_time"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="end|top"
+            android:visibility="gone"/>
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_gravity="end|bottom"
+            android:layout_marginTop="18dp"
+            android:orientation="horizontal">
+            <TextView android:id="@+id/info"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_gravity="center"
+                android:singleLine="true"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Info"
+            />
+            <ImageView android:id="@+id/right_icon"
+                android:layout_width="24dp"
+                android:layout_height="24dp"
+                android:layout_gravity="center"
+                android:layout_marginLeft="8dp"
+                android:alpha="0.7"
+                android:scaleType="center"
+                android:visibility="gone"
+            />
+        </LinearLayout>
+    </FrameLayout>
+</LinearLayout>
\ No newline at end of file
diff --git a/compat/res/layout/notification_template_icon_group.xml b/compat/res/layout/notification_template_icon_group.xml
new file mode 100644
index 0000000..f225737
--- /dev/null
+++ b/compat/res/layout/notification_template_icon_group.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<ImageView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/icon"
+    android:layout_width="@dimen/notification_large_icon_width"
+    android:layout_height="@dimen/notification_large_icon_height"
+    android:scaleType="centerCrop"
+/>
diff --git a/compat/res/layout/notification_template_part_chronometer.xml b/compat/res/layout/notification_template_part_chronometer.xml
new file mode 100644
index 0000000..245353b
--- /dev/null
+++ b/compat/res/layout/notification_template_part_chronometer.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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
+  -->
+
+<Chronometer android:id="@+id/chronometer" xmlns:android="http://schemas.android.com/apk/res/android"
+    android:textAppearance="@style/TextAppearance.Compat.Notification.Time"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:singleLine="true"
+    />
diff --git a/compat/res/layout/notification_template_part_time.xml b/compat/res/layout/notification_template_part_time.xml
new file mode 100644
index 0000000..9a78a93
--- /dev/null
+++ b/compat/res/layout/notification_template_part_time.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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
+  -->
+
+<DateTimeView android:id="@+id/time" xmlns:android="http://schemas.android.com/apk/res/android"
+    android:textAppearance="@style/TextAppearance.Compat.Notification.Time"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:singleLine="true"
+    />
diff --git a/compat/res/values-af/strings.xml b/compat/res/values-af/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-af/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-am/strings.xml b/compat/res/values-am/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-am/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ar/strings.xml b/compat/res/values-ar/strings.xml
new file mode 100644
index 0000000..d9094fb
--- /dev/null
+++ b/compat/res/values-ar/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"+999"</string>
+</resources>
diff --git a/compat/res/values-az/strings.xml b/compat/res/values-az/strings.xml
new file mode 100644
index 0000000..f2e04fe
--- /dev/null
+++ b/compat/res/values-az/strings.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <!-- String.format failed for translation -->
+    <!-- no translation found for abc_shareactionprovider_share_with_application (7165123711973476752) -->
+    <skip />
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-b+sr+Latn/strings.xml b/compat/res/values-b+sr+Latn/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-b+sr+Latn/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-be/strings.xml b/compat/res/values-be/strings.xml
new file mode 100644
index 0000000..ae35194
--- /dev/null
+++ b/compat/res/values-be/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"больш за 999"</string>
+</resources>
diff --git a/compat/res/values-bg/strings.xml b/compat/res/values-bg/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-bg/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-bn/strings.xml b/compat/res/values-bn/strings.xml
new file mode 100644
index 0000000..01516f8
--- /dev/null
+++ b/compat/res/values-bn/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"৯৯৯+"</string>
+</resources>
diff --git a/compat/res/values-bs/strings.xml b/compat/res/values-bs/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-bs/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-ca/strings.xml b/compat/res/values-ca/strings.xml
new file mode 100644
index 0000000..d9094fb
--- /dev/null
+++ b/compat/res/values-ca/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"+999"</string>
+</resources>
diff --git a/compat/res/values-cs/strings.xml b/compat/res/values-cs/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-cs/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-da/strings.xml b/compat/res/values-da/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-da/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-de/strings.xml b/compat/res/values-de/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-de/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-el/strings.xml b/compat/res/values-el/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-el/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-en-rAU/strings.xml b/compat/res/values-en-rAU/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-en-rAU/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-en-rGB/strings.xml b/compat/res/values-en-rGB/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-en-rGB/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-en-rIN/strings.xml b/compat/res/values-en-rIN/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-en-rIN/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-es-rUS/strings.xml b/compat/res/values-es-rUS/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-es-rUS/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-es/strings.xml b/compat/res/values-es/strings.xml
new file mode 100644
index 0000000..d9094fb
--- /dev/null
+++ b/compat/res/values-es/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"+999"</string>
+</resources>
diff --git a/compat/res/values-et/strings.xml b/compat/res/values-et/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-et/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-eu/strings.xml b/compat/res/values-eu/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-eu/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-fa/strings.xml b/compat/res/values-fa/strings.xml
new file mode 100644
index 0000000..0470999
--- /dev/null
+++ b/compat/res/values-fa/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"۹۹۹+"</string>
+</resources>
diff --git a/compat/res/values-fi/strings.xml b/compat/res/values-fi/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-fi/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-fr-rCA/strings.xml b/compat/res/values-fr-rCA/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-fr-rCA/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-fr/strings.xml b/compat/res/values-fr/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-fr/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-gl/strings.xml b/compat/res/values-gl/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-gl/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-gu/strings.xml b/compat/res/values-gu/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-gu/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-hi/strings.xml b/compat/res/values-hi/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-hi/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-hr/strings.xml b/compat/res/values-hr/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-hr/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-hu/strings.xml b/compat/res/values-hu/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-hu/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-hy/strings.xml b/compat/res/values-hy/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-hy/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-in/strings.xml b/compat/res/values-in/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-in/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-is/strings.xml b/compat/res/values-is/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-is/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-it/strings.xml b/compat/res/values-it/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-it/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-iw/strings.xml b/compat/res/values-iw/strings.xml
new file mode 100644
index 0000000..6799e67
--- /dev/null
+++ b/compat/res/values-iw/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"‎999+‎"</string>
+</resources>
diff --git a/compat/res/values-ja/strings.xml b/compat/res/values-ja/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ja/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ka/strings.xml b/compat/res/values-ka/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ka/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-kk/strings.xml b/compat/res/values-kk/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-kk/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-km/strings.xml b/compat/res/values-km/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-km/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-kn/strings.xml b/compat/res/values-kn/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-kn/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ko/strings.xml b/compat/res/values-ko/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ko/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ky/strings.xml b/compat/res/values-ky/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ky/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-lo/strings.xml b/compat/res/values-lo/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-lo/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-lt/strings.xml b/compat/res/values-lt/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-lt/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-lv/strings.xml b/compat/res/values-lv/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-lv/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-mk/strings.xml b/compat/res/values-mk/strings.xml
new file mode 100644
index 0000000..8c8797d
--- /dev/null
+++ b/compat/res/values-mk/strings.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <!-- String.format failed for translation -->
+    <!-- no translation found for abc_action_bar_home_description_format (1397052879051804371) -->
+    <skip />
+    <!-- String.format failed for translation -->
+    <!-- no translation found for abc_shareactionprovider_share_with_application (7165123711973476752) -->
+    <skip />
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ml/strings.xml b/compat/res/values-ml/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ml/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-mn/strings.xml b/compat/res/values-mn/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-mn/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-mr/strings.xml b/compat/res/values-mr/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-mr/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ms/strings.xml b/compat/res/values-ms/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ms/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-my/strings.xml b/compat/res/values-my/strings.xml
new file mode 100644
index 0000000..cfad64a
--- /dev/null
+++ b/compat/res/values-my/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"၉၉၉+"</string>
+</resources>
diff --git a/compat/res/values-nb/strings.xml b/compat/res/values-nb/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-nb/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ne/strings.xml b/compat/res/values-ne/strings.xml
new file mode 100644
index 0000000..3dd1d09
--- /dev/null
+++ b/compat/res/values-ne/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"९९९+"</string>
+</resources>
diff --git a/compat/res/values-nl/strings.xml b/compat/res/values-nl/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-nl/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-pa/strings.xml b/compat/res/values-pa/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-pa/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-pl/strings.xml b/compat/res/values-pl/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-pl/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-port/bools.xml b/compat/res/values-port/bools.xml
new file mode 100644
index 0000000..25053be
--- /dev/null
+++ b/compat/res/values-port/bools.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<resources>
+
+    <bool name="abc_action_bar_embed_tabs">false</bool>
+
+</resources>
diff --git a/compat/res/values-pt-rBR/strings.xml b/compat/res/values-pt-rBR/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-pt-rBR/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-pt-rPT/strings.xml b/compat/res/values-pt-rPT/strings.xml
new file mode 100644
index 0000000..d9094fb
--- /dev/null
+++ b/compat/res/values-pt-rPT/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"+999"</string>
+</resources>
diff --git a/compat/res/values-pt/strings.xml b/compat/res/values-pt/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-pt/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ro/strings.xml b/compat/res/values-ro/strings.xml
new file mode 100644
index 0000000..42598dc
--- /dev/null
+++ b/compat/res/values-ro/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"˃999"</string>
+</resources>
diff --git a/compat/res/values-ru/strings.xml b/compat/res/values-ru/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-ru/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-si/strings.xml b/compat/res/values-si/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-si/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-sk/strings.xml b/compat/res/values-sk/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-sk/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-sl/strings.xml b/compat/res/values-sl/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-sl/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-sq/strings.xml b/compat/res/values-sq/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-sq/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-sr/strings.xml b/compat/res/values-sr/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-sr/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-sv/strings.xml b/compat/res/values-sv/strings.xml
new file mode 100644
index 0000000..df46d35
--- /dev/null
+++ b/compat/res/values-sv/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"&gt;999"</string>
+</resources>
diff --git a/compat/res/values-sw/strings.xml b/compat/res/values-sw/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-sw/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ta/strings.xml b/compat/res/values-ta/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-ta/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-te/strings.xml b/compat/res/values-te/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-te/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-th/strings.xml b/compat/res/values-th/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-th/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-tl/strings.xml b/compat/res/values-tl/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-tl/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-tr/strings.xml b/compat/res/values-tr/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-tr/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-uk/strings.xml b/compat/res/values-uk/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-uk/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-ur/strings.xml b/compat/res/values-ur/strings.xml
new file mode 100644
index 0000000..6799e67
--- /dev/null
+++ b/compat/res/values-ur/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"‎999+‎"</string>
+</resources>
diff --git a/compat/res/values-uz/strings.xml b/compat/res/values-uz/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-uz/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/v7/appcompat/res/values-v16/dimens.xml b/compat/res/values-v16/dimens.xml
similarity index 100%
rename from v7/appcompat/res/values-v16/dimens.xml
rename to compat/res/values-v16/dimens.xml
diff --git a/v7/appcompat/res/values-v21/colors.xml b/compat/res/values-v21/colors.xml
similarity index 100%
rename from v7/appcompat/res/values-v21/colors.xml
rename to compat/res/values-v21/colors.xml
diff --git a/compat/res/values-v21/dimens.xml b/compat/res/values-v21/dimens.xml
new file mode 100644
index 0000000..b56faf1
--- /dev/null
+++ b/compat/res/values-v21/dimens.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+
+<resources>
+    <!-- the margin at the beginning of the notification content -->
+    <dimen name="notification_content_margin_start">0dp</dimen>
+    <!-- image margin on the large icon in the narrow media template -->
+    <dimen name="notification_media_narrow_margin">12dp</dimen>
+    <!-- the top padding of the notification content -->
+    <dimen name="notification_main_column_padding_top">0dp</dimen>
+</resources>
diff --git a/compat/res/values-v21/styles.xml b/compat/res/values-v21/styles.xml
new file mode 100644
index 0000000..fb87295
--- /dev/null
+++ b/compat/res/values-v21/styles.xml
@@ -0,0 +1,42 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+
+    <!-- Use platform styles -->
+    <style name="TextAppearance.Compat.Notification"
+        parent="@android:style/TextAppearance.Material.Notification"/>
+
+    <style name="TextAppearance.Compat.Notification.Title"
+        parent="@android:style/TextAppearance.Material.Notification.Title"/>
+
+    <style name="TextAppearance.Compat.Notification.Info"
+        parent="@android:style/TextAppearance.Material.Notification.Info"/>
+
+    <style name="TextAppearance.Compat.Notification.Time"
+        parent="@android:style/TextAppearance.Material.Notification.Time"/>
+
+    <style name="Widget.Compat.NotificationActionText" parent="">
+        <item name="android:textAppearance">?android:attr/textAppearanceButton</item>
+        <item name="android:textColor">@color/secondary_text_default_material_light</item>
+        <item name="android:textSize">@dimen/notification_action_text_size</item>
+    </style>
+
+    <style name="Widget.Compat.NotificationActionContainer" parent="">
+        <item name="android:background">@drawable/notification_action_background</item>
+    </style>
+
+</resources>
diff --git a/compat/res/values-vi/strings.xml b/compat/res/values-vi/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-vi/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-zh-rCN/strings.xml b/compat/res/values-zh-rCN/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-zh-rCN/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-zh-rHK/strings.xml b/compat/res/values-zh-rHK/strings.xml
new file mode 100644
index 0000000..d509360
--- /dev/null
+++ b/compat/res/values-zh-rHK/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999 +"</string>
+</resources>
diff --git a/compat/res/values-zh-rTW/strings.xml b/compat/res/values-zh-rTW/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-zh-rTW/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values-zu/strings.xml b/compat/res/values-zu/strings.xml
new file mode 100644
index 0000000..4640923
--- /dev/null
+++ b/compat/res/values-zu/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="status_bar_notification_info_overflow" msgid="2869576371154716097">"999+"</string>
+</resources>
diff --git a/compat/res/values/colors.xml b/compat/res/values/colors.xml
new file mode 100644
index 0000000..a3eccb7
--- /dev/null
+++ b/compat/res/values/colors.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<resources>
+    <drawable name="notification_template_icon_bg">#3333B5E5</drawable>
+    <drawable name="notification_template_icon_low_bg">#0cffffff</drawable>
+    <color name="notification_action_color_filter">#ffffffff</color>
+    <color name="notification_icon_bg_color">#ff9e9e9e</color>
+</resources>
diff --git a/compat/res/values/colors_material.xml b/compat/res/values/colors_material.xml
new file mode 100644
index 0000000..c6cffdc
--- /dev/null
+++ b/compat/res/values/colors_material.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Colors specific to Material themes. -->
+<resources>
+    <!-- 12% black (foreground) -->
+    <color name="ripple_material_light">#1f000000</color>
+    <!-- 54% black -->
+    <color name="secondary_text_default_material_light">#8a000000</color>
+</resources>
diff --git a/compat/res/values/config.xml b/compat/res/values/config.xml
new file mode 100644
index 0000000..42633cc
--- /dev/null
+++ b/compat/res/values/config.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- These resources are around just to allow their values to be customized
+     for different hardware and product builds. -->
+<resources>
+    <!-- Maximum numerical value that will be shown in a status bar
+         notification icon or in the notification itself. Will be replaced
+         with @string/status_bar_notification_info_overflow when shown in the
+         UI. -->
+    <integer name="status_bar_notification_info_maxnum">999</integer>
+</resources>
diff --git a/compat/res/values/dimens.xml b/compat/res/values/dimens.xml
new file mode 100644
index 0000000..1dcff5e
--- /dev/null
+++ b/compat/res/values/dimens.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <dimen name="compat_button_inset_vertical_material">6dp</dimen>
+    <dimen name="compat_button_inset_horizontal_material">4dp</dimen>
+    <!-- Default inner padding within buttons -->
+    <dimen name="compat_button_padding_vertical_material">4dp</dimen>
+    <dimen name="compat_button_padding_horizontal_material">8dp</dimen>
+
+    <!-- Default rounded corner for controls -->
+    <dimen name="compat_control_corner_material">2dp</dimen>
+
+    <!-- The width of the big icons in notifications. -->
+    <dimen name="notification_large_icon_width">64dp</dimen>
+
+    <!-- The width of the big icons in notifications. -->
+    <dimen name="notification_large_icon_height">64dp</dimen>
+
+    <!-- Size of smaller notification text (see TextAppearance.StatusBar.EventContent.Line2, Info,
+         Time) -->
+    <dimen name="notification_subtext_size">13sp</dimen>
+
+    <!-- Size of notification action text -->
+    <dimen name="notification_action_text_size">13sp</dimen>
+
+    <!-- Top padding for notifications in the standard layout. -->
+    <dimen name="notification_top_pad">10dp</dimen>
+
+    <!-- Top padding for notification when text is large -->
+    <dimen name="notification_top_pad_large_text">5dp</dimen>
+
+    <!-- The size of the action icons -->
+    <dimen name="notification_action_icon_size">32dp</dimen>
+
+    <!-- the size of the small icon on the right of the largeIcon -->
+    <dimen name="notification_right_icon_size">16dp</dimen>
+
+    <!-- the padding of the small icon to the circle -->
+    <dimen name="notification_small_icon_background_padding">3dp</dimen>
+
+    <!-- the side margin of the big notification circle -->
+    <dimen name="notification_big_circle_margin">12dp</dimen>
+
+    <!-- small icon size when placed as large icon -->
+    <dimen name="notification_small_icon_size_as_large">24dp</dimen>
+
+    <!-- the margin at the beginning of the notification content -->
+    <dimen name="notification_content_margin_start">8dp</dimen>
+
+    <!-- image margin on the large icon in the narrow media template -->
+    <dimen name="notification_media_narrow_margin">@dimen/notification_content_margin_start</dimen>
+
+    <!-- the top padding of the notification content -->
+    <dimen name="notification_main_column_padding_top">10dp</dimen>
+
+    <!-- the paddingtop on the right side of the notification (for time etc.) -->
+    <dimen name="notification_right_side_padding_top">2dp</dimen>
+</resources>
diff --git a/compat/res/values/ids.xml b/compat/res/values/ids.xml
new file mode 100644
index 0000000..e83d5f9
--- /dev/null
+++ b/compat/res/values/ids.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<resources>
+    <item type="id" name="title"/>
+    <item type="id" name="text"/>
+    <item type="id" name="text2"/>
+    <item type="id" name="line1"/>
+    <item type="id" name="line3"/>
+</resources>
diff --git a/compat/res/values/strings.xml b/compat/res/values/strings.xml
new file mode 100644
index 0000000..ceeb183
--- /dev/null
+++ b/compat/res/values/strings.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <!-- Text to use when the number in a notification info is too large
+         (greater than status_bar_notification_info_maxnum, defined in
+         values/config.xml) and must be truncated. May need to be localized
+         for most appropriate textual indicator of "more than X".
+         [CHAR LIMIT=4] -->
+    <string name="status_bar_notification_info_overflow">999+</string>
+</resources>
diff --git a/compat/res/values/styles.xml b/compat/res/values/styles.xml
new file mode 100644
index 0000000..3503e77
--- /dev/null
+++ b/compat/res/values/styles.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <style name="TextAppearance.Compat.Notification"
+        parent="@android:style/TextAppearance.StatusBar.EventContent"/>
+
+    <style name="TextAppearance.Compat.Notification.Title"
+        parent="@android:style/TextAppearance.StatusBar.EventContent.Title"/>
+
+    <style name="TextAppearance.Compat.Notification.Info">
+        <item name="android:textSize">12sp</item>
+        <item name="android:textColor">?android:attr/textColorSecondary</item>
+    </style>
+    <style name="TextAppearance.Compat.Notification.Time">
+        <item name="android:textSize">12sp</item>
+        <item name="android:textColor">?android:attr/textColorSecondary</item>
+    </style>
+    <style name="TextAppearance.Compat.Notification.Line2"
+         parent="TextAppearance.Compat.Notification.Info" />
+
+    <style name="Widget.Compat.NotificationActionText" parent=""/>
+    <style name="Widget.Compat.NotificationActionContainer" parent=""/>
+</resources>
diff --git a/compat/tests/AndroidManifest.xml b/compat/tests/AndroidManifest.xml
index 124d877..4988845 100644
--- a/compat/tests/AndroidManifest.xml
+++ b/compat/tests/AndroidManifest.xml
@@ -15,21 +15,16 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.compat.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="26"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.VIBRATE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
 
     <application
-            android:supportsRtl="true"
-            android:theme="@style/TestActivityTheme">
+        android:supportsRtl="true"
+        android:theme="@style/TestActivityTheme">
         <activity android:name="android.support.v4.widget.ListViewTestActivity"/>
 
         <activity android:name="android.support.v4.widget.TextViewTestActivity"/>
@@ -38,19 +33,19 @@
 
         <activity
             android:name="android.support.v4.ThemedYellowActivity"
-            android:theme="@style/YellowTheme" />
+            android:theme="@style/YellowTheme"/>
 
         <activity android:name="android.support.v4.view.ViewCompatActivity"/>
 
-        <activity android:name="android.support.v4.app.TestSupportActivity" />
+        <activity android:name="android.support.v4.app.TestSupportActivity"/>
 
         <provider android:name="android.support.v4.provider.MockFontProvider"
                   android:authorities="android.support.provider.fonts.font"
                   android:exported="false"
-                  android:multiprocess="true" />
+                  android:multiprocess="true"/>
 
         <service android:name="android.support.v4.app.JobIntentServiceTest$TargetService"
-            android:permission="android.permission.BIND_JOB_SERVICE" />
+                 android:permission="android.permission.BIND_JOB_SERVICE"/>
 
     </application>
 
diff --git a/compat/tests/java/android/support/v4/app/JobIntentServiceTest.java b/compat/tests/java/android/support/v4/app/JobIntentServiceTest.java
index b108053..c5fa715 100644
--- a/compat/tests/java/android/support/v4/app/JobIntentServiceTest.java
+++ b/compat/tests/java/android/support/v4/app/JobIntentServiceTest.java
@@ -19,13 +19,16 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
+import android.app.job.JobScheduler;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.net.Uri;
+import android.os.Build;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.MediumTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -47,6 +50,9 @@
 
     static final Object sLock = new Object();
     static CountDownLatch sReadyToRunLatch;
+    static CountDownLatch sServiceWaitingLatch;
+    static CountDownLatch sServiceStoppedLatch;
+    static CountDownLatch sWaitCompleteLatch;
     static CountDownLatch sServiceFinishedLatch;
 
     static boolean sFinished;
@@ -62,14 +68,28 @@
     }
 
     public static final class TestIntentItem implements Parcelable {
+        public static final int FLAG_WAIT = 1 << 0;
+        public static final int FLAG_STOPPED_AFTER_WAIT = 1 << 1;
+
         public final Intent intent;
         public final TestIntentItem[] subitems;
+        public final int flags;
         public final Uri[] requireUrisGranted;
         public final Uri[] requireUrisNotGranted;
 
         public TestIntentItem(Intent intent) {
             this.intent = intent;
             subitems = null;
+            flags = 0;
+            requireUrisGranted = null;
+            requireUrisNotGranted = null;
+        }
+
+        public TestIntentItem(Intent intent, int flags) {
+            this.intent = intent;
+            subitems = null;
+            this.flags = flags;
+            intent.putExtra("flags", flags);
             requireUrisGranted = null;
             requireUrisNotGranted = null;
         }
@@ -78,6 +98,7 @@
             this.intent = intent;
             this.subitems = subitems;
             intent.putExtra("subitems", subitems);
+            flags = 0;
             requireUrisGranted = null;
             requireUrisNotGranted = null;
         }
@@ -86,6 +107,7 @@
                 Uri[] requireUrisNotGranted) {
             this.intent = intent;
             subitems = null;
+            flags = 0;
             this.requireUrisGranted = requireUrisGranted;
             this.requireUrisNotGranted = requireUrisNotGranted;
         }
@@ -108,11 +130,13 @@
         public void writeToParcel(Parcel parcel, int flags) {
             intent.writeToParcel(parcel, flags);
             parcel.writeTypedArray(subitems, flags);
+            parcel.writeInt(flags);
         }
 
         TestIntentItem(Parcel parcel) {
             intent = Intent.CREATOR.createFromParcel(parcel);
             subitems = parcel.createTypedArray(CREATOR);
+            flags = parcel.readInt();
             requireUrisGranted = null;
             requireUrisNotGranted = null;
         }
@@ -133,6 +157,9 @@
     static void initStatics() {
         synchronized (sLock) {
             sReadyToRunLatch = new CountDownLatch(1);
+            sServiceWaitingLatch = new CountDownLatch(1);
+            sServiceStoppedLatch = new CountDownLatch(1);
+            sWaitCompleteLatch = new CountDownLatch(1);
             sServiceFinishedLatch = new CountDownLatch(1);
             sFinished = false;
             sFinishedWork = null;
@@ -144,6 +171,38 @@
         sReadyToRunLatch.countDown();
     }
 
+    static void serviceReportWaiting() {
+        sServiceWaitingLatch.countDown();
+    }
+
+    static void ensureServiceWaiting() {
+        try {
+            if (!sServiceWaitingLatch.await(10, TimeUnit.SECONDS)) {
+                fail("Timed out waiting for wait, service state " + sLastServiceState);
+            }
+        } catch (InterruptedException e) {
+            fail("Interrupted waiting for service to wait: " + e);
+        }
+    }
+
+    static void serviceReportStopped() {
+        sServiceStoppedLatch.countDown();
+    }
+
+    static void ensureServiceStopped() {
+        try {
+            if (!sServiceStoppedLatch.await(10, TimeUnit.SECONDS)) {
+                fail("Timed out waiting for stop, service state " + sLastServiceState);
+            }
+        } catch (InterruptedException e) {
+            fail("Interrupted waiting for service to stop: " + e);
+        }
+    }
+
+    static void allowServiceToResumeFromWait() {
+        sWaitCompleteLatch.countDown();
+    }
+
     static void finishServiceExecution(ArrayList<Intent> work, String errorMsg) {
         synchronized (sLock) {
             if (!sFinished) {
@@ -207,6 +266,22 @@
             updateServiceState("Handling work: " + intent);
             mReceivedWork.add(intent);
             intent.setExtrasClassLoader(TestIntentItem.class.getClassLoader());
+            int flags = intent.getIntExtra("flags", 0);
+            if ((flags & TestIntentItem.FLAG_WAIT) != 0) {
+                serviceReportWaiting();
+                try {
+                    if (!sWaitCompleteLatch.await(10, TimeUnit.SECONDS)) {
+                        finishServiceExecution(null, "Timeout waiting for wait complete");
+                    }
+                } catch (InterruptedException e) {
+                    finishServiceExecution(null, "Interrupted waiting for wait complete: " + e);
+                }
+                if ((flags & TestIntentItem.FLAG_STOPPED_AFTER_WAIT) != 0) {
+                    if (!isStopped()) {
+                        finishServiceExecution(null, "Service not stopped after waiting");
+                    }
+                }
+            }
             Parcelable[] subitems = intent.getParcelableArrayExtra("subitems");
             if (subitems != null) {
                 for (Parcelable pitem : subitems) {
@@ -217,6 +292,12 @@
         }
 
         @Override
+        public boolean onStopCurrentWork() {
+            serviceReportStopped();
+            return super.onStopCurrentWork();
+        }
+
+        @Override
         public void onDestroy() {
             Log.i(TAG, "Destroying: " + this);
             updateServiceState("Destroying: " + this);
@@ -347,4 +428,42 @@
         waitServiceFinish();
         compareIntents(items, sFinishedWork);
     }
+
+    /**
+     * Test case of job stopping while it is doing work.
+     */
+    @MediumTest
+    @Test
+    @RequiresApi(26)
+    public void testStopWhileWorking() throws Throwable {
+        if (Build.VERSION.SDK_INT < 26) {
+            // This test only makes sense when running on top of JobScheduler.
+            return;
+        }
+
+        initStatics();
+
+        TestIntentItem[] items = new TestIntentItem[] {
+                new TestIntentItem(new Intent("FIRST"),
+                        TestIntentItem.FLAG_WAIT | TestIntentItem.FLAG_STOPPED_AFTER_WAIT),
+        };
+
+        for (TestIntentItem item : items) {
+            JobIntentService.enqueueWork(mContext, TargetService.class, JOB_ID, item.intent);
+        }
+        allowServiceToRun();
+        ensureServiceWaiting();
+
+        // At this point we will make the job stop...  this isn't normally how this would
+        // happen with an IntentJobService, and doing it this way breaks re-delivery of
+        // work, but we have CTS tests for the underlying redlivery mechanism.
+        ((JobScheduler) mContext.getApplicationContext().getSystemService(
+                Context.JOB_SCHEDULER_SERVICE)).cancel(JOB_ID);
+        ensureServiceStopped();
+
+        allowServiceToResumeFromWait();
+
+        waitServiceFinish();
+        compareIntents(items, sFinishedWork);
+    }
 }
diff --git a/compat/tests/java/android/support/v4/app/NotificationCompatTest.java b/compat/tests/java/android/support/v4/app/NotificationCompatTest.java
index 7e1ea30..dd870dd 100644
--- a/compat/tests/java/android/support/v4/app/NotificationCompatTest.java
+++ b/compat/tests/java/android/support/v4/app/NotificationCompatTest.java
@@ -41,7 +41,6 @@
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.BaseInstrumentationTestCase;
-import android.support.v4.os.BuildCompat;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -74,7 +73,7 @@
         Notification n = new NotificationCompat.Builder(mActivityTestRule.getActivity())
                 .setBadgeIconType(badgeIcon)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             assertEquals(badgeIcon, NotificationCompat.getBadgeIconType(n));
         } else {
             assertEquals(NotificationCompat.BADGE_ICON_NONE,
@@ -86,12 +85,12 @@
     public void testTimeout() throws Throwable {
         long timeout = 23552;
         Notification n = new NotificationCompat.Builder(mActivityTestRule.getActivity())
-                .setTimeout(timeout)
+                .setTimeoutAfter(timeout)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
-            assertEquals(timeout, NotificationCompat.getTimeout(n));
+        if (Build.VERSION.SDK_INT >= 26) {
+            assertEquals(timeout, NotificationCompat.getTimeoutAfter(n));
         } else {
-            assertEquals(0, NotificationCompat.getTimeout(n));
+            assertEquals(0, NotificationCompat.getTimeoutAfter(n));
         }
     }
 
@@ -101,7 +100,7 @@
         Notification n = new NotificationCompat.Builder(mActivityTestRule.getActivity())
                 .setShortcutId(shortcutId)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             assertEquals(shortcutId, NotificationCompat.getShortcutId(n));
         } else {
             assertEquals(null, NotificationCompat.getShortcutId(n));
@@ -112,12 +111,12 @@
     public void testNotificationChannel() throws Throwable {
         String channelId = "new ID";
         Notification n  = new NotificationCompat.Builder(mActivityTestRule.getActivity())
-                .setChannel(channelId)
+                .setChannelId(channelId)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
-            assertEquals(channelId, NotificationCompat.getChannel(n));
+        if (Build.VERSION.SDK_INT >= 26) {
+            assertEquals(channelId, NotificationCompat.getChannelId(n));
         } else {
-            assertNull(NotificationCompat.getChannel(n));
+            assertNull(NotificationCompat.getChannelId(n));
         }
     }
 
@@ -126,17 +125,17 @@
         String channelId = "new ID";
         Notification n  = new NotificationCompat.Builder(mActivityTestRule.getActivity(), channelId)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
-            assertEquals(channelId, NotificationCompat.getChannel(n));
+        if (Build.VERSION.SDK_INT >= 26) {
+            assertEquals(channelId, NotificationCompat.getChannelId(n));
         } else {
-            assertNull(NotificationCompat.getChannel(n));
+            assertNull(NotificationCompat.getChannelId(n));
         }
     }
 
     @Test
     public void testNotificationActionBuilder_assignsColorized() throws Throwable {
         Notification n = newNotificationBuilder().setColorized(true).build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             Bundle extras = NotificationCompat.getExtras(n);
             assertTrue(Boolean.TRUE.equals(extras.get(EXTRA_COLORIZED)));
         }
@@ -145,7 +144,7 @@
     @Test
     public void testNotificationActionBuilder_unassignesColorized() throws Throwable {
         Notification n = newNotificationBuilder().setColorized(false).build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             Bundle extras = NotificationCompat.getExtras(n);
             assertTrue(Boolean.FALSE.equals(extras.get(EXTRA_COLORIZED)));
         }
@@ -154,7 +153,7 @@
     @Test
     public void testNotificationActionBuilder_doesntAssignColorized() throws Throwable {
         Notification n = newNotificationBuilder().build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             Bundle extras = NotificationCompat.getExtras(n);
             assertFalse(extras.containsKey(EXTRA_COLORIZED));
         }
@@ -180,6 +179,18 @@
         assertEquals(a.getAllowGeneratedReplies(), aCopy.getAllowGeneratedReplies());
     }
 
+    @SdkSuppress(minSdkVersion = 24)
+    @TargetApi(24)
+    @Test
+    public void testFrameworkNotificationActionBuilder_setAllowGeneratedRepliesTrue()
+            throws Throwable {
+        Notification notif = new Notification.Builder(mContext)
+                .addAction(new Notification.Action.Builder(0, "title", null)
+                        .setAllowGeneratedReplies(true).build()).build();
+        NotificationCompat.Action action = NotificationCompat.getAction(notif, 0);
+        assertTrue(action.getAllowGeneratedReplies());
+    }
+
     @Test
     public void testNotificationActionBuilder_defaultAllowGeneratedRepliesTrue() throws Throwable {
         NotificationCompat.Action a = newActionBuilder().build();
@@ -288,7 +299,7 @@
         Notification n = new NotificationCompat.Builder(mActivityTestRule.getActivity())
                 .setGroupAlertBehavior(GROUP_ALERT_CHILDREN)
                 .build();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             assertEquals(GROUP_ALERT_CHILDREN, NotificationCompat.getGroupAlertBehavior(n));
         } else {
             assertEquals(GROUP_ALERT_ALL, NotificationCompat.getGroupAlertBehavior(n));
@@ -318,7 +329,7 @@
                 .setGroupSummary(false)
                 .build();
 
-        if (Build.VERSION.SDK_INT >= 20 && !BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 20 && !(Build.VERSION.SDK_INT >= 26)) {
             assertNull(n.sound);
             assertNull(n.vibrate);
             assertTrue((n.defaults & DEFAULT_LIGHTS) != 0);
@@ -373,7 +384,7 @@
                 .setGroupSummary(false)
                 .build();
 
-        if (Build.VERSION.SDK_INT >= 20 && !BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 20 && !(Build.VERSION.SDK_INT >= 26)) {
             assertNotNull(n.sound);
             assertNotNull(n.vibrate);
             assertTrue((n.defaults & DEFAULT_LIGHTS) != 0);
@@ -404,7 +415,7 @@
                 .setGroup(null)
                 .setGroupSummary(false)
                 .build();
-        if (!BuildCompat.isAtLeastO()) {
+        if (!(Build.VERSION.SDK_INT >= 26)) {
             assertNotNull(n.sound);
             assertNotNull(n.vibrate);
             assertTrue((n.defaults & DEFAULT_LIGHTS) != 0);
diff --git a/compat/tests/java/android/support/v4/content/pm/ShortcutManagerCompatTest.java b/compat/tests/java/android/support/v4/content/pm/ShortcutManagerCompatTest.java
index 54a17c6..77e7ae8 100644
--- a/compat/tests/java/android/support/v4/content/pm/ShortcutManagerCompatTest.java
+++ b/compat/tests/java/android/support/v4/content/pm/ShortcutManagerCompatTest.java
@@ -45,13 +45,13 @@
 import android.content.pm.ShortcutInfo;
 import android.content.pm.ShortcutManager;
 import android.graphics.Bitmap;
+import android.os.Build;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.BaseInstrumentationTestCase;
 import android.support.v4.app.TestSupportActivity;
-import android.support.v4.os.BuildCompat;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -86,7 +86,7 @@
     @SmallTest
     @TargetApi(26)
     public void testIsRequestPinShortcutSupported_v26() throws Throwable {
-        if (!BuildCompat.isAtLeastO()) {
+        if (!(Build.VERSION.SDK_INT >= 26)) {
             return;
         }
 
@@ -104,7 +104,7 @@
     @SmallTest
     @TargetApi(26)
     public void testRequestPinShortcut_v26()  throws Throwable {
-        if (!BuildCompat.isAtLeastO()) {
+        if (!(Build.VERSION.SDK_INT >= 26)) {
             return;
         }
 
@@ -124,7 +124,7 @@
     @SmallTest
     @TargetApi(26)
     public void testCreateShortcutResultIntent_v26()  throws Throwable {
-        if (!BuildCompat.isAtLeastO()) {
+        if (!(Build.VERSION.SDK_INT >= 26)) {
             return;
         }
 
@@ -146,7 +146,7 @@
     @SmallTest
     @Test
     public void testIsRequestPinShortcutSupported_v4() throws Throwable {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return;
         }
         setMockPm(mockResolveInfo(null));
@@ -173,7 +173,7 @@
     @LargeTest
     @Test
     public void testRequestPinShortcut_v4_noCallback()  throws Throwable {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return;
         }
 
@@ -188,7 +188,7 @@
     @MediumTest
     @Test
     public void testRequestPinShortcut_v4_withCallback()  throws Throwable {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return;
         }
 
@@ -209,7 +209,7 @@
     @SmallTest
     @Test
     public void testCreateShortcutResultIntent_v4() throws Throwable {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return;
         }
 
diff --git a/compat/tests/java/android/support/v4/graphics/PaintCompatHasGlyphTest.java b/compat/tests/java/android/support/v4/graphics/PaintCompatHasGlyphTest.java
index 26f0691..f17c881 100644
--- a/compat/tests/java/android/support/v4/graphics/PaintCompatHasGlyphTest.java
+++ b/compat/tests/java/android/support/v4/graphics/PaintCompatHasGlyphTest.java
@@ -47,6 +47,7 @@
                 {"\t\t\t", false},  // more white space
                 {"☺", SDK_INT >= 16}, // glyph added in API 16
                 {"\uD83D\uDC66\uD83C\uDFFF", SDK_INT >= 24}, // glyph added in API 24
+                {"\uD83C\uDDEF\uD83C\uDDF5", SDK_INT >= 20}, // Japan flag emoji, added in API 20
         });
     }
 
diff --git a/compat/tests/java/android/support/v4/graphics/TypefaceCompatTest.java b/compat/tests/java/android/support/v4/graphics/TypefaceCompatTest.java
index dc0650b..dab7f0f 100644
--- a/compat/tests/java/android/support/v4/graphics/TypefaceCompatTest.java
+++ b/compat/tests/java/android/support/v4/graphics/TypefaceCompatTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
+import android.annotation.SuppressLint;
 import android.app.Instrumentation;
 import android.content.Context;
 import android.content.pm.PackageInfo;
@@ -29,7 +30,6 @@
 import android.graphics.Typeface;
 import android.support.compat.test.R;
 import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.SdkSuppress;
 import android.support.test.filters.SmallTest;
 import android.support.testutils.PollingCheck;
 import android.support.v4.content.res.FontResourcesParserCompat;
@@ -48,11 +48,8 @@
 import java.util.ArrayList;
 import java.util.List;
 
-@SdkSuppress(maxSdkVersion = 25)  // on API 26, use platform implementation.
 @SmallTest
 public class TypefaceCompatTest {
-    private static final String AUTHORITY = "android.provider.fonts.font";
-    private static final String PACKAGE = "android.support.compat.test";
 
     public Context mContext;
     public Resources mResources;
@@ -142,34 +139,92 @@
         Typeface typeface = TypefaceCompat.createFromResourcesFamilyXml(mContext,
                 getProviderResourceEntry(R.font.styletest_sync_providerfont), mResources,
                 R.font.styletest_sync_providerfont, Typeface.NORMAL, null /* TextView */);
-        // TODO: Add support of styled font selection from family result.
-        assertNotNull(typeface);
+        typeface = Typeface.create(typeface, Typeface.NORMAL);
+        assertEquals(R.font.large_a, getSelectedFontResourceId(typeface));
+
+        typeface = TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                getProviderResourceEntry(R.font.styletest_sync_providerfont), mResources,
+                R.font.styletest_sync_providerfont, Typeface.ITALIC, null /* TextView */);
+        typeface = Typeface.create(typeface, Typeface.ITALIC);
+        assertEquals(R.font.large_b, getSelectedFontResourceId(typeface));
+
+        typeface = TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                getProviderResourceEntry(R.font.styletest_sync_providerfont), mResources,
+                R.font.styletest_sync_providerfont, Typeface.BOLD, null /* TextView */);
+        typeface = Typeface.create(typeface, Typeface.BOLD);
+        assertEquals(R.font.large_c, getSelectedFontResourceId(typeface));
+
+        typeface = TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                getProviderResourceEntry(R.font.styletest_sync_providerfont), mResources,
+                R.font.styletest_sync_providerfont, Typeface.BOLD_ITALIC, null /* TextView */);
+        typeface = Typeface.create(typeface, Typeface.BOLD_ITALIC);
+        assertEquals(R.font.large_d, getSelectedFontResourceId(typeface));
     }
 
     @Test
     public void testCreateFromResourcesFamilyXml_resourceFont_asyncloading() throws Exception {
         Instrumentation inst = InstrumentationRegistry.getInstrumentation();
         final TextView textView = new TextView(mContext);
+        PollingCheck.PollingCheckCondition condition = new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return textView.getTypeface() != null;
+            }
+        };
+
+        textView.setTypeface(null);
         inst.runOnMainSync(new Runnable() {
             @Override
             public void run() {
                 TypefaceCompat.createFromResourcesFamilyXml(mContext,
                         getProviderResourceEntry(R.font.styletest_async_providerfont), mResources,
-                        R.font.styletest_sync_providerfont, Typeface.NORMAL, textView);
+                        R.font.styletest_async_providerfont, Typeface.NORMAL, textView);
             }
         });
-        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+        PollingCheck.waitFor(condition);
+        assertEquals(R.font.large_a, getSelectedFontResourceId(textView.getTypeface()));
+
+        textView.setTypeface(null);
+        inst.runOnMainSync(new Runnable() {
             @Override
-            public boolean canProceed() {
-                return textView.getTypeface() != null;
+            public void run() {
+                TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                        getProviderResourceEntry(R.font.styletest_async_providerfont), mResources,
+                        R.font.styletest_async_providerfont, Typeface.ITALIC, textView);
             }
         });
-        // TODO: Add support of styled font selection from family result.
-        assertNotNull(textView.getTypeface());
+        PollingCheck.waitFor(condition);
+        assertEquals(R.font.large_b, getSelectedFontResourceId(textView.getTypeface()));
+
+        textView.setTypeface(null);
+        inst.runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                        getProviderResourceEntry(R.font.styletest_async_providerfont), mResources,
+                        R.font.styletest_async_providerfont, Typeface.BOLD, textView);
+            }
+        });
+        PollingCheck.waitFor(condition);
+        assertEquals(R.font.large_c, getSelectedFontResourceId(textView.getTypeface()));
+
+        textView.setTypeface(null);
+        inst.runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                TypefaceCompat.createFromResourcesFamilyXml(mContext,
+                        getProviderResourceEntry(R.font.styletest_async_providerfont), mResources,
+                        R.font.styletest_async_providerfont, Typeface.BOLD_ITALIC, textView);
+            }
+        });
+        PollingCheck.waitFor(condition);
+        assertEquals(R.font.large_d, getSelectedFontResourceId(textView.getTypeface()));
     }
 
     @Test
     public void testCreateFromResourcesFamilyXml_resourceFont() throws Exception {
+        @SuppressLint("ResourceType")
+        // We are retrieving the XML font as an XML resource for testing purposes.
         final FamilyResourceEntry entry = FontResourcesParserCompat.parse(
                 mResources.getXml(R.font.styletestfont), mResources);
         Typeface typeface = TypefaceCompat.createFromResourcesFamilyXml(mContext, entry, mResources,
@@ -207,14 +262,16 @@
 
     @Test
     public void testCreateFromResourcesFontFile() {
-        Typeface typeface = TypefaceCompat.createFromResourcesFontFile(
-                mContext, mResources, R.font.large_a, Typeface.NORMAL);
+        Typeface typeface = TypefaceCompat.createFromResourcesFontFile(mContext, mResources,
+                R.font.large_a, "res/font/large_a.ttf", Typeface.NORMAL);
+        assertNotNull(typeface);
         assertEquals(typeface, TypefaceCompat.findFromCache(
                 mResources, R.font.large_a, Typeface.NORMAL));
         assertEquals(R.font.large_a, getSelectedFontResourceId(typeface));
 
-        typeface = TypefaceCompat.createFromResourcesFontFile(
-                mContext, mResources, R.font.large_b, Typeface.NORMAL);
+        typeface = TypefaceCompat.createFromResourcesFontFile(mContext, mResources, R.font.large_b,
+                "res/font/large_b.ttf", Typeface.NORMAL);
+        assertNotNull(typeface);
         assertEquals(typeface, TypefaceCompat.findFromCache(
                 mResources, R.font.large_b, Typeface.NORMAL));
         assertEquals(R.font.large_b, getSelectedFontResourceId(typeface));
diff --git a/compat/tests/java/android/support/v4/graphics/drawable/IconCompatTest.java b/compat/tests/java/android/support/v4/graphics/drawable/IconCompatTest.java
index ddf56ed..d87ddac 100644
--- a/compat/tests/java/android/support/v4/graphics/drawable/IconCompatTest.java
+++ b/compat/tests/java/android/support/v4/graphics/drawable/IconCompatTest.java
@@ -34,7 +34,6 @@
 import android.support.test.filters.SdkSuppress;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
-import android.support.v4.os.BuildCompat;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -105,7 +104,7 @@
         bitmap.eraseColor(Color.GREEN);
         IconCompat compat = IconCompat.createWithAdaptiveBitmap(bitmap);
         Drawable d = compat.toIcon().loadDrawable(InstrumentationRegistry.getContext());
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             assertTrue(d instanceof AdaptiveIconDrawable);
         } else {
             assertTrue(d instanceof BitmapDrawable);
diff --git a/compat/tests/java/android/support/v4/provider/MockFontProvider.java b/compat/tests/java/android/support/v4/provider/MockFontProvider.java
index 323dfe1..f07d92d 100644
--- a/compat/tests/java/android/support/v4/provider/MockFontProvider.java
+++ b/compat/tests/java/android/support/v4/provider/MockFontProvider.java
@@ -204,7 +204,15 @@
             InputStream is = null;
             try {
                 is = mgr.open("fonts/" + file);
-                copy(is, getCopiedFile(context, file));
+                File copied = getCopiedFile(context, file);
+                File parent = copied.getParentFile();
+                if (!parent.isDirectory()) {
+                    parent.mkdirs();
+                    parent.setReadable(true, false);
+                    parent.setExecutable(true, false);
+                }
+                copy(is, copied);
+                copied.setReadable(true, false);
             } catch (IOException e) {
                 throw new RuntimeException(e);
             } finally {
@@ -245,7 +253,8 @@
     }
 
     public static File getCopiedFile(Context context, String path) {
-        return new File(context.getFilesDir(), path);
+        final File cacheDir = new File(context.getFilesDir(), "fontCache");
+        return new File(cacheDir, path);
     }
 
     @Override
diff --git a/core-utils/tests/java/android/support/v4/text/BidiFormatterTest.java b/compat/tests/java/android/support/v4/text/BidiFormatterTest.java
similarity index 100%
rename from core-utils/tests/java/android/support/v4/text/BidiFormatterTest.java
rename to compat/tests/java/android/support/v4/text/BidiFormatterTest.java
diff --git a/compat/tests/java/android/support/v4/text/util/LinkifyCompatTest.java b/compat/tests/java/android/support/v4/text/util/LinkifyCompatTest.java
index 51bb7d0..d79c789 100644
--- a/compat/tests/java/android/support/v4/text/util/LinkifyCompatTest.java
+++ b/compat/tests/java/android/support/v4/text/util/LinkifyCompatTest.java
@@ -245,12 +245,21 @@
             assertTrue(LinkifyCompat.addLinks(spannable, Linkify.ALL));
             URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
             assertEquals(3, spans.length);
-            assertEquals("tel:8005551233", spans[0].getURL());
-            assertEquals("mailto:800-555-1211@gmail.com", spans[1].getURL());
-            assertEquals("http://800-555-1222.com", spans[2].getURL());
+            assertTrue(containsUrl(spans, "tel:8005551233"));
+            assertTrue(containsUrl(spans, "mailto:800-555-1211@gmail.com"));
+            assertTrue(containsUrl(spans, "http://800-555-1222.com"));
         }
     }
 
+    private boolean containsUrl(URLSpan[] spans, String expectedValue) {
+        for (URLSpan span : spans) {
+            if (span.getURL().equals(expectedValue)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     @Test
     public void testAddLinks_addsLinksWhenDefaultSchemeIsNull() {
         Spannable spannable = new SpannableString("any https://android.com any android.com any");
diff --git a/compat/tests/java/android/support/v4/util/ObjectsCompatTest.java b/compat/tests/java/android/support/v4/util/ObjectsCompatTest.java
new file mode 100644
index 0000000..9fdf451
--- /dev/null
+++ b/compat/tests/java/android/support/v4/util/ObjectsCompatTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.util;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Unit tests for ObjectsCompat
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ObjectsCompatTest {
+
+    @Test
+    public void testEquals() throws Exception {
+        String a = "aaa";
+        String b = "bbb";
+        String c = new String(a);
+        String n = null;
+
+        assertFalse(ObjectsCompat.equals(a, b));
+        assertFalse(ObjectsCompat.equals(a, n));
+        assertFalse(ObjectsCompat.equals(n, a));
+
+        assertTrue(ObjectsCompat.equals(n, n));
+        assertTrue(ObjectsCompat.equals(a, a));
+        assertTrue(ObjectsCompat.equals(a, c));
+    }
+
+}
diff --git a/compat/tests/java/android/support/v4/util/SimpleArrayMapTest.java b/compat/tests/java/android/support/v4/util/SimpleArrayMapTest.java
index 2a07272..350b917 100644
--- a/compat/tests/java/android/support/v4/util/SimpleArrayMapTest.java
+++ b/compat/tests/java/android/support/v4/util/SimpleArrayMapTest.java
@@ -24,6 +24,7 @@
 import org.junit.runner.RunWith;
 
 import java.util.ConcurrentModificationException;
+import java.util.Locale;
 
 /**
  * Unit tests for SimpleArrayMap
@@ -49,7 +50,7 @@
                 int i = 0;
                 while (!mDone) {
                     try {
-                        map.put(String.format("key %d", i++), "B_DONT_DO_THAT");
+                        map.put(String.format(Locale.US, "key %d", i++), "B_DONT_DO_THAT");
                     } catch (ArrayIndexOutOfBoundsException e) {
                         // SimpleArrayMap is not thread safe, so lots of concurrent modifications
                         // can still cause data corruption
@@ -87,7 +88,7 @@
     public void testNonConcurrentAccesses() throws Exception {
         for (int i = 0; i < 100000; i++) {
             try {
-                map.put(String.format("key %d", i++), "B_DONT_DO_THAT");
+                map.put(String.format(Locale.US, "key %d", i++), "B_DONT_DO_THAT");
                 if (i % 500 == 0) {
                     map.clear();
                 }
diff --git a/compat/tests/java/android/support/v4/widget/ListViewCompatTest.java b/compat/tests/java/android/support/v4/widget/ListViewCompatTest.java
index 4fc65ec..27b1487 100644
--- a/compat/tests/java/android/support/v4/widget/ListViewCompatTest.java
+++ b/compat/tests/java/android/support/v4/widget/ListViewCompatTest.java
@@ -20,6 +20,7 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import android.annotation.SuppressLint;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.compat.test.R;
@@ -52,7 +53,7 @@
 
     @Before
     public void setUp() throws Throwable {
-        mListView = (ListView) mActivityTestRule.getActivity().findViewById(R.id.content);
+        mListView = mActivityTestRule.getActivity().findViewById(R.id.content);
         runOnMainAndLayoutSync(mActivityTestRule, mListView, new Runnable() {
             @Override
             public void run() {
@@ -72,6 +73,7 @@
                         return position;
                     }
 
+                    @SuppressLint("SetTextI18n")
                     @Override
                     public View getView(int position, View convertView, ViewGroup parent) {
                         if (convertView == null) {
diff --git a/compat/tests/res/font/dummyproviderfont.xml b/compat/tests/res/font/dummyproviderfont.xml
index b0b41c3..6295c91 100644
--- a/compat/tests/res/font/dummyproviderfont.xml
+++ b/compat/tests/res/font/dummyproviderfont.xml
@@ -1,10 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto"
-         android:fontProviderAuthority="android.provider.fonts.font"
-         android:fontProviderPackage="android.support.compat.test"
-         android:fontProviderQuery="styleTest"
-         app:fontProviderAuthority="android.provider.fonts.font"
-         app:fontProviderPackage="android.support.compat.test"
-         app:fontProviderQuery="styleTest" >
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
+    app:fontProviderAuthority="android.provider.fonts.font"
+    app:fontProviderPackage="android.support.compat.test"
+    app:fontProviderQuery="styleTest" >
 </font-family>
diff --git a/compat/tests/res/font/invalid_xmlfamily.xml b/compat/tests/res/font/invalid_xmlfamily.xml
index 02ae6bb..ea9ec97 100644
--- a/compat/tests/res/font/invalid_xmlfamily.xml
+++ b/compat/tests/res/font/invalid_xmlfamily.xml
@@ -1,5 +1,3 @@
-<invalid-tag xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto">
-  <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/samplefont"
-        app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
+<invalid-tag xmlns:app="http://schemas.android.com/apk/res-auto">
+  <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
 </invalid-tag>
diff --git a/compat/tests/res/font/invalid_xmlfont.xml b/compat/tests/res/font/invalid_xmlfont.xml
index d4bffb8..4d3afc2 100644
--- a/compat/tests/res/font/invalid_xmlfont.xml
+++ b/compat/tests/res/font/invalid_xmlfont.xml
@@ -1,7 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto">
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
   <!-- the tag inside font-family must be 'font' -->
-  <ttf android:fontStyle="normal" android:fontWeight="400" android:font="@font/samplefont"
-       app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
+  <ttf app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
 </font-family>
diff --git a/compat/tests/res/font/invalid_xmlfont_contains_invalid_font_file.xml b/compat/tests/res/font/invalid_xmlfont_contains_invalid_font_file.xml
index b87db2b..f876e15 100644
--- a/compat/tests/res/font/invalid_xmlfont_contains_invalid_font_file.xml
+++ b/compat/tests/res/font/invalid_xmlfont_contains_invalid_font_file.xml
@@ -1,6 +1,4 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto">
-  <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/invalid_font"
-        app:fontStyle="normal" app:fontWeight="400" app:font="@font/invalid_font" />
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
+  <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/invalid_font" />
 </font-family>
diff --git a/compat/tests/res/font/samplexmldownloadedfont.xml b/compat/tests/res/font/samplexmldownloadedfont.xml
index 59a0a05..659d196 100644
--- a/compat/tests/res/font/samplexmldownloadedfont.xml
+++ b/compat/tests/res/font/samplexmldownloadedfont.xml
@@ -1,10 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto"
-         android:fontProviderAuthority="com.example.test.fontprovider.authority"
-         android:fontProviderPackage="com.example.test.fontprovider.package"
-         android:fontProviderQuery="MyRequestedFont"
-         app:fontProviderAuthority="com.example.test.fontprovider.authority"
-         app:fontProviderPackage="com.example.test.fontprovider.package"
-         app:fontProviderQuery="MyRequestedFont">
-</font-family>
\ No newline at end of file
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
+    app:fontProviderAuthority="com.example.test.fontprovider.authority"
+    app:fontProviderPackage="com.example.test.fontprovider.package"
+    app:fontProviderQuery="MyRequestedFont">
+</font-family>
diff --git a/compat/tests/res/font/samplexmlfont.xml b/compat/tests/res/font/samplexmlfont.xml
index dc7fb4f..8a6876d 100644
--- a/compat/tests/res/font/samplexmlfont.xml
+++ b/compat/tests/res/font/samplexmlfont.xml
@@ -1,12 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <font-family xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto">
-    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont"
-          android:fontStyle="normal" android:fontWeight="400" android:font="@font/samplefont" />
-    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/samplefont2"
-          android:fontStyle="italic" android:fontWeight="400" android:font="@font/samplefont2" />
-    <font app:fontStyle="normal" app:fontWeight="700" app:font="@font/samplefont3"
-          android:fontStyle="normal" android:fontWeight="700" android:font="@font/samplefont3" />
-    <font app:fontStyle="italic" app:fontWeight="700" app:font="@font/samplefont4"
-          android:fontStyle="italic" android:fontWeight="700" android:font="@font/samplefont4" />
+    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
+    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/samplefont2" />
+    <font app:fontStyle="normal" app:fontWeight="700" app:font="@font/samplefont3" />
+    <font app:fontStyle="italic" app:fontWeight="700" app:font="@font/samplefont4" />
 </font-family>
diff --git a/compat/tests/res/font/styletest_async_providerfont.xml b/compat/tests/res/font/styletest_async_providerfont.xml
index 8d934cb..aa28179 100644
--- a/compat/tests/res/font/styletest_async_providerfont.xml
+++ b/compat/tests/res/font/styletest_async_providerfont.xml
@@ -1,11 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto"
-         android:fontProviderAuthority="android.support.provider.fonts.font"
-         android:fontProviderPackage="android.support.compat.test"
-         android:fontProviderQuery="styleTest"
-         app:fontProviderAuthority="android.support.provider.fonts.font"
-         app:fontProviderPackage="android.support.compat.test"
-         app:fontProviderQuery="styleTest"
-         app:fontProviderFetchStrategy="async">
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
+    app:fontProviderAuthority="android.support.provider.fonts.font"
+    app:fontProviderPackage="android.support.compat.test"
+    app:fontProviderQuery="styleTest"
+    app:fontProviderFetchStrategy="async">
 </font-family>
diff --git a/compat/tests/res/font/styletest_sync_providerfont.xml b/compat/tests/res/font/styletest_sync_providerfont.xml
index 4e9c7d6..f89301b 100644
--- a/compat/tests/res/font/styletest_sync_providerfont.xml
+++ b/compat/tests/res/font/styletest_sync_providerfont.xml
@@ -1,12 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto"
-         android:fontProviderAuthority="android.support.provider.fonts.font"
-         android:fontProviderPackage="android.support.compat.test"
-         android:fontProviderQuery="styleTest"
-         app:fontProviderAuthority="android.support.provider.fonts.font"
-         app:fontProviderPackage="android.support.compat.test"
-         app:fontProviderQuery="styleTest"
-         app:fontProviderFetchStrategy="blocking"
-         app:fontProviderFetchTimeout="forever">
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
+    app:fontProviderAuthority="android.support.provider.fonts.font"
+    app:fontProviderPackage="android.support.compat.test"
+    app:fontProviderQuery="styleTest"
+    app:fontProviderFetchStrategy="blocking"
+    app:fontProviderFetchTimeout="forever">
 </font-family>
diff --git a/compat/tests/res/font/styletestfont.xml b/compat/tests/res/font/styletestfont.xml
index f1326d5..dca3fe2 100644
--- a/compat/tests/res/font/styletestfont.xml
+++ b/compat/tests/res/font/styletestfont.xml
@@ -1,12 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto">
-    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/large_a"
-          android:fontStyle="normal" android:fontWeight="400" android:font="@font/large_a" />
-    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/large_b"
-          android:fontStyle="italic" android:fontWeight="400" android:font="@font/large_b" />
-    <font app:fontStyle="normal" app:fontWeight="700" app:font="@font/large_c"
-          android:fontStyle="normal" android:fontWeight="700" android:font="@font/large_c" />
-    <font app:fontStyle="italic" app:fontWeight="700" app:font="@font/large_d"
-          android:fontStyle="italic" android:fontWeight="700" android:font="@font/large_d" />
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
+    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/large_a" />
+    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/large_b" />
+    <font app:fontStyle="normal" app:fontWeight="700" app:font="@font/large_c" />
+    <font app:fontStyle="italic" app:fontWeight="700" app:font="@font/large_d" />
 </font-family>
diff --git a/core-ui/Android.mk b/core-ui/Android.mk
index 9e4ad0e..bb7a4be 100644
--- a/core-ui/Android.mk
+++ b/core-ui/Android.mk
@@ -26,11 +26,7 @@
 LOCAL_USE_AAPT2 := true
 LOCAL_MODULE := android-support-core-ui
 LOCAL_SDK_VERSION := $(SUPPORT_CURRENT_SDK_VERSION)
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under,ics) \
-    $(call all-java-files-under,jellybean-mr2) \
-    $(call all-java-files-under,api21) \
-    $(call all-java-files-under,java)
+LOCAL_SRC_FILES := $(call all-java-files-under,java)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 LOCAL_SHARED_ANDROID_LIBRARIES := \
     android-support-compat \
diff --git a/core-ui/api21/android/support/v4/widget/DrawerLayoutCompatApi21.java b/core-ui/api21/android/support/v4/widget/DrawerLayoutCompatApi21.java
deleted file mode 100644
index f0612d1..0000000
--- a/core-ui/api21/android/support/v4/widget/DrawerLayoutCompatApi21.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2014 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 android.support.v4.widget;
-
-import android.content.Context;
-import android.content.res.TypedArray;
-import android.graphics.drawable.Drawable;
-import android.support.annotation.RequiresApi;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.WindowInsets;
-
-/**
- * Provides functionality for DrawerLayout unique to API 21
- */
-@RequiresApi(21)
-class DrawerLayoutCompatApi21 {
-
-    private static final int[] THEME_ATTRS = {
-            android.R.attr.colorPrimaryDark
-    };
-
-    public static void configureApplyInsets(View drawerLayout) {
-        if (drawerLayout instanceof DrawerLayoutImpl) {
-            drawerLayout.setOnApplyWindowInsetsListener(new InsetsListener());
-            drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
-                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
-        }
-    }
-
-    public static void dispatchChildInsets(View child, Object insets, int gravity) {
-        WindowInsets wi = (WindowInsets) insets;
-        if (gravity == Gravity.LEFT) {
-            wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
-                    wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
-        } else if (gravity == Gravity.RIGHT) {
-            wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
-                    wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
-        }
-        child.dispatchApplyWindowInsets(wi);
-    }
-
-    public static void applyMarginInsets(ViewGroup.MarginLayoutParams lp, Object insets,
-            int gravity) {
-        WindowInsets wi = (WindowInsets) insets;
-        if (gravity == Gravity.LEFT) {
-            wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
-                    wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
-        } else if (gravity == Gravity.RIGHT) {
-            wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
-                    wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
-        }
-        lp.leftMargin = wi.getSystemWindowInsetLeft();
-        lp.topMargin = wi.getSystemWindowInsetTop();
-        lp.rightMargin = wi.getSystemWindowInsetRight();
-        lp.bottomMargin = wi.getSystemWindowInsetBottom();
-    }
-
-    public static int getTopInset(Object insets) {
-        return insets != null ? ((WindowInsets) insets).getSystemWindowInsetTop() : 0;
-    }
-
-    public static Drawable getDefaultStatusBarBackground(Context context) {
-        final TypedArray a = context.obtainStyledAttributes(THEME_ATTRS);
-        try {
-            return a.getDrawable(0);
-        } finally {
-            a.recycle();
-        }
-    }
-
-    static class InsetsListener implements View.OnApplyWindowInsetsListener {
-        @Override
-        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
-            final DrawerLayoutImpl drawerLayout = (DrawerLayoutImpl) v;
-            drawerLayout.setChildInsets(insets, insets.getSystemWindowInsetTop() > 0);
-            return insets.consumeSystemWindowInsets();
-        }
-    }
-}
diff --git a/core-ui/api21/android/support/v4/widget/DrawerLayoutImpl.java b/core-ui/api21/android/support/v4/widget/DrawerLayoutImpl.java
deleted file mode 100644
index 02545c1..0000000
--- a/core-ui/api21/android/support/v4/widget/DrawerLayoutImpl.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2014 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 android.support.v4.widget;
-
-/**
- * Interface used to communicate from the v21-specific code for configuring a DrawerLayout
- * to the DrawerLayout itself.
- */
-interface DrawerLayoutImpl {
-    void setChildInsets(Object insets, boolean drawStatusBar);
-}
diff --git a/core-ui/build.gradle b/core-ui/build.gradle
index 86fa71a..e25b916 100644
--- a/core-ui/build.gradle
+++ b/core-ui/build.gradle
@@ -2,19 +2,18 @@
 archivesBaseName = 'support-core-ui'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
+    api project(':support-annotations')
+    api project(':support-compat')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
@@ -24,9 +23,6 @@
 
     sourceSets {
         main.java.srcDirs = [
-                'ics',
-                'jellybean-mr2',
-                'api21',
                 'java'
         ]
     }
diff --git a/core-ui/ics/android/support/v4/app/ActionBarDrawerToggleIcs.java b/core-ui/ics/android/support/v4/app/ActionBarDrawerToggleIcs.java
deleted file mode 100644
index a332b8a..0000000
--- a/core-ui/ics/android/support/v4/app/ActionBarDrawerToggleIcs.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2013 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 android.support.v4.app;
-
-import android.R;
-import android.app.ActionBar;
-import android.app.Activity;
-import android.content.res.TypedArray;
-import android.graphics.drawable.Drawable;
-import android.os.Build;
-import android.support.annotation.RequiresApi;
-import android.util.Log;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.lang.reflect.Method;
-
-/**
- * This class encapsulates some awful hacks.
- *
- * Before JB-MR2 (API 18) it was not possible to change the home-as-up indicator glyph
- * in an action bar without some really gross hacks. Since the MR2 SDK is not published as of
- * this writing, the new API is accessed via reflection here if available.
- */
-@RequiresApi(14)
-class ActionBarDrawerToggleIcs {
-    private static final String TAG = "ActionBarDrawerToggle";
-
-    private static final int[] THEME_ATTRS = new int[] {
-            R.attr.homeAsUpIndicator
-    };
-
-    public static Object setActionBarUpIndicator(Object info, Activity activity,
-            Drawable drawable, int contentDescRes) {
-        if (info == null) {
-            info = new SetIndicatorInfo(activity);
-        }
-        final SetIndicatorInfo sii = (SetIndicatorInfo) info;
-        if (sii.setHomeAsUpIndicator != null) {
-            try {
-                final ActionBar actionBar = activity.getActionBar();
-                sii.setHomeAsUpIndicator.invoke(actionBar, drawable);
-                sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes);
-            } catch (Exception e) {
-                Log.w(TAG, "Couldn't set home-as-up indicator via JB-MR2 API", e);
-            }
-        } else if (sii.upIndicatorView != null) {
-            sii.upIndicatorView.setImageDrawable(drawable);
-        } else {
-            Log.w(TAG, "Couldn't set home-as-up indicator");
-        }
-        return info;
-    }
-
-    public static Object setActionBarDescription(Object info, Activity activity,
-            int contentDescRes) {
-        if (info == null) {
-            info = new SetIndicatorInfo(activity);
-        }
-        final SetIndicatorInfo sii = (SetIndicatorInfo) info;
-        if (sii.setHomeAsUpIndicator != null) {
-            try {
-                final ActionBar actionBar = activity.getActionBar();
-                sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes);
-                if (Build.VERSION.SDK_INT <= 19) {
-                    // For API 19 and earlier, we need to manually force the
-                    // action bar to generate a new content description.
-                    actionBar.setSubtitle(actionBar.getSubtitle());
-                }
-            } catch (Exception e) {
-                Log.w(TAG, "Couldn't set content description via JB-MR2 API", e);
-            }
-        }
-        return info;
-    }
-
-    public static Drawable getThemeUpIndicator(Activity activity) {
-        final TypedArray a = activity.obtainStyledAttributes(THEME_ATTRS);
-        final Drawable result = a.getDrawable(0);
-        a.recycle();
-        return result;
-    }
-
-    private static class SetIndicatorInfo {
-        public Method setHomeAsUpIndicator;
-        public Method setHomeActionContentDescription;
-        public ImageView upIndicatorView;
-
-        SetIndicatorInfo(Activity activity) {
-            try {
-                setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator",
-                        Drawable.class);
-                setHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
-                        "setHomeActionContentDescription", Integer.TYPE);
-
-                // If we got the method we won't need the stuff below.
-                return;
-            } catch (NoSuchMethodException e) {
-                // Oh well. We'll use the other mechanism below instead.
-            }
-
-            final View home = activity.findViewById(android.R.id.home);
-            if (home == null) {
-                // Action bar doesn't have a known configuration, an OEM messed with things.
-                return;
-            }
-
-            final ViewGroup parent = (ViewGroup) home.getParent();
-            final int childCount = parent.getChildCount();
-            if (childCount != 2) {
-                // No idea which one will be the right one, an OEM messed with things.
-                return;
-            }
-
-            final View first = parent.getChildAt(0);
-            final View second = parent.getChildAt(1);
-            final View up = first.getId() == android.R.id.home ? second : first;
-
-            if (up instanceof ImageView) {
-                // Jackpot! (Probably...)
-                upIndicatorView = (ImageView) up;
-            }
-        }
-    }
-}
diff --git a/core-ui/java/android/support/v4/app/ActionBarDrawerToggle.java b/core-ui/java/android/support/v4/app/ActionBarDrawerToggle.java
index 226154f..d95e42c 100644
--- a/core-ui/java/android/support/v4/app/ActionBarDrawerToggle.java
+++ b/core-ui/java/android/support/v4/app/ActionBarDrawerToggle.java
@@ -17,24 +17,31 @@
 
 package android.support.v4.app;
 
+import android.app.ActionBar;
 import android.app.Activity;
 import android.content.Context;
 import android.content.res.Configuration;
+import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.InsetDrawable;
 import android.os.Build;
 import android.support.annotation.DrawableRes;
+import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
-import android.support.annotation.RequiresApi;
 import android.support.annotation.StringRes;
 import android.support.v4.content.ContextCompat;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.view.ViewCompat;
 import android.support.v4.widget.DrawerLayout;
+import android.util.Log;
 import android.view.MenuItem;
 import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+
+import java.lang.reflect.Method;
 
 /**
  * This class provides a handy way to tie together the functionality of
@@ -107,71 +114,11 @@
         void setActionBarDescription(@StringRes int contentDescRes);
     }
 
-    private interface ActionBarDrawerToggleImpl {
-        Drawable getThemeUpIndicator(Activity activity);
-        Object setActionBarUpIndicator(Object info, Activity activity,
-                Drawable themeImage, int contentDescRes);
-        Object setActionBarDescription(Object info, Activity activity, int contentDescRes);
-    }
+    private static final String TAG = "ActionBarDrawerToggle";
 
-    @RequiresApi(11)
-    private static class ActionBarDrawerToggleImplIcs implements ActionBarDrawerToggleImpl {
-        ActionBarDrawerToggleImplIcs() {
-        }
-
-        @Override
-        public Drawable getThemeUpIndicator(Activity activity) {
-            return ActionBarDrawerToggleIcs.getThemeUpIndicator(activity);
-        }
-
-        @Override
-        public Object setActionBarUpIndicator(Object info, Activity activity,
-                Drawable themeImage, int contentDescRes) {
-            return ActionBarDrawerToggleIcs.setActionBarUpIndicator(info, activity,
-                    themeImage, contentDescRes);
-        }
-
-        @Override
-        public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) {
-            return ActionBarDrawerToggleIcs.setActionBarDescription(info, activity,
-                    contentDescRes);
-        }
-    }
-
-    @RequiresApi(18)
-    private static class ActionBarDrawerToggleImplJellybeanMR2
-            implements ActionBarDrawerToggleImpl {
-        ActionBarDrawerToggleImplJellybeanMR2() {
-        }
-
-        @Override
-        public Drawable getThemeUpIndicator(Activity activity) {
-            return ActionBarDrawerToggleJellybeanMR2.getThemeUpIndicator(activity);
-        }
-
-        @Override
-        public Object setActionBarUpIndicator(Object info, Activity activity,
-                Drawable themeImage, int contentDescRes) {
-            return ActionBarDrawerToggleJellybeanMR2.setActionBarUpIndicator(info, activity,
-                    themeImage, contentDescRes);
-        }
-
-        @Override
-        public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) {
-            return ActionBarDrawerToggleJellybeanMR2.setActionBarDescription(info, activity,
-                    contentDescRes);
-        }
-    }
-
-    private static final ActionBarDrawerToggleImpl IMPL;
-
-    static {
-        if (Build.VERSION.SDK_INT >= 18) {
-            IMPL = new ActionBarDrawerToggleImplJellybeanMR2();
-        } else {
-            IMPL = new ActionBarDrawerToggleImplIcs();
-        }
-    }
+    private static final int[] THEME_ATTRS = new int[] {
+            android.R.attr.homeAsUpIndicator
+    };
 
     /** Fraction of its total width by which to offset the toggle drawable. */
     private static final float TOGGLE_DRAWABLE_OFFSET = 1 / 3f;
@@ -192,7 +139,7 @@
     private final int mOpenDrawerContentDescRes;
     private final int mCloseDrawerContentDescRes;
 
-    private Object mSetIndicatorInfo;
+    private SetIndicatorInfo mSetIndicatorInfo;
 
     /**
      * Construct a new ActionBarDrawerToggle.
@@ -463,29 +410,133 @@
     public void onDrawerStateChanged(int newState) {
     }
 
-    Drawable getThemeUpIndicator() {
+    private Drawable getThemeUpIndicator() {
         if (mActivityImpl != null) {
             return mActivityImpl.getThemeUpIndicator();
         }
-        return IMPL.getThemeUpIndicator(mActivity);
+        if (Build.VERSION.SDK_INT >= 18) {
+            final ActionBar actionBar = mActivity.getActionBar();
+            final Context context;
+            if (actionBar != null) {
+                context = actionBar.getThemedContext();
+            } else {
+                context = mActivity;
+            }
+
+            final TypedArray a = context.obtainStyledAttributes(null, THEME_ATTRS,
+                    android.R.attr.actionBarStyle, 0);
+            final Drawable result = a.getDrawable(0);
+            a.recycle();
+            return result;
+        } else {
+            final TypedArray a = mActivity.obtainStyledAttributes(THEME_ATTRS);
+            final Drawable result = a.getDrawable(0);
+            a.recycle();
+            return result;
+        }
     }
 
-    void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes) {
+    private void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes) {
         if (mActivityImpl != null) {
             mActivityImpl.setActionBarUpIndicator(upDrawable, contentDescRes);
             return;
         }
-        mSetIndicatorInfo = IMPL
-                .setActionBarUpIndicator(mSetIndicatorInfo, mActivity, upDrawable, contentDescRes);
+        if (Build.VERSION.SDK_INT >= 18) {
+            final ActionBar actionBar = mActivity.getActionBar();
+            if (actionBar != null) {
+                actionBar.setHomeAsUpIndicator(upDrawable);
+                actionBar.setHomeActionContentDescription(contentDescRes);
+            }
+        } else {
+            if (mSetIndicatorInfo == null) {
+                mSetIndicatorInfo = new SetIndicatorInfo(mActivity);
+            }
+            if (mSetIndicatorInfo.mSetHomeAsUpIndicator != null) {
+                try {
+                    final ActionBar actionBar = mActivity.getActionBar();
+                    mSetIndicatorInfo.mSetHomeAsUpIndicator.invoke(actionBar, upDrawable);
+                    mSetIndicatorInfo.mSetHomeActionContentDescription.invoke(
+                            actionBar, contentDescRes);
+                } catch (Exception e) {
+                    Log.w(TAG, "Couldn't set home-as-up indicator via JB-MR2 API", e);
+                }
+            } else if (mSetIndicatorInfo.mUpIndicatorView != null) {
+                mSetIndicatorInfo.mUpIndicatorView.setImageDrawable(upDrawable);
+            } else {
+                Log.w(TAG, "Couldn't set home-as-up indicator");
+            }
+        }
     }
 
-    void setActionBarDescription(int contentDescRes) {
+    private void setActionBarDescription(int contentDescRes) {
         if (mActivityImpl != null) {
             mActivityImpl.setActionBarDescription(contentDescRes);
             return;
         }
-        mSetIndicatorInfo = IMPL
-                .setActionBarDescription(mSetIndicatorInfo, mActivity, contentDescRes);
+        if (Build.VERSION.SDK_INT >= 18) {
+            final ActionBar actionBar = mActivity.getActionBar();
+            if (actionBar != null) {
+                actionBar.setHomeActionContentDescription(contentDescRes);
+            }
+        } else {
+            if (mSetIndicatorInfo == null) {
+                mSetIndicatorInfo = new SetIndicatorInfo(mActivity);
+            }
+            if (mSetIndicatorInfo.mSetHomeAsUpIndicator != null) {
+                try {
+                    final ActionBar actionBar = mActivity.getActionBar();
+                    mSetIndicatorInfo.mSetHomeActionContentDescription.invoke(
+                            actionBar, contentDescRes);
+                    // For API 19 and earlier, we need to manually force the
+                    // action bar to generate a new content description.
+                    actionBar.setSubtitle(actionBar.getSubtitle());
+                } catch (Exception e) {
+                    Log.w(TAG, "Couldn't set content description via JB-MR2 API", e);
+                }
+            }
+        }
+    }
+
+    private static class SetIndicatorInfo {
+        Method mSetHomeAsUpIndicator;
+        Method mSetHomeActionContentDescription;
+        ImageView mUpIndicatorView;
+
+        SetIndicatorInfo(Activity activity) {
+            try {
+                mSetHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator",
+                        Drawable.class);
+                mSetHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
+                        "setHomeActionContentDescription", Integer.TYPE);
+
+                // If we got the method we won't need the stuff below.
+                return;
+            } catch (NoSuchMethodException e) {
+                // Oh well. We'll use the other mechanism below instead.
+            }
+
+            final View home = activity.findViewById(android.R.id.home);
+            if (home == null) {
+                // Action bar doesn't have a known configuration, an OEM messed with things.
+                return;
+            }
+
+            final ViewGroup parent = (ViewGroup) home.getParent();
+            final int childCount = parent.getChildCount();
+            if (childCount != 2) {
+                // No idea which one will be the right one, an OEM messed with things.
+                return;
+            }
+
+            final View first = parent.getChildAt(0);
+            final View second = parent.getChildAt(1);
+            final View up = first.getId() == android.R.id.home ? second : first;
+
+            if (up instanceof ImageView) {
+                // Jackpot! (Probably...)
+                mUpIndicatorView = (ImageView) up;
+            }
+        }
     }
 
     private class SlideDrawable extends InsetDrawable implements Drawable.Callback {
@@ -526,7 +577,7 @@
         }
 
         @Override
-        public void draw(Canvas canvas) {
+        public void draw(@NonNull Canvas canvas) {
             copyBounds(mTmpRect);
             canvas.save();
 
diff --git a/core-ui/java/android/support/v4/widget/CircularProgressDrawable.java b/core-ui/java/android/support/v4/widget/CircularProgressDrawable.java
new file mode 100644
index 0000000..ac29541
--- /dev/null
+++ b/core-ui/java/android/support/v4/widget/CircularProgressDrawable.java
@@ -0,0 +1,945 @@
+/*
+ * Copyright (C) 2014 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 android.support.v4.widget;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.animation.Animator;
+import android.animation.ValueAnimator;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.ColorFilter;
+import android.graphics.Paint;
+import android.graphics.Paint.Style;
+import android.graphics.Path;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.drawable.Animatable;
+import android.graphics.drawable.Drawable;
+import android.support.annotation.IntDef;
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+import android.support.v4.util.Preconditions;
+import android.support.v4.view.animation.FastOutSlowInInterpolator;
+import android.util.DisplayMetrics;
+import android.view.animation.Interpolator;
+import android.view.animation.LinearInterpolator;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Drawable that renders the animated indeterminate progress indicator in the Material design style
+ * without depending on API level 11.
+ *
+ * <p>While this may be used to draw an indeterminate spinner using {@link #start()} and {@link
+ * #stop()} methods, this may also be used to draw a progress arc using {@link
+ * #setStartEndTrim(float, float)} method. CircularProgressDrawable also supports adding an arrow
+ * at the end of the arc by {@link #setArrowEnabled(boolean)} and {@link #setArrowDimensions(float,
+ * float)} methods.
+ *
+ * <p>To use one of the pre-defined sizes instead of using your own, {@link #setStyle(int)} should
+ * be called with one of the {@link #DEFAULT} or {@link #LARGE} styles as its parameter. Doing it
+ * so will update the arrow dimensions, ring size and stroke width to fit the one specified.
+ *
+ * <p>If no center radius is set via {@link #setCenterRadius(float)} or {@link #setStyle(int)}
+ * methods, CircularProgressDrawable will fill the bounds set via {@link #setBounds(Rect)}.
+ */
+public class CircularProgressDrawable extends Drawable implements Animatable {
+    private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
+    private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
+
+    /** @hide */
+    @RestrictTo(LIBRARY_GROUP)
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({LARGE, DEFAULT})
+    public @interface ProgressDrawableSize {
+    }
+
+    /** Maps to ProgressBar.Large style. */
+    public static final int LARGE = 0;
+
+    private static final float CENTER_RADIUS_LARGE = 11f;
+    private static final float STROKE_WIDTH_LARGE = 3f;
+    private static final int ARROW_WIDTH_LARGE = 12;
+    private static final int ARROW_HEIGHT_LARGE = 6;
+
+    /** Maps to ProgressBar default style. */
+    public static final int DEFAULT = 1;
+
+    private static final float CENTER_RADIUS = 7.5f;
+    private static final float STROKE_WIDTH = 2.5f;
+    private static final int ARROW_WIDTH = 10;
+    private static final int ARROW_HEIGHT = 5;
+
+    /**
+     * This is the default set of colors that's used in spinner. {@link
+     * #setColorSchemeColors(int...)} allows modifying colors.
+     */
+    private static final int[] COLORS = new int[]{
+            Color.BLACK
+    };
+
+    /**
+     * The value in the linear interpolator for animating the drawable at which
+     * the color transition should start
+     */
+    private static final float COLOR_CHANGE_OFFSET = 0.75f;
+    private static final float SHRINK_OFFSET = 0.5f;
+
+    /** The duration of a single progress spin in milliseconds. */
+    private static final int ANIMATION_DURATION = 1332;
+
+    /** Full rotation that's done for the animation duration in degrees. */
+    private static final float GROUP_FULL_ROTATION = 1080f / 5f;
+
+    /** The indicator ring, used to manage animation state. */
+    private final Ring mRing;
+
+    /** Canvas rotation in degrees. */
+    private float mRotation;
+
+    /** Maximum length of the progress arc during the animation. */
+    private static final float MAX_PROGRESS_ARC = .8f;
+    /** Minimum length of the progress arc during the animation. */
+    private static final float MIN_PROGRESS_ARC = .01f;
+
+    /** Rotation applied to ring during the animation, to complete it to a full circle. */
+    private static final float RING_ROTATION = 1f - (MAX_PROGRESS_ARC - MIN_PROGRESS_ARC);
+
+    private Resources mResources;
+    private Animator mAnimator;
+    private float mRotationCount;
+    private boolean mFinishing;
+
+    /**
+     * @param context application context
+     */
+    public CircularProgressDrawable(Context context) {
+        mResources = Preconditions.checkNotNull(context).getResources();
+
+        mRing = new Ring();
+        mRing.setColors(COLORS);
+
+        setStrokeWidth(STROKE_WIDTH);
+        setupAnimators();
+    }
+
+    /** Sets all parameters at once in dp. */
+    private void setSizeParameters(float centerRadius, float strokeWidth, float arrowWidth,
+            float arrowHeight) {
+        final Ring ring = mRing;
+        final DisplayMetrics metrics = mResources.getDisplayMetrics();
+        final float screenDensity = metrics.density;
+
+        ring.setStrokeWidth(strokeWidth * screenDensity);
+        ring.setCenterRadius(centerRadius * screenDensity);
+        ring.setColorIndex(0);
+        ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
+    }
+
+    /**
+     * Sets the overall size for the progress spinner. This updates the radius
+     * and stroke width of the ring, and arrow dimensions.
+     *
+     * @param size one of {@link #LARGE} or {@link #DEFAULT}
+     */
+    public void setStyle(@ProgressDrawableSize int size) {
+        if (size == LARGE) {
+            setSizeParameters(CENTER_RADIUS_LARGE, STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE,
+                    ARROW_HEIGHT_LARGE);
+        } else {
+            setSizeParameters(CENTER_RADIUS, STROKE_WIDTH, ARROW_WIDTH, ARROW_HEIGHT);
+        }
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the stroke width for the progress spinner in pixels.
+     *
+     * @return stroke width in pixels
+     */
+    public float getStrokeWidth() {
+        return mRing.getStrokeWidth();
+    }
+
+    /**
+     * Sets the stroke width for the progress spinner in pixels.
+     *
+     * @param strokeWidth stroke width in pixels
+     */
+    public void setStrokeWidth(float strokeWidth) {
+        mRing.setStrokeWidth(strokeWidth);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the center radius for the progress spinner in pixels.
+     *
+     * @return center radius in pixels
+     */
+    public float getCenterRadius() {
+        return mRing.getCenterRadius();
+    }
+
+    /**
+     * Sets the center radius for the progress spinner in pixels. If set to 0, this drawable will
+     * fill the bounds when drawn.
+     *
+     * @param centerRadius center radius in pixels
+     */
+    public void setCenterRadius(float centerRadius) {
+        mRing.setCenterRadius(centerRadius);
+        invalidateSelf();
+    }
+
+    /**
+     * Sets the stroke cap of the progress spinner. Default stroke cap is {@link Paint.Cap#SQUARE}.
+     *
+     * @param strokeCap stroke cap
+     */
+    public void setStrokeCap(Paint.Cap strokeCap) {
+        mRing.setStrokeCap(strokeCap);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the stroke cap of the progress spinner.
+     *
+     * @return stroke cap
+     */
+    public Paint.Cap getStrokeCap() {
+        return mRing.getStrokeCap();
+    }
+
+    /**
+     * Returns the arrow width in pixels.
+     *
+     * @return arrow width in pixels
+     */
+    public float getArrowWidth() {
+        return mRing.getArrowWidth();
+    }
+
+    /**
+     * Returns the arrow height in pixels.
+     *
+     * @return arrow height in pixels
+     */
+    public float getArrowHeight() {
+        return mRing.getArrowHeight();
+    }
+
+    /**
+     * Sets the dimensions of the arrow at the end of the spinner in pixels.
+     *
+     * @param width width of the baseline of the arrow in pixels
+     * @param height distance from tip of the arrow to its baseline in pixels
+     */
+    public void setArrowDimensions(float width, float height) {
+        mRing.setArrowDimensions(width, height);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns {@code true} if the arrow at the end of the spinner is shown.
+     *
+     * @return {@code true} if the arrow is shown, {@code false} otherwise.
+     */
+    public boolean getArrowEnabled() {
+        return mRing.getShowArrow();
+    }
+
+    /**
+     * Sets if the arrow at the end of the spinner should be shown.
+     *
+     * @param show {@code true} if the arrow should be drawn, {@code false} otherwise
+     */
+    public void setArrowEnabled(boolean show) {
+        mRing.setShowArrow(show);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the scale of the arrow at the end of the spinner.
+     *
+     * @return scale of the arrow
+     */
+    public float getArrowScale() {
+        return mRing.getArrowScale();
+    }
+
+    /**
+     * Sets the scale of the arrow at the end of the spinner.
+     *
+     * @param scale scaling that will be applied to the arrow's both width and height when drawing.
+     */
+    public void setArrowScale(float scale) {
+        mRing.setArrowScale(scale);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the start trim for the progress spinner arc
+     *
+     * @return start trim from [0..1]
+     */
+    public float getStartTrim() {
+        return mRing.getStartTrim();
+    }
+
+    /**
+     * Returns the end trim for the progress spinner arc
+     *
+     * @return end trim from [0..1]
+     */
+    public float getEndTrim() {
+        return mRing.getEndTrim();
+    }
+
+    /**
+     * Sets the start and end trim for the progress spinner arc. 0 corresponds to the geometric
+     * angle of 0 degrees (3 o'clock on a watch) and it increases clockwise, coming to a full circle
+     * at 1.
+     *
+     * @param start starting position of the arc from [0..1]
+     * @param end ending position of the arc from [0..1]
+     */
+    public void setStartEndTrim(float start, float end) {
+        mRing.setStartTrim(start);
+        mRing.setEndTrim(end);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the amount of rotation applied to the progress spinner.
+     *
+     * @return amount of rotation from [0..1]
+     */
+    public float getProgressRotation() {
+        return mRing.getRotation();
+    }
+
+    /**
+     * Sets the amount of rotation to apply to the progress spinner.
+     *
+     * @param rotation rotation from [0..1]
+     */
+    public void setProgressRotation(float rotation) {
+        mRing.setRotation(rotation);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the background color of the circle drawn inside the drawable.
+     *
+     * @return an ARGB color
+     */
+    public int getBackgroundColor() {
+        return mRing.getBackgroundColor();
+    }
+
+    /**
+     * Sets the background color of the circle inside the drawable. Calling {@link
+     * #setAlpha(int)} does not affect the visibility background color, so it should be set
+     * separately if it needs to be hidden or visible.
+     *
+     * @param color an ARGB color
+     */
+    public void setBackgroundColor(int color) {
+        mRing.setBackgroundColor(color);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the colors used in the progress animation
+     *
+     * @return list of ARGB colors
+     */
+    public int[] getColorSchemeColors() {
+        return mRing.getColors();
+    }
+
+    /**
+     * Sets the colors used in the progress animation from a color list. The first color will also
+     * be the color to be used if animation is not started yet.
+     *
+     * @param colors list of ARGB colors to be used in the spinner
+     */
+    public void setColorSchemeColors(int... colors) {
+        mRing.setColors(colors);
+        mRing.setColorIndex(0);
+        invalidateSelf();
+    }
+
+    @Override
+    public void draw(Canvas canvas) {
+        final Rect bounds = getBounds();
+        canvas.save();
+        canvas.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
+        mRing.draw(canvas, bounds);
+        canvas.restore();
+    }
+
+    @Override
+    public void setAlpha(int alpha) {
+        mRing.setAlpha(alpha);
+        invalidateSelf();
+    }
+
+    @Override
+    public int getAlpha() {
+        return mRing.getAlpha();
+    }
+
+    @Override
+    public void setColorFilter(ColorFilter colorFilter) {
+        mRing.setColorFilter(colorFilter);
+        invalidateSelf();
+    }
+
+    private void setRotation(float rotation) {
+        mRotation = rotation;
+    }
+
+    private float getRotation() {
+        return mRotation;
+    }
+
+    @Override
+    public int getOpacity() {
+        return PixelFormat.TRANSLUCENT;
+    }
+
+    @Override
+    public boolean isRunning() {
+        return mAnimator.isRunning();
+    }
+
+    /**
+     * Starts the animation for the spinner.
+     */
+    @Override
+    public void start() {
+        mAnimator.cancel();
+        mRing.storeOriginals();
+        // Already showing some part of the ring
+        if (mRing.getEndTrim() != mRing.getStartTrim()) {
+            mFinishing = true;
+            mAnimator.setDuration(ANIMATION_DURATION / 2);
+            mAnimator.start();
+        } else {
+            mRing.setColorIndex(0);
+            mRing.resetOriginals();
+            mAnimator.setDuration(ANIMATION_DURATION);
+            mAnimator.start();
+        }
+    }
+
+    /**
+     * Stops the animation for the spinner.
+     */
+    @Override
+    public void stop() {
+        mAnimator.cancel();
+        setRotation(0);
+        mRing.setShowArrow(false);
+        mRing.setColorIndex(0);
+        mRing.resetOriginals();
+        invalidateSelf();
+    }
+
+    // Adapted from ArgbEvaluator.java
+    private int evaluateColorChange(float fraction, int startValue, int endValue) {
+        int startA = (startValue >> 24) & 0xff;
+        int startR = (startValue >> 16) & 0xff;
+        int startG = (startValue >> 8) & 0xff;
+        int startB = startValue & 0xff;
+
+        int endA = (endValue >> 24) & 0xff;
+        int endR = (endValue >> 16) & 0xff;
+        int endG = (endValue >> 8) & 0xff;
+        int endB = endValue & 0xff;
+
+        return (startA + (int) (fraction * (endA - startA))) << 24
+                | (startR + (int) (fraction * (endR - startR))) << 16
+                | (startG + (int) (fraction * (endG - startG))) << 8
+                | (startB + (int) (fraction * (endB - startB)));
+    }
+
+    /**
+     * Update the ring color if this is within the last 25% of the animation.
+     * The new ring color will be a translation from the starting ring color to
+     * the next color.
+     */
+    private void updateRingColor(float interpolatedTime, Ring ring) {
+        if (interpolatedTime > COLOR_CHANGE_OFFSET) {
+            ring.setColor(evaluateColorChange((interpolatedTime - COLOR_CHANGE_OFFSET)
+                            / (1f - COLOR_CHANGE_OFFSET), ring.getStartingColor(),
+                    ring.getNextColor()));
+        } else {
+            ring.setColor(ring.getStartingColor());
+        }
+    }
+
+    /**
+     * Update the ring start and end trim if the animation is finishing (i.e. it started with
+     * already visible progress, so needs to shrink back down before starting the spinner).
+     */
+    private void applyFinishTranslation(float interpolatedTime, Ring ring) {
+        // shrink back down and complete a full rotation before
+        // starting other circles
+        // Rotation goes between [0..1].
+        updateRingColor(interpolatedTime, ring);
+        float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
+                + 1f);
+        final float startTrim = ring.getStartingStartTrim()
+                + (ring.getStartingEndTrim() - MIN_PROGRESS_ARC - ring.getStartingStartTrim())
+                * interpolatedTime;
+        ring.setStartTrim(startTrim);
+        ring.setEndTrim(ring.getStartingEndTrim());
+        final float rotation = ring.getStartingRotation()
+                + ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
+        ring.setRotation(rotation);
+    }
+
+    /**
+     * Update the ring start and end trim according to current time of the animation.
+     */
+    private void applyTransformation(float interpolatedTime, Ring ring, boolean lastFrame) {
+        if (mFinishing) {
+            applyFinishTranslation(interpolatedTime, ring);
+            // Below condition is to work around a ValueAnimator issue where onAnimationRepeat is
+            // called before last frame (1f).
+        } else if (interpolatedTime != 1f || lastFrame) {
+            final float startingRotation = ring.getStartingRotation();
+            float startTrim, endTrim;
+
+            if (interpolatedTime < SHRINK_OFFSET) { // Expansion occurs on first half of animation
+                final float scaledTime = interpolatedTime / SHRINK_OFFSET;
+                startTrim = ring.getStartingStartTrim();
+                endTrim = startTrim + ((MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
+                        * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime) + MIN_PROGRESS_ARC);
+            } else { // Shrinking occurs on second half of animation
+                float scaledTime = (interpolatedTime - SHRINK_OFFSET) / (1f - SHRINK_OFFSET);
+                endTrim = ring.getStartingStartTrim() + (MAX_PROGRESS_ARC - MIN_PROGRESS_ARC);
+                startTrim = endTrim - ((MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
+                        * (1f - MATERIAL_INTERPOLATOR.getInterpolation(scaledTime))
+                        + MIN_PROGRESS_ARC);
+            }
+
+            final float rotation = startingRotation + (RING_ROTATION * interpolatedTime);
+            float groupRotation = GROUP_FULL_ROTATION * (interpolatedTime + mRotationCount);
+
+            ring.setStartTrim(startTrim);
+            ring.setEndTrim(endTrim);
+            ring.setRotation(rotation);
+            setRotation(groupRotation);
+        }
+    }
+
+    private void setupAnimators() {
+        final Ring ring = mRing;
+        final ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
+        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
+            @Override
+            public void onAnimationUpdate(ValueAnimator animation) {
+                float interpolatedTime = (float) animation.getAnimatedValue();
+                updateRingColor(interpolatedTime, ring);
+                applyTransformation(interpolatedTime, ring, false);
+                invalidateSelf();
+            }
+        });
+        animator.setRepeatCount(ValueAnimator.INFINITE);
+        animator.setRepeatMode(ValueAnimator.RESTART);
+        animator.setInterpolator(LINEAR_INTERPOLATOR);
+        animator.addListener(new Animator.AnimatorListener() {
+
+            @Override
+            public void onAnimationStart(Animator animator) {
+                mRotationCount = 0;
+            }
+
+            @Override
+            public void onAnimationEnd(Animator animator) {
+                // do nothing
+            }
+
+            @Override
+            public void onAnimationCancel(Animator animation) {
+                // do nothing
+            }
+
+            @Override
+            public void onAnimationRepeat(Animator animator) {
+                applyTransformation(1f, ring, true);
+                ring.storeOriginals();
+                ring.goToNextColor();
+                if (mFinishing) {
+                    // finished closing the last ring from the swipe gesture; go
+                    // into progress mode
+                    mFinishing = false;
+                    animator.cancel();
+                    animator.setDuration(ANIMATION_DURATION);
+                    animator.start();
+                    ring.setShowArrow(false);
+                } else {
+                    mRotationCount = mRotationCount + 1;
+                }
+            }
+        });
+        mAnimator = animator;
+    }
+
+    /**
+     * A private class to do all the drawing of CircularProgressDrawable, which includes background,
+     * progress spinner and the arrow. This class is to separate drawing from animation.
+     */
+    private static class Ring {
+        final RectF mTempBounds = new RectF();
+        final Paint mPaint = new Paint();
+        final Paint mArrowPaint = new Paint();
+        final Paint mCirclePaint = new Paint();
+
+        float mStartTrim = 0f;
+        float mEndTrim = 0f;
+        float mRotation = 0f;
+        float mStrokeWidth = 5f;
+
+        int[] mColors;
+        // mColorIndex represents the offset into the available mColors that the
+        // progress circle should currently display. As the progress circle is
+        // animating, the mColorIndex moves by one to the next available color.
+        int mColorIndex;
+        float mStartingStartTrim;
+        float mStartingEndTrim;
+        float mStartingRotation;
+        boolean mShowArrow;
+        Path mArrow;
+        float mArrowScale = 1;
+        float mRingCenterRadius;
+        int mArrowWidth;
+        int mArrowHeight;
+        int mAlpha = 255;
+        int mCurrentColor;
+
+        Ring() {
+            mPaint.setStrokeCap(Paint.Cap.SQUARE);
+            mPaint.setAntiAlias(true);
+            mPaint.setStyle(Style.STROKE);
+
+            mArrowPaint.setStyle(Paint.Style.FILL);
+            mArrowPaint.setAntiAlias(true);
+
+            mCirclePaint.setColor(Color.TRANSPARENT);
+        }
+
+        /**
+         * Sets the dimensions of the arrowhead.
+         *
+         * @param width width of the hypotenuse of the arrow head
+         * @param height height of the arrow point
+         */
+        void setArrowDimensions(float width, float height) {
+            mArrowWidth = (int) width;
+            mArrowHeight = (int) height;
+        }
+
+        void setStrokeCap(Paint.Cap strokeCap) {
+            mPaint.setStrokeCap(strokeCap);
+        }
+
+        Paint.Cap getStrokeCap() {
+            return mPaint.getStrokeCap();
+        }
+
+        float getArrowWidth() {
+            return mArrowWidth;
+        }
+
+        float getArrowHeight() {
+            return mArrowHeight;
+        }
+
+        /**
+         * Draw the progress spinner
+         */
+        void draw(Canvas c, Rect bounds) {
+            final RectF arcBounds = mTempBounds;
+            float arcRadius = mRingCenterRadius + mStrokeWidth / 2f;
+            if (mRingCenterRadius <= 0) {
+                // If center radius is not set, fill the bounds
+                arcRadius = Math.min(bounds.width(), bounds.height()) / 2f - Math.max(
+                        (mArrowWidth * mArrowScale) / 2f, mStrokeWidth / 2f);
+            }
+            arcBounds.set(bounds.centerX() - arcRadius,
+                    bounds.centerY() - arcRadius,
+                    bounds.centerX() + arcRadius,
+                    bounds.centerY() + arcRadius);
+
+            final float startAngle = (mStartTrim + mRotation) * 360;
+            final float endAngle = (mEndTrim + mRotation) * 360;
+            float sweepAngle = endAngle - startAngle;
+
+            mPaint.setColor(mCurrentColor);
+            mPaint.setAlpha(mAlpha);
+
+            // Draw the background first
+            float inset = mStrokeWidth / 2f; // Calculate inset to draw inside the arc
+            arcBounds.inset(inset, inset); // Apply inset
+            c.drawCircle(arcBounds.centerX(), arcBounds.centerY(), arcBounds.width() / 2f,
+                    mCirclePaint);
+            arcBounds.inset(-inset, -inset); // Revert the inset
+
+            c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
+
+            drawTriangle(c, startAngle, sweepAngle, arcBounds);
+        }
+
+        void drawTriangle(Canvas c, float startAngle, float sweepAngle, RectF bounds) {
+            if (mShowArrow) {
+                if (mArrow == null) {
+                    mArrow = new android.graphics.Path();
+                    mArrow.setFillType(android.graphics.Path.FillType.EVEN_ODD);
+                } else {
+                    mArrow.reset();
+                }
+                float centerRadius = Math.min(bounds.width(), bounds.height()) / 2f;
+                float inset = mArrowWidth * mArrowScale / 2f;
+                // Update the path each time. This works around an issue in SKIA
+                // where concatenating a rotation matrix to a scale matrix
+                // ignored a starting negative rotation. This appears to have
+                // been fixed as of API 21.
+                mArrow.moveTo(0, 0);
+                mArrow.lineTo(mArrowWidth * mArrowScale, 0);
+                mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
+                        * mArrowScale));
+                mArrow.offset(centerRadius + bounds.centerX() - inset,
+                        bounds.centerY() + mStrokeWidth / 2f);
+                mArrow.close();
+                // draw a triangle
+                mArrowPaint.setColor(mCurrentColor);
+                mArrowPaint.setAlpha(mAlpha);
+                c.save();
+                c.rotate(startAngle + sweepAngle, bounds.centerX(),
+                        bounds.centerY());
+                c.drawPath(mArrow, mArrowPaint);
+                c.restore();
+            }
+        }
+
+        /**
+         * Sets the colors the progress spinner alternates between.
+         *
+         * @param colors array of ARGB colors. Must be non-{@code null}.
+         */
+        void setColors(@NonNull int[] colors) {
+            mColors = colors;
+            // if colors are reset, make sure to reset the color index as well
+            setColorIndex(0);
+        }
+
+        int[] getColors() {
+            return mColors;
+        }
+
+        /**
+         * Sets the absolute color of the progress spinner. This is should only
+         * be used when animating between current and next color when the
+         * spinner is rotating.
+         *
+         * @param color an ARGB color
+         */
+        void setColor(int color) {
+            mCurrentColor = color;
+        }
+
+        /**
+         * Sets the background color of the circle inside the spinner.
+         */
+        void setBackgroundColor(int color) {
+            mCirclePaint.setColor(color);
+        }
+
+        int getBackgroundColor() {
+            return mCirclePaint.getColor();
+        }
+
+        /**
+         * @param index index into the color array of the color to display in
+         *              the progress spinner.
+         */
+        void setColorIndex(int index) {
+            mColorIndex = index;
+            mCurrentColor = mColors[mColorIndex];
+        }
+
+        /**
+         * @return int describing the next color the progress spinner should use when drawing.
+         */
+        int getNextColor() {
+            return mColors[getNextColorIndex()];
+        }
+
+        int getNextColorIndex() {
+            return (mColorIndex + 1) % (mColors.length);
+        }
+
+        /**
+         * Proceed to the next available ring color. This will automatically
+         * wrap back to the beginning of colors.
+         */
+        void goToNextColor() {
+            setColorIndex(getNextColorIndex());
+        }
+
+        void setColorFilter(ColorFilter filter) {
+            mPaint.setColorFilter(filter);
+        }
+
+        /**
+         * @param alpha alpha of the progress spinner and associated arrowhead.
+         */
+        void setAlpha(int alpha) {
+            mAlpha = alpha;
+        }
+
+        /**
+         * @return current alpha of the progress spinner and arrowhead
+         */
+        int getAlpha() {
+            return mAlpha;
+        }
+
+        /**
+         * @param strokeWidth set the stroke width of the progress spinner in pixels.
+         */
+        void setStrokeWidth(float strokeWidth) {
+            mStrokeWidth = strokeWidth;
+            mPaint.setStrokeWidth(strokeWidth);
+        }
+
+        float getStrokeWidth() {
+            return mStrokeWidth;
+        }
+
+        void setStartTrim(float startTrim) {
+            mStartTrim = startTrim;
+        }
+
+        float getStartTrim() {
+            return mStartTrim;
+        }
+
+        float getStartingStartTrim() {
+            return mStartingStartTrim;
+        }
+
+        float getStartingEndTrim() {
+            return mStartingEndTrim;
+        }
+
+        int getStartingColor() {
+            return mColors[mColorIndex];
+        }
+
+        void setEndTrim(float endTrim) {
+            mEndTrim = endTrim;
+        }
+
+        float getEndTrim() {
+            return mEndTrim;
+        }
+
+        void setRotation(float rotation) {
+            mRotation = rotation;
+        }
+
+        float getRotation() {
+            return mRotation;
+        }
+
+        /**
+         * @param centerRadius inner radius in px of the circle the progress spinner arc traces
+         */
+        void setCenterRadius(float centerRadius) {
+            mRingCenterRadius = centerRadius;
+        }
+
+        float getCenterRadius() {
+            return mRingCenterRadius;
+        }
+
+        /**
+         * @param show {@code true} if should show the arrow head on the progress spinner
+         */
+        void setShowArrow(boolean show) {
+            if (mShowArrow != show) {
+                mShowArrow = show;
+            }
+        }
+
+        boolean getShowArrow() {
+            return mShowArrow;
+        }
+
+        /**
+         * @param scale scale of the arrowhead for the spinner
+         */
+        void setArrowScale(float scale) {
+            if (scale != mArrowScale) {
+                mArrowScale = scale;
+            }
+        }
+
+        float getArrowScale() {
+            return mArrowScale;
+        }
+
+        /**
+         * @return The amount the progress spinner is currently rotated, between [0..1].
+         */
+        float getStartingRotation() {
+            return mStartingRotation;
+        }
+
+        /**
+         * If the start / end trim are offset to begin with, store them so that animation starts
+         * from that offset.
+         */
+        void storeOriginals() {
+            mStartingStartTrim = mStartTrim;
+            mStartingEndTrim = mEndTrim;
+            mStartingRotation = mRotation;
+        }
+
+        /**
+         * Reset the progress spinner to default rotation, start and end angles.
+         */
+        void resetOriginals() {
+            mStartingStartTrim = 0;
+            mStartingEndTrim = 0;
+            mStartingRotation = 0;
+            setStartTrim(0);
+            setEndTrim(0);
+            setRotation(0);
+        }
+    }
+}
diff --git a/core-ui/java/android/support/v4/widget/DrawerLayout.java b/core-ui/java/android/support/v4/widget/DrawerLayout.java
index fe35212..c7b40e9 100644
--- a/core-ui/java/android/support/v4/widget/DrawerLayout.java
+++ b/core-ui/java/android/support/v4/widget/DrawerLayout.java
@@ -17,6 +17,9 @@
 
 package android.support.v4.widget;
 
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.annotation.TargetApi;
 import android.content.Context;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
@@ -34,7 +37,7 @@
 import android.support.annotation.IntDef;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
-import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
 import android.support.v4.content.ContextCompat;
 import android.support.v4.graphics.drawable.DrawableCompat;
 import android.support.v4.view.AbsSavedState;
@@ -51,6 +54,7 @@
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ViewParent;
+import android.view.WindowInsets;
 import android.view.accessibility.AccessibilityEvent;
 
 import java.lang.annotation.Retention;
@@ -91,9 +95,13 @@
  * href="{@docRoot}training/implementing-navigation/nav-drawer.html">Creating a Navigation
  * Drawer</a>.</p>
  */
-public class DrawerLayout extends ViewGroup implements DrawerLayoutImpl {
+public class DrawerLayout extends ViewGroup {
     private static final String TAG = "DrawerLayout";
 
+    private static final int[] THEME_ATTRS = {
+            android.R.attr.colorPrimaryDark
+    };
+
     @IntDef({STATE_IDLE, STATE_DRAGGING, STATE_SETTLING})
     @Retention(RetentionPolicy.SOURCE)
     private @interface State {}
@@ -140,7 +148,8 @@
      */
     public static final int LOCK_MODE_UNDEFINED = 3;
 
-    @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
+    @IntDef(value = {Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END},
+            flag = true)
     @Retention(RetentionPolicy.SOURCE)
     private @interface EdgeGravity {}
 
@@ -287,79 +296,6 @@
         }
     }
 
-    interface DrawerLayoutCompatImpl {
-        void configureApplyInsets(View drawerLayout);
-        void dispatchChildInsets(View child, Object insets, int drawerGravity);
-        void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity);
-        int getTopInset(Object lastInsets);
-        Drawable getDefaultStatusBarBackground(Context context);
-    }
-
-    static class DrawerLayoutCompatImplBase implements DrawerLayoutCompatImpl {
-        @Override
-        public void configureApplyInsets(View drawerLayout) {
-            // This space for rent
-        }
-
-        @Override
-        public void dispatchChildInsets(View child, Object insets, int drawerGravity) {
-            // This space for rent
-        }
-
-        @Override
-        public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) {
-            // This space for rent
-        }
-
-        @Override
-        public int getTopInset(Object insets) {
-            return 0;
-        }
-
-        @Override
-        public Drawable getDefaultStatusBarBackground(Context context) {
-            return null;
-        }
-    }
-
-    @RequiresApi(21)
-    static class DrawerLayoutCompatImplApi21 implements DrawerLayoutCompatImpl {
-        @Override
-        public void configureApplyInsets(View drawerLayout) {
-            DrawerLayoutCompatApi21.configureApplyInsets(drawerLayout);
-        }
-
-        @Override
-        public void dispatchChildInsets(View child, Object insets, int drawerGravity) {
-            DrawerLayoutCompatApi21.dispatchChildInsets(child, insets, drawerGravity);
-        }
-
-        @Override
-        public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) {
-            DrawerLayoutCompatApi21.applyMarginInsets(lp, insets, drawerGravity);
-        }
-
-        @Override
-        public int getTopInset(Object insets) {
-            return DrawerLayoutCompatApi21.getTopInset(insets);
-        }
-
-        @Override
-        public Drawable getDefaultStatusBarBackground(Context context) {
-            return DrawerLayoutCompatApi21.getDefaultStatusBarBackground(context);
-        }
-    }
-
-    static {
-        if (Build.VERSION.SDK_INT >= 21) {
-            IMPL = new DrawerLayoutCompatImplApi21();
-        } else {
-            IMPL = new DrawerLayoutCompatImplBase();
-        }
-    }
-
-    static final DrawerLayoutCompatImpl IMPL;
-
     public DrawerLayout(Context context) {
         this(context, null);
     }
@@ -397,8 +333,27 @@
         ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
         ViewGroupCompat.setMotionEventSplittingEnabled(this, false);
         if (ViewCompat.getFitsSystemWindows(this)) {
-            IMPL.configureApplyInsets(this);
-            mStatusBarBackground = IMPL.getDefaultStatusBarBackground(context);
+            if (Build.VERSION.SDK_INT >= 21) {
+                setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
+                    @TargetApi(21)
+                    @Override
+                    public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) {
+                        final DrawerLayout drawerLayout = (DrawerLayout) view;
+                        drawerLayout.setChildInsets(insets, insets.getSystemWindowInsetTop() > 0);
+                        return insets.consumeSystemWindowInsets();
+                    }
+                });
+                setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
+                final TypedArray a = context.obtainStyledAttributes(THEME_ATTRS);
+                try {
+                    mStatusBarBackground = a.getDrawable(0);
+                } finally {
+                    a.recycle();
+                }
+            } else {
+                mStatusBarBackground = null;
+            }
         }
 
         mDrawerElevation = DRAWER_ELEVATION * density;
@@ -440,7 +395,7 @@
      * @hide Internal use only; called to apply window insets when configured
      * with fitsSystemWindows="true"
      */
-    @Override
+    @RestrictTo(LIBRARY_GROUP)
     public void setChildInsets(Object insets, boolean draw) {
         mLastInsets = insets;
         mDrawStatusBarBackground = draw;
@@ -1063,9 +1018,36 @@
             if (applyInsets) {
                 final int cgrav = GravityCompat.getAbsoluteGravity(lp.gravity, layoutDirection);
                 if (ViewCompat.getFitsSystemWindows(child)) {
-                    IMPL.dispatchChildInsets(child, mLastInsets, cgrav);
+                    if (Build.VERSION.SDK_INT >= 21) {
+                        WindowInsets wi = (WindowInsets) mLastInsets;
+                        if (cgrav == Gravity.LEFT) {
+                            wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
+                                    wi.getSystemWindowInsetTop(), 0,
+                                    wi.getSystemWindowInsetBottom());
+                        } else if (cgrav == Gravity.RIGHT) {
+                            wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
+                                    wi.getSystemWindowInsetRight(),
+                                    wi.getSystemWindowInsetBottom());
+                        }
+                        child.dispatchApplyWindowInsets(wi);
+                    }
                 } else {
-                    IMPL.applyMarginInsets(lp, mLastInsets, cgrav);
+                    if (Build.VERSION.SDK_INT >= 21) {
+                        WindowInsets wi = (WindowInsets) mLastInsets;
+                        if (cgrav == Gravity.LEFT) {
+                            wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
+                                    wi.getSystemWindowInsetTop(), 0,
+                                    wi.getSystemWindowInsetBottom());
+                        } else if (cgrav == Gravity.RIGHT) {
+                            wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
+                                    wi.getSystemWindowInsetRight(),
+                                    wi.getSystemWindowInsetBottom());
+                        }
+                        lp.leftMargin = wi.getSystemWindowInsetLeft();
+                        lp.topMargin = wi.getSystemWindowInsetTop();
+                        lp.rightMargin = wi.getSystemWindowInsetRight();
+                        lp.bottomMargin = wi.getSystemWindowInsetBottom();
+                    }
                 }
             }
 
@@ -1340,7 +1322,13 @@
     public void onDraw(Canvas c) {
         super.onDraw(c);
         if (mDrawStatusBarBackground && mStatusBarBackground != null) {
-            final int inset = IMPL.getTopInset(mLastInsets);
+            final int inset;
+            if (Build.VERSION.SDK_INT >= 21) {
+                inset = mLastInsets != null
+                        ? ((WindowInsets) mLastInsets).getSystemWindowInsetTop() : 0;
+            } else {
+                inset = 0;
+            }
             if (inset > 0) {
                 mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
                 mStatusBarBackground.draw(c);
diff --git a/core-ui/java/android/support/v4/widget/ExploreByTouchHelper.java b/core-ui/java/android/support/v4/widget/ExploreByTouchHelper.java
index 780d34e..8a29eff 100644
--- a/core-ui/java/android/support/v4/widget/ExploreByTouchHelper.java
+++ b/core-ui/java/android/support/v4/widget/ExploreByTouchHelper.java
@@ -28,7 +28,6 @@
 import android.support.v4.view.ViewCompat.FocusRealDirection;
 import android.support.v4.view.ViewParentCompat;
 import android.support.v4.view.accessibility.AccessibilityEventCompat;
-import android.support.v4.view.accessibility.AccessibilityManagerCompat;
 import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
 import android.support.v4.view.accessibility.AccessibilityNodeProviderCompat;
 import android.support.v4.view.accessibility.AccessibilityRecordCompat;
@@ -177,8 +176,7 @@
      * @return Whether the hover event was handled.
      */
     public final boolean dispatchHoverEvent(@NonNull MotionEvent event) {
-        if (!mManager.isEnabled()
-                || !AccessibilityManagerCompat.isTouchExplorationEnabled(mManager)) {
+        if (!mManager.isEnabled() || !mManager.isTouchExplorationEnabled()) {
             return false;
         }
 
@@ -650,7 +648,7 @@
      */
     private AccessibilityEvent createEventForHost(int eventType) {
         final AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
-        ViewCompat.onInitializeAccessibilityEvent(mHost, event);
+        mHost.onInitializeAccessibilityEvent(event);
         return event;
     }
 
@@ -941,7 +939,7 @@
         ViewParent viewParent = mHost.getParent();
         while (viewParent instanceof View) {
             final View view = (View) viewParent;
-            if ((ViewCompat.getAlpha(view) <= 0) || (view.getVisibility() != View.VISIBLE)) {
+            if ((view.getAlpha() <= 0) || (view.getVisibility() != View.VISIBLE)) {
                 return false;
             }
             viewParent = view.getParent();
@@ -964,8 +962,7 @@
      * @return whether this virtual view actually took accessibility focus
      */
     private boolean requestAccessibilityFocus(int virtualViewId) {
-        if (!mManager.isEnabled()
-                || !AccessibilityManagerCompat.isTouchExplorationEnabled(mManager)) {
+        if (!mManager.isEnabled() || !mManager.isTouchExplorationEnabled()) {
             return false;
         }
         // TODO: Check virtual view visibility.
diff --git a/core-ui/java/android/support/v4/widget/MaterialProgressDrawable.java b/core-ui/java/android/support/v4/widget/MaterialProgressDrawable.java
deleted file mode 100644
index cad36d9..0000000
--- a/core-ui/java/android/support/v4/widget/MaterialProgressDrawable.java
+++ /dev/null
@@ -1,792 +0,0 @@
-/*
- * Copyright (C) 2014 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 android.support.v4.widget;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.ColorFilter;
-import android.graphics.Paint;
-import android.graphics.Paint.Style;
-import android.graphics.Path;
-import android.graphics.PixelFormat;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.Animatable;
-import android.graphics.drawable.Drawable;
-import android.support.annotation.IntDef;
-import android.support.annotation.NonNull;
-import android.support.v4.view.animation.FastOutSlowInInterpolator;
-import android.util.DisplayMetrics;
-import android.view.View;
-import android.view.animation.Animation;
-import android.view.animation.Interpolator;
-import android.view.animation.LinearInterpolator;
-import android.view.animation.Transformation;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-
-/**
- * Fancy progress indicator for Material theme.
- */
-class MaterialProgressDrawable extends Drawable implements Animatable {
-    private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
-    static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
-
-    private static final float FULL_ROTATION = 1080.0f;
-
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({LARGE, DEFAULT})
-    public @interface ProgressDrawableSize {}
-
-    // Maps to ProgressBar.Large style
-    static final int LARGE = 0;
-    // Maps to ProgressBar default style
-    static final int DEFAULT = 1;
-
-    // Maps to ProgressBar default style
-    private static final int CIRCLE_DIAMETER = 40;
-    private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
-    private static final float STROKE_WIDTH = 2.5f;
-
-    // Maps to ProgressBar.Large style
-    private static final int CIRCLE_DIAMETER_LARGE = 56;
-    private static final float CENTER_RADIUS_LARGE = 12.5f;
-    private static final float STROKE_WIDTH_LARGE = 3f;
-
-    private static final int[] COLORS = new int[] {
-        Color.BLACK
-    };
-
-    /**
-     * The value in the linear interpolator for animating the drawable at which
-     * the color transition should start
-     */
-    private static final float COLOR_START_DELAY_OFFSET = 0.75f;
-    private static final float END_TRIM_START_DELAY_OFFSET = 0.5f;
-    private static final float START_TRIM_DURATION_OFFSET = 0.5f;
-
-    /** The duration of a single progress spin in milliseconds. */
-    private static final int ANIMATION_DURATION = 1332;
-
-    /** The number of points in the progress "star". */
-    private static final float NUM_POINTS = 5f;
-    /** The list of animators operating on this drawable. */
-    private final ArrayList<Animation> mAnimators = new ArrayList<Animation>();
-
-    /** The indicator ring, used to manage animation state. */
-    private final Ring mRing;
-
-    /** Canvas rotation in degrees. */
-    private float mRotation;
-
-    /** Layout info for the arrowhead in dp */
-    private static final int ARROW_WIDTH = 10;
-    private static final int ARROW_HEIGHT = 5;
-    private static final float ARROW_OFFSET_ANGLE = 5;
-
-    /** Layout info for the arrowhead for the large spinner in dp */
-    private static final int ARROW_WIDTH_LARGE = 12;
-    private static final int ARROW_HEIGHT_LARGE = 6;
-    private static final float MAX_PROGRESS_ARC = .8f;
-
-    private Resources mResources;
-    private View mParent;
-    private Animation mAnimation;
-    float mRotationCount;
-    private double mWidth;
-    private double mHeight;
-    boolean mFinishing;
-
-    MaterialProgressDrawable(Context context, View parent) {
-        mParent = parent;
-        mResources = context.getResources();
-
-        mRing = new Ring(mCallback);
-        mRing.setColors(COLORS);
-
-        updateSizes(DEFAULT);
-        setupAnimators();
-    }
-
-    private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
-            double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) {
-        final Ring ring = mRing;
-        final DisplayMetrics metrics = mResources.getDisplayMetrics();
-        final float screenDensity = metrics.density;
-
-        mWidth = progressCircleWidth * screenDensity;
-        mHeight = progressCircleHeight * screenDensity;
-        ring.setStrokeWidth((float) strokeWidth * screenDensity);
-        ring.setCenterRadius(centerRadius * screenDensity);
-        ring.setColorIndex(0);
-        ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
-        ring.setInsets((int) mWidth, (int) mHeight);
-    }
-
-    /**
-     * Set the overall size for the progress spinner. This updates the radius
-     * and stroke width of the ring.
-     *
-     * @param size One of {@link MaterialProgressDrawable.LARGE} or
-     *            {@link MaterialProgressDrawable.DEFAULT}
-     */
-    public void updateSizes(@ProgressDrawableSize int size) {
-        if (size == LARGE) {
-            setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
-                    STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
-        } else {
-            setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
-                    ARROW_WIDTH, ARROW_HEIGHT);
-        }
-    }
-
-    /**
-     * @param show Set to true to display the arrowhead on the progress spinner.
-     */
-    public void showArrow(boolean show) {
-        mRing.setShowArrow(show);
-    }
-
-    /**
-     * @param scale Set the scale of the arrowhead for the spinner.
-     */
-    public void setArrowScale(float scale) {
-        mRing.setArrowScale(scale);
-    }
-
-    /**
-     * Set the start and end trim for the progress spinner arc.
-     *
-     * @param startAngle start angle
-     * @param endAngle end angle
-     */
-    public void setStartEndTrim(float startAngle, float endAngle) {
-        mRing.setStartTrim(startAngle);
-        mRing.setEndTrim(endAngle);
-    }
-
-    /**
-     * Set the amount of rotation to apply to the progress spinner.
-     *
-     * @param rotation Rotation is from [0..1]
-     */
-    public void setProgressRotation(float rotation) {
-        mRing.setRotation(rotation);
-    }
-
-    /**
-     * Update the background color of the circle image view.
-     */
-    public void setBackgroundColor(int color) {
-        mRing.setBackgroundColor(color);
-    }
-
-    /**
-     * Set the colors used in the progress animation from color resources.
-     * The first color will also be the color of the bar that grows in response
-     * to a user swipe gesture.
-     *
-     * @param colors
-     */
-    public void setColorSchemeColors(int... colors) {
-        mRing.setColors(colors);
-        mRing.setColorIndex(0);
-    }
-
-    @Override
-    public int getIntrinsicHeight() {
-        return (int) mHeight;
-    }
-
-    @Override
-    public int getIntrinsicWidth() {
-        return (int) mWidth;
-    }
-
-    @Override
-    public void draw(Canvas c) {
-        final Rect bounds = getBounds();
-        final int saveCount = c.save();
-        c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
-        mRing.draw(c, bounds);
-        c.restoreToCount(saveCount);
-    }
-
-    @Override
-    public void setAlpha(int alpha) {
-        mRing.setAlpha(alpha);
-    }
-
-    @Override
-    public int getAlpha() {
-        return mRing.getAlpha();
-    }
-
-    @Override
-    public void setColorFilter(ColorFilter colorFilter) {
-        mRing.setColorFilter(colorFilter);
-    }
-
-    @SuppressWarnings("unused")
-    void setRotation(float rotation) {
-        mRotation = rotation;
-        invalidateSelf();
-    }
-
-    @SuppressWarnings("unused")
-    private float getRotation() {
-        return mRotation;
-    }
-
-    @Override
-    public int getOpacity() {
-        return PixelFormat.TRANSLUCENT;
-    }
-
-    @Override
-    public boolean isRunning() {
-        final ArrayList<Animation> animators = mAnimators;
-        final int N = animators.size();
-        for (int i = 0; i < N; i++) {
-            final Animation animator = animators.get(i);
-            if (animator.hasStarted() && !animator.hasEnded()) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Override
-    public void start() {
-        mAnimation.reset();
-        mRing.storeOriginals();
-        // Already showing some part of the ring
-        if (mRing.getEndTrim() != mRing.getStartTrim()) {
-            mFinishing = true;
-            mAnimation.setDuration(ANIMATION_DURATION / 2);
-            mParent.startAnimation(mAnimation);
-        } else {
-            mRing.setColorIndex(0);
-            mRing.resetOriginals();
-            mAnimation.setDuration(ANIMATION_DURATION);
-            mParent.startAnimation(mAnimation);
-        }
-    }
-
-    @Override
-    public void stop() {
-        mParent.clearAnimation();
-        setRotation(0);
-        mRing.setShowArrow(false);
-        mRing.setColorIndex(0);
-        mRing.resetOriginals();
-    }
-
-    float getMinProgressArc(Ring ring) {
-        return (float) Math.toRadians(
-                ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
-    }
-
-    // Adapted from ArgbEvaluator.java
-    private int evaluateColorChange(float fraction, int startValue, int endValue) {
-        int startInt = (Integer) startValue;
-        int startA = (startInt >> 24) & 0xff;
-        int startR = (startInt >> 16) & 0xff;
-        int startG = (startInt >> 8) & 0xff;
-        int startB = startInt & 0xff;
-
-        int endInt = (Integer) endValue;
-        int endA = (endInt >> 24) & 0xff;
-        int endR = (endInt >> 16) & 0xff;
-        int endG = (endInt >> 8) & 0xff;
-        int endB = endInt & 0xff;
-
-        return (int) ((startA + (int) (fraction * (endA - startA))) << 24)
-                | (int) ((startR + (int) (fraction * (endR - startR))) << 16)
-                | (int) ((startG + (int) (fraction * (endG - startG))) << 8)
-                | (int) ((startB + (int) (fraction * (endB - startB))));
-    }
-
-    /**
-     * Update the ring color if this is within the last 25% of the animation.
-     * The new ring color will be a translation from the starting ring color to
-     * the next color.
-     */
-    void updateRingColor(float interpolatedTime, Ring ring) {
-        if (interpolatedTime > COLOR_START_DELAY_OFFSET) {
-            // scale the interpolatedTime so that the full
-            // transformation from 0 - 1 takes place in the
-            // remaining time
-            ring.setColor(evaluateColorChange((interpolatedTime - COLOR_START_DELAY_OFFSET)
-                    / (1.0f - COLOR_START_DELAY_OFFSET), ring.getStartingColor(),
-                    ring.getNextColor()));
-        }
-    }
-
-    void applyFinishTranslation(float interpolatedTime, Ring ring) {
-        // shrink back down and complete a full rotation before
-        // starting other circles
-        // Rotation goes between [0..1].
-        updateRingColor(interpolatedTime, ring);
-        float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
-                + 1f);
-        final float minProgressArc = getMinProgressArc(ring);
-        final float startTrim = ring.getStartingStartTrim()
-                + (ring.getStartingEndTrim() - minProgressArc - ring.getStartingStartTrim())
-                * interpolatedTime;
-        ring.setStartTrim(startTrim);
-        ring.setEndTrim(ring.getStartingEndTrim());
-        final float rotation = ring.getStartingRotation()
-                + ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
-        ring.setRotation(rotation);
-    }
-
-    private void setupAnimators() {
-        final Ring ring = mRing;
-        final Animation animation = new Animation() {
-                @Override
-            public void applyTransformation(float interpolatedTime, Transformation t) {
-                if (mFinishing) {
-                    applyFinishTranslation(interpolatedTime, ring);
-                } else {
-                    // The minProgressArc is calculated from 0 to create an
-                    // angle that matches the stroke width.
-                    final float minProgressArc = getMinProgressArc(ring);
-                    final float startingEndTrim = ring.getStartingEndTrim();
-                    final float startingTrim = ring.getStartingStartTrim();
-                    final float startingRotation = ring.getStartingRotation();
-
-                    updateRingColor(interpolatedTime, ring);
-
-                    // Moving the start trim only occurs in the first 50% of a
-                    // single ring animation
-                    if (interpolatedTime <= START_TRIM_DURATION_OFFSET) {
-                        // scale the interpolatedTime so that the full
-                        // transformation from 0 - 1 takes place in the
-                        // remaining time
-                        final float scaledTime = (interpolatedTime)
-                                / (1.0f - START_TRIM_DURATION_OFFSET);
-                        final float startTrim = startingTrim
-                                + ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR
-                                        .getInterpolation(scaledTime));
-                        ring.setStartTrim(startTrim);
-                    }
-
-                    // Moving the end trim starts after 50% of a single ring
-                    // animation completes
-                    if (interpolatedTime > END_TRIM_START_DELAY_OFFSET) {
-                        // scale the interpolatedTime so that the full
-                        // transformation from 0 - 1 takes place in the
-                        // remaining time
-                        final float minArc = MAX_PROGRESS_ARC - minProgressArc;
-                        float scaledTime = (interpolatedTime - START_TRIM_DURATION_OFFSET)
-                                / (1.0f - START_TRIM_DURATION_OFFSET);
-                        final float endTrim = startingEndTrim
-                                + (minArc * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime));
-                        ring.setEndTrim(endTrim);
-                    }
-
-                    final float rotation = startingRotation + (0.25f * interpolatedTime);
-                    ring.setRotation(rotation);
-
-                    float groupRotation = ((FULL_ROTATION / NUM_POINTS) * interpolatedTime)
-                            + (FULL_ROTATION * (mRotationCount / NUM_POINTS));
-                    setRotation(groupRotation);
-                }
-            }
-        };
-        animation.setRepeatCount(Animation.INFINITE);
-        animation.setRepeatMode(Animation.RESTART);
-        animation.setInterpolator(LINEAR_INTERPOLATOR);
-        animation.setAnimationListener(new Animation.AnimationListener() {
-
-                @Override
-            public void onAnimationStart(Animation animation) {
-                mRotationCount = 0;
-            }
-
-                @Override
-            public void onAnimationEnd(Animation animation) {
-                // do nothing
-            }
-
-                @Override
-            public void onAnimationRepeat(Animation animation) {
-                ring.storeOriginals();
-                ring.goToNextColor();
-                ring.setStartTrim(ring.getEndTrim());
-                if (mFinishing) {
-                    // finished closing the last ring from the swipe gesture; go
-                    // into progress mode
-                    mFinishing = false;
-                    animation.setDuration(ANIMATION_DURATION);
-                    ring.setShowArrow(false);
-                } else {
-                    mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
-                }
-            }
-        });
-        mAnimation = animation;
-    }
-
-    private final Callback mCallback = new Callback() {
-        @Override
-        public void invalidateDrawable(Drawable d) {
-            invalidateSelf();
-        }
-
-        @Override
-        public void scheduleDrawable(Drawable d, Runnable what, long when) {
-            scheduleSelf(what, when);
-        }
-
-        @Override
-        public void unscheduleDrawable(Drawable d, Runnable what) {
-            unscheduleSelf(what);
-        }
-    };
-
-    private static class Ring {
-        private final RectF mTempBounds = new RectF();
-        private final Paint mPaint = new Paint();
-        private final Paint mArrowPaint = new Paint();
-
-        private final Callback mCallback;
-
-        private float mStartTrim = 0.0f;
-        private float mEndTrim = 0.0f;
-        private float mRotation = 0.0f;
-        private float mStrokeWidth = 5.0f;
-        private float mStrokeInset = 2.5f;
-
-        private int[] mColors;
-        // mColorIndex represents the offset into the available mColors that the
-        // progress circle should currently display. As the progress circle is
-        // animating, the mColorIndex moves by one to the next available color.
-        private int mColorIndex;
-        private float mStartingStartTrim;
-        private float mStartingEndTrim;
-        private float mStartingRotation;
-        private boolean mShowArrow;
-        private Path mArrow;
-        private float mArrowScale;
-        private double mRingCenterRadius;
-        private int mArrowWidth;
-        private int mArrowHeight;
-        private int mAlpha;
-        private final Paint mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
-        private int mBackgroundColor;
-        private int mCurrentColor;
-
-        Ring(Callback callback) {
-            mCallback = callback;
-
-            mPaint.setStrokeCap(Paint.Cap.SQUARE);
-            mPaint.setAntiAlias(true);
-            mPaint.setStyle(Style.STROKE);
-
-            mArrowPaint.setStyle(Paint.Style.FILL);
-            mArrowPaint.setAntiAlias(true);
-        }
-
-        public void setBackgroundColor(int color) {
-            mBackgroundColor = color;
-        }
-
-        /**
-         * Set the dimensions of the arrowhead.
-         *
-         * @param width Width of the hypotenuse of the arrow head
-         * @param height Height of the arrow point
-         */
-        public void setArrowDimensions(float width, float height) {
-            mArrowWidth = (int) width;
-            mArrowHeight = (int) height;
-        }
-
-        /**
-         * Draw the progress spinner
-         */
-        public void draw(Canvas c, Rect bounds) {
-            final RectF arcBounds = mTempBounds;
-            arcBounds.set(bounds);
-            arcBounds.inset(mStrokeInset, mStrokeInset);
-
-            final float startAngle = (mStartTrim + mRotation) * 360;
-            final float endAngle = (mEndTrim + mRotation) * 360;
-            float sweepAngle = endAngle - startAngle;
-
-            mPaint.setColor(mCurrentColor);
-            c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
-
-            drawTriangle(c, startAngle, sweepAngle, bounds);
-
-            if (mAlpha < 255) {
-                mCirclePaint.setColor(mBackgroundColor);
-                mCirclePaint.setAlpha(255 - mAlpha);
-                c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2,
-                        mCirclePaint);
-            }
-        }
-
-        private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
-            if (mShowArrow) {
-                if (mArrow == null) {
-                    mArrow = new android.graphics.Path();
-                    mArrow.setFillType(android.graphics.Path.FillType.EVEN_ODD);
-                } else {
-                    mArrow.reset();
-                }
-
-                // Adjust the position of the triangle so that it is inset as
-                // much as the arc, but also centered on the arc.
-                float inset = (int) mStrokeInset / 2 * mArrowScale;
-                float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
-                float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());
-
-                // Update the path each time. This works around an issue in SKIA
-                // where concatenating a rotation matrix to a scale matrix
-                // ignored a starting negative rotation. This appears to have
-                // been fixed as of API 21.
-                mArrow.moveTo(0, 0);
-                mArrow.lineTo(mArrowWidth * mArrowScale, 0);
-                mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
-                        * mArrowScale));
-                mArrow.offset(x - inset, y);
-                mArrow.close();
-                // draw a triangle
-                mArrowPaint.setColor(mCurrentColor);
-                c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
-                        bounds.exactCenterY());
-                c.drawPath(mArrow, mArrowPaint);
-            }
-        }
-
-        /**
-         * Set the colors the progress spinner alternates between.
-         *
-         * @param colors Array of integers describing the colors. Must be non-<code>null</code>.
-         */
-        public void setColors(@NonNull int[] colors) {
-            mColors = colors;
-            // if colors are reset, make sure to reset the color index as well
-            setColorIndex(0);
-        }
-
-        /**
-         * Set the absolute color of the progress spinner. This is should only
-         * be used when animating between current and next color when the
-         * spinner is rotating.
-         *
-         * @param color int describing the color.
-         */
-        public void setColor(int color) {
-            mCurrentColor = color;
-        }
-
-        /**
-         * @param index Index into the color array of the color to display in
-         *            the progress spinner.
-         */
-        public void setColorIndex(int index) {
-            mColorIndex = index;
-            mCurrentColor = mColors[mColorIndex];
-        }
-
-        /**
-         * @return int describing the next color the progress spinner should use when drawing.
-         */
-        public int getNextColor() {
-            return mColors[getNextColorIndex()];
-        }
-
-        private int getNextColorIndex() {
-            return (mColorIndex + 1) % (mColors.length);
-        }
-
-        /**
-         * Proceed to the next available ring color. This will automatically
-         * wrap back to the beginning of colors.
-         */
-        public void goToNextColor() {
-            setColorIndex(getNextColorIndex());
-        }
-
-        public void setColorFilter(ColorFilter filter) {
-            mPaint.setColorFilter(filter);
-            invalidateSelf();
-        }
-
-        /**
-         * @param alpha Set the alpha of the progress spinner and associated arrowhead.
-         */
-        public void setAlpha(int alpha) {
-            mAlpha = alpha;
-        }
-
-        /**
-         * @return Current alpha of the progress spinner and arrowhead.
-         */
-        public int getAlpha() {
-            return mAlpha;
-        }
-
-        /**
-         * @param strokeWidth Set the stroke width of the progress spinner in pixels.
-         */
-        public void setStrokeWidth(float strokeWidth) {
-            mStrokeWidth = strokeWidth;
-            mPaint.setStrokeWidth(strokeWidth);
-            invalidateSelf();
-        }
-
-        @SuppressWarnings("unused")
-        public float getStrokeWidth() {
-            return mStrokeWidth;
-        }
-
-        @SuppressWarnings("unused")
-        public void setStartTrim(float startTrim) {
-            mStartTrim = startTrim;
-            invalidateSelf();
-        }
-
-        @SuppressWarnings("unused")
-        public float getStartTrim() {
-            return mStartTrim;
-        }
-
-        public float getStartingStartTrim() {
-            return mStartingStartTrim;
-        }
-
-        public float getStartingEndTrim() {
-            return mStartingEndTrim;
-        }
-
-        public int getStartingColor() {
-            return mColors[mColorIndex];
-        }
-
-        @SuppressWarnings("unused")
-        public void setEndTrim(float endTrim) {
-            mEndTrim = endTrim;
-            invalidateSelf();
-        }
-
-        @SuppressWarnings("unused")
-        public float getEndTrim() {
-            return mEndTrim;
-        }
-
-        @SuppressWarnings("unused")
-        public void setRotation(float rotation) {
-            mRotation = rotation;
-            invalidateSelf();
-        }
-
-        @SuppressWarnings("unused")
-        public float getRotation() {
-            return mRotation;
-        }
-
-        public void setInsets(int width, int height) {
-            final float minEdge = (float) Math.min(width, height);
-            float insets;
-            if (mRingCenterRadius <= 0 || minEdge < 0) {
-                insets = (float) Math.ceil(mStrokeWidth / 2.0f);
-            } else {
-                insets = (float) (minEdge / 2.0f - mRingCenterRadius);
-            }
-            mStrokeInset = insets;
-        }
-
-        @SuppressWarnings("unused")
-        public float getInsets() {
-            return mStrokeInset;
-        }
-
-        /**
-         * @param centerRadius Inner radius in px of the circle the progress
-         *            spinner arc traces.
-         */
-        public void setCenterRadius(double centerRadius) {
-            mRingCenterRadius = centerRadius;
-        }
-
-        public double getCenterRadius() {
-            return mRingCenterRadius;
-        }
-
-        /**
-         * @param show Set to true to show the arrow head on the progress spinner.
-         */
-        public void setShowArrow(boolean show) {
-            if (mShowArrow != show) {
-                mShowArrow = show;
-                invalidateSelf();
-            }
-        }
-
-        /**
-         * @param scale Set the scale of the arrowhead for the spinner.
-         */
-        public void setArrowScale(float scale) {
-            if (scale != mArrowScale) {
-                mArrowScale = scale;
-                invalidateSelf();
-            }
-        }
-
-        /**
-         * @return The amount the progress spinner is currently rotated, between [0..1].
-         */
-        public float getStartingRotation() {
-            return mStartingRotation;
-        }
-
-        /**
-         * If the start / end trim are offset to begin with, store them so that
-         * animation starts from that offset.
-         */
-        public void storeOriginals() {
-            mStartingStartTrim = mStartTrim;
-            mStartingEndTrim = mEndTrim;
-            mStartingRotation = mRotation;
-        }
-
-        /**
-         * Reset the progress spinner to default rotation, start and end angles.
-         */
-        public void resetOriginals() {
-            mStartingStartTrim = 0;
-            mStartingEndTrim = 0;
-            mStartingRotation = 0;
-            setStartTrim(0);
-            setEndTrim(0);
-            setRotation(0);
-        }
-
-        private void invalidateSelf() {
-            mCallback.invalidateDrawable(null);
-        }
-    }
-}
diff --git a/core-ui/java/android/support/v4/widget/SlidingPaneLayout.java b/core-ui/java/android/support/v4/widget/SlidingPaneLayout.java
index 0e482d7..e3f2462 100644
--- a/core-ui/java/android/support/v4/widget/SlidingPaneLayout.java
+++ b/core-ui/java/android/support/v4/widget/SlidingPaneLayout.java
@@ -16,10 +16,8 @@
 
 package android.support.v4.widget;
 
-import android.support.annotation.RequiresApi;
 import android.content.Context;
 import android.content.res.TypedArray;
-import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Paint;
 import android.graphics.PixelFormat;
@@ -32,6 +30,7 @@
 import android.os.Parcelable;
 import android.support.annotation.ColorInt;
 import android.support.annotation.DrawableRes;
+import android.support.annotation.RequiresApi;
 import android.support.v4.content.ContextCompat;
 import android.support.v4.view.AbsSavedState;
 import android.support.v4.view.AccessibilityDelegateCompat;
@@ -41,7 +40,6 @@
 import android.util.Log;
 import android.view.MotionEvent;
 import android.view.View;
-import android.view.ViewConfiguration;
 import android.view.ViewGroup;
 import android.view.ViewParent;
 import android.view.accessibility.AccessibilityEvent;
@@ -192,8 +190,7 @@
 
     private final Rect mTmpRect = new Rect();
 
-    final ArrayList<DisableLayerRunnable> mPostedRunnables =
-            new ArrayList<DisableLayerRunnable>();
+    final ArrayList<DisableLayerRunnable> mPostedRunnables = new ArrayList<>();
 
     static final SlidingPanelLayoutImpl IMPL;
 
@@ -262,8 +259,6 @@
         final float density = context.getResources().getDisplayMetrics().density;
         mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f);
 
-        final ViewConfiguration viewConfig = ViewConfiguration.get(context);
-
         setWillNotDraw(false);
 
         ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
@@ -482,7 +477,7 @@
         }
 
         int layoutHeight = 0;
-        int maxLayoutHeight = -1;
+        int maxLayoutHeight = 0;
         switch (heightMode) {
             case MeasureSpec.EXACTLY:
                 layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
@@ -1012,28 +1007,7 @@
             canvas.clipRect(mTmpRect);
         }
 
-        if (Build.VERSION.SDK_INT >= 11) { // HC
-            result = super.drawChild(canvas, child, drawingTime);
-        } else {
-            if (lp.dimWhenOffset && mSlideOffset > 0) {
-                if (!child.isDrawingCacheEnabled()) {
-                    child.setDrawingCacheEnabled(true);
-                }
-                final Bitmap cache = child.getDrawingCache();
-                if (cache != null) {
-                    canvas.drawBitmap(cache, child.getLeft(), child.getTop(), lp.dimPaint);
-                    result = false;
-                } else {
-                    Log.e(TAG, "drawChild: child view " + child + " returned null drawing cache");
-                    result = super.drawChild(canvas, child, drawingTime);
-                }
-            } else {
-                if (child.isDrawingCacheEnabled()) {
-                    child.setDrawingCacheEnabled(false);
-                }
-                result = super.drawChild(canvas, child, drawingTime);
-            }
-        }
+        result = super.drawChild(canvas, child, drawingTime);
 
         canvas.restoreToCount(save);
 
diff --git a/core-ui/java/android/support/v4/widget/SwipeRefreshLayout.java b/core-ui/java/android/support/v4/widget/SwipeRefreshLayout.java
index 25231aa..d36ae22 100644
--- a/core-ui/java/android/support/v4/widget/SwipeRefreshLayout.java
+++ b/core-ui/java/android/support/v4/widget/SwipeRefreshLayout.java
@@ -66,9 +66,9 @@
 public class SwipeRefreshLayout extends ViewGroup implements NestedScrollingParent,
         NestedScrollingChild {
     // Maps to ProgressBar.Large style
-    public static final int LARGE = MaterialProgressDrawable.LARGE;
+    public static final int LARGE = CircularProgressDrawable.LARGE;
     // Maps to ProgressBar default style
-    public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
+    public static final int DEFAULT = CircularProgressDrawable.DEFAULT;
 
     @VisibleForTesting
     static final int CIRCLE_DIAMETER = 40;
@@ -146,7 +146,7 @@
 
     int mSpinnerOffsetEnd;
 
-    MaterialProgressDrawable mProgress;
+    CircularProgressDrawable mProgress;
 
     private Animation mScaleAnimation;
 
@@ -294,11 +294,11 @@
      * One of DEFAULT, or LARGE.
      */
     public void setSize(int size) {
-        if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
+        if (size != CircularProgressDrawable.LARGE && size != CircularProgressDrawable.DEFAULT) {
             return;
         }
         final DisplayMetrics metrics = getResources().getDisplayMetrics();
-        if (size == MaterialProgressDrawable.LARGE) {
+        if (size == CircularProgressDrawable.LARGE) {
             mCircleDiameter = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
         } else {
             mCircleDiameter = (int) (CIRCLE_DIAMETER * metrics.density);
@@ -307,7 +307,7 @@
         // update by setting it to null before updating its size and then
         // re-setting it
         mCircleView.setImageDrawable(null);
-        mProgress.updateSizes(size);
+        mProgress.setStyle(size);
         mCircleView.setImageDrawable(mProgress);
     }
 
@@ -376,8 +376,8 @@
 
     private void createProgressView() {
         mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT);
-        mProgress = new MaterialProgressDrawable(getContext(), this);
-        mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
+        mProgress = new CircularProgressDrawable(getContext());
+        mProgress.setStyle(CircularProgressDrawable.DEFAULT);
         mCircleView.setImageDrawable(mProgress);
         mCircleView.setVisibility(View.GONE);
         addView(mCircleView);
@@ -520,7 +520,6 @@
      */
     public void setProgressBackgroundColorSchemeColor(@ColorInt int color) {
         mCircleView.setBackgroundColor(color);
-        mProgress.setBackgroundColor(color);
     }
 
     /**
@@ -661,7 +660,7 @@
         if (mTarget instanceof ListView) {
             return ListViewCompat.canScrollList((ListView) mTarget, -1);
         }
-        return ViewCompat.canScrollVertically(mTarget, -1);
+        return mTarget.canScrollVertically(-1);
     }
 
     /**
@@ -899,7 +898,7 @@
     }
 
     private void moveSpinner(float overscrollTop) {
-        mProgress.showArrow(true);
+        mProgress.setArrowEnabled(true);
         float originalDragPercent = overscrollTop / mTotalDragDistance;
 
         float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
@@ -976,7 +975,7 @@
                 };
             }
             animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener);
-            mProgress.showArrow(false);
+            mProgress.setArrowEnabled(false);
         }
     }
 
diff --git a/core-ui/jellybean-mr2/android/support/v4/app/ActionBarDrawerToggleJellybeanMR2.java b/core-ui/jellybean-mr2/android/support/v4/app/ActionBarDrawerToggleJellybeanMR2.java
deleted file mode 100644
index 40d180c..0000000
--- a/core-ui/jellybean-mr2/android/support/v4/app/ActionBarDrawerToggleJellybeanMR2.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 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 android.support.v4.app;
-
-import android.R;
-import android.app.ActionBar;
-import android.app.Activity;
-import android.content.Context;
-import android.content.res.TypedArray;
-import android.graphics.drawable.Drawable;
-import android.support.annotation.RequiresApi;
-
-@RequiresApi(18)
-class ActionBarDrawerToggleJellybeanMR2 {
-    private static final String TAG = "ActionBarDrawerToggleImplJellybeanMR2";
-
-    private static final int[] THEME_ATTRS = new int[] {
-            R.attr.homeAsUpIndicator
-    };
-
-    public static Object setActionBarUpIndicator(Object info, Activity activity,
-            Drawable drawable, int contentDescRes) {
-        final ActionBar actionBar = activity.getActionBar();
-        if (actionBar != null) {
-            actionBar.setHomeAsUpIndicator(drawable);
-            actionBar.setHomeActionContentDescription(contentDescRes);
-        }
-        return info;
-    }
-
-    public static Object setActionBarDescription(Object info, Activity activity,
-            int contentDescRes) {
-        final ActionBar actionBar = activity.getActionBar();
-        if (actionBar != null) {
-            actionBar.setHomeActionContentDescription(contentDescRes);
-        }
-        return info;
-    }
-
-    public static Drawable getThemeUpIndicator(Activity activity) {
-        final ActionBar actionBar = activity.getActionBar();
-        final Context context;
-        if (actionBar != null) {
-            context = actionBar.getThemedContext();
-        } else {
-            context = activity;
-        }
-
-        final TypedArray a = context.obtainStyledAttributes(null, THEME_ATTRS,
-                R.attr.actionBarStyle, 0);
-        final Drawable result = a.getDrawable(0);
-        a.recycle();
-        return result;
-    }
-}
diff --git a/core-ui/lint-baseline.xml b/core-ui/lint-baseline.xml
new file mode 100644
index 0000000..8961812
--- /dev/null
+++ b/core-ui/lint-baseline.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="WrongConstant"
+        message="Must be one or more of: Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END"
+        errorLine1="                            + gravityToString(childGravity) + &quot; but this &quot; + TAG + &quot; already has a &quot;"
+        errorLine2="                                              ~~~~~~~~~~~~">
+        <location
+            file="java/android/support/v4/widget/DrawerLayout.java"
+            line="1075"
+            column="47"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one or more of: Canvas.ALL_SAVE_FLAG"
+        errorLine1="        final int save = canvas.save(Canvas.CLIP_SAVE_FLAG);"
+        errorLine2="                                     ~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="java/android/support/v4/widget/SlidingPaneLayout.java"
+            line="997"
+            column="38"/>
+    </issue>
+
+</issues>
diff --git a/core-ui/tests/AndroidManifest.xml b/core-ui/tests/AndroidManifest.xml
index 8632a7c..c1b1a75 100644
--- a/core-ui/tests/AndroidManifest.xml
+++ b/core-ui/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.coreui.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.VIBRATE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
@@ -29,15 +24,18 @@
     <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
 
     <application
-            android:supportsRtl="true"
-            android:theme="@style/TestActivityTheme">
+        android:supportsRtl="true"
+        android:theme="@style/TestActivityTheme">
         <activity android:name="android.support.v4.widget.ExploreByTouchHelperTestActivity"/>
 
+        <activity android:name="android.support.v4.widget.CircularProgressDrawableActivity"/>
+
         <activity android:name="android.support.v4.widget.SwipeRefreshLayoutActivity"/>
 
         <activity android:name="android.support.v4.view.ViewPagerWithTitleStripActivity"/>
 
         <activity android:name="android.support.v4.view.ViewPagerWithTabStripActivity"/>
+
     </application>
 
 </manifest>
diff --git a/core-ui/tests/java/android/support/v4/view/BaseViewPagerTest.java b/core-ui/tests/java/android/support/v4/view/BaseViewPagerTest.java
index 1544e76..855d01d 100644
--- a/core-ui/tests/java/android/support/v4/view/BaseViewPagerTest.java
+++ b/core-ui/tests/java/android/support/v4/view/BaseViewPagerTest.java
@@ -1076,7 +1076,7 @@
     }
 
     @Test
-    @MediumTest
+    @LargeTest
     public void testKeyboardNavigation() {
         ButtonPagerAdapter adapter = new ButtonPagerAdapter();
         adapter.add("Red", Color.RED);
diff --git a/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableActivity.java b/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableActivity.java
new file mode 100644
index 0000000..743cd7d
--- /dev/null
+++ b/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableActivity.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.widget;
+
+import android.support.coreui.test.R;
+import android.support.v4.BaseTestActivity;
+
+public class CircularProgressDrawableActivity extends BaseTestActivity {
+    @Override
+    protected int getContentViewLayoutResId() {
+        return R.layout.circular_progress_drawable_activity;
+    }
+}
diff --git a/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableTest.java b/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableTest.java
new file mode 100644
index 0000000..cf31952
--- /dev/null
+++ b/core-ui/tests/java/android/support/v4/widget/CircularProgressDrawableTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.widget;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyFloat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.support.test.filters.SmallTest;
+import android.support.v4.BaseInstrumentationTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+
+/**
+ * Tests for CircularProgressDrawable
+ */
+public class CircularProgressDrawableTest extends
+        BaseInstrumentationTestCase<CircularProgressDrawableActivity> {
+
+    public CircularProgressDrawableTest() {
+        super(CircularProgressDrawableActivity.class);
+    }
+
+    private CircularProgressDrawable mDrawableUnderTest;
+
+    @Mock
+    Canvas mMockCanvas;
+
+    @Before
+    public void setUp() {
+        Context context = mActivityTestRule.getActivity().getApplicationContext();
+        mMockCanvas = mock(Canvas.class);
+        mDrawableUnderTest = new CircularProgressDrawable(context);
+    }
+
+    @Test
+    @SmallTest
+    public void sizeIsSquareBasedOnSmallerEdgeWithNoCenterRadius() {
+        int width = 100;
+        int height = 50;
+        mDrawableUnderTest.setBounds(new Rect(0, 0, width, height));
+        mDrawableUnderTest.draw(mMockCanvas);
+
+        ArgumentCaptor<RectF> captor = ArgumentCaptor.forClass(RectF.class);
+        verify(mMockCanvas).drawArc(captor.capture(), anyFloat(), anyFloat(), anyBoolean(),
+                any(Paint.class));
+
+        assertTrue(captor.getValue().width() == captor.getValue().height());
+        assertTrue(captor.getValue().width() <= width);
+        assertTrue(captor.getValue().width() <= height);
+    }
+
+    @Test
+    @SmallTest
+    public void setCenterRadiusFixesSize() {
+        float radius = 10f;
+        float strokeWidth = 4f;
+        mDrawableUnderTest.setCenterRadius(radius);
+        mDrawableUnderTest.setStrokeWidth(strokeWidth);
+        mDrawableUnderTest.setBounds(new Rect(0, 0, 100, 50));
+        mDrawableUnderTest.draw(mMockCanvas);
+
+        ArgumentCaptor<RectF> boundsCaptor = ArgumentCaptor.forClass(RectF.class);
+        verify(mMockCanvas).drawArc(boundsCaptor.capture(), anyFloat(), anyFloat(), anyBoolean(),
+                any(Paint.class));
+
+        assertEquals((radius + strokeWidth / 2f) * 2, boundsCaptor.getValue().width(), 0.5);
+        assertEquals((radius + strokeWidth / 2f) * 2, boundsCaptor.getValue().height(), 0.5);
+    }
+}
diff --git a/core-ui/tests/res/layout/circular_progress_drawable_activity.xml b/core-ui/tests/res/layout/circular_progress_drawable_activity.xml
new file mode 100644
index 0000000..6bb6beb
--- /dev/null
+++ b/core-ui/tests/res/layout/circular_progress_drawable_activity.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+
+    <ImageView android:id="@+id/imageView" android:layout_width="match_parent"
+               android:layout_height="match_parent"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/core-utils/Android.mk b/core-utils/Android.mk
index b22c376..5ea200e 100644
--- a/core-utils/Android.mk
+++ b/core-utils/Android.mk
@@ -29,10 +29,7 @@
 LOCAL_SRC_FILES := \
     $(call all-java-files-under,gingerbread) \
     $(call all-java-files-under,kitkat) \
-    $(call all-java-files-under,api20) \
     $(call all-java-files-under,api21) \
-    $(call all-java-files-under,api23) \
-    $(call all-java-files-under,api24) \
     $(call all-java-files-under,java)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 LOCAL_SHARED_ANDROID_LIBRARIES := \
diff --git a/core-utils/api20/android/support/v4/print/PrintHelperApi20.java b/core-utils/api20/android/support/v4/print/PrintHelperApi20.java
deleted file mode 100644
index 54699a5..0000000
--- a/core-utils/api20/android/support/v4/print/PrintHelperApi20.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v4.print;
-
-import android.content.Context;
-import android.support.annotation.RequiresApi;
-
-/**
- * Api20 specific PrintManager API implementation.
- */
-@RequiresApi(20)
-class PrintHelperApi20 extends PrintHelperKitkat {
-    PrintHelperApi20(Context context) {
-        super(context);
-
-        /**
-         * There is a bug in the PrintActivity that causes it to ignore the orientation
-         */
-        mPrintActivityRespectsOrientation = false;
-    }
-}
\ No newline at end of file
diff --git a/core-utils/api23/android/support/v4/print/PrintHelperApi23.java b/core-utils/api23/android/support/v4/print/PrintHelperApi23.java
deleted file mode 100644
index bd949b9..0000000
--- a/core-utils/api23/android/support/v4/print/PrintHelperApi23.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v4.print;
-
-import android.content.Context;
-import android.print.PrintAttributes;
-import android.support.annotation.RequiresApi;
-
-/**
- * Api23 specific PrintManager API implementation.
- */
-@RequiresApi(23)
-class PrintHelperApi23 extends PrintHelperApi20 {
-    @Override
-    protected PrintAttributes.Builder copyAttributes(PrintAttributes other) {
-        PrintAttributes.Builder b = super.copyAttributes(other);
-
-        if (other.getDuplexMode() != 0) {
-            b.setDuplexMode(other.getDuplexMode());
-        }
-
-        return b;
-    }
-
-    PrintHelperApi23(Context context) {
-        super(context);
-
-        mIsMinMarginsHandlingCorrect = false;
-    }
-}
diff --git a/core-utils/api24/android/support/v4/print/PrintHelperApi24.java b/core-utils/api24/android/support/v4/print/PrintHelperApi24.java
deleted file mode 100644
index 9ae32b4..0000000
--- a/core-utils/api24/android/support/v4/print/PrintHelperApi24.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v4.print;
-
-import android.content.Context;
-import android.support.annotation.RequiresApi;
-
-/**
- * Api24 specific PrintManager API implementation.
- */
-@RequiresApi(24)
-class PrintHelperApi24 extends PrintHelperApi23 {
-    PrintHelperApi24(Context context) {
-        super(context);
-
-        mIsMinMarginsHandlingCorrect = true;
-        mPrintActivityRespectsOrientation = true;
-    }
-}
\ No newline at end of file
diff --git a/core-utils/build.gradle b/core-utils/build.gradle
index 7ac7cd3..234ae39 100644
--- a/core-utils/build.gradle
+++ b/core-utils/build.gradle
@@ -2,18 +2,17 @@
 archivesBaseName = 'support-core-utils'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
+    api project(':support-annotations')
+    api project(':support-compat')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/core-utils/java/android/support/v4/content/WakefulBroadcastReceiver.java b/core-utils/java/android/support/v4/content/WakefulBroadcastReceiver.java
index b960939..b0cd653 100644
--- a/core-utils/java/android/support/v4/content/WakefulBroadcastReceiver.java
+++ b/core-utils/java/android/support/v4/content/WakefulBroadcastReceiver.java
@@ -70,8 +70,7 @@
 public abstract class WakefulBroadcastReceiver extends BroadcastReceiver {
     private static final String EXTRA_WAKE_LOCK_ID = "android.support.content.wakelockid";
 
-    private static final SparseArray<PowerManager.WakeLock> mActiveWakeLocks
-            = new SparseArray<PowerManager.WakeLock>();
+    private static final SparseArray<PowerManager.WakeLock> sActiveWakeLocks = new SparseArray<>();
     private static int mNextId = 1;
 
     /**
@@ -89,7 +88,7 @@
      * Context.startService}.
      */
     public static ComponentName startWakefulService(Context context, Intent intent) {
-        synchronized (mActiveWakeLocks) {
+        synchronized (sActiveWakeLocks) {
             int id = mNextId;
             mNextId++;
             if (mNextId <= 0) {
@@ -106,8 +105,8 @@
             PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                     "wake:" + comp.flattenToShortString());
             wl.setReferenceCounted(false);
-            wl.acquire(60*1000);
-            mActiveWakeLocks.put(id, wl);
+            wl.acquire(60 * 1000);
+            sActiveWakeLocks.put(id, wl);
             return comp;
         }
     }
@@ -125,11 +124,11 @@
         if (id == 0) {
             return false;
         }
-        synchronized (mActiveWakeLocks) {
-            PowerManager.WakeLock wl = mActiveWakeLocks.get(id);
+        synchronized (sActiveWakeLocks) {
+            PowerManager.WakeLock wl = sActiveWakeLocks.get(id);
             if (wl != null) {
                 wl.release();
-                mActiveWakeLocks.remove(id);
+                sActiveWakeLocks.remove(id);
                 return true;
             }
             // We return true whether or not we actually found the wake lock
@@ -138,7 +137,7 @@
             // We just log a warning here if there is no wake lock found, which could
             // happen for example if this function is called twice on the same
             // intent or the process is killed and restarted before processing the intent.
-            Log.w("WakefulBroadcastReceiver", "No active wake lock id #" + id);
+            Log.w("WakefulBroadcastReceiv.", "No active wake lock id #" + id);
             return true;
         }
     }
diff --git a/core-utils/java/android/support/v4/graphics/drawable/RoundedBitmapDrawableFactory.java b/core-utils/java/android/support/v4/graphics/drawable/RoundedBitmapDrawableFactory.java
index 5efc74b..5e144c7 100644
--- a/core-utils/java/android/support/v4/graphics/drawable/RoundedBitmapDrawableFactory.java
+++ b/core-utils/java/android/support/v4/graphics/drawable/RoundedBitmapDrawableFactory.java
@@ -31,7 +31,7 @@
  * either from Bitmaps directly, or from streams and files.
  */
 public final class RoundedBitmapDrawableFactory {
-    private static final String TAG = "RoundedBitmapDrawableFactory";
+    private static final String TAG = "RoundedBitmapDrawableFa";
 
     private static class DefaultRoundedBitmapDrawable extends RoundedBitmapDrawable {
         DefaultRoundedBitmapDrawable(Resources res, Bitmap bitmap) {
diff --git a/core-utils/java/android/support/v4/print/PrintHelper.java b/core-utils/java/android/support/v4/print/PrintHelper.java
index fb8bc12..ce342e3 100644
--- a/core-utils/java/android/support/v4/print/PrintHelper.java
+++ b/core-utils/java/android/support/v4/print/PrintHelper.java
@@ -16,14 +16,38 @@
 
 package android.support.v4.print;
 
-import android.support.annotation.RequiresApi;
 import android.content.Context;
 import android.graphics.Bitmap;
-import android.os.Build;
-
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.ColorMatrix;
+import android.graphics.ColorMatrixColorFilter;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.RectF;
+import android.graphics.pdf.PdfDocument;
 import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.CancellationSignal;
+import android.os.ParcelFileDescriptor;
+import android.print.PageRange;
+import android.print.PrintAttributes;
+import android.print.PrintDocumentAdapter;
+import android.print.PrintDocumentInfo;
+import android.print.PrintManager;
+import android.print.pdf.PrintedPdfDocument;
+import android.support.annotation.IntDef;
+import android.support.annotation.RequiresApi;
+import android.util.Log;
 
 import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 
 /**
  * Helper for printing bitmaps.
@@ -42,12 +66,12 @@
     /**
      * this is a black and white image
      */
-    public static final int COLOR_MODE_MONOCHROME = 1;
+    public static final int COLOR_MODE_MONOCHROME = PrintAttributes.COLOR_MODE_MONOCHROME;
 
     /**
      * this is a color image (default)
      */
-    public static final int COLOR_MODE_COLOR = 2;
+    public static final int COLOR_MODE_COLOR = PrintAttributes.COLOR_MODE_COLOR;
 
     /**
      * Print the image in landscape orientation (default).
@@ -65,14 +89,25 @@
      * document to print or printing was cancelled.
      */
     public interface OnPrintFinishCallback {
-
         /**
          * Called when a print operation is finished.
          */
-        public void onFinish();
+        void onFinish();
     }
 
-    PrintHelperVersionImpl mImpl;
+    @IntDef({SCALE_MODE_FIT, SCALE_MODE_FILL})
+    @Retention(RetentionPolicy.SOURCE)
+    private @interface ScaleMode {}
+
+    @IntDef({COLOR_MODE_MONOCHROME, COLOR_MODE_COLOR})
+    @Retention(RetentionPolicy.SOURCE)
+    private @interface ColorMode {}
+
+    @IntDef({ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT})
+    @Retention(RetentionPolicy.SOURCE)
+    private @interface Orientation {}
+
+    private final PrintHelperVersionImpl mImpl;
 
     /**
      * Gets whether the system supports printing.
@@ -87,57 +122,65 @@
     /**
      * Interface implemented by classes that support printing
      */
-    static interface PrintHelperVersionImpl {
+    interface PrintHelperVersionImpl {
 
-        public void setScaleMode(int scaleMode);
+        void setScaleMode(int scaleMode);
 
-        public int getScaleMode();
+        int getScaleMode();
 
-        public void setColorMode(int colorMode);
+        void setColorMode(int colorMode);
 
-        public int getColorMode();
+        int getColorMode();
 
-        public void setOrientation(int orientation);
+        void setOrientation(int orientation);
 
-        public int getOrientation();
+        int getOrientation();
 
-        public void printBitmap(String jobName, Bitmap bitmap, OnPrintFinishCallback callback);
+        void printBitmap(String jobName, Bitmap bitmap, OnPrintFinishCallback callback);
 
-        public void printBitmap(String jobName, Uri imageFile, OnPrintFinishCallback callback)
+        void printBitmap(String jobName, Uri imageFile, OnPrintFinishCallback callback)
                 throws FileNotFoundException;
     }
 
     /**
      * Implementation used when we do not support printing
      */
-    private static final class PrintHelperStubImpl implements PrintHelperVersionImpl {
-        int mScaleMode = SCALE_MODE_FILL;
-        int mColorMode = COLOR_MODE_COLOR;
-        int mOrientation = ORIENTATION_LANDSCAPE;
+    private static final class PrintHelperStub implements PrintHelperVersionImpl {
+        @ScaleMode int mScaleMode = SCALE_MODE_FILL;
+        @ColorMode int mColorMode = COLOR_MODE_COLOR;
+        @Orientation int mOrientation = ORIENTATION_LANDSCAPE;
+
         @Override
-        public void setScaleMode(int scaleMode) {
+        public void setScaleMode(@ScaleMode int scaleMode) {
             mScaleMode = scaleMode;
         }
 
+        @ScaleMode
+        @Override
+        public int getScaleMode() {
+            return mScaleMode;
+        }
+
+        @ColorMode
         @Override
         public int getColorMode() {
             return mColorMode;
         }
 
         @Override
-        public void setColorMode(int colorMode) {
+        public void setColorMode(@ColorMode int colorMode) {
             mColorMode = colorMode;
         }
 
         @Override
-        public void setOrientation(int orientation) { mOrientation = orientation; }
+        public void setOrientation(@Orientation int orientation) {
+            mOrientation = orientation;
+        }
 
+        @Orientation
         @Override
-        public int getOrientation() { return mOrientation; }
-
-        @Override
-        public int getScaleMode() {
-            return mScaleMode;
+        public int getOrientation() {
+            return mOrientation;
         }
 
         @Override
@@ -150,137 +193,710 @@
     }
 
     /**
-     * Generic implementation for KitKat to Api24
+     * Kitkat specific PrintManager API implementation.
      */
     @RequiresApi(19)
-    private static class PrintHelperImpl<RealHelper extends PrintHelperKitkat>
-            implements PrintHelperVersionImpl {
-        private final RealHelper mPrintHelper;
+    private static class PrintHelperApi19 implements PrintHelperVersionImpl{
+        private static final String LOG_TAG = "PrintHelperApi19";
+        // will be <= 300 dpi on A4 (8.3×11.7) paper (worst case of 150 dpi)
+        private static final int MAX_PRINT_SIZE = 3500;
+        final Context mContext;
+        BitmapFactory.Options mDecodeOptions = null;
+        private final Object mLock = new Object();
 
-        protected PrintHelperImpl(RealHelper helper) {
-            mPrintHelper = helper;
+        /**
+         * Whether the PrintActivity respects the suggested orientation
+         */
+        protected boolean mPrintActivityRespectsOrientation;
+
+        /**
+         * Whether the print subsystem handles min margins correctly. If not the print helper needs
+         * to fake this.
+         */
+        protected boolean mIsMinMarginsHandlingCorrect;
+
+        @ScaleMode int mScaleMode = SCALE_MODE_FILL;
+
+        @ColorMode int mColorMode = COLOR_MODE_COLOR;
+
+        @Orientation int mOrientation;
+
+        PrintHelperApi19(Context context) {
+            mPrintActivityRespectsOrientation = true;
+            mIsMinMarginsHandlingCorrect = true;
+
+            mContext = context;
         }
 
+        /**
+         * Selects whether the image will fill the paper and be cropped
+         * <p/>
+         * {@link #SCALE_MODE_FIT}
+         * or whether the image will be scaled but leave white space
+         * {@link #SCALE_MODE_FILL}.
+         *
+         * @param scaleMode {@link #SCALE_MODE_FIT} or
+         *                  {@link #SCALE_MODE_FILL}
+         */
         @Override
-        public void setScaleMode(int scaleMode) {
-            mPrintHelper.setScaleMode(scaleMode);
+        public void setScaleMode(@ScaleMode int scaleMode) {
+            mScaleMode = scaleMode;
         }
 
+        /**
+         * Returns the scale mode with which the image will fill the paper.
+         *
+         * @return The scale Mode: {@link #SCALE_MODE_FIT} or
+         * {@link #SCALE_MODE_FILL}
+         */
+        @ScaleMode
         @Override
         public int getScaleMode() {
-            return mPrintHelper.getScaleMode();
+            return mScaleMode;
         }
 
+        /**
+         * Sets whether the image will be printed in color (default)
+         * {@link #COLOR_MODE_COLOR} or in back and white
+         * {@link #COLOR_MODE_MONOCHROME}.
+         *
+         * @param colorMode The color mode which is one of
+         *                  {@link #COLOR_MODE_COLOR} and {@link #COLOR_MODE_MONOCHROME}.
+         */
         @Override
-        public void setColorMode(int colorMode) {
-            mPrintHelper.setColorMode(colorMode);
+        public void setColorMode(@ColorMode int colorMode) {
+            mColorMode = colorMode;
         }
 
+        /**
+         * Sets whether to select landscape (default), {@link #ORIENTATION_LANDSCAPE}
+         * or portrait {@link #ORIENTATION_PORTRAIT}
+         * @param orientation The page orientation which is one of
+         *                    {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT}.
+         */
         @Override
-        public int getColorMode() {
-            return mPrintHelper.getColorMode();
+        public void setOrientation(@Orientation int orientation) {
+            mOrientation = orientation;
         }
 
-        @Override
-        public void setOrientation(int orientation) {
-            mPrintHelper.setOrientation(orientation);
-        }
-
+        /**
+         * Gets the page orientation with which the image will be printed.
+         *
+         * @return The preferred orientation which is one of
+         * {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT}
+         */
+        @Orientation
         @Override
         public int getOrientation() {
-            return mPrintHelper.getOrientation();
+            /// Unset defaults to landscape but might turn image
+            if (mOrientation == 0) {
+                return ORIENTATION_LANDSCAPE;
+            }
+            return mOrientation;
         }
 
+        /**
+         * Gets the color mode with which the image will be printed.
+         *
+         * @return The color mode which is one of {@link #COLOR_MODE_COLOR}
+         * and {@link #COLOR_MODE_MONOCHROME}.
+         */
+        @ColorMode
         @Override
-        public void printBitmap(String jobName, Bitmap bitmap,
+        public int getColorMode() {
+            return mColorMode;
+        }
+
+        /**
+         * Check if the supplied bitmap should best be printed on a portrait orientation paper.
+         *
+         * @param bitmap The bitmap to be printed.
+         * @return true iff the picture should best be printed on a portrait orientation paper.
+         */
+        private static boolean isPortrait(Bitmap bitmap) {
+            return bitmap.getWidth() <= bitmap.getHeight();
+        }
+
+        /**
+         * Create a build with a copy from the other print attributes.
+         *
+         * @param other The other print attributes
+         *
+         * @return A builder that will build print attributes that match the other attributes
+         */
+        protected PrintAttributes.Builder copyAttributes(PrintAttributes other) {
+            PrintAttributes.Builder b = (new PrintAttributes.Builder())
+                    .setMediaSize(other.getMediaSize())
+                    .setResolution(other.getResolution())
+                    .setMinMargins(other.getMinMargins());
+
+            if (other.getColorMode() != 0) {
+                b.setColorMode(other.getColorMode());
+            }
+
+            return b;
+        }
+
+        /**
+         * Prints a bitmap.
+         *
+         * @param jobName The print job name.
+         * @param bitmap  The bitmap to print.
+         * @param callback Optional callback to observe when printing is finished.
+         */
+        @Override
+        public void printBitmap(final String jobName, final Bitmap bitmap,
                 final OnPrintFinishCallback callback) {
-            PrintHelperKitkat.OnPrintFinishCallback delegateCallback = null;
-            if (callback != null) {
-                delegateCallback = new PrintHelperKitkat.OnPrintFinishCallback() {
-                    @Override
-                    public void onFinish() {
-                        callback.onFinish();
-                    }
-                };
+            if (bitmap == null) {
+                return;
             }
-            mPrintHelper.printBitmap(jobName, bitmap, delegateCallback);
+
+            final int fittingMode = mScaleMode; // grab the fitting mode at time of call
+            PrintManager printManager =
+                    (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
+            PrintAttributes.MediaSize mediaSize;
+            if (isPortrait(bitmap)) {
+                mediaSize = PrintAttributes.MediaSize.UNKNOWN_PORTRAIT;
+            } else {
+                mediaSize = PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE;
+            }
+            PrintAttributes attr = new PrintAttributes.Builder()
+                    .setMediaSize(mediaSize)
+                    .setColorMode(mColorMode)
+                    .build();
+
+            printManager.print(jobName,
+                    new PrintDocumentAdapter() {
+                        private PrintAttributes mAttributes;
+
+                        @Override
+                        public void onLayout(PrintAttributes oldPrintAttributes,
+                                PrintAttributes newPrintAttributes,
+                                CancellationSignal cancellationSignal,
+                                LayoutResultCallback layoutResultCallback,
+                                Bundle bundle) {
+
+                            mAttributes = newPrintAttributes;
+
+                            PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
+                                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
+                                    .setPageCount(1)
+                                    .build();
+                            boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
+                            layoutResultCallback.onLayoutFinished(info, changed);
+                        }
+
+                        @Override
+                        public void onWrite(PageRange[] pageRanges,
+                                ParcelFileDescriptor fileDescriptor,
+                                CancellationSignal cancellationSignal,
+                                WriteResultCallback writeResultCallback) {
+                            writeBitmap(mAttributes, fittingMode, bitmap, fileDescriptor,
+                                    cancellationSignal, writeResultCallback);
+                        }
+
+                        @Override
+                        public void onFinish() {
+                            if (callback != null) {
+                                callback.onFinish();
+                            }
+                        }
+                    }, attr);
         }
 
+        /**
+         * Calculates the transform the print an Image to fill the page
+         *
+         * @param imageWidth  with of bitmap
+         * @param imageHeight height of bitmap
+         * @param content     The output page dimensions
+         * @param fittingMode The mode of fitting {@link #SCALE_MODE_FILL} vs
+         *                    {@link #SCALE_MODE_FIT}
+         * @return Matrix to be used in canvas.drawBitmap(bitmap, matrix, null) call
+         */
+        private Matrix getMatrix(int imageWidth, int imageHeight, RectF content,
+                @ScaleMode int fittingMode) {
+            Matrix matrix = new Matrix();
+
+            // Compute and apply scale to fill the page.
+            float scale = content.width() / imageWidth;
+            if (fittingMode == SCALE_MODE_FILL) {
+                scale = Math.max(scale, content.height() / imageHeight);
+            } else {
+                scale = Math.min(scale, content.height() / imageHeight);
+            }
+            matrix.postScale(scale, scale);
+
+            // Center the content.
+            final float translateX = (content.width()
+                    - imageWidth * scale) / 2;
+            final float translateY = (content.height()
+                    - imageHeight * scale) / 2;
+            matrix.postTranslate(translateX, translateY);
+            return matrix;
+        }
+
+        /**
+         * Write a bitmap for a PDF document.
+         *
+         * @param attributes          The print attributes
+         * @param fittingMode         How to fit the bitmap
+         * @param bitmap              The bitmap to write
+         * @param fileDescriptor      The file to write to
+         * @param cancellationSignal  Signal cancelling operation
+         * @param writeResultCallback Callback to call once written
+         */
+        private void writeBitmap(final PrintAttributes attributes, final int fittingMode,
+                final Bitmap bitmap, final ParcelFileDescriptor fileDescriptor,
+                final CancellationSignal cancellationSignal,
+                final PrintDocumentAdapter.WriteResultCallback writeResultCallback) {
+            final PrintAttributes pdfAttributes;
+            if (mIsMinMarginsHandlingCorrect) {
+                pdfAttributes = attributes;
+            } else {
+                // If the handling of any margin != 0 is broken, strip the margins and add them to
+                // the bitmap later
+                pdfAttributes = copyAttributes(attributes)
+                        .setMinMargins(new PrintAttributes.Margins(0, 0, 0, 0)).build();
+            }
+
+            (new AsyncTask<Void, Void, Throwable>() {
+                @Override
+                protected Throwable doInBackground(Void... params) {
+                    try {
+                        if (cancellationSignal.isCanceled()) {
+                            return null;
+                        }
+
+                        PrintedPdfDocument pdfDocument = new PrintedPdfDocument(mContext,
+                                pdfAttributes);
+
+                        Bitmap maybeGrayscale = convertBitmapForColorMode(bitmap,
+                                pdfAttributes.getColorMode());
+
+                        if (cancellationSignal.isCanceled()) {
+                            return null;
+                        }
+
+                        try {
+                            PdfDocument.Page page = pdfDocument.startPage(1);
+
+                            RectF contentRect;
+                            if (mIsMinMarginsHandlingCorrect) {
+                                contentRect = new RectF(page.getInfo().getContentRect());
+                            } else {
+                                // Create dummy doc that has the margins to compute correctly sized
+                                // content rectangle
+                                PrintedPdfDocument dummyDocument = new PrintedPdfDocument(mContext,
+                                        attributes);
+                                PdfDocument.Page dummyPage = dummyDocument.startPage(1);
+                                contentRect = new RectF(dummyPage.getInfo().getContentRect());
+                                dummyDocument.finishPage(dummyPage);
+                                dummyDocument.close();
+                            }
+
+                            // Resize bitmap
+                            Matrix matrix = getMatrix(
+                                    maybeGrayscale.getWidth(), maybeGrayscale.getHeight(),
+                                    contentRect, fittingMode);
+
+                            if (mIsMinMarginsHandlingCorrect) {
+                                // The pdfDocument takes care of the positioning and margins
+                            } else {
+                                // Move it to the correct position.
+                                matrix.postTranslate(contentRect.left, contentRect.top);
+
+                                // Cut off margins
+                                page.getCanvas().clipRect(contentRect);
+                            }
+
+                            // Draw the bitmap.
+                            page.getCanvas().drawBitmap(maybeGrayscale, matrix, null);
+
+                            // Finish the page.
+                            pdfDocument.finishPage(page);
+
+                            if (cancellationSignal.isCanceled()) {
+                                return null;
+                            }
+
+                            // Write the document.
+                            pdfDocument.writeTo(
+                                    new FileOutputStream(fileDescriptor.getFileDescriptor()));
+                            return null;
+                        } finally {
+                            pdfDocument.close();
+
+                            if (fileDescriptor != null) {
+                                try {
+                                    fileDescriptor.close();
+                                } catch (IOException ioe) {
+                                    // ignore
+                                }
+                            }
+                            // If we created a new instance for grayscaling, then recycle it here.
+                            if (maybeGrayscale != bitmap) {
+                                maybeGrayscale.recycle();
+                            }
+                        }
+                    } catch (Throwable t) {
+                        return t;
+                    }
+                }
+
+                @Override
+                protected void onPostExecute(Throwable throwable) {
+                    if (cancellationSignal.isCanceled()) {
+                        // Cancelled.
+                        writeResultCallback.onWriteCancelled();
+                    } else if (throwable == null) {
+                        // Done.
+                        writeResultCallback.onWriteFinished(
+                                new PageRange[] { PageRange.ALL_PAGES });
+                    } else {
+                        // Failed.
+                        Log.e(LOG_TAG, "Error writing printed content", throwable);
+                        writeResultCallback.onWriteFailed(null);
+                    }
+                }
+            }).execute();
+        }
+
+        /**
+         * Prints an image located at the Uri. Image types supported are those of
+         * <code>BitmapFactory.decodeStream</code> (JPEG, GIF, PNG, BMP, WEBP)
+         *
+         * @param jobName   The print job name.
+         * @param imageFile The <code>Uri</code> pointing to an image to print.
+         * @param callback Optional callback to observe when printing is finished.
+         * @throws FileNotFoundException if <code>Uri</code> is not pointing to a valid image.
+         */
         @Override
-        public void printBitmap(String jobName, Uri imageFile,
-                final OnPrintFinishCallback callback) throws FileNotFoundException {
-            PrintHelperKitkat.OnPrintFinishCallback delegateCallback = null;
-            if (callback != null) {
-                delegateCallback = new PrintHelperKitkat.OnPrintFinishCallback() {
-                    @Override
-                    public void onFinish() {
+        public void printBitmap(final String jobName, final Uri imageFile,
+                final OnPrintFinishCallback callback)
+                throws FileNotFoundException {
+            final int fittingMode = mScaleMode;
+
+            PrintDocumentAdapter printDocumentAdapter = new PrintDocumentAdapter() {
+                private PrintAttributes mAttributes;
+                AsyncTask<Uri, Boolean, Bitmap> mLoadBitmap;
+                Bitmap mBitmap = null;
+
+                @Override
+                public void onLayout(final PrintAttributes oldPrintAttributes,
+                        final PrintAttributes newPrintAttributes,
+                        final CancellationSignal cancellationSignal,
+                        final LayoutResultCallback layoutResultCallback,
+                        Bundle bundle) {
+
+                    synchronized (this) {
+                        mAttributes = newPrintAttributes;
+                    }
+
+                    if (cancellationSignal.isCanceled()) {
+                        layoutResultCallback.onLayoutCancelled();
+                        return;
+                    }
+                    // we finished the load
+                    if (mBitmap != null) {
+                        PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
+                                .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
+                                .setPageCount(1)
+                                .build();
+                        boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
+                        layoutResultCallback.onLayoutFinished(info, changed);
+                        return;
+                    }
+
+                    mLoadBitmap = new AsyncTask<Uri, Boolean, Bitmap>() {
+                        @Override
+                        protected void onPreExecute() {
+                            // First register for cancellation requests.
+                            cancellationSignal.setOnCancelListener(
+                                    new CancellationSignal.OnCancelListener() {
+                                        @Override
+                                        public void onCancel() { // on different thread
+                                            cancelLoad();
+                                            cancel(false);
+                                        }
+                                    });
+                        }
+
+                        @Override
+                        protected Bitmap doInBackground(Uri... uris) {
+                            try {
+                                return loadConstrainedBitmap(imageFile);
+                            } catch (FileNotFoundException e) {
+                          /* ignore */
+                            }
+                            return null;
+                        }
+
+                        @Override
+                        protected void onPostExecute(Bitmap bitmap) {
+                            super.onPostExecute(bitmap);
+
+                            // If orientation was not set by the caller, try to fit the bitmap on
+                            // the current paper by potentially rotating the bitmap by 90 degrees.
+                            if (bitmap != null
+                                    && (!mPrintActivityRespectsOrientation || mOrientation == 0)) {
+                                PrintAttributes.MediaSize mediaSize;
+
+                                synchronized (this) {
+                                    mediaSize = mAttributes.getMediaSize();
+                                }
+
+                                if (mediaSize != null) {
+                                    if (mediaSize.isPortrait() != isPortrait(bitmap)) {
+                                        Matrix rotation = new Matrix();
+
+                                        rotation.postRotate(90);
+                                        bitmap = Bitmap.createBitmap(bitmap, 0, 0,
+                                                bitmap.getWidth(), bitmap.getHeight(), rotation,
+                                                true);
+                                    }
+                                }
+                            }
+
+                            mBitmap = bitmap;
+                            if (bitmap != null) {
+                                PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
+                                        .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
+                                        .setPageCount(1)
+                                        .build();
+
+                                boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
+
+                                layoutResultCallback.onLayoutFinished(info, changed);
+
+                            } else {
+                                layoutResultCallback.onLayoutFailed(null);
+                            }
+                            mLoadBitmap = null;
+                        }
+
+                        @Override
+                        protected void onCancelled(Bitmap result) {
+                            // Task was cancelled, report that.
+                            layoutResultCallback.onLayoutCancelled();
+                            mLoadBitmap = null;
+                        }
+                    }.execute();
+                }
+
+                private void cancelLoad() {
+                    synchronized (mLock) { // prevent race with set null below
+                        if (mDecodeOptions != null) {
+                            mDecodeOptions.requestCancelDecode();
+                            mDecodeOptions = null;
+                        }
+                    }
+                }
+
+                @Override
+                public void onFinish() {
+                    super.onFinish();
+                    cancelLoad();
+                    if (mLoadBitmap != null) {
+                        mLoadBitmap.cancel(true);
+                    }
+                    if (callback != null) {
                         callback.onFinish();
                     }
-                };
+                    if (mBitmap != null) {
+                        mBitmap.recycle();
+                        mBitmap = null;
+                    }
+                }
+
+                @Override
+                public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor fileDescriptor,
+                        CancellationSignal cancellationSignal,
+                        WriteResultCallback writeResultCallback) {
+                    writeBitmap(mAttributes, fittingMode, mBitmap, fileDescriptor,
+                            cancellationSignal, writeResultCallback);
+                }
+            };
+
+            PrintManager printManager =
+                    (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
+            PrintAttributes.Builder builder = new PrintAttributes.Builder();
+            builder.setColorMode(mColorMode);
+
+            if (mOrientation == ORIENTATION_LANDSCAPE || mOrientation == 0) {
+                builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE);
+            } else if (mOrientation == ORIENTATION_PORTRAIT) {
+                builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT);
             }
-            mPrintHelper.printBitmap(jobName, imageFile, delegateCallback);
+            PrintAttributes attr = builder.build();
+
+            printManager.print(jobName, printDocumentAdapter, attr);
+        }
+
+        /**
+         * Loads a bitmap while limiting its size
+         *
+         * @param uri           location of a valid image
+         * @return the Bitmap
+         * @throws FileNotFoundException if the Uri does not point to an image
+         */
+        private Bitmap loadConstrainedBitmap(Uri uri)
+                throws FileNotFoundException {
+            if (uri == null || mContext == null) {
+                throw new IllegalArgumentException("bad argument to getScaledBitmap");
+            }
+            // Get width and height of stored bitmap
+            BitmapFactory.Options opt = new BitmapFactory.Options();
+            opt.inJustDecodeBounds = true;
+            loadBitmap(uri, opt);
+
+            int w = opt.outWidth;
+            int h = opt.outHeight;
+
+            // If bitmap cannot be decoded, return null
+            if (w <= 0 || h <= 0) {
+                return null;
+            }
+
+            // Find best downsampling size
+            int imageSide = Math.max(w, h);
+
+            int sampleSize = 1;
+            while (imageSide > MAX_PRINT_SIZE) {
+                imageSide >>>= 1;
+                sampleSize <<= 1;
+            }
+
+            // Make sure sample size is reasonable
+            if (sampleSize <= 0 || 0 >= (Math.min(w, h) / sampleSize)) {
+                return null;
+            }
+            BitmapFactory.Options decodeOptions;
+            synchronized (mLock) { // prevent race with set null below
+                mDecodeOptions = new BitmapFactory.Options();
+                mDecodeOptions.inMutable = true;
+                mDecodeOptions.inSampleSize = sampleSize;
+                decodeOptions = mDecodeOptions;
+            }
+            try {
+                return loadBitmap(uri, decodeOptions);
+            } finally {
+                synchronized (mLock) {
+                    mDecodeOptions = null;
+                }
+            }
+        }
+
+        /**
+         * Returns the bitmap from the given uri loaded using the given options.
+         * Returns null on failure.
+         */
+        private Bitmap loadBitmap(Uri uri, BitmapFactory.Options o) throws FileNotFoundException {
+            if (uri == null || mContext == null) {
+                throw new IllegalArgumentException("bad argument to loadBitmap");
+            }
+            InputStream is = null;
+            try {
+                is = mContext.getContentResolver().openInputStream(uri);
+                return BitmapFactory.decodeStream(is, null, o);
+            } finally {
+                if (is != null) {
+                    try {
+                        is.close();
+                    } catch (IOException t) {
+                        Log.w(LOG_TAG, "close fail ", t);
+                    }
+                }
+            }
+        }
+
+        private Bitmap convertBitmapForColorMode(Bitmap original, @ColorMode int colorMode) {
+            if (colorMode != COLOR_MODE_MONOCHROME) {
+                return original;
+            }
+            // Create a grayscale bitmap
+            Bitmap grayscale = Bitmap.createBitmap(original.getWidth(), original.getHeight(),
+                    Bitmap.Config.ARGB_8888);
+            Canvas c = new Canvas(grayscale);
+            Paint p = new Paint();
+            ColorMatrix cm = new ColorMatrix();
+            cm.setSaturation(0);
+            ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
+            p.setColorFilter(f);
+            c.drawBitmap(original, 0, 0, p);
+            c.setBitmap(null);
+
+            return grayscale;
         }
     }
 
     /**
-     * Implementation used on KitKat
-     */
-    @RequiresApi(19)
-    private static final class PrintHelperKitkatImpl extends PrintHelperImpl<PrintHelperKitkat> {
-        PrintHelperKitkatImpl(Context context) {
-            super(new PrintHelperKitkat(context));
-        }
-    }
-
-    /**
-     * Implementation used on Api20 to Api22
+     * Api20 specific PrintManager API implementation.
      */
     @RequiresApi(20)
-    private static final class PrintHelperApi20Impl extends PrintHelperImpl<PrintHelperApi20> {
-        PrintHelperApi20Impl(Context context) {
-            super(new PrintHelperApi20(context));
+    private static class PrintHelperApi20 extends PrintHelperApi19 {
+        PrintHelperApi20(Context context) {
+            super(context);
+
+
+            // There is a bug in the PrintActivity that causes it to ignore the orientation
+            mPrintActivityRespectsOrientation = false;
         }
     }
 
     /**
-     * Implementation used on Api23
+     * Api23 specific PrintManager API implementation.
      */
     @RequiresApi(23)
-    private static final class PrintHelperApi23Impl extends PrintHelperImpl<PrintHelperApi23> {
-        PrintHelperApi23Impl(Context context) {
-            super(new PrintHelperApi23(context));
+    private static class PrintHelperApi23 extends PrintHelperApi20 {
+        @Override
+        protected PrintAttributes.Builder copyAttributes(PrintAttributes other) {
+            PrintAttributes.Builder b = super.copyAttributes(other);
+
+            if (other.getDuplexMode() != 0) {
+                b.setDuplexMode(other.getDuplexMode());
+            }
+
+            return b;
+        }
+
+        PrintHelperApi23(Context context) {
+            super(context);
+
+            mIsMinMarginsHandlingCorrect = false;
         }
     }
 
-
     /**
-     * Implementation used on Api24 and above
+     * Api24 specific PrintManager API implementation.
      */
     @RequiresApi(24)
-    private static final class PrintHelperApi24Impl extends PrintHelperImpl<PrintHelperApi24> {
-        PrintHelperApi24Impl(Context context) {
-            super(new PrintHelperApi24(context));
+    private static class PrintHelperApi24 extends PrintHelperApi23 {
+        PrintHelperApi24(Context context) {
+            super(context);
+
+            mIsMinMarginsHandlingCorrect = true;
+            mPrintActivityRespectsOrientation = true;
         }
     }
 
     /**
-     * Returns the PrintHelper that can be used to print images.
+     * Constructs the PrintHelper that can be used to print images.
      *
      * @param context A context for accessing system resources.
-     * @return the <code>PrintHelper</code> to support printing images.
      */
     public PrintHelper(Context context) {
         if (Build.VERSION.SDK_INT >= 24) {
-            mImpl = new PrintHelperApi24Impl(context);
+            mImpl = new PrintHelperApi24(context);
         } else if (Build.VERSION.SDK_INT >= 23) {
-            mImpl = new PrintHelperApi23Impl(context);
+            mImpl = new PrintHelperApi23(context);
         } else if (Build.VERSION.SDK_INT >= 20) {
-            mImpl = new PrintHelperApi20Impl(context);
-        } else if (Build.VERSION.SDK_INT >= 19){
-            mImpl = new PrintHelperKitkatImpl(context);
+            mImpl = new PrintHelperApi20(context);
+        } else if (Build.VERSION.SDK_INT >= 19) {
+            mImpl = new PrintHelperApi19(context);
         } else {
             // System does not support printing.
-            mImpl = new PrintHelperStubImpl();
+            mImpl = new PrintHelperStub();
         }
     }
 
@@ -293,7 +909,7 @@
      * @param scaleMode {@link #SCALE_MODE_FIT} or
      *                  {@link #SCALE_MODE_FILL}
      */
-    public void setScaleMode(int scaleMode) {
+    public void setScaleMode(@ScaleMode int scaleMode) {
         mImpl.setScaleMode(scaleMode);
     }
 
@@ -303,6 +919,7 @@
      * @return The scale Mode: {@link #SCALE_MODE_FIT} or
      * {@link #SCALE_MODE_FILL}
      */
+    @ScaleMode
     public int getScaleMode() {
         return mImpl.getScaleMode();
     }
@@ -315,7 +932,7 @@
      * @param colorMode The color mode which is one of
      * {@link #COLOR_MODE_COLOR} and {@link #COLOR_MODE_MONOCHROME}.
      */
-    public void setColorMode(int colorMode) {
+    public void setColorMode(@ColorMode int colorMode) {
         mImpl.setColorMode(colorMode);
     }
 
@@ -325,6 +942,7 @@
      * @return The color mode which is one of {@link #COLOR_MODE_COLOR}
      * and {@link #COLOR_MODE_MONOCHROME}.
      */
+    @ColorMode
     public int getColorMode() {
         return mImpl.getColorMode();
     }
diff --git a/core-utils/java/android/support/v4/utils/ObjectUtils.java b/core-utils/java/android/support/v4/utils/ObjectUtils.java
deleted file mode 100644
index cd4afc7..0000000
--- a/core-utils/java/android/support/v4/utils/ObjectUtils.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2017 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 android.support.v4.utils;
-
-/**
- * This class consists of static utility methods for operating on objects.
- */
-public class ObjectUtils {
-    /**
-     * Returns true if the arguments are equal to each other and false otherwise.
-     * @param a an object
-     * @param b an object to be compared with <code>a</code> for equality
-     * @return <code>true</code> if the arguments are equal to each other and
-     *         <code>false</code> otherwise.
-     */
-    public static boolean objectEquals(Object a, Object b) {
-        return (a == b) || (a != null && a.equals(b));
-    }
-
-    private ObjectUtils() {
-    }
-}
diff --git a/core-utils/kitkat/android/support/v4/print/PrintHelperKitkat.java b/core-utils/kitkat/android/support/v4/print/PrintHelperKitkat.java
deleted file mode 100644
index 355e878..0000000
--- a/core-utils/kitkat/android/support/v4/print/PrintHelperKitkat.java
+++ /dev/null
@@ -1,701 +0,0 @@
-/*
- * Copyright (C) 2013 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 android.support.v4.print;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.RectF;
-import android.graphics.pdf.PdfDocument.Page;
-import android.net.Uri;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.os.CancellationSignal;
-import android.os.ParcelFileDescriptor;
-import android.print.PageRange;
-import android.print.PrintAttributes;
-import android.print.PrintAttributes.MediaSize;
-import android.print.PrintDocumentAdapter;
-import android.print.PrintDocumentInfo;
-import android.print.PrintManager;
-import android.print.pdf.PrintedPdfDocument;
-import android.support.annotation.RequiresApi;
-import android.util.Log;
-
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Kitkat specific PrintManager API implementation.
- */
-@RequiresApi(19)
-class PrintHelperKitkat {
-    private static final String LOG_TAG = "PrintHelperKitkat";
-    // will be <= 300 dpi on A4 (8.3×11.7) paper (worst case of 150 dpi)
-    private final static int MAX_PRINT_SIZE = 3500;
-    final Context mContext;
-    BitmapFactory.Options mDecodeOptions = null;
-    private final Object mLock = new Object();
-    /**
-     * image will be scaled but leave white space
-     */
-    public static final int SCALE_MODE_FIT = 1;
-    /**
-     * image will fill the paper and be cropped (default)
-     */
-    public static final int SCALE_MODE_FILL = 2;
-
-    /**
-     * select landscape (default)
-     */
-    public static final int ORIENTATION_LANDSCAPE = 1;
-
-    /**
-     * select portrait
-     */
-    public static final int ORIENTATION_PORTRAIT = 2;
-
-    /**
-     * this is a black and white image
-     */
-    public static final int COLOR_MODE_MONOCHROME = 1;
-    /**
-     * this is a color image (default)
-     */
-    public static final int COLOR_MODE_COLOR = 2;
-
-    public interface OnPrintFinishCallback {
-        public void onFinish();
-    }
-
-    /**
-     * Whether the PrintActivity respects the suggested orientation
-     */
-    protected boolean mPrintActivityRespectsOrientation;
-
-    /**
-     * Whether the print subsystem handles min margins correctly. If not the print helper needs to
-     * fake this.
-     */
-    protected boolean mIsMinMarginsHandlingCorrect;
-
-    int mScaleMode = SCALE_MODE_FILL;
-
-    int mColorMode = COLOR_MODE_COLOR;
-
-    int mOrientation;
-
-    PrintHelperKitkat(Context context) {
-        mPrintActivityRespectsOrientation = true;
-        mIsMinMarginsHandlingCorrect = true;
-
-        mContext = context;
-    }
-
-    /**
-     * Selects whether the image will fill the paper and be cropped
-     * <p/>
-     * {@link #SCALE_MODE_FIT}
-     * or whether the image will be scaled but leave white space
-     * {@link #SCALE_MODE_FILL}.
-     *
-     * @param scaleMode {@link #SCALE_MODE_FIT} or
-     *                  {@link #SCALE_MODE_FILL}
-     */
-    public void setScaleMode(int scaleMode) {
-        mScaleMode = scaleMode;
-    }
-
-    /**
-     * Returns the scale mode with which the image will fill the paper.
-     *
-     * @return The scale Mode: {@link #SCALE_MODE_FIT} or
-     * {@link #SCALE_MODE_FILL}
-     */
-    public int getScaleMode() {
-        return mScaleMode;
-    }
-
-    /**
-     * Sets whether the image will be printed in color (default)
-     * {@link #COLOR_MODE_COLOR} or in back and white
-     * {@link #COLOR_MODE_MONOCHROME}.
-     *
-     * @param colorMode The color mode which is one of
-     *                  {@link #COLOR_MODE_COLOR} and {@link #COLOR_MODE_MONOCHROME}.
-     */
-    public void setColorMode(int colorMode) {
-        mColorMode = colorMode;
-    }
-
-    /**
-     * Sets whether to select landscape (default), {@link #ORIENTATION_LANDSCAPE}
-     * or portrait {@link #ORIENTATION_PORTRAIT}
-     * @param orientation The page orientation which is one of
-     *                    {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT}.
-     */
-    public void setOrientation(int orientation) {
-        mOrientation = orientation;
-    }
-
-    /**
-     * Gets the page orientation with which the image will be printed.
-     *
-     * @return The preferred orientation which is one of
-     * {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT}
-     */
-    public int getOrientation() {
-        /// Unset defaults to landscape but might turn image
-        if (mOrientation == 0) {
-            return ORIENTATION_LANDSCAPE;
-        }
-        return mOrientation;
-    }
-
-    /**
-     * Gets the color mode with which the image will be printed.
-     *
-     * @return The color mode which is one of {@link #COLOR_MODE_COLOR}
-     * and {@link #COLOR_MODE_MONOCHROME}.
-     */
-    public int getColorMode() {
-        return mColorMode;
-    }
-
-    /**
-     * Check if the supplied bitmap should best be printed on a portrait orientation paper.
-     *
-     * @param bitmap The bitmap to be printed.
-     * @return true iff the picture should best be printed on a portrait orientation paper.
-     */
-    private static boolean isPortrait(Bitmap bitmap) {
-        if (bitmap.getWidth() <= bitmap.getHeight()) {
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * Create a build with a copy from the other print attributes.
-     *
-     * @param other The other print attributes
-     *
-     * @return A builder that will build print attributes that match the other attributes
-     */
-    protected PrintAttributes.Builder copyAttributes(PrintAttributes other) {
-        PrintAttributes.Builder b = (new PrintAttributes.Builder())
-                .setMediaSize(other.getMediaSize())
-                .setResolution(other.getResolution())
-                .setMinMargins(other.getMinMargins());
-
-        if (other.getColorMode() != 0) {
-            b.setColorMode(other.getColorMode());
-        }
-
-        return b;
-    }
-
-    /**
-     * Prints a bitmap.
-     *
-     * @param jobName The print job name.
-     * @param bitmap  The bitmap to print.
-     * @param callback Optional callback to observe when printing is finished.
-     */
-    public void printBitmap(final String jobName, final Bitmap bitmap,
-            final OnPrintFinishCallback callback) {
-        if (bitmap == null) {
-            return;
-        }
-        final int fittingMode = mScaleMode; // grab the fitting mode at time of call
-        PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
-        PrintAttributes.MediaSize mediaSize;
-        if (isPortrait(bitmap)) {
-            mediaSize = PrintAttributes.MediaSize.UNKNOWN_PORTRAIT;
-        } else {
-            mediaSize = PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE;
-        }
-        PrintAttributes attr = new PrintAttributes.Builder()
-                .setMediaSize(mediaSize)
-                .setColorMode(mColorMode)
-                .build();
-
-        printManager.print(jobName,
-                new PrintDocumentAdapter() {
-                    private PrintAttributes mAttributes;
-
-                    @Override
-                    public void onLayout(PrintAttributes oldPrintAttributes,
-                                         PrintAttributes newPrintAttributes,
-                                         CancellationSignal cancellationSignal,
-                                         LayoutResultCallback layoutResultCallback,
-                                         Bundle bundle) {
-
-                        mAttributes = newPrintAttributes;
-
-                        PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
-                                .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
-                                .setPageCount(1)
-                                .build();
-                        boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
-                        layoutResultCallback.onLayoutFinished(info, changed);
-                    }
-
-                    @Override
-                    public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor fileDescriptor,
-                                        CancellationSignal cancellationSignal,
-                                        WriteResultCallback writeResultCallback) {
-                        writeBitmap(mAttributes, fittingMode, bitmap, fileDescriptor,
-                                cancellationSignal, writeResultCallback);
-                    }
-
-                    @Override
-                    public void onFinish() {
-                        if (callback != null) {
-                            callback.onFinish();
-                        }
-                    }
-                }, attr);
-    }
-
-    /**
-     * Calculates the transform the print an Image to fill the page
-     *
-     * @param imageWidth  with of bitmap
-     * @param imageHeight height of bitmap
-     * @param content     The output page dimensions
-     * @param fittingMode The mode of fitting {@link #SCALE_MODE_FILL} vs {@link #SCALE_MODE_FIT}
-     * @return Matrix to be used in canvas.drawBitmap(bitmap, matrix, null) call
-     */
-    private Matrix getMatrix(int imageWidth, int imageHeight, RectF content, int fittingMode) {
-        Matrix matrix = new Matrix();
-
-        // Compute and apply scale to fill the page.
-        float scale = content.width() / imageWidth;
-        if (fittingMode == SCALE_MODE_FILL) {
-            scale = Math.max(scale, content.height() / imageHeight);
-        } else {
-            scale = Math.min(scale, content.height() / imageHeight);
-        }
-        matrix.postScale(scale, scale);
-
-        // Center the content.
-        final float translateX = (content.width()
-                - imageWidth * scale) / 2;
-        final float translateY = (content.height()
-                - imageHeight * scale) / 2;
-        matrix.postTranslate(translateX, translateY);
-        return matrix;
-    }
-
-    /**
-     * Write a bitmap for a PDF document.
-     *
-     * @param attributes          The print attributes
-     * @param fittingMode         How to fit the bitmap
-     * @param bitmap              The bitmap to write
-     * @param fileDescriptor      The file to write to
-     * @param cancellationSignal  Signal cancelling operation
-     * @param writeResultCallback Callback to call once written
-     */
-    private void writeBitmap(final PrintAttributes attributes, final int fittingMode,
-            final Bitmap bitmap, final ParcelFileDescriptor fileDescriptor,
-            final CancellationSignal cancellationSignal,
-            final PrintDocumentAdapter.WriteResultCallback writeResultCallback) {
-        final PrintAttributes pdfAttributes;
-        if (mIsMinMarginsHandlingCorrect) {
-            pdfAttributes = attributes;
-        } else {
-            // If the handling of any margin != 0 is broken, strip the margins and add them to the
-            // bitmap later
-            pdfAttributes = copyAttributes(attributes)
-                    .setMinMargins(new PrintAttributes.Margins(0,0,0,0)).build();
-        }
-
-        (new AsyncTask<Void, Void, Throwable>() {
-            @Override
-            protected Throwable doInBackground(Void... params) {
-                try {
-                    if (cancellationSignal.isCanceled()) {
-                        return null;
-                    }
-
-                    PrintedPdfDocument pdfDocument = new PrintedPdfDocument(mContext,
-                            pdfAttributes);
-
-                    Bitmap maybeGrayscale = convertBitmapForColorMode(bitmap,
-                            pdfAttributes.getColorMode());
-
-                    if (cancellationSignal.isCanceled()) {
-                        return null;
-                    }
-
-                    try {
-                        Page page = pdfDocument.startPage(1);
-
-                        RectF contentRect;
-                        if (mIsMinMarginsHandlingCorrect) {
-                            contentRect = new RectF(page.getInfo().getContentRect());
-                        } else {
-                            // Create dummy doc that has the margins to compute correctly sized
-                            // content rectangle
-                            PrintedPdfDocument dummyDocument = new PrintedPdfDocument(mContext,
-                                    attributes);
-                            Page dummyPage = dummyDocument.startPage(1);
-                            contentRect = new RectF(dummyPage.getInfo().getContentRect());
-                            dummyDocument.finishPage(dummyPage);
-                            dummyDocument.close();
-                        }
-
-                        // Resize bitmap
-                        Matrix matrix = getMatrix(
-                                maybeGrayscale.getWidth(), maybeGrayscale.getHeight(),
-                                contentRect, fittingMode);
-
-                        if (mIsMinMarginsHandlingCorrect) {
-                            // The pdfDocument takes care of the positioning and margins
-                        } else {
-                            // Move it to the correct position.
-                            matrix.postTranslate(contentRect.left, contentRect.top);
-
-                            // Cut off margins
-                            page.getCanvas().clipRect(contentRect);
-                        }
-
-                        // Draw the bitmap.
-                        page.getCanvas().drawBitmap(maybeGrayscale, matrix, null);
-
-                        // Finish the page.
-                        pdfDocument.finishPage(page);
-
-                        if (cancellationSignal.isCanceled()) {
-                            return null;
-                        }
-
-                        // Write the document.
-                        pdfDocument
-                                .writeTo(new FileOutputStream(fileDescriptor.getFileDescriptor()));
-                        return null;
-                    } finally {
-                        pdfDocument.close();
-
-                        if (fileDescriptor != null) {
-                            try {
-                                fileDescriptor.close();
-                            } catch (IOException ioe) {
-                                // ignore
-                            }
-                        }
-                        // If we created a new instance for grayscaling, then recycle it here.
-                        if (maybeGrayscale != bitmap) {
-                            maybeGrayscale.recycle();
-                        }
-                    }
-                } catch (Throwable t) {
-                    return t;
-                }
-            }
-
-            @Override
-            protected void onPostExecute(Throwable throwable) {
-                if (cancellationSignal.isCanceled()) {
-                    // Cancelled.
-                    writeResultCallback.onWriteCancelled();
-                } else if (throwable == null) {
-                    // Done.
-                    writeResultCallback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });
-                } else {
-                    // Failed.
-                    Log.e(LOG_TAG, "Error writing printed content", throwable);
-                    writeResultCallback.onWriteFailed(null);
-                }
-            }
-        }).execute();
-    }
-
-    /**
-     * Prints an image located at the Uri. Image types supported are those of
-     * <code>BitmapFactory.decodeStream</code> (JPEG, GIF, PNG, BMP, WEBP)
-     *
-     * @param jobName   The print job name.
-     * @param imageFile The <code>Uri</code> pointing to an image to print.
-     * @param callback Optional callback to observe when printing is finished.
-     * @throws FileNotFoundException if <code>Uri</code> is not pointing to a valid image.
-     */
-    public void printBitmap(final String jobName, final Uri imageFile,
-            final OnPrintFinishCallback callback) throws FileNotFoundException {
-        final int fittingMode = mScaleMode;
-
-        PrintDocumentAdapter printDocumentAdapter = new PrintDocumentAdapter() {
-            private PrintAttributes mAttributes;
-            AsyncTask<Uri, Boolean, Bitmap> mLoadBitmap;
-            Bitmap mBitmap = null;
-
-            @Override
-            public void onLayout(final PrintAttributes oldPrintAttributes,
-                                 final PrintAttributes newPrintAttributes,
-                                 final CancellationSignal cancellationSignal,
-                                 final LayoutResultCallback layoutResultCallback,
-                                 Bundle bundle) {
-
-                synchronized (this) {
-                    mAttributes = newPrintAttributes;
-                }
-
-                if (cancellationSignal.isCanceled()) {
-                    layoutResultCallback.onLayoutCancelled();
-                    return;
-                }
-                // we finished the load
-                if (mBitmap != null) {
-                    PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
-                            .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
-                            .setPageCount(1)
-                            .build();
-                    boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
-                    layoutResultCallback.onLayoutFinished(info, changed);
-                    return;
-                }
-
-                mLoadBitmap = new AsyncTask<Uri, Boolean, Bitmap>() {
-                    @Override
-                    protected void onPreExecute() {
-                        // First register for cancellation requests.
-                        cancellationSignal.setOnCancelListener(
-                                new CancellationSignal.OnCancelListener() {
-                                    @Override
-                                    public void onCancel() { // on different thread
-                                        cancelLoad();
-                                        cancel(false);
-                                    }
-                                });
-                    }
-
-                    @Override
-                    protected Bitmap doInBackground(Uri... uris) {
-                        try {
-                            return loadConstrainedBitmap(imageFile, MAX_PRINT_SIZE);
-                        } catch (FileNotFoundException e) {
-                          /* ignore */
-                        }
-                        return null;
-                    }
-
-                    @Override
-                    protected void onPostExecute(Bitmap bitmap) {
-                        super.onPostExecute(bitmap);
-
-                        // If orientation was not set by the caller, try to fit the bitmap on
-                        // the current paper by potentially rotating the bitmap by 90 degrees.
-                        if (bitmap != null
-                                && (!mPrintActivityRespectsOrientation || mOrientation == 0)) {
-                            MediaSize mediaSize;
-
-                            synchronized (this) {
-                                mediaSize = mAttributes.getMediaSize();
-                            }
-
-                            if (mediaSize != null) {
-                                if (mediaSize.isPortrait() != isPortrait(bitmap)) {
-                                    Matrix rotation = new Matrix();
-
-                                    rotation.postRotate(90);
-                                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
-                                            bitmap.getHeight(), rotation, true);
-                                }
-                            }
-                        }
-
-                        mBitmap = bitmap;
-                        if (bitmap != null) {
-                            PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName)
-                                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
-                                    .setPageCount(1)
-                                    .build();
-
-                            boolean changed = !newPrintAttributes.equals(oldPrintAttributes);
-
-                            layoutResultCallback.onLayoutFinished(info, changed);
-
-                        } else {
-                            layoutResultCallback.onLayoutFailed(null);
-                        }
-                        mLoadBitmap = null;
-                    }
-
-                    @Override
-                    protected void onCancelled(Bitmap result) {
-                        // Task was cancelled, report that.
-                        layoutResultCallback.onLayoutCancelled();
-                        mLoadBitmap = null;
-                    }
-                }.execute();
-            }
-
-            private void cancelLoad() {
-                synchronized (mLock) { // prevent race with set null below
-                    if (mDecodeOptions != null) {
-                        mDecodeOptions.requestCancelDecode();
-                        mDecodeOptions = null;
-                    }
-                }
-            }
-
-            @Override
-            public void onFinish() {
-                super.onFinish();
-                cancelLoad();
-                if (mLoadBitmap != null) {
-                    mLoadBitmap.cancel(true);
-                }
-                if (callback != null) {
-                    callback.onFinish();
-                }
-                if (mBitmap != null) {
-                    mBitmap.recycle();
-                    mBitmap = null;
-                }
-            }
-
-            @Override
-            public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor fileDescriptor,
-                                CancellationSignal cancellationSignal,
-                                WriteResultCallback writeResultCallback) {
-                writeBitmap(mAttributes, fittingMode, mBitmap, fileDescriptor, cancellationSignal,
-                        writeResultCallback);
-            }
-        };
-
-        PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
-        PrintAttributes.Builder builder = new PrintAttributes.Builder();
-        builder.setColorMode(mColorMode);
-
-        if (mOrientation == ORIENTATION_LANDSCAPE || mOrientation == 0) {
-            builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE);
-        } else if (mOrientation == ORIENTATION_PORTRAIT) {
-            builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT);
-        }
-        PrintAttributes attr = builder.build();
-
-        printManager.print(jobName, printDocumentAdapter, attr);
-    }
-
-    /**
-     * Loads a bitmap while limiting its size
-     *
-     * @param uri           location of a valid image
-     * @param maxSideLength the maximum length of a size
-     * @return the Bitmap
-     * @throws FileNotFoundException if the Uri does not point to an image
-     */
-    private Bitmap loadConstrainedBitmap(Uri uri, int maxSideLength) throws FileNotFoundException {
-        if (maxSideLength <= 0 || uri == null || mContext == null) {
-            throw new IllegalArgumentException("bad argument to getScaledBitmap");
-        }
-        // Get width and height of stored bitmap
-        BitmapFactory.Options opt = new BitmapFactory.Options();
-        opt.inJustDecodeBounds = true;
-        loadBitmap(uri, opt);
-
-        int w = opt.outWidth;
-        int h = opt.outHeight;
-
-        // If bitmap cannot be decoded, return null
-        if (w <= 0 || h <= 0) {
-            return null;
-        }
-
-        // Find best downsampling size
-        int imageSide = Math.max(w, h);
-
-        int sampleSize = 1;
-        while (imageSide > maxSideLength) {
-            imageSide >>>= 1;
-            sampleSize <<= 1;
-        }
-
-        // Make sure sample size is reasonable
-        if (sampleSize <= 0 || 0 >= (int) (Math.min(w, h) / sampleSize)) {
-            return null;
-        }
-        BitmapFactory.Options decodeOptions = null;
-        synchronized (mLock) { // prevent race with set null below
-            mDecodeOptions = new BitmapFactory.Options();
-            mDecodeOptions.inMutable = true;
-            mDecodeOptions.inSampleSize = sampleSize;
-            decodeOptions = mDecodeOptions;
-        }
-        try {
-            return loadBitmap(uri, decodeOptions);
-        } finally {
-            synchronized (mLock) {
-                mDecodeOptions = null;
-            }
-        }
-    }
-
-    /**
-     * Returns the bitmap from the given uri loaded using the given options.
-     * Returns null on failure.
-     */
-    private Bitmap loadBitmap(Uri uri, BitmapFactory.Options o) throws FileNotFoundException {
-        if (uri == null || mContext == null) {
-            throw new IllegalArgumentException("bad argument to loadBitmap");
-        }
-        InputStream is = null;
-        try {
-            is = mContext.getContentResolver().openInputStream(uri);
-            return BitmapFactory.decodeStream(is, null, o);
-        } finally {
-            if (is != null) {
-                try {
-                    is.close();
-                } catch (IOException t) {
-                    Log.w(LOG_TAG, "close fail ", t);
-                }
-            }
-        }
-    }
-
-    private Bitmap convertBitmapForColorMode(Bitmap original, int colorMode) {
-        if (colorMode != COLOR_MODE_MONOCHROME) {
-            return original;
-        }
-        // Create a grayscale bitmap
-        Bitmap grayscale = Bitmap.createBitmap(original.getWidth(), original.getHeight(),
-                Config.ARGB_8888);
-        Canvas c = new Canvas(grayscale);
-        Paint p = new Paint();
-        ColorMatrix cm = new ColorMatrix();
-        cm.setSaturation(0);
-        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
-        p.setColorFilter(f);
-        c.drawBitmap(original, 0, 0, p);
-        c.setBitmap(null);
-
-        return grayscale;
-    }
-}
diff --git a/core-utils/lint-baseline.xml b/core-utils/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/core-utils/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/core-utils/tests/AndroidManifest.xml b/core-utils/tests/AndroidManifest.xml
index dc706df..e3d060c 100644
--- a/core-utils/tests/AndroidManifest.xml
+++ b/core-utils/tests/AndroidManifest.xml
@@ -15,21 +15,16 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.coreutils.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.VIBRATE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="android.permission.READ_CONTACTS"/>
     <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
 
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
     <application>
         <activity android:name="android.support.v4.widget.test.TextViewTestActivity"/>
@@ -39,8 +34,8 @@
         <activity android:name="android.support.v4.provider.GrantActivity"
                   android:label="_GrantActivity">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
         <provider
@@ -50,7 +45,7 @@
             android:grantUriPermissions="true">
             <meta-data
                 android:name="android.support.FILE_PROVIDER_PATHS"
-                android:resource="@xml/paths" />
+                android:resource="@xml/paths"/>
         </provider>
     </application>
 
diff --git a/customtabs/build.gradle b/customtabs/build.gradle
index 6bc7dd5..2576d29 100644
--- a/customtabs/build.gradle
+++ b/customtabs/build.gradle
@@ -2,18 +2,16 @@
 archivesBaseName = 'customtabs'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-annotations')
+    api project(':support-compat')
+    api project(':support-annotations')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
diff --git a/customtabs/lint-baseline.xml b/customtabs/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/customtabs/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/customtabs/tests/AndroidManifest.xml b/customtabs/tests/AndroidManifest.xml
index 8807d6c..644f9e0 100644
--- a/customtabs/tests/AndroidManifest.xml
+++ b/customtabs/tests/AndroidManifest.xml
@@ -15,19 +15,14 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.customtabs.test">
-    <uses-sdk
-        android:minSdkVersion="15"
-        android:targetSdkVersion="23"
-        tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-              android.support.test.espresso, android.support.test.espresso.idling" />
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application>
-        <activity   android:name="android.support.customtabs.TestActivity"/>
+        <activity android:name="android.support.customtabs.TestActivity"/>
 
-        <service    android:name="android.support.customtabs.PostMessageService"/>
+        <service android:name="android.support.customtabs.PostMessageService"/>
 
-        <service    android:name="android.support.customtabs.TestCustomTabsService"/>
+        <service android:name="android.support.customtabs.TestCustomTabsService"/>
     </application>
 </manifest>
diff --git a/design/build.gradle b/design/build.gradle
index ea256fa..23cbeb7 100644
--- a/design/build.gradle
+++ b/design/build.gradle
@@ -2,27 +2,20 @@
 archivesBaseName = 'design'
 
 dependencies {
-    compile project(':support-v4')
-    compile project(':support-appcompat-v7')
-    compile project(':support-recyclerview-v7')
-    compile project(':support-transition')
+    api project(':support-v4')
+    api project(':support-appcompat-v7')
+    api project(':support-recyclerview-v7')
+    api project(':support-transition')
 
-    androidTestCompile (libs.test_runner) {
-        exclude module: 'support-annotations'
-    }
-    androidTestCompile (libs.espresso_core) {
-        exclude module: 'support-annotations'
-    }
-    androidTestCompile (libs.espresso_contrib) {
-        exclude group: 'com.android.support'
-    }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.test_runner,      { exclude module: 'support-annotations' }
+    androidTestImplementation libs.espresso_core,    { exclude module: 'support-annotations' }
+    androidTestImplementation libs.espresso_contrib, { exclude group: 'com.android.support' }
+    androidTestImplementation libs.mockito_core,     { exclude group: 'net.bytebuddy' } // DexMaker has it"s own MockMaker
+    androidTestImplementation libs.dexmaker_mockito, { exclude group: 'net.bytebuddy' } // DexMaker has it"s own MockMaker
+    androidTestImplementation project(':support-testutils')
 
-    testCompile libs.junit
-    testCompile ("$libs.test_runner") {
+    testImplementation libs.junit
+    testImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/design/lint-baseline.xml b/design/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/design/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/design/res/values/styles.xml b/design/res/values/styles.xml
index f7624ec..93fb7eb 100644
--- a/design/res/values/styles.xml
+++ b/design/res/values/styles.xml
@@ -115,7 +115,6 @@
     </style>
 
     <style name="Widget.Design.AppBarLayout" parent="Base.Widget.Design.AppBarLayout">
-        <item name="android:paddingLeft">300px</item>
     </style>
 
     <style name="Widget.Design.CoordinatorLayout" parent="android:Widget">
diff --git a/design/src/android/support/design/internal/BottomNavigationItemView.java b/design/src/android/support/design/internal/BottomNavigationItemView.java
index 885ea02..fe5e636 100644
--- a/design/src/android/support/design/internal/BottomNavigationItemView.java
+++ b/design/src/android/support/design/internal/BottomNavigationItemView.java
@@ -125,7 +125,6 @@
     public void setTitle(CharSequence title) {
         mSmallLabel.setText(title);
         mLargeLabel.setText(title);
-        setContentDescription(title);
     }
 
     @Override
diff --git a/design/src/android/support/design/widget/AppBarLayout.java b/design/src/android/support/design/widget/AppBarLayout.java
index 89fcf7c..8304cd6 100644
--- a/design/src/android/support/design/widget/AppBarLayout.java
+++ b/design/src/android/support/design/widget/AppBarLayout.java
@@ -17,7 +17,6 @@
 package android.support.design.widget;
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 
 import android.animation.ValueAnimator;
 import android.content.Context;
@@ -34,7 +33,7 @@
 import android.support.annotation.VisibleForTesting;
 import android.support.design.R;
 import android.support.v4.math.MathUtils;
-import android.support.v4.os.BuildCompat;
+import android.support.v4.util.ObjectsCompat;
 import android.support.v4.view.AbsSavedState;
 import android.support.v4.view.ViewCompat;
 import android.support.v4.view.WindowInsetsCompat;
@@ -179,7 +178,7 @@
             ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(
                     this, a.getDimensionPixelSize(R.styleable.AppBarLayout_elevation, 0));
         }
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             // In O+, we have these values set in the style. Since there is no defStyleAttr for
             // AppBarLayout at the AppCompat level, check for these attributes here.
             if (a.hasValue(R.styleable.AppBarLayout_android_keyboardNavigationCluster)) {
@@ -603,7 +602,7 @@
         }
 
         // If our insets have changed, keep them and invalidate the scroll ranges...
-        if (!objectEquals(mLastInsets, newInsets)) {
+        if (!ObjectsCompat.equals(mLastInsets, newInsets)) {
             mLastInsets = newInsets;
             invalidateScrollRanges();
         }
@@ -1085,7 +1084,7 @@
                 // If we have a reference to a scrolling view, check it
                 final View scrollingView = mLastNestedScrollingChildRef.get();
                 return scrollingView != null && scrollingView.isShown()
-                        && !ViewCompat.canScrollVertically(scrollingView, -1);
+                        && !scrollingView.canScrollVertically(-1);
             } else {
                 // Otherwise we assume that the scrolling view hasn't been scrolled and can drag.
                 return true;
diff --git a/design/src/android/support/design/widget/BottomSheetBehavior.java b/design/src/android/support/design/widget/BottomSheetBehavior.java
index 6868d29..a28d3be 100644
--- a/design/src/android/support/design/widget/BottomSheetBehavior.java
+++ b/design/src/android/support/design/widget/BottomSheetBehavior.java
@@ -359,7 +359,7 @@
                 setStateInternal(STATE_DRAGGING);
             }
         } else if (dy < 0) { // Downward
-            if (!ViewCompat.canScrollVertically(target, -1)) {
+            if (!target.canScrollVertically(-1)) {
                 if (newTop <= mMaxOffset || mHideable) {
                     consumed[1] = dy;
                     ViewCompat.offsetTopAndBottom(child, -dy);
@@ -648,7 +648,7 @@
             }
             if (mState == STATE_EXPANDED && mActivePointerId == pointerId) {
                 View scroll = mNestedScrollingChildRef.get();
-                if (scroll != null && ViewCompat.canScrollVertically(scroll, -1)) {
+                if (scroll != null && scroll.canScrollVertically(-1)) {
                     // Let the content scroll up
                     return false;
                 }
diff --git a/design/src/android/support/design/widget/CollapsingToolbarLayout.java b/design/src/android/support/design/widget/CollapsingToolbarLayout.java
index 100b0dc..0051de9 100644
--- a/design/src/android/support/design/widget/CollapsingToolbarLayout.java
+++ b/design/src/android/support/design/widget/CollapsingToolbarLayout.java
@@ -17,7 +17,6 @@
 package android.support.design.widget;
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 
 import android.animation.ValueAnimator;
 import android.content.Context;
@@ -41,6 +40,7 @@
 import android.support.v4.content.ContextCompat;
 import android.support.v4.graphics.drawable.DrawableCompat;
 import android.support.v4.math.MathUtils;
+import android.support.v4.util.ObjectsCompat;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.view.ViewCompat;
 import android.support.v4.view.WindowInsetsCompat;
@@ -270,7 +270,7 @@
         }
 
         // If our insets have changed, keep them and invalidate the scroll ranges...
-        if (!objectEquals(mLastInsets, newInsets)) {
+        if (!ObjectsCompat.equals(mLastInsets, newInsets)) {
             mLastInsets = newInsets;
             requestLayout();
         }
diff --git a/design/src/android/support/design/widget/CoordinatorLayout.java b/design/src/android/support/design/widget/CoordinatorLayout.java
index cc63050..818e3a6 100644
--- a/design/src/android/support/design/widget/CoordinatorLayout.java
+++ b/design/src/android/support/design/widget/CoordinatorLayout.java
@@ -17,7 +17,6 @@
 package android.support.design.widget;
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 
 import android.content.Context;
 import android.content.res.Resources;
@@ -46,6 +45,7 @@
 import android.support.v4.content.ContextCompat;
 import android.support.v4.graphics.drawable.DrawableCompat;
 import android.support.v4.math.MathUtils;
+import android.support.v4.util.ObjectsCompat;
 import android.support.v4.util.Pools;
 import android.support.v4.view.AbsSavedState;
 import android.support.v4.view.GravityCompat;
@@ -351,7 +351,7 @@
     }
 
     final WindowInsetsCompat setWindowInsets(WindowInsetsCompat insets) {
-        if (!objectEquals(mLastInsets, insets)) {
+        if (!ObjectsCompat.equals(mLastInsets, insets)) {
             mLastInsets = insets;
             mDrawStatusBarBackground = insets != null && insets.getSystemWindowInsetTop() > 0;
             setWillNotDraw(!mDrawStatusBarBackground && getBackground() == null);
diff --git a/design/src/android/support/design/widget/TextInputLayout.java b/design/src/android/support/design/widget/TextInputLayout.java
index 52efdde..c9e8010 100644
--- a/design/src/android/support/design/widget/TextInputLayout.java
+++ b/design/src/android/support/design/widget/TextInputLayout.java
@@ -961,6 +961,7 @@
 
     static class SavedState extends AbsSavedState {
         CharSequence error;
+        boolean isPasswordToggledVisible;
 
         SavedState(Parcelable superState) {
             super(superState);
@@ -969,6 +970,7 @@
         SavedState(Parcel source, ClassLoader loader) {
             super(source, loader);
             error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
+            isPasswordToggledVisible = (source.readInt() == 1);
 
         }
 
@@ -976,6 +978,7 @@
         public void writeToParcel(Parcel dest, int flags) {
             super.writeToParcel(dest, flags);
             TextUtils.writeToParcel(error, dest, flags);
+            dest.writeInt(isPasswordToggledVisible ? 1 : 0);
         }
 
         @Override
@@ -1010,6 +1013,7 @@
         if (mErrorShown) {
             ss.error = getError();
         }
+        ss.isPasswordToggledVisible = mPasswordToggledVisible;
         return ss;
     }
 
@@ -1022,6 +1026,9 @@
         SavedState ss = (SavedState) state;
         super.onRestoreInstanceState(ss.getSuperState());
         setError(ss.error);
+        if (ss.isPasswordToggledVisible) {
+            passwordVisibilityToggleRequested(true);
+        }
         requestLayout();
     }
 
@@ -1100,7 +1107,7 @@
                 mPasswordToggleView.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
-                        passwordVisibilityToggleRequested();
+                        passwordVisibilityToggleRequested(false);
                     }
                 });
             }
@@ -1313,7 +1320,7 @@
         applyPasswordToggleTint();
     }
 
-    void passwordVisibilityToggleRequested() {
+    private void passwordVisibilityToggleRequested(boolean shouldSkipAnimations) {
         if (mPasswordToggleEnabled) {
             // Store the current cursor position
             final int selection = mEditText.getSelectionEnd();
@@ -1327,6 +1334,9 @@
             }
 
             mPasswordToggleView.setChecked(mPasswordToggledVisible);
+            if (shouldSkipAnimations) {
+                mPasswordToggleView.jumpDrawablesToCurrentState();
+            }
 
             // And restore the cursor position
             mEditText.setSelection(selection);
diff --git a/design/tests/AndroidManifest.xml b/design/tests/AndroidManifest.xml
index 6d7a7e6..c4673b3 100755
--- a/design/tests/AndroidManifest.xml
+++ b/design/tests/AndroidManifest.xml
@@ -15,77 +15,71 @@
   limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.design.test">
-
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application
-            android:supportsRtl="true"
-            android:theme="@style/Theme.Design">
+        android:supportsRtl="true"
+        android:theme="@style/Theme.Design">
 
         <activity
-                android:theme="@style/Theme.AppCompat.NoActionBar"
-                android:name="android.support.design.widget.TabLayoutWithViewPagerActivity"/>
+            android:name="android.support.design.widget.TabLayoutWithViewPagerActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:theme="@style/Theme.AppCompat.NoActionBar"
-                android:name="android.support.design.widget.SnackbarActivity"/>
+            android:name="android.support.design.widget.SnackbarActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-            android:theme="@style/Theme.TranslucentNavBar"
-            android:name="android.support.design.widget.SnackbarActivityWithTranslucentNavBar"/>
+            android:name="android.support.design.widget.SnackbarActivityWithTranslucentNavBar"
+            android:theme="@style/Theme.TranslucentNavBar"/>
 
         <activity
-            android:theme="@style/Theme.AppCompat.NoActionBar"
-            android:name="android.support.design.widget.SnackbarActivityWithFAB"/>
+            android:name="android.support.design.widget.SnackbarActivityWithFAB"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:theme="@style/Theme.TranslucentStatus"
-                android:name="android.support.design.widget.DynamicCoordinatorLayoutActivity"/>
+            android:name="android.support.design.widget.DynamicCoordinatorLayoutActivity"
+            android:theme="@style/Theme.TranslucentStatus"/>
 
         <activity
-                android:theme="@style/Theme.AppCompat.NoActionBar"
-                android:name="android.support.design.widget.TabLayoutPoolingActivity"/>
+            android:name="android.support.design.widget.TabLayoutPoolingActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:theme="@style/Theme.AppCompat.NoActionBar"
-                android:name="android.support.design.widget.BottomSheetBehaviorActivity"/>
+            android:name="android.support.design.widget.BottomSheetBehaviorActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-            android:theme="@style/Theme.AppCompat.NoActionBar"
-            android:name="android.support.design.widget.BottomSheetBehaviorWithInsetsActivity"/>
+            android:name="android.support.design.widget.BottomSheetBehaviorWithInsetsActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:theme="@style/Theme.AppCompat.NoActionBar"
-                android:name="android.support.design.widget.BottomSheetDialogActivity"/>
+            android:name="android.support.design.widget.BottomSheetDialogActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-            android:theme="@style/Theme.AppCompat.NoActionBar"
-            android:name="android.support.design.widget.CoordinatorLayoutActivity"/>
+            android:name="android.support.design.widget.CoordinatorLayoutActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:name="android.support.design.widget.FloatingActionButtonActivity"
-                android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
+            android:name="android.support.design.widget.FloatingActionButtonActivity"
+            android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
 
         <activity
-            android:theme="@style/Theme.AppCompat.NoActionBar"
-            android:name="android.support.design.widget.NavigationViewActivity"/>
+            android:name="android.support.design.widget.NavigationViewActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-            android:theme="@style/Theme.AppCompat.NoActionBar"
-            android:name="android.support.design.widget.BottomNavigationViewActivity"/>
+            android:name="android.support.design.widget.BottomNavigationViewActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-              android:theme="@style/Theme.AppCompat.NoActionBar"
-              android:name="android.support.design.widget.TextInputLayoutActivity"/>
+            android:name="android.support.design.widget.TextInputLayoutActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:name="android.support.v7.app.AppCompatActivity"/>
+            android:name="android.support.v7.app.AppCompatActivity"/>
 
         <activity
             android:name="android.support.design.widget.AppBarLayoutCollapsePinTestActivity"
diff --git a/design/tests/res/menu/bottom_navigation_view_content.xml b/design/tests/res/menu/bottom_navigation_view_content.xml
index 6d19060..d61d6d8 100644
--- a/design/tests/res/menu/bottom_navigation_view_content.xml
+++ b/design/tests/res/menu/bottom_navigation_view_content.xml
@@ -13,14 +13,21 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+      xmlns:app="http://schemas.android.com/apk/res-auto">
     <item android:id="@+id/destination_home"
+          android:icon="@drawable/test_drawable_red"
           android:title="@string/navigate_home"
-          android:icon="@drawable/test_drawable_red" />
+          app:contentDescription="@string/navigate_home"
+          app:tooltipText="@string/navigate_home"/>
     <item android:id="@+id/destination_profile"
+          android:icon="@drawable/test_drawable_green"
           android:title="@string/navigate_profile"
-          android:icon="@drawable/test_drawable_green" />
+          app:contentDescription="@string/navigate_profile"
+          app:tooltipText="@string/navigate_profile"/>
     <item android:id="@+id/destination_people"
+          android:icon="@drawable/test_drawable_blue"
           android:title="@string/navigate_people"
-          android:icon="@drawable/test_drawable_blue" />
+          app:contentDescription="@string/navigate_people"
+          app:tooltipText="@string/navigate_people"/>
 </menu>
diff --git a/design/tests/src/android/support/design/testutils/ActivityUtils.java b/design/tests/src/android/support/design/testutils/ActivityUtils.java
new file mode 100644
index 0000000..1ed6a3f
--- /dev/null
+++ b/design/tests/src/android/support/design/testutils/ActivityUtils.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 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 android.support.design.testutils;
+
+import static org.junit.Assert.assertTrue;
+
+import android.os.Looper;
+import android.support.test.rule.ActivityTestRule;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Utility methods for testing activities.
+ */
+public class ActivityUtils {
+    private static final Runnable DO_NOTHING = new Runnable() {
+        @Override
+        public void run() {
+        }
+    };
+
+    public static void waitForExecution(
+            final ActivityTestRule<? extends RecreatedAppCompatActivity> rule) {
+        // Wait for two cycles. When starting a postponed transition, it will post to
+        // the UI thread and then the execution will be added onto the queue after that.
+        // The two-cycle wait makes sure fragments have the opportunity to complete both
+        // before returning.
+        try {
+            rule.runOnUiThread(DO_NOTHING);
+            rule.runOnUiThread(DO_NOTHING);
+        } catch (Throwable throwable) {
+            throw new RuntimeException(throwable);
+        }
+    }
+
+    private static void runOnUiThreadRethrow(
+            ActivityTestRule<? extends RecreatedAppCompatActivity> rule, Runnable r) {
+        if (Looper.getMainLooper() == Looper.myLooper()) {
+            r.run();
+        } else {
+            try {
+                rule.runOnUiThread(r);
+            } catch (Throwable t) {
+                throw new RuntimeException(t);
+            }
+        }
+    }
+
+    /**
+     * Restarts the RecreatedAppCompatActivity and waits for the new activity to be resumed.
+     *
+     * @return The newly-restarted RecreatedAppCompatActivity
+     */
+    public static <T extends RecreatedAppCompatActivity> T recreateActivity(
+            ActivityTestRule<? extends RecreatedAppCompatActivity> rule, final T activity)
+            throws InterruptedException {
+        // Now switch the orientation
+        RecreatedAppCompatActivity.sResumed = new CountDownLatch(1);
+        RecreatedAppCompatActivity.sDestroyed = new CountDownLatch(1);
+
+        runOnUiThreadRethrow(rule, new Runnable() {
+            @Override
+            public void run() {
+                activity.recreate();
+            }
+        });
+        assertTrue(RecreatedAppCompatActivity.sResumed.await(1, TimeUnit.SECONDS));
+        assertTrue(RecreatedAppCompatActivity.sDestroyed.await(1, TimeUnit.SECONDS));
+        T newActivity = (T) RecreatedAppCompatActivity.sActivity;
+
+        waitForExecution(rule);
+
+        RecreatedAppCompatActivity.clearState();
+        return newActivity;
+    }
+}
diff --git a/design/tests/src/android/support/design/testutils/RecreatedAppCompatActivity.java b/design/tests/src/android/support/design/testutils/RecreatedAppCompatActivity.java
new file mode 100644
index 0000000..52ba059
--- /dev/null
+++ b/design/tests/src/android/support/design/testutils/RecreatedAppCompatActivity.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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 android.support.design.testutils;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v7.app.AppCompatActivity;
+
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * Activity that keeps track of resume / destroy lifecycle events, as well as of the last
+ * instance of itself.
+ */
+public class RecreatedAppCompatActivity extends AppCompatActivity {
+    // These must be cleared after each test using clearState()
+    public static RecreatedAppCompatActivity sActivity;
+    public static CountDownLatch sResumed;
+    public static CountDownLatch sDestroyed;
+
+    public static void clearState() {
+        sActivity = null;
+        sResumed = null;
+        sDestroyed = null;
+    }
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        sActivity = this;
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        if (sResumed != null) {
+            sResumed.countDown();
+        }
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        if (sDestroyed != null) {
+            sDestroyed.countDown();
+        }
+    }
+}
diff --git a/design/tests/src/android/support/design/testutils/TextInputLayoutActions.java b/design/tests/src/android/support/design/testutils/TextInputLayoutActions.java
index f49644f..c4d4520 100755
--- a/design/tests/src/android/support/design/testutils/TextInputLayoutActions.java
+++ b/design/tests/src/android/support/design/testutils/TextInputLayoutActions.java
@@ -19,9 +19,11 @@
 import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
 
 import android.graphics.Typeface;
+import android.support.design.R;
 import android.support.design.widget.TextInputLayout;
 import android.support.test.espresso.UiController;
 import android.support.test.espresso.ViewAction;
+import android.support.test.espresso.matcher.ViewMatchers;
 import android.view.View;
 
 import org.hamcrest.Matcher;
@@ -196,4 +198,32 @@
         };
     }
 
+    /**
+     * Toggles password.
+     */
+    public static ViewAction clickPasswordToggle() {
+        return new ViewAction() {
+
+            @Override
+            public Matcher<View> getConstraints() {
+                return ViewMatchers.isAssignableFrom(TextInputLayout.class);
+            }
+
+            @Override
+            public String getDescription() {
+                return "Clicks the password toggle";
+            }
+
+            @Override
+            public void perform(UiController uiController, View view) {
+                TextInputLayout textInputLayout = (TextInputLayout) view;
+                // Reach in and find the password toggle since we don't have a public API
+                // to get a reference to it
+                View passwordToggle = textInputLayout.findViewById(R.id.text_input_password_toggle);
+                passwordToggle.performClick();
+                uiController.loopMainThreadUntilIdle();
+            }
+        };
+    }
+
 }
diff --git a/design/tests/src/android/support/design/testutils/TextInputLayoutMatchers.java b/design/tests/src/android/support/design/testutils/TextInputLayoutMatchers.java
index d13a39d..d67e555 100755
--- a/design/tests/src/android/support/design/testutils/TextInputLayoutMatchers.java
+++ b/design/tests/src/android/support/design/testutils/TextInputLayoutMatchers.java
@@ -16,8 +16,11 @@
 
 package android.support.design.testutils;
 
+import android.support.design.R;
+import android.support.design.widget.CheckableImageButton;
 import android.support.design.widget.TextInputLayout;
 import android.text.TextUtils;
+import android.view.View;
 
 import org.hamcrest.Description;
 import org.hamcrest.Matcher;
@@ -29,7 +32,7 @@
      * Returns a matcher that matches TextInputLayouts with non-empty content descriptions for
      * the password toggle.
      */
-    public static Matcher hasPasswordToggleContentDescription() {
+    public static Matcher passwordToggleHasContentDescription() {
         return new TypeSafeMatcher<TextInputLayout>() {
             @Override
             public void describeTo(Description description) {
@@ -39,9 +42,53 @@
 
             @Override
             protected boolean matchesSafely(TextInputLayout item) {
-                return !TextUtils.isEmpty(item.getPasswordVisibilityToggleContentDescription());
+                // Reach in and find the password toggle since we don't have a public API
+                // to get a reference to it
+                View passwordToggle = item.findViewById(R.id.text_input_password_toggle);
+                return !TextUtils.isEmpty(item.getPasswordVisibilityToggleContentDescription())
+                    && !TextUtils.isEmpty(passwordToggle.getContentDescription());
             }
         };
     }
 
+    /**
+     * Returns a matcher that matches TextInputLayouts with non-displayed password toggles
+     */
+    public static Matcher doesNotShowPasswordToggle() {
+        return new TypeSafeMatcher<TextInputLayout>() {
+            @Override
+            public void describeTo(Description description) {
+                description.appendText("TextInputLayout shows password toggle.");
+            }
+
+            @Override
+            protected boolean matchesSafely(TextInputLayout item) {
+                // Reach in and find the password toggle since we don't have a public API
+                // to get a reference to it
+                View passwordToggle = item.findViewById(R.id.text_input_password_toggle);
+                return passwordToggle.getVisibility() != View.VISIBLE;
+            }
+        };
+    }
+
+    /**
+     * Returns a matcher that matches TextInputLayouts with non-displayed password toggles
+     */
+    public static Matcher passwordToggleIsNotChecked() {
+        return new TypeSafeMatcher<TextInputLayout>() {
+            @Override
+            public void describeTo(Description description) {
+                description.appendText("TextInputLayout has checked password toggle.");
+            }
+
+            @Override
+            protected boolean matchesSafely(TextInputLayout item) {
+                // Reach in and find the password toggle since we don't have a public API
+                // to get a reference to it
+                CheckableImageButton passwordToggle = (CheckableImageButton) item.findViewById(
+                        R.id.text_input_password_toggle);
+                return !passwordToggle.isChecked();
+            }
+        };
+    }
 }
diff --git a/design/tests/src/android/support/design/widget/AppBarWithCollapsingToolbarStateRestoreTest.java b/design/tests/src/android/support/design/widget/AppBarWithCollapsingToolbarStateRestoreTest.java
index 82c9582..b9a6518 100644
--- a/design/tests/src/android/support/design/widget/AppBarWithCollapsingToolbarStateRestoreTest.java
+++ b/design/tests/src/android/support/design/widget/AppBarWithCollapsingToolbarStateRestoreTest.java
@@ -23,14 +23,10 @@
 import static android.support.test.espresso.assertion.ViewAssertions.matches;
 import static android.support.test.espresso.matcher.ViewMatchers.withId;
 
-import android.app.Activity;
-import android.content.pm.ActivityInfo;
-import android.content.res.Configuration;
 import android.support.design.test.R;
+import android.support.design.testutils.ActivityUtils;
 import android.support.test.filters.LargeTest;
-import android.support.testutils.PollingCheck;
 
-import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -38,8 +34,7 @@
 public class AppBarWithCollapsingToolbarStateRestoreTest
         extends BaseInstrumentationTestCase<AppBarLayoutCollapsePinTestActivity> {
 
-    private Activity mActivity;
-    private int mOldOrientation;
+    private AppBarLayoutCollapsePinTestActivity mActivity;
 
     public AppBarWithCollapsingToolbarStateRestoreTest() {
         super(AppBarLayoutCollapsePinTestActivity.class);
@@ -48,22 +43,10 @@
     @Before
     public void setup() {
         mActivity = mActivityTestRule.getActivity();
-        mOldOrientation = mActivity.getResources().getConfiguration().orientation;
-    }
-
-    @After
-    public void tearDown() {
-        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
-        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
-            @Override
-            public boolean canProceed() {
-                return mActivity.getResources().getConfiguration().orientation == mOldOrientation;
-            }
-        });
     }
 
     @Test
-    public void testRotateAndRestore() {
+    public void testRecreateAndRestore() throws Throwable {
         final AppBarLayout appBar = (AppBarLayout) mActivity.findViewById(R.id.app_bar);
 
         // Swipe up and collapse the AppBarLayout
@@ -76,27 +59,12 @@
                 .check(matches(hasZ()))
                 .check(matches(isCollapsed()));
 
-        // Now rotate the Activity
-        final int newOrientation = mOldOrientation == Configuration.ORIENTATION_PORTRAIT
-                ? Configuration.ORIENTATION_LANDSCAPE
-                : Configuration.ORIENTATION_PORTRAIT;
-        mActivity.setRequestedOrientation(toActivityInfoConfiguration(newOrientation));
-        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
-            @Override
-            public boolean canProceed() {
-                return mActivity.getResources().getConfiguration().orientation == newOrientation;
-            }
-        });
+        mActivity = ActivityUtils.recreateActivity(mActivityTestRule, mActivity);
+        ActivityUtils.waitForExecution(mActivityTestRule);
 
         // And check that the app bar still is restored correctly
         onView(withId(R.id.app_bar))
                 .check(matches(hasZ()))
                 .check(matches(isCollapsed()));
     }
-
-    private static int toActivityInfoConfiguration(int configuration) {
-        return configuration == Configuration.ORIENTATION_PORTRAIT
-                ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
-                : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
-    }
 }
diff --git a/design/tests/src/android/support/design/widget/BaseTestActivity.java b/design/tests/src/android/support/design/widget/BaseTestActivity.java
index 0c801cb..bdeb231 100755
--- a/design/tests/src/android/support/design/widget/BaseTestActivity.java
+++ b/design/tests/src/android/support/design/widget/BaseTestActivity.java
@@ -17,10 +17,10 @@
 package android.support.design.widget;
 
 import android.os.Bundle;
-import android.support.v7.app.AppCompatActivity;
+import android.support.design.testutils.RecreatedAppCompatActivity;
 import android.view.WindowManager;
 
-abstract class BaseTestActivity extends AppCompatActivity {
+abstract class BaseTestActivity extends RecreatedAppCompatActivity {
 
     private boolean mDestroyed;
 
diff --git a/design/tests/src/android/support/design/widget/BottomNavigationViewTest.java b/design/tests/src/android/support/design/widget/BottomNavigationViewTest.java
index cbf2fc9..3365fac 100644
--- a/design/tests/src/android/support/design/widget/BottomNavigationViewTest.java
+++ b/design/tests/src/android/support/design/widget/BottomNavigationViewTest.java
@@ -56,6 +56,7 @@
 import android.view.MotionEvent;
 import android.view.PointerIcon;
 import android.view.View;
+import android.view.ViewGroup;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -434,6 +435,22 @@
         });
     }
 
+    @UiThreadTest
+    @Test
+    @SmallTest
+    public void testContentDescription() {
+        ViewGroup menuView = (ViewGroup) mBottomNavigation.getChildAt(0);
+        final int count = menuView.getChildCount();
+        for (int i = 0; i < count; i++) {
+            View child = menuView.getChildAt(i);
+            // We're using the same strings for content description
+            assertEquals(mMenuStringContent.get(child.getId()),
+                    child.getContentDescription().toString());
+        }
+
+        menuView.getChildAt(0).getContentDescription();
+    }
+
     private void checkAndVerifyExclusiveItem(final Menu menu, final int id) throws Throwable {
         menu.findItem(id).setChecked(true);
         for (int i = 0; i < menu.size(); i++) {
diff --git a/design/tests/src/android/support/design/widget/TextInputLayoutTest.java b/design/tests/src/android/support/design/widget/TextInputLayoutTest.java
index 226463c..52471a9 100755
--- a/design/tests/src/android/support/design/widget/TextInputLayoutTest.java
+++ b/design/tests/src/android/support/design/widget/TextInputLayoutTest.java
@@ -21,6 +21,7 @@
 import static android.support.design.testutils.TestUtilsMatchers.withCompoundDrawable;
 import static android.support.design.testutils.TestUtilsMatchers.withTextColor;
 import static android.support.design.testutils.TestUtilsMatchers.withTypeface;
+import static android.support.design.testutils.TextInputLayoutActions.clickPasswordToggle;
 import static android.support.design.testutils.TextInputLayoutActions.setCounterEnabled;
 import static android.support.design.testutils.TextInputLayoutActions.setCounterMaxLength;
 import static android.support.design.testutils.TextInputLayoutActions.setError;
@@ -29,8 +30,10 @@
 import static android.support.design.testutils.TextInputLayoutActions
         .setPasswordVisibilityToggleEnabled;
 import static android.support.design.testutils.TextInputLayoutActions.setTypeface;
+import static android.support.design.testutils.TextInputLayoutMatchers.doesNotShowPasswordToggle;
 import static android.support.design.testutils.TextInputLayoutMatchers
-        .hasPasswordToggleContentDescription;
+        .passwordToggleHasContentDescription;
+import static android.support.design.testutils.TextInputLayoutMatchers.passwordToggleIsNotChecked;
 import static android.support.test.InstrumentationRegistry.getInstrumentation;
 import static android.support.test.espresso.Espresso.onView;
 import static android.support.test.espresso.action.ViewActions.click;
@@ -38,15 +41,15 @@
 import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
 import static android.support.test.espresso.assertion.ViewAssertions.matches;
 import static android.support.test.espresso.contrib.AccessibilityChecks.accessibilityAssertion;
-import static android.support.test.espresso.matcher.ViewMatchers.hasContentDescription;
 import static android.support.test.espresso.matcher.ViewMatchers.hasFocus;
-import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
+import static android.support.test.espresso.matcher.ViewMatchers.isDescendantOfA;
 import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
 import static android.support.test.espresso.matcher.ViewMatchers.isEnabled;
 import static android.support.test.espresso.matcher.ViewMatchers.withId;
 import static android.support.test.espresso.matcher.ViewMatchers.withText;
 
 import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.AllOf.allOf;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNull;
@@ -62,14 +65,19 @@
 import android.os.Build;
 import android.os.Parcelable;
 import android.support.design.test.R;
+import android.support.design.testutils.ActivityUtils;
+import android.support.design.testutils.RecreatedAppCompatActivity;
 import android.support.design.testutils.TestUtils;
 import android.support.design.testutils.ViewStructureImpl;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.espresso.NoMatchingViewException;
 import android.support.test.espresso.ViewAssertion;
+import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.SdkSuppress;
 import android.support.v4.widget.TextViewCompat;
+import android.text.method.PasswordTransformationMethod;
+import android.text.method.TransformationMethod;
 import android.util.AttributeSet;
 import android.util.SparseArray;
 import android.view.KeyEvent;
@@ -167,7 +175,7 @@
         assertNotEquals(INPUT_TEXT, textInput.getLayout().getText().toString());
 
         // Now click the toggle button
-        onView(withId(R.id.text_input_password_toggle)).perform(click());
+        onView(withId(R.id.textinput_password)).perform(clickPasswordToggle());
 
         // And assert that the password is not disguised
         assertEquals(INPUT_TEXT, textInput.getLayout().getText().toString());
@@ -189,7 +197,7 @@
                 .perform(setPasswordVisibilityToggleEnabled(false));
 
         // Check that the password toggle view is not visible
-        onView(withId(R.id.text_input_password_toggle)).check(matches(not(isDisplayed())));
+        onView(withId(R.id.textinput_password)).check(matches(doesNotShowPasswordToggle()));
         // ...and that the password is disguised still
         assertNotEquals(INPUT_TEXT, textInput.getLayout().getText().toString());
     }
@@ -205,7 +213,7 @@
         assertNotEquals(INPUT_TEXT, textInput.getLayout().getText().toString());
 
         // Now click the toggle button
-        onView(withId(R.id.text_input_password_toggle)).perform(click());
+        onView(withId(R.id.textinput_password)).perform(clickPasswordToggle());
         // Disable the password toggle
         onView(withId(R.id.textinput_password))
                 .perform(setPasswordVisibilityToggleEnabled(false));
@@ -252,7 +260,7 @@
 
         // Type some text on the EditText and then click the toggle button
         onView(withId(R.id.textinput_edittext_pwd)).perform(typeText(INPUT_TEXT));
-        onView(withId(R.id.text_input_password_toggle)).perform(click());
+        onView(withId(R.id.textinput_password)).perform(clickPasswordToggle());
 
         // Disable the password toggle, and then re-enable it
         onView(withId(R.id.textinput_password))
@@ -261,7 +269,7 @@
 
         // Check that the password is disguised and the toggle button reflects the same state
         assertNotEquals(INPUT_TEXT, textInput.getLayout().getText().toString());
-        onView(withId(R.id.text_input_password_toggle)).check(matches(not(isChecked())));
+        onView(withId(R.id.textinput_password)).check(matches(passwordToggleIsNotChecked()));
     }
 
     @Test
@@ -430,13 +438,10 @@
 
     @Test
     public void testPasswordToggleHasDefaultContentDescription() {
-        // Check that the TextInputLayout says that it has a content description
+        // Check that the TextInputLayout says that it has a content description and that the
+        // underlying toggle has content description as well
         onView(withId(R.id.textinput_password))
-                .check(matches(hasPasswordToggleContentDescription()));
-
-        // Check that the underlying toggle view says that it also has a content description
-        onView(withId(R.id.text_input_password_toggle))
-                .check(matches(hasContentDescription()));
+                .check(matches(passwordToggleHasContentDescription()));
     }
 
     /**
@@ -445,8 +450,8 @@
      */
     @Test
     public void testPasswordToggleIsAccessible() {
-        onView(withId(R.id.text_input_password_toggle))
-                .check(accessibilityAssertion());
+        onView(allOf(withId(R.id.text_input_password_toggle),
+                isDescendantOfA(withId(R.id.textinput_password)))).check(accessibilityAssertion());
     }
 
     @Test
@@ -489,8 +494,7 @@
 
     @Test
     public void testTextSetViaAttributeCollapsedHint() {
-        onView(withId(R.id.textinput_with_text))
-                .check(isHintExpanded(false));
+        onView(withId(R.id.textinput_with_text)).check(isHintExpanded(false));
     }
 
     @Test
@@ -508,6 +512,25 @@
                 .check(matches(hasFocus()));
     }
 
+    @Test
+    @LargeTest
+    public void testSaveAndRestorePasswordVisibility() throws Throwable {
+        // Type some text on the EditText
+        onView(withId(R.id.textinput_edittext_pwd)).perform(typeText(INPUT_TEXT));
+        onView(withId(R.id.textinput_password)).check(isPasswordToggledVisible(false));
+
+        // Toggle password to be shown as plain text
+        onView(withId(R.id.textinput_password)).perform(clickPasswordToggle());
+        onView(withId(R.id.textinput_password)).check(isPasswordToggledVisible(true));
+
+        RecreatedAppCompatActivity activity = mActivityTestRule.getActivity();
+        activity = ActivityUtils.recreateActivity(mActivityTestRule, activity);
+        ActivityUtils.waitForExecution(mActivityTestRule);
+
+        // Check that the password is still toggled to be shown as plain text
+        onView(withId(R.id.textinput_password)).check(isPasswordToggledVisible(true));
+    }
+
     static ViewAssertion isHintExpanded(final boolean expanded) {
         return new ViewAssertion() {
             @Override
@@ -517,4 +540,20 @@
             }
         };
     }
+
+    static ViewAssertion isPasswordToggledVisible(final boolean isToggledVisible) {
+        return new ViewAssertion() {
+            @Override
+            public void check(View view, NoMatchingViewException noViewFoundException) {
+                assertTrue(view instanceof TextInputLayout);
+                EditText editText = ((TextInputLayout) view).getEditText();
+                TransformationMethod transformationMethod = editText.getTransformationMethod();
+                if (isToggledVisible) {
+                    assertNull(transformationMethod);
+                } else {
+                    assertEquals(PasswordTransformationMethod.getInstance(), transformationMethod);
+                }
+            }
+        };
+    }
 }
diff --git a/development/refaster/IsAtLeastO.java b/development/refaster/IsAtLeastO.java
new file mode 100644
index 0000000..9198441
--- /dev/null
+++ b/development/refaster/IsAtLeastO.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+import android.os.Build.VERSION;
+import android.support.v4.os.BuildCompat;
+
+import com.google.errorprone.refaster.annotation.AfterTemplate;
+import com.google.errorprone.refaster.annotation.AlsoNegation;
+import com.google.errorprone.refaster.annotation.BeforeTemplate;
+
+/**
+ * Replace usages of BuildCompat.isAtLeastO() with SDK_INT check.
+ */
+public class IsAtLeastO {
+    @BeforeTemplate
+    boolean usingAtLeastO() {
+        return BuildCompat.isAtLeastO();
+    }
+
+    @AfterTemplate
+    @AlsoNegation
+    boolean optimizedMethod() {
+        return VERSION.SDK_INT >= 26;
+    }
+}
diff --git a/development/refaster/README b/development/refaster/README
new file mode 100644
index 0000000..daf8f0d
--- /dev/null
+++ b/development/refaster/README
@@ -0,0 +1,25 @@
+Author: aurimas@google.com
+Updated: 6/6/2017
+
+Instructions on how to compile and apply refaster rules to support library
+
+0. Download error-prone and refaster jars
+http://errorprone.info/docs/refaster will have up to date instructions
+
+1. Compile the refaster rule (in this example IsAtLeastO.java)
+java -cp /path/to/android.jar:/path/to/support-compat.jar:javac-9-dev-r3297-4.jar:error_prone_refaster-2.0.18.jar com.google.errorprone.refaster.RefasterRuleCompiler IsAtLeastO.java --out `pwd`/myrule.refaster
+
+2. Update build to use the refaster rule
+Add compiler args to error-prone in SupportLibraryPlugin.groovy
+'-XepPatchChecks:refaster:/path/to/refaster/myrule.refaster',
+'-XepPatchLocation:' + project.projectDir
+
+3. Compile support library using the refaster rule
+./gradlew assembleErrorProne
+
+4. Apply patches
+error-prone will produce patch files like "design/error-prone.patch" and to apply them, cd into the
+directory e.g. "design" and then run:
+patch -p0 -u -i error-prone.patch
+
+5. Rules have been applied! Celebrate!
\ No newline at end of file
diff --git a/dynamic-animation/build.gradle b/dynamic-animation/build.gradle
index a84e872..d51c8b9 100644
--- a/dynamic-animation/build.gradle
+++ b/dynamic-animation/build.gradle
@@ -2,17 +2,16 @@
 archivesBaseName = 'support-dynamic-animation'
 
 dependencies {
-    compile project(':support-core-utils')
+    api project(':support-core-utils')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/dynamic-animation/lint-baseline.xml b/dynamic-animation/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/dynamic-animation/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/dynamic-animation/src/android/support/animation/DynamicAnimation.java b/dynamic-animation/src/android/support/animation/DynamicAnimation.java
index 18b7d60..8ea48b9 100644
--- a/dynamic-animation/src/android/support/animation/DynamicAnimation.java
+++ b/dynamic-animation/src/android/support/animation/DynamicAnimation.java
@@ -380,7 +380,8 @@
     }
 
     /**
-     * Start velocity of the animation. Default velocity is 0. Unit: pixel/second
+     * Start velocity of the animation. Default velocity is 0. Unit: change in property per
+     * second (e.g. pixels per second, scale/alpha value change per second).
      *
      * <p>Note when using a fixed value as the start velocity (as opposed to getting the velocity
      * through touch events), it is recommended to define such a value in dp/second and convert it
@@ -393,7 +394,7 @@
      *         getResources().getDisplayMetrics());
      * </pre>
      *
-     * @param startVelocity start velocity of the animation in pixel/second
+     * @param startVelocity start velocity of the animation
      * @return the Animation whose start velocity is being set
      */
     public T setStartVelocity(float startVelocity) {
diff --git a/dynamic-animation/tests/AndroidManifest.xml b/dynamic-animation/tests/AndroidManifest.xml
index 2703ffc..79b4331 100755
--- a/dynamic-animation/tests/AndroidManifest.xml
+++ b/dynamic-animation/tests/AndroidManifest.xml
@@ -15,15 +15,10 @@
   limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.animation.test">
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
-    <uses-sdk
-        android:minSdkVersion="16"
-        android:targetSdkVersion="23"/>
     <application android:supportsRtl="true">
-        <uses-library android:name="android.test.runner"/>
-
         <activity android:name="android.support.dynamicanimation.tests.AnimationActivity"/>
     </application>
 </manifest>
diff --git a/dynamic-animation/tests/src/android/support/dynamicanimation/tests/SpringTests.java b/dynamic-animation/tests/src/android/support/dynamicanimation/tests/SpringTests.java
index eb4eb5f..1e891eb 100644
--- a/dynamic-animation/tests/src/android/support/dynamicanimation/tests/SpringTests.java
+++ b/dynamic-animation/tests/src/android/support/dynamicanimation/tests/SpringTests.java
@@ -641,8 +641,6 @@
             }
         });
 
-        View mockView = mock(View.class);
-
         final SpringAnimation[] anims = new SpringAnimation[properties.length];
         final DynamicAnimation.OnAnimationUpdateListener[] mockListeners =
                 new DynamicAnimation.OnAnimationUpdateListener[properties.length];
diff --git a/emoji/appcompat/build.gradle b/emoji/appcompat/build.gradle
index 0a28690..b95842e 100644
--- a/emoji/appcompat/build.gradle
+++ b/emoji/appcompat/build.gradle
@@ -18,19 +18,18 @@
 archivesBaseName = 'support-emoji-appcompat'
 
 dependencies {
-    compile fileTree(include: ['*.jar'], dir: 'libs')
-    compile project(':support-emoji')
-    compile project(':support-appcompat-v7')
+    api fileTree(include: ['*.jar'], dir: 'libs')
+    api project(':support-emoji')
+    api project(':support-appcompat-v7')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/emoji/appcompat/lint-baseline.xml b/emoji/appcompat/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/emoji/appcompat/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatButton.java b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatButton.java
index 8de7ae8..b9e6df0 100644
--- a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatButton.java
+++ b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatButton.java
@@ -27,6 +27,11 @@
  */
 public class EmojiAppCompatButton extends AppCompatButton {
     private EmojiTextViewHelper mEmojiTextViewHelper;
+
+    /**
+     * Prevent calling {@link #init()} multiple times in case super() constructors
+     * call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiAppCompatButton(Context context) {
diff --git a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatEditText.java b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatEditText.java
index 94224a2..87c17c2 100644
--- a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatEditText.java
+++ b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatEditText.java
@@ -29,9 +29,16 @@
  * AppCompatEditText widget enhanced with emoji capability by using {@link EmojiEditTextHelper}.
  * When used on devices running API 18 or below, this widget acts as a regular
  * {@link AppCompatEditText}.
+ *
+ * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
  */
 public class EmojiAppCompatEditText extends AppCompatEditText {
     private EmojiEditTextHelper mEmojiEditTextHelper;
+
+    /**
+     * Prevent calling {@link #init(AttributeSet, int)} multiple times in case super() constructors
+     * call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiAppCompatEditText(Context context) {
@@ -53,7 +60,7 @@
         if (!mInitialized) {
             mInitialized = true;
             final EditTextAttributeHelper attrHelper = new EditTextAttributeHelper(this, attrs,
-                    defStyleAttr);
+                    defStyleAttr, 0);
             setMaxEmojiCount(attrHelper.getMaxEmojiCount());
             setKeyListener(super.getKeyListener());
         }
@@ -79,6 +86,8 @@
      *                      should be equal or greater than 0
      *
      * @see EmojiCompat#process(CharSequence, int, int, int)
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
      */
     public void setMaxEmojiCount(@IntRange(from = 0) int maxEmojiCount) {
         getEmojiEditTextHelper().setMaxEmojiCount(maxEmojiCount);
@@ -89,6 +98,8 @@
      *
      * @see #setMaxEmojiCount(int)
      * @see EmojiCompat#process(CharSequence, int, int, int)
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
      */
     public int getMaxEmojiCount() {
         return getEmojiEditTextHelper().getMaxEmojiCount();
diff --git a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatTextView.java b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatTextView.java
index 744db0a..262cc07 100644
--- a/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatTextView.java
+++ b/emoji/appcompat/src/android/support/text/emoji/widget/EmojiAppCompatTextView.java
@@ -28,6 +28,11 @@
  */
 public class EmojiAppCompatTextView extends AppCompatTextView {
     private EmojiTextViewHelper mEmojiTextViewHelper;
+
+    /**
+     * Prevent calling {@link #init()} multiple times in case super() constructors
+     * call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiAppCompatTextView(Context context) {
diff --git a/emoji/bundled/build.gradle b/emoji/bundled/build.gradle
index 05fb17f..34a644f 100644
--- a/emoji/bundled/build.gradle
+++ b/emoji/bundled/build.gradle
@@ -19,7 +19,7 @@
 }
 
 dependencies {
-    compile project(path: ':support-emoji')
+    api project(':support-emoji')
 }
 
 supportLibrary {
diff --git a/emoji/bundled/lint-baseline.xml b/emoji/bundled/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/emoji/bundled/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/emoji/bundled/src/android/support/text/emoji/bundled/BundledEmojiCompatConfig.java b/emoji/bundled/src/android/support/text/emoji/bundled/BundledEmojiCompatConfig.java
index 37fc444..97ea363 100644
--- a/emoji/bundled/src/android/support/text/emoji/bundled/BundledEmojiCompatConfig.java
+++ b/emoji/bundled/src/android/support/text/emoji/bundled/BundledEmojiCompatConfig.java
@@ -43,7 +43,7 @@
         super(new BundledMetadataLoader(context));
     }
 
-    private static class BundledMetadataLoader implements EmojiCompat.MetadataLoader {
+    private static class BundledMetadataLoader implements EmojiCompat.MetadataRepoLoader {
         private final Context mContext;
 
         private BundledMetadataLoader(@NonNull Context context) {
@@ -52,7 +52,7 @@
 
         @Override
         @RequiresApi(19)
-        public void load(@NonNull EmojiCompat.LoaderCallback loaderCallback) {
+        public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
             Preconditions.checkNotNull(loaderCallback, "loaderCallback cannot be null");
             final InitRunnable runnable = new InitRunnable(mContext, loaderCallback);
             final Thread thread = new Thread(runnable);
@@ -64,11 +64,11 @@
     @RequiresApi(19)
     private static class InitRunnable implements Runnable {
         private static final String FONT_NAME = "NotoColorEmojiCompat.ttf";
-        private final EmojiCompat.LoaderCallback mLoaderCallback;
+        private final EmojiCompat.MetadataRepoLoaderCallback mLoaderCallback;
         private final Context mContext;
 
         private InitRunnable(final Context context,
-                final EmojiCompat.LoaderCallback loaderCallback) {
+                final EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
             mContext = context;
             mLoaderCallback = loaderCallback;
         }
diff --git a/emoji/core/build.gradle b/emoji/core/build.gradle
index 1488c0e..e71c16c 100644
--- a/emoji/core/build.gradle
+++ b/emoji/core/build.gradle
@@ -5,21 +5,27 @@
     fontDir = project(':noto-emoji-compat').projectDir
 }
 
-evaluationDependsOn(':noto-emoji-compat')
-dependencies {
-    compile project(':support-compat')
-    compile files(project(':noto-emoji-compat').configurations.parser.artifacts.getFiles())
+configurations {
+    repackage
+}
 
-    androidTestCompile (libs.test_runner) {
+dependencies {
+    repackage project(path: ':noto-emoji-compat', configuration: "parser")
+    // Wrap the noto-emoji-compat dependency in a FileCollection so that the Android Gradle plugin
+    // treats this as local jar and package it inside the aar.
+    api files(configurations.repackage)
+
+    api project(':support-compat')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(path: ':support-testutils')
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
diff --git a/emoji/core/lint-baseline.xml b/emoji/core/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/emoji/core/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/emoji/core/res-public/values/public_attrs.xml b/emoji/core/res-public/values/public_attrs.xml
index 56f49ff..56634ff 100644
--- a/emoji/core/res-public/values/public_attrs.xml
+++ b/emoji/core/res-public/values/public_attrs.xml
@@ -18,4 +18,5 @@
 <!-- Definitions of attributes to be exposed as public -->
 <resources>
     <public type="attr" name="maxEmojiCount"/>
+    <public type="attr" name="emojiReplaceStrategy"/>
 </resources>
diff --git a/emoji/core/res/layout/input_method_extract_view.xml b/emoji/core/res/layout/input_method_extract_view.xml
new file mode 100644
index 0000000..7eb3d1c
--- /dev/null
+++ b/emoji/core/res/layout/input_method_extract_view.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<merge
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <android.support.text.emoji.widget.EmojiExtractEditText
+        android:id="@+id/android:inputExtractEditText"
+        android:layout_width="0px"
+        android:layout_height="match_parent"
+        android:layout_weight="1"
+        android:gravity="top"
+        android:inputType="text"
+        android:minLines="1"
+        android:scrollbars="vertical"/>
+
+    <FrameLayout
+        android:id="@+id/inputExtractAccessories"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:paddingEnd="8dip"
+        android:paddingStart="8dip">
+
+        <android.support.text.emoji.widget.ExtractButtonCompat
+            android:id="@+id/inputExtractAction"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center"/>
+
+    </FrameLayout>
+
+</merge>
\ No newline at end of file
diff --git a/emoji/core/res/values/attrs.xml b/emoji/core/res/values/attrs.xml
index d34bb7c..77254a4 100644
--- a/emoji/core/res/values/attrs.xml
+++ b/emoji/core/res/values/attrs.xml
@@ -18,4 +18,16 @@
     <declare-styleable name="EmojiEditText">
         <attr name="maxEmojiCount" format="integer"/>
     </declare-styleable>
+    <declare-styleable name="EmojiExtractTextLayout">
+        <attr name="emojiReplaceStrategy" format="enum">
+            <!-- Replace strategy that uses the value given in EmojiCompat.Config. Default
+            value. -->
+            <enum name="defaultStrategy" value="0" />
+            <!-- Replace strategy to add EmojiSpans for all emoji that were found. -->
+            <enum name="all" value="1" />
+            <!-- Replace strategy to add EmojiSpans only for emoji that do not exist in the
+            system. -->
+            <enum name="nonExistent" value="2" />
+        </attr>
+    </declare-styleable>
 </resources>
diff --git a/emoji/core/src/android/support/text/emoji/EmojiCompat.java b/emoji/core/src/android/support/text/emoji/EmojiCompat.java
index 5d816e5..f258c12 100644
--- a/emoji/core/src/android/support/text/emoji/EmojiCompat.java
+++ b/emoji/core/src/android/support/text/emoji/EmojiCompat.java
@@ -105,24 +105,12 @@
     public static final int LOAD_STATE_SUCCEEDED = 1;
 
     /**
-     * @deprecated Use {@link #LOAD_STATE_SUCCEEDED} instead.
-     */
-    @Deprecated
-    public static final int LOAD_STATE_SUCCESS = 1;
-
-    /**
      * An unrecoverable error occurred during initialization of EmojiCompat. Calls to functions
      * such as {@link #process(CharSequence)} will fail.
      */
     public static final int LOAD_STATE_FAILED = 2;
 
     /**
-     * @deprecated Use {@link #LOAD_STATE_FAILED} instead.
-     */
-    @Deprecated
-    public static final int LOAD_STATE_FAILURE = 2;
-
-    /**
      * @hide
      */
     @RestrictTo(LIBRARY_GROUP)
@@ -155,6 +143,12 @@
     public @interface ReplaceStrategy {
     }
 
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    static final int EMOJI_COUNT_UNLIMITED = Integer.MAX_VALUE;
+
     private static final Object sInstanceLock = new Object();
 
     @GuardedBy("sInstanceLock")
@@ -180,9 +174,9 @@
     private final CompatInternal mHelper;
 
     /**
-     * MetadataLoader instance given in the Config instance.
+     * Metadata loader instance given in the Config instance.
      */
-    private final MetadataLoader mMetadataLoader;
+    private final MetadataRepoLoader mMetadataLoader;
 
     /**
      * @see Config#setReplaceAll(boolean)
@@ -525,6 +519,7 @@
         // since charSequence might be null here we have to check it. Passing through here to the
         // main function so that it can do all the checks including isInitialized. It will also
         // be the main point that decides what to return.
+        //noinspection ConstantConditions
         @IntRange(from = 0) final int length = charSequence == null ? 0 : charSequence.length();
         return process(charSequence, 0, length);
     }
@@ -558,7 +553,7 @@
     @CheckResult
     public CharSequence process(@NonNull final CharSequence charSequence,
             @IntRange(from = 0) final int start, @IntRange(from = 0) final int end) {
-        return process(charSequence, start, end, EmojiProcessor.EMOJI_COUNT_UNLIMITED);
+        return process(charSequence, start, end, EMOJI_COUNT_UNLIMITED);
     }
 
     /**
@@ -641,6 +636,7 @@
         Preconditions.checkArgument(start <= end, "start should be <= than end");
 
         // early return since there is nothing to do
+        //noinspection ConstantConditions
         if (charSequence == null) {
             return charSequence;
         }
@@ -673,6 +669,19 @@
     }
 
     /**
+     * Returns signature for the currently loaded emoji assets. The signature is a SHA that is
+     * constructed using emoji assets. Can be used to detect if currently loaded asset is different
+     * then previous executions. When used on devices running API 18 or below, returns empty string.
+     *
+     * @throws IllegalStateException if not initialized yet
+     */
+    @NonNull
+    public String getAssetSignature() {
+        Preconditions.checkState(isInitialized(), "Not initialized yet");
+        return mHelper.getAssetSignature();
+    }
+
+    /**
      * Updates the EditorInfo attributes in order to communicate information to Keyboards. When
      * used on devices running API 18 or below, does not update EditorInfo attributes.
      *
@@ -686,6 +695,7 @@
      */
     @RestrictTo(LIBRARY_GROUP)
     public void updateEditorInfoAttrs(@NonNull final EditorInfo outAttrs) {
+        //noinspection ConstantConditions
         if (isInitialized() && outAttrs != null && outAttrs.extras != null) {
             mHelper.updateEditorInfoAttrs(outAttrs);
         }
@@ -733,32 +743,32 @@
     /**
      * Interface to load emoji metadata.
      */
-    public interface MetadataLoader {
+    public interface MetadataRepoLoader {
         /**
          * Start loading the metadata. When the loading operation is finished {@link
-         * LoaderCallback#onLoaded(MetadataRepo)} or {@link LoaderCallback#onFailed(Throwable)}
-         * should be called. When used on devices running API 18 or below, this function is never
-         * called.
+         * MetadataRepoLoaderCallback#onLoaded(MetadataRepo)} or
+         * {@link MetadataRepoLoaderCallback#onFailed(Throwable)} should be called. When used on
+         * devices running API 18 or below, this function is never called.
          *
          * @param loaderCallback callback to signal the loading state
          */
-        void load(@NonNull LoaderCallback loaderCallback);
+        void load(@NonNull MetadataRepoLoaderCallback loaderCallback);
     }
 
     /**
-     * Callback to inform EmojiCompat about the state of the metadata load. Passed to MetadataLoader
-     * during {@link MetadataLoader#load(LoaderCallback)} call.
+     * Callback to inform EmojiCompat about the state of the metadata load. Passed to
+     * MetadataRepoLoader during {@link MetadataRepoLoader#load(MetadataRepoLoaderCallback)} call.
      */
-    public abstract static class LoaderCallback {
+    public abstract static class MetadataRepoLoaderCallback {
         /**
-         * Called by {@link MetadataLoader} when metadata is loaded successfully.
+         * Called by {@link MetadataRepoLoader} when metadata is loaded successfully.
          *
          * @param metadataRepo MetadataRepo instance, cannot be {@code null}
          */
         public abstract void onLoaded(@NonNull MetadataRepo metadataRepo);
 
         /**
-         * Called by {@link MetadataLoader} if an error occurs while loading the metadata.
+         * Called by {@link MetadataRepoLoader} if an error occurs while loading the metadata.
          *
          * @param throwable the exception that caused the failure, {@code nullable}
          */
@@ -772,7 +782,7 @@
      * @see #init(EmojiCompat.Config)
      */
     public abstract static class Config {
-        private final MetadataLoader mMetadataLoader;
+        private final MetadataRepoLoader mMetadataLoader;
         private boolean mReplaceAll;
         private Set<InitCallback> mInitCallbacks;
         private boolean mEmojiSpanIndicatorEnabled;
@@ -781,9 +791,9 @@
         /**
          * Default constructor.
          *
-         * @param metadataLoader MetadataLoader instance, cannot be {@code null}
+         * @param metadataLoader MetadataRepoLoader instance, cannot be {@code null}
          */
-        protected Config(@NonNull final MetadataLoader metadataLoader) {
+        protected Config(@NonNull final MetadataRepoLoader metadataLoader) {
             Preconditions.checkNotNull(metadataLoader, "metadataLoader cannot be null.");
             mMetadataLoader = metadataLoader;
         }
@@ -860,11 +870,9 @@
         }
 
         /**
-         * Returns the {@link MetadataLoader}.
-         * @hide
+         * Returns the {@link MetadataRepoLoader}.
          */
-        @RestrictTo(LIBRARY_GROUP)
-        public final MetadataLoader getMetadataLoader() {
+        protected final MetadataRepoLoader getMetadataRepoLoader() {
             return mMetadataLoader;
         }
     }
@@ -877,6 +885,7 @@
         private final Throwable mThrowable;
         private final int mLoadState;
 
+        @SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
         ListenerDispatcher(@NonNull final InitCallback initCallback,
                 @LoadState final int loadState) {
             this(Arrays.asList(Preconditions.checkNotNull(initCallback,
@@ -920,7 +929,7 @@
      * Internal helper class to behave no-op for certain functions.
      */
     private static class CompatInternal {
-        protected final EmojiCompat mEmojiCompat;
+        final EmojiCompat mEmojiCompat;
 
         CompatInternal(EmojiCompat emojiCompat) {
             mEmojiCompat = emojiCompat;
@@ -955,10 +964,14 @@
         void setGlyphChecker(@NonNull EmojiProcessor.GlyphChecker glyphChecker) {
             // intentionally empty
         }
+
+        String getAssetSignature() {
+            return "";
+        }
     }
 
     @RequiresApi(19)
-    private static class CompatInternal19 extends CompatInternal {
+    private static final class CompatInternal19 extends CompatInternal {
         /**
          * Responsible to process a CharSequence and add the spans. @{code Null} until the time the
          * metadata is loaded.
@@ -978,7 +991,7 @@
         @Override
         void loadMetadata() {
             try {
-                mEmojiCompat.mMetadataLoader.load(new LoaderCallback() {
+                final MetadataRepoLoaderCallback callback = new MetadataRepoLoaderCallback() {
                     @Override
                     public void onLoaded(@NonNull MetadataRepo metadataRepo) {
                         onMetadataLoadSuccess(metadataRepo);
@@ -988,13 +1001,15 @@
                     public void onFailed(@Nullable Throwable throwable) {
                         mEmojiCompat.onMetadataLoadFailed(throwable);
                     }
-                });
+                };
+                mEmojiCompat.mMetadataLoader.load(callback);
             } catch (Throwable t) {
                 mEmojiCompat.onMetadataLoadFailed(t);
             }
         }
 
         private void onMetadataLoadSuccess(@NonNull final MetadataRepo metadataRepo) {
+            //noinspection ConstantConditions
             if (metadataRepo == null) {
                 mEmojiCompat.onMetadataLoadFailed(
                         new IllegalArgumentException("metadataRepo cannot be null"));
@@ -1034,5 +1049,11 @@
         void setGlyphChecker(@NonNull EmojiProcessor.GlyphChecker glyphChecker) {
             mProcessor.setGlyphChecker(glyphChecker);
         }
+
+        @Override
+        String getAssetSignature() {
+            final String sha = mMetadataRepo.getMetadataList().sourceSha();
+            return sha == null ? "" : sha;
+        }
     }
 }
diff --git a/emoji/core/src/android/support/text/emoji/EmojiProcessor.java b/emoji/core/src/android/support/text/emoji/EmojiProcessor.java
index f168e59..da54754 100644
--- a/emoji/core/src/android/support/text/emoji/EmojiProcessor.java
+++ b/emoji/core/src/android/support/text/emoji/EmojiProcessor.java
@@ -56,7 +56,7 @@
      */
     @IntDef({ACTION_ADVANCE_BOTH, ACTION_ADVANCE_END, ACTION_FLUSH})
     @Retention(RetentionPolicy.SOURCE)
-    @interface Action {
+    private @interface Action {
     }
 
     /**
@@ -76,12 +76,6 @@
     private static final int ACTION_FLUSH = 3;
 
     /**
-     * @hide
-     */
-    @RestrictTo(LIBRARY_GROUP)
-    static final int EMOJI_COUNT_UNLIMITED = Integer.MAX_VALUE;
-
-    /**
      * Factory used to create EmojiSpans.
      */
     private final EmojiCompat.SpanFactory mSpanFactory;
@@ -190,7 +184,7 @@
 
             // calculate max number of emojis that can be added. since getSpans call is a relatively
             // expensive operation, do it only when maxEmojiCount is not unlimited.
-            if (maxEmojiCount != EMOJI_COUNT_UNLIMITED && spannable != null) {
+            if (maxEmojiCount != EmojiCompat.EMOJI_COUNT_UNLIMITED && spannable != null) {
                 maxEmojiCount -= spannable.getSpans(0, spannable.length(), EmojiSpan.class).length;
             }
             // add new ones
@@ -344,6 +338,7 @@
     static boolean handleDeleteSurroundingText(@NonNull final InputConnection inputConnection,
             @NonNull final Editable editable, @IntRange(from = 0) final int beforeLength,
             @IntRange(from = 0) final int afterLength, final boolean inCodePoints) {
+        //noinspection ConstantConditions
         if (editable == null || inputConnection == null) {
             return false;
         }
diff --git a/emoji/core/src/android/support/text/emoji/FontRequestEmojiCompatConfig.java b/emoji/core/src/android/support/text/emoji/FontRequestEmojiCompatConfig.java
index ae7cd14..05f367c 100644
--- a/emoji/core/src/android/support/text/emoji/FontRequestEmojiCompatConfig.java
+++ b/emoji/core/src/android/support/text/emoji/FontRequestEmojiCompatConfig.java
@@ -16,27 +16,27 @@
 
 package android.support.text.emoji;
 
-import android.content.ContentResolver;
 import android.content.Context;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.database.ContentObserver;
 import android.graphics.Typeface;
 import android.net.Uri;
-import android.os.ParcelFileDescriptor;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Process;
+import android.os.SystemClock;
+import android.support.annotation.GuardedBy;
 import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
-import android.support.v4.graphics.TypefaceCompat;
+import android.support.v4.graphics.TypefaceCompatUtil;
 import android.support.v4.provider.FontRequest;
 import android.support.v4.provider.FontsContractCompat;
 import android.support.v4.provider.FontsContractCompat.FontFamilyResult;
-import android.support.v4.provider.FontsContractCompat.FontInfo;
-import android.support.v4.util.ArrayMap;
 import android.support.v4.util.Preconditions;
 
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
 
 /**
  * {@link EmojiCompat.Config} implementation that asynchronously fetches the required font and the
@@ -45,6 +45,72 @@
  * <p/>
  */
 public class FontRequestEmojiCompatConfig extends EmojiCompat.Config {
+
+    /**
+     * Retry policy used when the font provider is not ready to give the font file.
+     *
+     * To control the thread the retries are handled on, see
+     * {@link FontRequestEmojiCompatConfig#setHandler}.
+     */
+    public abstract static class RetryPolicy {
+        /**
+         * Called each time the metadata loading fails.
+         *
+         * This is primarily due to a pending download of the font.
+         * If a value larger than zero is returned, metadata loader will retry after the given
+         * milliseconds.
+         * <br />
+         * If {@code zero} is returned, metadata loader will retry immediately.
+         * <br/>
+         * If a value less than 0 is returned, the metadata loader will stop retrying and
+         * EmojiCompat will get into {@link EmojiCompat#LOAD_STATE_FAILED} state.
+         * <p/>
+         * Note that the retry may happen earlier than you specified if the font provider notifies
+         * that the download is completed.
+         *
+         * @return long milliseconds to wait until next retry
+         */
+        public abstract long getRetryDelay();
+    }
+
+    /**
+     * A retry policy implementation that doubles the amount of time in between retries.
+     *
+     * If downloading hasn't finish within given amount of time, this policy give up and the
+     * EmojiCompat will get into {@link EmojiCompat#LOAD_STATE_FAILED} state.
+     */
+    public static class ExponentialBackoffRetryPolicy extends RetryPolicy {
+        private final long mTotalMs;
+        private long mRetryOrigin;
+
+        /**
+         * @param totalMs A total amount of time to wait in milliseconds.
+         */
+        public ExponentialBackoffRetryPolicy(long totalMs) {
+            mTotalMs = totalMs;
+        }
+
+        @Override
+        public long getRetryDelay() {
+            if (mRetryOrigin == 0) {
+                mRetryOrigin = SystemClock.uptimeMillis();
+                // Since download may be completed after getting query result and before registering
+                // observer, requesting later at the same time.
+                return 0;
+            } else {
+                // Retry periodically since we can't trust notify change event. Some font provider
+                // may not notify us.
+                final long elapsedMillis = SystemClock.uptimeMillis() - mRetryOrigin;
+                if (elapsedMillis > mTotalMs) {
+                    return -1;  // Give up since download hasn't finished in 10 min.
+                }
+                // Wait until the same amount of the time from the first scheduled time, but adjust
+                // the minimum request interval is 1 sec and never exceeds 10 min in total.
+                return Math.min(Math.max(elapsedMillis, 1000), mTotalMs - elapsedMillis);
+            }
+        }
+    };
+
     /**
      * @param context Context instance, cannot be {@code null}
      * @param request {@link FontRequest} to fetch the font asynchronously, cannot be {@code null}
@@ -58,112 +124,202 @@
      */
     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
     public FontRequestEmojiCompatConfig(@NonNull Context context, @NonNull FontRequest request,
-            @NonNull FontsContractDelegate fontsContract) {
-        super(new FontRequestMetadataLoader(context, request, fontsContract));
+            @NonNull FontProviderHelper fontProviderHelper) {
+        super(new FontRequestMetadataLoader(context, request, fontProviderHelper));
     }
 
+    /**
+     * Sets the custom handler to be used for initialization.
+     *
+     * Since font fetch take longer time, the metadata loader will fetch the fonts on the background
+     * thread. You can pass your own handler for this background fetching. This handler is also used
+     * for retrying.
+     *
+     * @param handler A {@link Handler} to be used for initialization. Can be {@code null}. In case
+     *               of {@code null}, the metadata loader creates own {@link HandlerThread} for
+     *               initialization.
+     */
+    public FontRequestEmojiCompatConfig setHandler(Handler handler) {
+        ((FontRequestMetadataLoader) getMetadataRepoLoader()).setHandler(handler);
+        return this;
+    }
 
     /**
-     * MetadataLoader implementation that uses FontsContractCompat and TypefaceCompat to load a
+     * Sets the retry policy.
+     *
+     * {@see RetryPolicy}
+     * @param policy The policy to be used when the font provider is not ready to give the font
+     *              file. Can be {@code null}. In case of {@code null}, the metadata loader never
+     *              retries.
+     */
+    public FontRequestEmojiCompatConfig setRetryPolicy(RetryPolicy policy) {
+        ((FontRequestMetadataLoader) getMetadataRepoLoader()).setRetryPolicy(policy);
+        return this;
+    }
+
+    /**
+     * MetadataRepoLoader implementation that uses FontsContractCompat and TypefaceCompat to load a
      * given FontRequest.
      */
-    private static class FontRequestMetadataLoader implements EmojiCompat.MetadataLoader {
+    private static class FontRequestMetadataLoader implements EmojiCompat.MetadataRepoLoader {
         private final Context mContext;
         private final FontRequest mRequest;
-        private final FontsContractDelegate mFontsContract;
+        private final FontProviderHelper mFontProviderHelper;
+
+        private final Object mLock = new Object();
+        @GuardedBy("mLock")
+        private Handler mHandler;
+        @GuardedBy("mLock")
+        private HandlerThread mThread;
+        @GuardedBy("mLock")
+        private @Nullable RetryPolicy mRetryPolicy;
+
+        // Following three variables must be touched only on the thread associated with mHandler.
+        private EmojiCompat.MetadataRepoLoaderCallback mCallback;
+        private ContentObserver mObserver;
+        private Runnable mHandleMetadataCreationRunner;
 
         FontRequestMetadataLoader(@NonNull Context context, @NonNull FontRequest request,
-                @NonNull FontsContractDelegate fontsContract) {
+                @NonNull FontProviderHelper fontProviderHelper) {
             Preconditions.checkNotNull(context, "Context cannot be null");
             Preconditions.checkNotNull(request, "FontRequest cannot be null");
             mContext = context.getApplicationContext();
             mRequest = request;
-            mFontsContract = fontsContract;
+            mFontProviderHelper = fontProviderHelper;
+        }
+
+        public void setHandler(Handler handler) {
+            synchronized (mLock) {
+                mHandler = handler;
+            }
+        }
+
+        public void setRetryPolicy(RetryPolicy policy) {
+            synchronized (mLock) {
+                mRetryPolicy = policy;
+            }
         }
 
         @Override
         @RequiresApi(19)
-        public void load(@NonNull final EmojiCompat.LoaderCallback loaderCallback) {
+        public void load(@NonNull final EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
             Preconditions.checkNotNull(loaderCallback, "LoaderCallback cannot be null");
-            final InitRunnable runnable =
-                    new InitRunnable(mContext, mRequest, mFontsContract, loaderCallback);
-            final Thread thread = new Thread(runnable);
-            thread.setDaemon(false);
-            thread.start();
-        }
-    }
-
-    /**
-     * Runnable used to create the Typeface and MetadataRepo from a given FontResult.
-     */
-    @RequiresApi(19)
-    private static class InitRunnable implements Runnable {
-        private final EmojiCompat.LoaderCallback mLoaderCallback;
-        private final Context mContext;
-        private final FontsContractDelegate mFontsContract;
-        private final FontRequest mFontRequest;
-
-        private InitRunnable(final Context context,
-                final FontRequest fontRequest,
-                final FontsContractDelegate fontsContract,
-                final EmojiCompat.LoaderCallback loaderCallback) {
-            mContext = context;
-            mFontRequest = fontRequest;
-            mFontsContract = fontsContract;
-            mLoaderCallback = loaderCallback;
-        }
-
-        @Override
-        public void run() {
-            try {
-                FontFamilyResult result = null;
-                try {
-                    result = mFontsContract.fetchFonts(mContext, mFontRequest);
-                } catch (NameNotFoundException e) {
-                    throwException("provider not found");
+            synchronized (mLock) {
+                if (mHandler == null) {
+                    // Developer didn't give a thread for fetching. Create our own one.
+                    mThread = new HandlerThread("emojiCompat", Process.THREAD_PRIORITY_BACKGROUND);
+                    mThread.start();
+                    mHandler = new Handler(mThread.getLooper());
                 }
-                if (result.getStatusCode() != FontFamilyResult.STATUS_OK) {
-                    throwException("fetchFonts failed (" + result.getStatusCode() + ")");
-                }
-                final FontInfo[] fonts = result.getFonts();
-                if (fonts == null || fonts.length == 0) {
-                    throwException("fetchFonts failed (empty result)");
-                }
-                // Assuming the GMS Core provides only one font file.
-                final FontInfo font = fonts[0];
-                if (font.getResultCode() != FontsContractCompat.Columns.RESULT_CODE_OK) {
-                    throwException("fetchFonts result is not OK. (" + font.getResultCode() + ")");
-                }
-
-                final ContentResolver resolver = mContext.getContentResolver();
-                ByteBuffer buffer = null;
-                try (ParcelFileDescriptor fd = resolver.openFileDescriptor(font.getUri(), "r");
-                    FileInputStream inputStream = new FileInputStream(fd.getFileDescriptor())) {
-                    final FileChannel fileChannel = inputStream.getChannel();
-                    buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
-                } catch (FileNotFoundException e) {
-                    throwException("Unable to open file.");
-                }
-
-                // TypefaceCompat.buildTypeface opens file descriptor again, so bypass the
-                // FontsContract.prepareFontData and create FontInfo and ByteBuffer directly.
-                final ArrayMap<Uri, ByteBuffer> bufferMap = new ArrayMap<>();
-                bufferMap.put(font.getUri(), buffer.duplicate());
-                final Typeface typeface = TypefaceCompat.createTypeface(mContext,
-                        new FontInfo[] { font }, bufferMap);
-                if (typeface == null) {
-                    throwException("Failed to create Typeface.");
-                }
-
-                mLoaderCallback.onLoaded(MetadataRepo.create(typeface, buffer));
-            } catch (Throwable t) {
-                mLoaderCallback.onFailed(t);
+                mHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        mCallback = loaderCallback;
+                        createMetadata();
+                    }
+                });
             }
         }
-    }
 
-    private static void throwException(String msg) {
-        throw new RuntimeException("Cannot load metadata: " + msg);
+        private FontsContractCompat.FontInfo retrieveFontInfo() {
+            final FontsContractCompat.FontFamilyResult result;
+            try {
+                result = mFontProviderHelper.fetchFonts(mContext, mRequest);
+            } catch (NameNotFoundException e) {
+                throw new RuntimeException("provider not found", e);
+            }
+            if (result.getStatusCode() != FontsContractCompat.FontFamilyResult.STATUS_OK) {
+                throw new RuntimeException("fetchFonts failed (" + result.getStatusCode() + ")");
+            }
+            final FontsContractCompat.FontInfo[] fonts = result.getFonts();
+            if (fonts == null || fonts.length == 0) {
+                throw new RuntimeException("fetchFonts failed (empty result)");
+            }
+            return fonts[0];  // Assuming the GMS Core provides only one font file.
+        }
+
+        // Must be called on the mHandler.
+        @RequiresApi(19)
+        private void scheduleRetry(Uri uri, long waitMs) {
+            synchronized (mLock) {
+                if (mObserver == null) {
+                    mObserver = new ContentObserver(mHandler) {
+                        @Override
+                        public void onChange(boolean selfChange, Uri uri) {
+                            createMetadata();
+                        }
+                    };
+                    mFontProviderHelper.registerObserver(mContext, uri, mObserver);
+                }
+                if (mHandleMetadataCreationRunner == null) {
+                    mHandleMetadataCreationRunner = new Runnable() {
+                        @Override
+                        public void run() {
+                            createMetadata();
+                        }
+                    };
+                }
+                mHandler.postDelayed(mHandleMetadataCreationRunner, waitMs);
+            }
+        }
+
+        // Must be called on the mHandler.
+        private void cleanUp() {
+            mCallback = null;
+            if (mObserver != null) {
+                mFontProviderHelper.unregisterObserver(mContext, mObserver);
+                mObserver = null;
+            }
+            synchronized (mLock) {
+                mHandler.removeCallbacks(mHandleMetadataCreationRunner);
+                if (mThread != null) {
+                    mThread.quit();
+                }
+                mHandler = null;
+                mThread = null;
+            }
+        }
+
+        // Must be called on the mHandler.
+        @RequiresApi(19)
+        private void createMetadata() {
+            if (mCallback == null) {
+                return;  // Already handled or cancelled. Do nothing.
+            }
+            try {
+                final FontsContractCompat.FontInfo font = retrieveFontInfo();
+
+                final int resultCode = font.getResultCode();
+                if (resultCode == FontsContractCompat.Columns.RESULT_CODE_FONT_UNAVAILABLE) {
+                    // The font provider is now downloading. Ask RetryPolicy for when to retry next.
+                    synchronized (mLock) {
+                        if (mRetryPolicy != null) {
+                            final long delayMs = mRetryPolicy.getRetryDelay();
+                            if (delayMs >= 0) {
+                                scheduleRetry(font.getUri(), delayMs);
+                                return;
+                            }
+                        }
+                    }
+                }
+
+                if (resultCode != FontsContractCompat.Columns.RESULT_CODE_OK) {
+                    throw new RuntimeException("fetchFonts result is not OK. (" + resultCode + ")");
+                }
+
+                // TODO: Good to add new API to create Typeface from FD not to open FD twice.
+                final Typeface typeface = mFontProviderHelper.buildTypeface(mContext, font);
+                final ByteBuffer buffer = TypefaceCompatUtil.mmap(mContext, null, font.getUri());
+                if (buffer == null) {
+                    throw new RuntimeException("Unable to open file.");
+                }
+                mCallback.onLoaded(MetadataRepo.create(typeface, buffer));
+                cleanUp();
+            } catch (Throwable t) {
+                mCallback.onFailed(t);
+                cleanUp();
+            }
+        }
     }
 
     /**
@@ -171,14 +327,34 @@
      * @hide
      */
     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
-    public static class FontsContractDelegate {
+    public static class FontProviderHelper {
         /** Calls FontsContractCompat.fetchFonts. */
         public FontFamilyResult fetchFonts(@NonNull Context context,
                 @NonNull FontRequest request) throws NameNotFoundException {
             return FontsContractCompat.fetchFonts(context, null /* cancellation signal */, request);
         }
+
+        /** Calls FontsContractCompat.buildTypeface. */
+        public Typeface buildTypeface(@NonNull Context context,
+                @NonNull FontsContractCompat.FontInfo font) throws NameNotFoundException {
+            return FontsContractCompat.buildTypeface(context, null /* cancellation signal */,
+                new FontsContractCompat.FontInfo[] { font });
+        }
+
+        /** Calls Context.getContentObserver().registerObserver */
+        public void registerObserver(@NonNull Context context, @NonNull Uri uri,
+                @NonNull ContentObserver observer) {
+            context.getContentResolver().registerContentObserver(
+                    uri, false /* notifyForDescendants */, observer);
+
+        }
+        /** Calls Context.getContentObserver().unregisterObserver */
+        public void unregisterObserver(@NonNull Context context,
+                @NonNull ContentObserver observer) {
+            context.getContentResolver().unregisterContentObserver(observer);
+        }
     };
 
-    private static final FontsContractDelegate DEFAULT_FONTS_CONTRACT = new FontsContractDelegate();
+    private static final FontProviderHelper DEFAULT_FONTS_CONTRACT = new FontProviderHelper();
 
 }
diff --git a/emoji/core/src/android/support/text/emoji/MetadataListReader.java b/emoji/core/src/android/support/text/emoji/MetadataListReader.java
index 95af1f0..6034726 100644
--- a/emoji/core/src/android/support/text/emoji/MetadataListReader.java
+++ b/emoji/core/src/android/support/text/emoji/MetadataListReader.java
@@ -182,11 +182,11 @@
         }
     }
 
-    static int toUnsignedShort(final short value) {
+    private static int toUnsignedShort(final short value) {
         return value & 0xFFFF;
     }
 
-    static long toUnsignedInt(final int value) {
+    private static long toUnsignedInt(final int value) {
         return value & 0xFFFFFFFFL;
     }
 
diff --git a/emoji/core/src/android/support/text/emoji/MetadataRepo.java b/emoji/core/src/android/support/text/emoji/MetadataRepo.java
index e6a5eea..e86277e 100644
--- a/emoji/core/src/android/support/text/emoji/MetadataRepo.java
+++ b/emoji/core/src/android/support/text/emoji/MetadataRepo.java
@@ -49,7 +49,8 @@
     private final MetadataList mMetadataList;
 
     /**
-     * char presentation of all EmojiMetadata's in a single array.
+     * char presentation of all EmojiMetadata's in a single array. All emojis we have are mapped to
+     * Private Use Area A, in the range U+F0000..U+FFFFD. Therefore each emoji takes 2 chars.
      */
     private final char[] mEmojiCharArray;
 
@@ -135,6 +136,9 @@
         int length = metadataList.listLength();
         for (int i = 0; i < length; i++) {
             final EmojiMetadata metadata = new EmojiMetadata(this, i);
+            //since all emojis are mapped to a single codepoint in Private Use Area A they are 2
+            //chars wide
+            //noinspection ResultOfMethodCallIgnored
             Character.toChars(metadata.getId(), mEmojiCharArray, i * 2);
             put(metadata);
         }
@@ -203,10 +207,11 @@
      */
     @RestrictTo(LIBRARY_GROUP)
     static class Node {
-        private SparseArray<Node> mChildren;
+        private final SparseArray<Node> mChildren;
         private EmojiMetadata mData;
 
         private Node() {
+            this(1);
         }
 
         private Node(final int defaultChildrenSize) {
@@ -224,9 +229,6 @@
         private void put(@NonNull final EmojiMetadata data, final int start, final int end) {
             Node node = get(data.getCodepointAt(start));
             if (node == null) {
-                if (mChildren == null) {
-                    mChildren = new SparseArray<>(1);
-                }
                 node = new Node();
                 mChildren.put(data.getCodepointAt(start), node);
             }
diff --git a/emoji/core/src/android/support/text/emoji/widget/EditTextAttributeHelper.java b/emoji/core/src/android/support/text/emoji/widget/EditTextAttributeHelper.java
index 49cd7c8..381a02c 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EditTextAttributeHelper.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EditTextAttributeHelper.java
@@ -33,16 +33,16 @@
  */
 @RestrictTo(LIBRARY_GROUP)
 public class EditTextAttributeHelper {
-
+    static final int MAX_EMOJI_COUNT = Integer.MAX_VALUE;
     private int mMaxEmojiCount;
 
-    public EditTextAttributeHelper(@NonNull View view, AttributeSet attrs, int defStyleAttr) {
-        if (view != null && attrs != null) {
+    public EditTextAttributeHelper(@NonNull View view, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        if (attrs != null) {
             final Context context = view.getContext();
             TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EmojiEditText,
-                    defStyleAttr, 0);
-            mMaxEmojiCount = a.getInteger(R.styleable.EmojiEditText_maxEmojiCount,
-                    EmojiTextWatcher.MAX_EMOJI_COUNT);
+                    defStyleAttr, defStyleRes);
+            mMaxEmojiCount = a.getInteger(R.styleable.EmojiEditText_maxEmojiCount, MAX_EMOJI_COUNT);
             a.recycle();
         }
     }
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiButton.java b/emoji/core/src/android/support/text/emoji/widget/EmojiButton.java
index c4119bc..65afd9c 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiButton.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiButton.java
@@ -28,6 +28,11 @@
  */
 public class EmojiButton extends Button {
     private EmojiTextViewHelper mEmojiTextViewHelper;
+
+    /**
+     * Prevent calling {@link #init()} multiple times in case super() constructors
+     * call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiButton(Context context) {
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiEditText.java b/emoji/core/src/android/support/text/emoji/widget/EmojiEditText.java
index a203bb9..a0e8a69 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiEditText.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiEditText.java
@@ -29,37 +29,44 @@
 /**
  * EditText widget enhanced with emoji capability by using {@link EmojiEditTextHelper}. When used
  * on devices running API 18 or below, this widget acts as a regular {@link EditText}.
+ *
+ * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
  */
 public class EmojiEditText extends EditText {
     private EmojiEditTextHelper mEmojiEditTextHelper;
+
+    /**
+     * Prevent calling {@link #init(AttributeSet, int, int)} multiple times in case super()
+     * constructors call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiEditText(Context context) {
         super(context);
-        init(null /*attrs*/, 0 /*defStyleAttr*/);
+        init(null /*attrs*/, 0 /*defStyleAttr*/, 0 /*defStyleRes*/);
     }
 
     public EmojiEditText(Context context, AttributeSet attrs) {
         super(context, attrs);
-        init(attrs, android.R.attr.editTextStyle);
+        init(attrs, android.R.attr.editTextStyle, 0 /*defStyleRes*/);
     }
 
     public EmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
         super(context, attrs, defStyleAttr);
-        init(attrs, defStyleAttr);
+        init(attrs, defStyleAttr, 0 /*defStyleRes*/);
     }
 
     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
     public EmojiEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
-        init(attrs, defStyleAttr);
+        init(attrs, defStyleAttr, defStyleRes);
     }
 
-    private void init(@Nullable AttributeSet attrs, int defStyleAttr) {
+    private void init(@Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
         if (!mInitialized) {
             mInitialized = true;
             final EditTextAttributeHelper attrHelper = new EditTextAttributeHelper(this, attrs,
-                    defStyleAttr);
+                    defStyleAttr, defStyleRes);
             setMaxEmojiCount(attrHelper.getMaxEmojiCount());
             setKeyListener(super.getKeyListener());
         }
@@ -85,6 +92,8 @@
      *                      should be equal or greater than 0
      *
      * @see EmojiCompat#process(CharSequence, int, int, int)
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
      */
     public void setMaxEmojiCount(@IntRange(from = 0) int maxEmojiCount) {
         getEmojiEditTextHelper().setMaxEmojiCount(maxEmojiCount);
@@ -95,6 +104,8 @@
      *
      * @see #setMaxEmojiCount(int)
      * @see EmojiCompat#process(CharSequence, int, int, int)
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiEditText_maxEmojiCount
      */
     public int getMaxEmojiCount() {
         return getEmojiEditTextHelper().getMaxEmojiCount();
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiEditTextHelper.java b/emoji/core/src/android/support/text/emoji/widget/EmojiEditTextHelper.java
index b010cf7..edc511f 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiEditTextHelper.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiEditTextHelper.java
@@ -15,11 +15,15 @@
  */
 package android.support.text.emoji.widget;
 
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
 import android.os.Build;
 import android.support.annotation.IntRange;
 import android.support.annotation.NonNull;
 import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
 import android.support.text.emoji.EmojiCompat;
+import android.support.text.emoji.EmojiSpan;
 import android.support.v4.util.Preconditions;
 import android.text.method.KeyListener;
 import android.view.inputmethod.EditorInfo;
@@ -63,9 +67,10 @@
  *
  */
 public final class EmojiEditTextHelper {
-
     private final HelperInternal mHelper;
-    private int mMaxEmojiCount;
+    private int mMaxEmojiCount = EditTextAttributeHelper.MAX_EMOJI_COUNT;
+    @EmojiCompat.ReplaceStrategy
+    private int mEmojiReplaceStrategy = EmojiCompat.REPLACE_STRATEGY_DEFAULT;
 
     /**
      * Default constructor.
@@ -96,7 +101,6 @@
         mHelper.setMaxEmojiCount(maxEmojiCount);
     }
 
-
     /**
      * Returns the maximum number of EmojiSpans to be added to a CharSequence.
      *
@@ -141,6 +145,36 @@
         return mHelper.onCreateInputConnection(inputConnection, outAttrs);
     }
 
+    /**
+     * Sets whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @param replaceStrategy should be one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     *
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
+        mEmojiReplaceStrategy = replaceStrategy;
+        mHelper.setEmojiReplaceStrategy(replaceStrategy);
+    }
+
+    /**
+     * Returns whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @return one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    int getEmojiReplaceStrategy() {
+        return mEmojiReplaceStrategy;
+    }
+
     private static class HelperInternal {
 
         KeyListener getKeyListener(@NonNull KeyListener keyListener) {
@@ -152,7 +186,11 @@
             return inputConnection;
         }
 
-        public void setMaxEmojiCount(int maxEmojiCount) {
+        void setMaxEmojiCount(int maxEmojiCount) {
+            // do nothing
+        }
+
+        void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
             // do nothing
         }
     }
@@ -170,11 +208,16 @@
         }
 
         @Override
-        public void setMaxEmojiCount(int maxEmojiCount) {
+        void setMaxEmojiCount(int maxEmojiCount) {
             mTextWatcher.setMaxEmojiCount(maxEmojiCount);
         }
 
         @Override
+        void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
+            mTextWatcher.setEmojiReplaceStrategy(replaceStrategy);
+        }
+
+        @Override
         KeyListener getKeyListener(@NonNull final KeyListener keyListener) {
             if (keyListener instanceof EmojiKeyListener) {
                 return keyListener;
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiExtractEditText.java b/emoji/core/src/android/support/text/emoji/widget/EmojiExtractEditText.java
new file mode 100644
index 0000000..ca1868e
--- /dev/null
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiExtractEditText.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2017 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 android.support.text.emoji.widget;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.inputmethodservice.ExtractEditText;
+import android.os.Build;
+import android.support.annotation.IntRange;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.text.emoji.EmojiCompat;
+import android.support.text.emoji.EmojiSpan;
+import android.util.AttributeSet;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputConnection;
+
+/**
+ * ExtractEditText widget enhanced with emoji capability by using {@link EmojiEditTextHelper}.
+ * When used on devices running API 18 or below, this widget acts as a {@link ExtractEditText} and
+ * does not provide any emoji compatibility feature.
+ *
+ * @hide
+ */
+@RestrictTo(LIBRARY_GROUP)
+public class EmojiExtractEditText extends ExtractEditText {
+    private EmojiEditTextHelper mEmojiEditTextHelper;
+
+    /**
+     * Prevent calling {@link #init(AttributeSet, int)} multiple times in case super() constructors
+     * call other constructors.
+     */
+    private boolean mInitialized;
+
+    public EmojiExtractEditText(Context context) {
+        super(context);
+        init(null /*attrs*/, 0 /*defStyleAttr*/, 0 /*defStyleRes*/);
+    }
+
+    public EmojiExtractEditText(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        init(attrs, android.R.attr.editTextStyle, 0 /*defStyleRes*/);
+    }
+
+    public EmojiExtractEditText(Context context, AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+        init(attrs, defStyleAttr, 0 /*defStyleRes*/);
+    }
+
+    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+    public EmojiExtractEditText(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+        init(attrs, defStyleAttr, defStyleRes);
+    }
+
+    private void init(@Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
+        if (!mInitialized) {
+            mInitialized = true;
+            final EditTextAttributeHelper attrHelper = new EditTextAttributeHelper(this, attrs,
+                    defStyleAttr, defStyleRes);
+            setMaxEmojiCount(attrHelper.getMaxEmojiCount());
+            setKeyListener(super.getKeyListener());
+        }
+    }
+
+    @Override
+    public void setKeyListener(android.text.method.KeyListener keyListener) {
+        super.setKeyListener(getEmojiEditTextHelper().getKeyListener(keyListener));
+    }
+
+    @Override
+    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
+        final InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
+        return getEmojiEditTextHelper().onCreateInputConnection(inputConnection, outAttrs);
+    }
+
+    /**
+     * Set the maximum number of EmojiSpans to be added to a CharSequence. The number of spans in a
+     * CharSequence affects the performance of the EditText insert/delete operations. Insert/delete
+     * operations slow down as the number of spans increases.
+     *
+     * @param maxEmojiCount maximum number of EmojiSpans to be added to a single CharSequence,
+     *                      should be equal or greater than 0
+     * @see EmojiCompat#process(CharSequence, int, int, int)
+     */
+    public void setMaxEmojiCount(@IntRange(from = 0) int maxEmojiCount) {
+        getEmojiEditTextHelper().setMaxEmojiCount(maxEmojiCount);
+    }
+
+    /**
+     * Sets whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @param replaceStrategy should be one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     */
+    public void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
+        getEmojiEditTextHelper().setEmojiReplaceStrategy(replaceStrategy);
+    }
+
+    /**
+     * Returns whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @return one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     */
+    public int getEmojiReplaceStrategy() {
+        return getEmojiEditTextHelper().getEmojiReplaceStrategy();
+    }
+
+    /**
+     * Returns the maximum number of EmojiSpans to be added to a CharSequence.
+     *
+     * @see #setMaxEmojiCount(int)
+     * @see EmojiCompat#process(CharSequence, int, int, int)
+     */
+    public int getMaxEmojiCount() {
+        return getEmojiEditTextHelper().getMaxEmojiCount();
+    }
+
+    private EmojiEditTextHelper getEmojiEditTextHelper() {
+        if (mEmojiEditTextHelper == null) {
+            mEmojiEditTextHelper = new EmojiEditTextHelper(this);
+        }
+        return mEmojiEditTextHelper;
+    }
+}
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiExtractTextLayout.java b/emoji/core/src/android/support/text/emoji/widget/EmojiExtractTextLayout.java
new file mode 100644
index 0000000..c75d6d0
--- /dev/null
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiExtractTextLayout.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright (C) 2017 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 android.support.text.emoji.widget;
+
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.inputmethodservice.InputMethodService;
+import android.os.Build;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
+import android.support.text.emoji.EmojiCompat;
+import android.support.text.emoji.EmojiSpan;
+import android.support.text.emoji.R;
+import android.text.InputType;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputConnection;
+import android.widget.LinearLayout;
+
+/**
+ * Layout that contains emoji compatibility enhanced ExtractEditText. Should be used by
+ * {@link InputMethodService} implementations.
+ * <p/>
+ * Call {@link #onUpdateExtractingViews(InputMethodService, EditorInfo)} from
+ * {@link InputMethodService#onUpdateExtractingViews(EditorInfo)
+ * InputMethodService#onUpdateExtractingViews(EditorInfo)}.
+ * <pre>
+ * public class MyInputMethodService extends InputMethodService {
+ *     // ..
+ *     {@literal @}Override
+ *     public View onCreateExtractTextView() {
+ *         mExtractView = getLayoutInflater().inflate(R.layout.emoji_input_method_extract_layout,
+ *                 null);
+ *         return mExtractView;
+ *     }
+ *
+ *     {@literal @}Override
+ *     public void onUpdateExtractingViews(EditorInfo ei) {
+ *         mExtractView.onUpdateExtractingViews(this, ei);
+ *     }
+ * }
+ * </pre>
+ *
+ * @attr ref android.support.text.emoji.R.styleable#EmojiExtractTextLayout_emojiReplaceStrategy
+ */
+public class EmojiExtractTextLayout extends LinearLayout {
+
+    private ExtractButtonCompat mExtractAction;
+    private EmojiExtractEditText mExtractEditText;
+    private ViewGroup mExtractAccessories;
+    private View.OnClickListener mButtonOnClickListener;
+
+    /**
+     * Prevent calling {@link #init(Context, AttributeSet, int)}} multiple times in case super()
+     * constructors call other constructors.
+     */
+    private boolean mInitialized;
+
+    public EmojiExtractTextLayout(Context context) {
+        super(context);
+        init(context, null /*attrs*/, 0 /*defStyleAttr*/, 0 /*defStyleRes*/);
+    }
+
+    public EmojiExtractTextLayout(Context context,
+            @Nullable AttributeSet attrs) {
+        super(context, attrs);
+        init(context, attrs, 0 /*defStyleAttr*/, 0 /*defStyleRes*/);
+    }
+
+    public EmojiExtractTextLayout(Context context,
+            @Nullable AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+        init(context, attrs, defStyleAttr, 0 /*defStyleRes*/);
+    }
+
+    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+    public EmojiExtractTextLayout(Context context, AttributeSet attrs,
+            int defStyleAttr, int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+        init(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    private void init(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        if (!mInitialized) {
+            mInitialized = true;
+            setOrientation(HORIZONTAL);
+            final View view = LayoutInflater.from(context)
+                    .inflate(R.layout.input_method_extract_view, this /*root*/,
+                            true /*attachToRoot*/);
+            mExtractAccessories = view.findViewById(R.id.inputExtractAccessories);
+            mExtractAction = view.findViewById(R.id.inputExtractAction);
+            mExtractEditText = view.findViewById(android.R.id.inputExtractEditText);
+
+            if (attrs != null) {
+                final TypedArray a = context.obtainStyledAttributes(attrs,
+                        R.styleable.EmojiExtractTextLayout, defStyleAttr, defStyleRes);
+                final int replaceStrategy = a.getInteger(
+                        R.styleable.EmojiExtractTextLayout_emojiReplaceStrategy,
+                        EmojiCompat.REPLACE_STRATEGY_DEFAULT);
+                mExtractEditText.setEmojiReplaceStrategy(replaceStrategy);
+                a.recycle();
+            }
+        }
+    }
+
+    /**
+     * Sets whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @param replaceStrategy should be one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiExtractTextLayout_emojiReplaceStrategy
+     */
+    public void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
+        mExtractEditText.setEmojiReplaceStrategy(replaceStrategy);
+    }
+
+    /**
+     * Returns whether to replace all emoji with {@link EmojiSpan}s. Default value is
+     * {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT}.
+     *
+     * @return one of {@link EmojiCompat#REPLACE_STRATEGY_DEFAULT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_NON_EXISTENT},
+     *                        {@link EmojiCompat#REPLACE_STRATEGY_ALL}
+     *
+     * @attr ref android.support.text.emoji.R.styleable#EmojiExtractTextLayout_emojiReplaceStrategy
+     */
+    public int getEmojiReplaceStrategy() {
+        return mExtractEditText.getEmojiReplaceStrategy();
+    }
+
+    /**
+     * Initializes the layout. Call this function from
+     * {@link InputMethodService#onUpdateExtractingViews(EditorInfo)
+     * InputMethodService#onUpdateExtractingViews(EditorInfo)}.
+     */
+    public void onUpdateExtractingViews(InputMethodService inputMethodService, EditorInfo ei) {
+        // the following code is ported as it is from InputMethodService.onUpdateExtractingViews
+        if (!inputMethodService.isExtractViewShown()) {
+            return;
+        }
+
+        if (mExtractAccessories == null) {
+            return;
+        }
+
+        final boolean hasAction = ei.actionLabel != null
+                || ((ei.imeOptions & EditorInfo.IME_MASK_ACTION) != EditorInfo.IME_ACTION_NONE
+                && (ei.imeOptions & EditorInfo.IME_FLAG_NO_ACCESSORY_ACTION) == 0
+                && ei.inputType != InputType.TYPE_NULL);
+
+        if (hasAction) {
+            mExtractAccessories.setVisibility(View.VISIBLE);
+            if (mExtractAction != null) {
+                if (ei.actionLabel != null) {
+                    mExtractAction.setText(ei.actionLabel);
+                } else {
+                    mExtractAction.setText(inputMethodService.getTextForImeAction(ei.imeOptions));
+                }
+                mExtractAction.setOnClickListener(getButtonClickListener(inputMethodService));
+            }
+        } else {
+            mExtractAccessories.setVisibility(View.GONE);
+            if (mExtractAction != null) {
+                mExtractAction.setOnClickListener(null);
+            }
+        }
+    }
+
+    private View.OnClickListener getButtonClickListener(
+            final InputMethodService inputMethodService) {
+        if (mButtonOnClickListener == null) {
+            mButtonOnClickListener = new ButtonOnclickListener(inputMethodService);
+        }
+        return mButtonOnClickListener;
+    }
+
+    private static final class ButtonOnclickListener implements View.OnClickListener {
+        private final InputMethodService mInputMethodService;
+
+        ButtonOnclickListener(InputMethodService inputMethodService) {
+            mInputMethodService = inputMethodService;
+        }
+
+        /**
+         * The following code is ported as it is from InputMethodService.mActionClickListener.
+         */
+        @Override
+        public void onClick(View v) {
+            final EditorInfo ei = mInputMethodService.getCurrentInputEditorInfo();
+            final InputConnection ic = mInputMethodService.getCurrentInputConnection();
+            if (ei != null && ic != null) {
+                if (ei.actionId != 0) {
+                    ic.performEditorAction(ei.actionId);
+                } else if ((ei.imeOptions & EditorInfo.IME_MASK_ACTION)
+                        != EditorInfo.IME_ACTION_NONE) {
+                    ic.performEditorAction(ei.imeOptions & EditorInfo.IME_MASK_ACTION);
+                }
+            }
+        }
+    }
+}
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiInputConnection.java b/emoji/core/src/android/support/text/emoji/widget/EmojiInputConnection.java
index e12a0bb..6232c52 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiInputConnection.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiInputConnection.java
@@ -53,7 +53,7 @@
     @Override
     public boolean deleteSurroundingText(final int beforeLength, final int afterLength) {
         final boolean result = EmojiCompat.handleDeleteSurroundingText(this, getEditable(),
-                beforeLength, afterLength, false /* in code ponints */);
+                beforeLength, afterLength, false /*inCodePoints*/);
         return result || super.deleteSurroundingText(beforeLength, afterLength);
     }
 
@@ -61,7 +61,7 @@
     public boolean deleteSurroundingTextInCodePoints(final int beforeLength,
             final int afterLength) {
         final boolean result = EmojiCompat.handleDeleteSurroundingText(this, getEditable(),
-                beforeLength, afterLength, true  /* in code ponints */);
+                beforeLength, afterLength, true /*inCodePoints*/);
         return result || super.deleteSurroundingTextInCodePoints(beforeLength, afterLength);
     }
 
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiInputFilter.java b/emoji/core/src/android/support/text/emoji/widget/EmojiInputFilter.java
index 4dec230..ba4201e 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiInputFilter.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiInputFilter.java
@@ -56,7 +56,6 @@
             return source;
         }
 
-
         switch (EmojiCompat.get().getLoadState()){
             case EmojiCompat.LOAD_STATE_SUCCEEDED:
                 boolean process = true;
@@ -81,8 +80,11 @@
             case EmojiCompat.LOAD_STATE_LOADING:
                 EmojiCompat.get().registerInitCallback(getInitCallback());
                 return source;
+
+            case EmojiCompat.LOAD_STATE_FAILED:
+            default:
+                return source;
         }
-        return source;
     }
 
     private InitCallback getInitCallback() {
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiTextView.java b/emoji/core/src/android/support/text/emoji/widget/EmojiTextView.java
index 50f58c1..3e450dc 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiTextView.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiTextView.java
@@ -28,6 +28,11 @@
  */
 public class EmojiTextView extends TextView {
     private EmojiTextViewHelper mEmojiTextViewHelper;
+
+    /**
+     * Prevent calling {@link #init()} multiple times in case super() constructors
+     * call other constructors.
+     */
     private boolean mInitialized;
 
     public EmojiTextView(Context context) {
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiTextWatcher.java b/emoji/core/src/android/support/text/emoji/widget/EmojiTextWatcher.java
index 81bcbd3..de3aea1 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiTextWatcher.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiTextWatcher.java
@@ -37,10 +37,11 @@
 @RestrictTo(LIBRARY_GROUP)
 @RequiresApi(19)
 final class EmojiTextWatcher implements android.text.TextWatcher {
-    static final int MAX_EMOJI_COUNT = Integer.MAX_VALUE;
     private final EditText mEditText;
     private InitCallback mInitCallback;
-    private int mMaxEmojiCount = MAX_EMOJI_COUNT;
+    private int mMaxEmojiCount = EditTextAttributeHelper.MAX_EMOJI_COUNT;
+    @EmojiCompat.ReplaceStrategy
+    private int mEmojiReplaceStrategy = EmojiCompat.REPLACE_STRATEGY_DEFAULT;
 
     EmojiTextWatcher(EditText editText) {
         mEditText = editText;
@@ -54,6 +55,14 @@
         return mMaxEmojiCount;
     }
 
+    @EmojiCompat.ReplaceStrategy int getEmojiReplaceStrategy() {
+        return mEmojiReplaceStrategy;
+    }
+
+    void setEmojiReplaceStrategy(@EmojiCompat.ReplaceStrategy int replaceStrategy) {
+        mEmojiReplaceStrategy = replaceStrategy;
+    }
+
     @Override
     public void onTextChanged(CharSequence charSequence, final int start, final int before,
             final int after) {
@@ -66,10 +75,15 @@
             switch (EmojiCompat.get().getLoadState()){
                 case EmojiCompat.LOAD_STATE_SUCCEEDED:
                     final Spannable s = (Spannable) charSequence;
-                    EmojiCompat.get().process(s, start, start + after, mMaxEmojiCount);
+                    EmojiCompat.get().process(s, start, start + after, mMaxEmojiCount,
+                            mEmojiReplaceStrategy);
                     break;
                 case EmojiCompat.LOAD_STATE_LOADING:
                     EmojiCompat.get().registerInitCallback(getInitCallback());
+                    break;
+                case EmojiCompat.LOAD_STATE_FAILED:
+                default:
+                    break;
             }
         }
     }
diff --git a/emoji/core/src/android/support/text/emoji/widget/EmojiTransformationMethod.java b/emoji/core/src/android/support/text/emoji/widget/EmojiTransformationMethod.java
index 6e66462..dac9905 100644
--- a/emoji/core/src/android/support/text/emoji/widget/EmojiTransformationMethod.java
+++ b/emoji/core/src/android/support/text/emoji/widget/EmojiTransformationMethod.java
@@ -54,6 +54,10 @@
             switch (EmojiCompat.get().getLoadState()){
                 case EmojiCompat.LOAD_STATE_SUCCEEDED:
                     return EmojiCompat.get().process(source);
+                case EmojiCompat.LOAD_STATE_LOADING:
+                case EmojiCompat.LOAD_STATE_FAILED:
+                default:
+                    break;
             }
         }
         return source;
diff --git a/emoji/core/src/android/support/text/emoji/widget/ExtractButtonCompat.java b/emoji/core/src/android/support/text/emoji/widget/ExtractButtonCompat.java
new file mode 100644
index 0000000..fc8eb78
--- /dev/null
+++ b/emoji/core/src/android/support/text/emoji/widget/ExtractButtonCompat.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2017 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 android.support.text.emoji.widget;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.content.Context;
+import android.os.Build;
+import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
+import android.util.AttributeSet;
+import android.widget.Button;
+
+/**
+ * Support library implementation for ExtractButton. Used by {@link EmojiExtractViewHelper} while
+ * inflating {@link EmojiExtractEditText} for keyboard use.
+ * @hide
+ */
+@RestrictTo(LIBRARY_GROUP)
+public class ExtractButtonCompat extends Button {
+    public ExtractButtonCompat(Context context) {
+        super(context, null);
+    }
+
+    public ExtractButtonCompat(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public ExtractButtonCompat(Context context, AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+    }
+
+    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+    public ExtractButtonCompat(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    /**
+     * Pretend like the window this view is in always has focus, so it will
+     * highlight when selected.
+     */
+    @Override
+    public boolean hasWindowFocus() {
+        return isEnabled() && getVisibility() == VISIBLE ? true : false;
+    }
+}
diff --git a/emoji/core/tests/AndroidManifest.xml b/emoji/core/tests/AndroidManifest.xml
index 4c706b2..061e751 100644
--- a/emoji/core/tests/AndroidManifest.xml
+++ b/emoji/core/tests/AndroidManifest.xml
@@ -15,6 +15,7 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.support.text.emoji">
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application>
         <activity android:name=".TestActivity"/>
diff --git a/emoji/core/tests/java/android/support/text/emoji/ConfigTest.java b/emoji/core/tests/java/android/support/text/emoji/ConfigTest.java
index 75692af..538ce99 100644
--- a/emoji/core/tests/java/android/support/text/emoji/ConfigTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/ConfigTest.java
@@ -102,9 +102,9 @@
     public void testInitCallback_callsFailCallback() {
         final EmojiCompat.InitCallback initCallback1 = mock(EmojiCompat.InitCallback.class);
         final EmojiCompat.InitCallback initCallback2 = mock(EmojiCompat.InitCallback.class);
-        final EmojiCompat.MetadataLoader loader = mock(EmojiCompat.MetadataLoader.class);
-        doThrow(new RuntimeException("")).when(loader).load(any(EmojiCompat.LoaderCallback
-                .class));
+        final EmojiCompat.MetadataRepoLoader loader = mock(EmojiCompat.MetadataRepoLoader.class);
+        doThrow(new RuntimeException("")).when(loader)
+                .load(any(EmojiCompat.MetadataRepoLoaderCallback.class));
 
         final EmojiCompat.Config config = new TestConfigBuilder.TestConfig(loader)
                 .registerInitCallback(initCallback1)
diff --git a/emoji/core/tests/java/android/support/text/emoji/EmojiCompatTest.java b/emoji/core/tests/java/android/support/text/emoji/EmojiCompatTest.java
index eb4ce2e..ee31ed7 100644
--- a/emoji/core/tests/java/android/support/text/emoji/EmojiCompatTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/EmojiCompatTest.java
@@ -643,6 +643,21 @@
     }
 
     @Test
+    @SdkSuppress(maxSdkVersion = 18)
+    public void testGetAssetSignature() {
+        final String signature = EmojiCompat.get().getAssetSignature();
+        assertTrue(signature.isEmpty());
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    public void testGetAssetSignature_api19() {
+        final String signature = EmojiCompat.get().getAssetSignature();
+        assertNotNull(signature);
+        assertFalse(signature.isEmpty());
+    }
+
+    @Test
     @SdkSuppress(minSdkVersion = 19)
     public void testUpdateEditorInfoAttrs_setsKeysIfInitialized() {
         final EditorInfo editorInfo = new EditorInfo();
@@ -680,8 +695,8 @@
         verifyNoMoreInteractions(inputConnection);
 
         // try backwards delete 1 character
-        assertFalse(
-                EmojiCompat.handleDeleteSurroundingText(inputConnection, editable, 1, 0, false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(inputConnection, editable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
     }
 
     @Test
diff --git a/emoji/core/tests/java/android/support/text/emoji/FontRequestEmojiCompatConfigTest.java b/emoji/core/tests/java/android/support/text/emoji/FontRequestEmojiCompatConfigTest.java
index 72602c5..ce2b098 100644
--- a/emoji/core/tests/java/android/support/text/emoji/FontRequestEmojiCompatConfigTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/FontRequestEmojiCompatConfigTest.java
@@ -28,10 +28,13 @@
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -39,7 +42,11 @@
 import android.annotation.TargetApi;
 import android.content.Context;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.database.ContentObserver;
 import android.net.Uri;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.support.annotation.GuardedBy;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.test.InstrumentationRegistry;
@@ -70,14 +77,14 @@
     private static final int DEFAULT_TIMEOUT_MILLIS = 3000;
     private Context mContext;
     private FontRequest mFontRequest;
-    private FontRequestEmojiCompatConfig.FontsContractDelegate mFontsContract;
+    private FontRequestEmojiCompatConfig.FontProviderHelper mFontProviderHelper;
 
     @Before
     public void setup() {
         mContext = InstrumentationRegistry.getContext();
         mFontRequest = new FontRequest("authority", "package", "query",
                 new ArrayList<List<byte[]>>());
-        mFontsContract = mock(FontRequestEmojiCompatConfig.FontsContractDelegate.class);
+        mFontProviderHelper = mock(FontRequestEmojiCompatConfig.FontProviderHelper.class);
     }
 
     @Test(expected = NullPointerException.class)
@@ -91,28 +98,32 @@
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_whenGetFontThrowsException() throws NameNotFoundException {
         final Exception exception = new RuntimeException();
-        doThrow(exception).when(mFontsContract).fetchFonts(
+        doThrow(exception).when(mFontProviderHelper).fetchFonts(
                 any(Context.class), any(FontRequest.class));
         final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
         final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext, mFontRequest,
-                mFontsContract);
+                mFontProviderHelper);
 
-        config.getMetadataLoader().load(callback);
+        config.getMetadataRepoLoader().load(callback);
         callback.await(DEFAULT_TIMEOUT_MILLIS);
         verify(callback, times(1)).onFailed(same(exception));
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_providerNotFound() throws NameNotFoundException {
-        doThrow(new NameNotFoundException()).when(mFontsContract).fetchFonts(
+        doThrow(new NameNotFoundException()).when(mFontProviderHelper).fetchFonts(
                 any(Context.class), any(FontRequest.class));
         final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
         final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
-                mFontRequest, mFontsContract);
+                mFontRequest, mFontProviderHelper);
 
-        config.getMetadataLoader().load(callback);
+        config.getMetadataRepoLoader().load(callback);
         callback.await(DEFAULT_TIMEOUT_MILLIS);
 
         final ArgumentCaptor<Throwable> argumentCaptor = ArgumentCaptor.forClass(Throwable.class);
@@ -121,26 +132,32 @@
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_wrongCertificate() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_WRONG_CERTIFICATES, null /* fonts */,
                 "fetchFonts failed (" + STATUS_WRONG_CERTIFICATES + ")");
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_fontNotFound() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_OK,
                 getTestFontInfoWithInvalidPath(RESULT_CODE_FONT_NOT_FOUND),
                 "fetchFonts result is not OK. (" + RESULT_CODE_FONT_NOT_FOUND + ")");
     }
 
-    @Test
+    @Test@SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_fontUnavailable() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_OK,
                 getTestFontInfoWithInvalidPath(RESULT_CODE_FONT_UNAVAILABLE),
                 "fetchFonts result is not OK. (" + RESULT_CODE_FONT_UNAVAILABLE + ")");
     }
 
-    @Test
+    @Test@SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_malformedQuery() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_OK,
                 getTestFontInfoWithInvalidPath(RESULT_CODE_MALFORMED_QUERY),
@@ -148,18 +165,24 @@
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_resultNotFound() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_OK, new FontInfo[] {},
                 "fetchFonts failed (empty result)");
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_nullFontInfo() throws NameNotFoundException {
         verifyLoaderOnFailedCalled(STATUS_OK, null /* fonts */,
                 "fetchFonts failed (empty result)");
     }
 
     @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
     public void testLoad_cannotLoadTypeface() throws NameNotFoundException {
         // getTestFontInfoWithInvalidPath returns FontInfo with invalid path to file.
         verifyLoaderOnFailedCalled(STATUS_OK,
@@ -176,26 +199,306 @@
                 new FontInfo(Uri.fromFile(file), 0 /* ttc index */, 400 /* weight */,
                         false /* italic */, RESULT_CODE_OK)
         };
-        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontsContract).fetchFonts(
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
                 any(Context.class), any(FontRequest.class));
         final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
         final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
-                mFontRequest, mFontsContract);
+                mFontRequest, mFontProviderHelper);
 
-        config.getMetadataLoader().load(callback);
+        config.getMetadataRepoLoader().load(callback);
         callback.await(DEFAULT_TIMEOUT_MILLIS);
         verify(callback, times(1)).onLoaded(any(MetadataRepo.class));
     }
 
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_retryPolicy() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final FontInfo[] fonts =  new FontInfo[] {
+                new FontInfo(Uri.fromFile(file), 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(-1, 1));
+        final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                mFontRequest, mFontProviderHelper).setRetryPolicy(retryPolicy);
+
+        config.getMetadataRepoLoader().load(callback);
+        callback.await(DEFAULT_TIMEOUT_MILLIS);
+        verify(callback, never()).onLoaded(any(MetadataRepo.class));
+        verify(callback, times(1)).onFailed(any(Throwable.class));
+        verify(retryPolicy, times(1)).getRetryDelay();
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_keepRetryingAndGiveUp() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final FontInfo[] fonts =  new FontInfo[] {
+                new FontInfo(Uri.fromFile(file), 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(500, 1));
+        final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                mFontRequest, mFontProviderHelper).setRetryPolicy(retryPolicy);
+
+        config.getMetadataRepoLoader().load(callback);
+        retryPolicy.await(DEFAULT_TIMEOUT_MILLIS);
+        verify(callback, never()).onLoaded(any(MetadataRepo.class));
+        verify(callback, never()).onFailed(any(Throwable.class));
+        verify(retryPolicy, atLeastOnce()).getRetryDelay();
+        retryPolicy.changeReturnValue(-1);
+        callback.await(DEFAULT_TIMEOUT_MILLIS);
+        verify(callback, never()).onLoaded(any(MetadataRepo.class));
+        verify(callback, times(1)).onFailed(any(Throwable.class));
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_keepRetryingAndFail() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final Uri uri = Uri.fromFile(file);
+
+        final FontInfo[] fonts = new FontInfo[] {
+                new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(500, 1));
+
+        HandlerThread thread = new HandlerThread("testThread");
+        thread.start();
+        try {
+            Handler handler = new Handler(thread.getLooper());
+
+            final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                    mFontRequest, mFontProviderHelper).setHandler(handler)
+                    .setRetryPolicy(retryPolicy);
+
+            config.getMetadataRepoLoader().load(callback);
+            retryPolicy.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+            verify(retryPolicy, atLeastOnce()).getRetryDelay();
+
+            // To avoid race condition, change the fetchFonts result on the handler thread.
+            handler.post(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        final FontInfo[] fontsSuccess = new FontInfo[] {
+                                new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                                        false /* italic */, RESULT_CODE_FONT_NOT_FOUND)
+                        };
+
+                        doReturn(new FontFamilyResult(STATUS_OK, fontsSuccess)).when(
+                                mFontProviderHelper).fetchFonts(any(Context.class),
+                                any(FontRequest.class));
+                    } catch (NameNotFoundException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            });
+
+            callback.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, times(1)).onFailed(any(Throwable.class));
+        } finally {
+            thread.quit();
+        }
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_keepRetryingAndSuccess() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final Uri uri = Uri.fromFile(file);
+
+        final FontInfo[] fonts = new FontInfo[]{
+                new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(500, 1));
+
+        HandlerThread thread = new HandlerThread("testThread");
+        thread.start();
+        try {
+            Handler handler = new Handler(thread.getLooper());
+
+            final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                    mFontRequest, mFontProviderHelper).setHandler(handler)
+                    .setRetryPolicy(retryPolicy);
+
+            config.getMetadataRepoLoader().load(callback);
+            retryPolicy.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+            verify(retryPolicy, atLeastOnce()).getRetryDelay();
+
+            final FontInfo[] fontsSuccess = new FontInfo[]{
+                    new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                            false /* italic */, RESULT_CODE_OK)
+            };
+
+            // To avoid race condition, change the fetchFonts result on the handler thread.
+            handler.post(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        doReturn(new FontFamilyResult(STATUS_OK, fontsSuccess)).when(
+                                mFontProviderHelper).fetchFonts(any(Context.class),
+                                any(FontRequest.class));
+                    } catch (NameNotFoundException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            });
+
+            callback.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, times(1)).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+        } finally {
+            thread.quit();
+        }
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_ObserverNotifyAndSuccess() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final Uri uri = Uri.fromFile(file);
+        final FontInfo[] fonts = new FontInfo[]{
+                new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(500, 2));
+
+        HandlerThread thread = new HandlerThread("testThread");
+        thread.start();
+        try {
+            Handler handler = new Handler(thread.getLooper());
+            final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                    mFontRequest, mFontProviderHelper).setHandler(handler)
+                    .setRetryPolicy(retryPolicy);
+
+            ArgumentCaptor<ContentObserver> observerCaptor =
+                    ArgumentCaptor.forClass(ContentObserver.class);
+
+            config.getMetadataRepoLoader().load(callback);
+            retryPolicy.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+            verify(retryPolicy, atLeastOnce()).getRetryDelay();
+            verify(mFontProviderHelper, times(1)).registerObserver(
+                    any(Context.class), eq(uri), observerCaptor.capture());
+
+            final FontInfo[] fontsSuccess = new FontInfo[]{
+                    new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                            false /* italic */, RESULT_CODE_OK)
+            };
+            doReturn(new FontFamilyResult(STATUS_OK, fontsSuccess)).when(
+                    mFontProviderHelper).fetchFonts(any(Context.class), any(FontRequest.class));
+
+            final ContentObserver observer = observerCaptor.getValue();
+            handler.post(new Runnable() {
+                @Override
+                public void run() {
+                    observer.onChange(false /* self change */, uri);
+                }
+            });
+
+            callback.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, times(1)).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+        } finally {
+            thread.quit();
+        }
+    }
+
+    @Test
+    @SdkSuppress(minSdkVersion = 19)
+    @TargetApi(19)
+    public void testLoad_ObserverNotifyAndFail() throws IOException, NameNotFoundException {
+        final File file = loadFont(mContext, "NotoColorEmojiCompat.ttf");
+        final Uri uri = Uri.fromFile(file);
+        final FontInfo[] fonts = new FontInfo[]{
+                new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                        false /* italic */, RESULT_CODE_FONT_UNAVAILABLE)
+        };
+        doReturn(new FontFamilyResult(STATUS_OK, fonts)).when(mFontProviderHelper).fetchFonts(
+                any(Context.class), any(FontRequest.class));
+        final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
+        final WaitingRetryPolicy retryPolicy = spy(new WaitingRetryPolicy(500, 2));
+
+        HandlerThread thread = new HandlerThread("testThread");
+        thread.start();
+        try {
+            Handler handler = new Handler(thread.getLooper());
+            final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext,
+                    mFontRequest, mFontProviderHelper).setHandler(handler)
+                    .setRetryPolicy(retryPolicy);
+
+            ArgumentCaptor<ContentObserver> observerCaptor =
+                    ArgumentCaptor.forClass(ContentObserver.class);
+
+            config.getMetadataRepoLoader().load(callback);
+            retryPolicy.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, never()).onFailed(any(Throwable.class));
+            verify(retryPolicy, atLeastOnce()).getRetryDelay();
+            verify(mFontProviderHelper, times(1)).registerObserver(
+                    any(Context.class), eq(uri), observerCaptor.capture());
+
+            final FontInfo[] fontsSuccess = new FontInfo[]{
+                    new FontInfo(uri, 0 /* ttc index */, 400 /* weight */,
+                            false /* italic */, RESULT_CODE_FONT_NOT_FOUND)
+            };
+            doReturn(new FontFamilyResult(STATUS_OK, fontsSuccess)).when(
+                    mFontProviderHelper).fetchFonts(any(Context.class), any(FontRequest.class));
+
+            final ContentObserver observer = observerCaptor.getValue();
+            handler.post(new Runnable() {
+                @Override
+                public void run() {
+                    observer.onChange(false /* self change */, uri);
+                }
+            });
+
+            callback.await(DEFAULT_TIMEOUT_MILLIS);
+            verify(callback, never()).onLoaded(any(MetadataRepo.class));
+            verify(callback, times(1)).onFailed(any(Throwable.class));
+        } finally {
+            thread.quit();
+        }
+    }
+
     private void verifyLoaderOnFailedCalled(final int statusCode,
             final FontInfo[] fonts, String exceptionMessage) throws NameNotFoundException {
-        doReturn(new FontFamilyResult(statusCode, fonts)).when(mFontsContract).fetchFonts(
+        doReturn(new FontFamilyResult(statusCode, fonts)).when(mFontProviderHelper).fetchFonts(
                 any(Context.class), any(FontRequest.class));
         final WaitingLoaderCallback callback = spy(new WaitingLoaderCallback());
         final EmojiCompat.Config config = new FontRequestEmojiCompatConfig(mContext, mFontRequest,
-                mFontsContract);
+                mFontProviderHelper);
 
-        config.getMetadataLoader().load(callback);
+        config.getMetadataRepoLoader().load(callback);
         callback.await(DEFAULT_TIMEOUT_MILLIS);
 
         final ArgumentCaptor<Throwable> argumentCaptor = ArgumentCaptor.forClass(Throwable.class);
@@ -203,7 +506,43 @@
         assertThat(argumentCaptor.getValue().getMessage(), containsString(exceptionMessage));
     }
 
-    public static class WaitingLoaderCallback extends EmojiCompat.LoaderCallback {
+    public static class WaitingRetryPolicy extends FontRequestEmojiCompatConfig.RetryPolicy {
+        private final CountDownLatch mLatch;
+        private final Object mLock = new Object();
+        @GuardedBy("mLock")
+        private long mReturnValue;
+
+        public WaitingRetryPolicy(long returnValue, int callCount) {
+            mLatch = new CountDownLatch(callCount);
+            synchronized (mLock) {
+                mReturnValue = returnValue;
+            }
+        }
+
+        @Override
+        public long getRetryDelay() {
+            mLatch.countDown();
+            synchronized (mLock) {
+                return mReturnValue;
+            }
+        }
+
+        public void changeReturnValue(long value) {
+            synchronized (mLock) {
+                mReturnValue = value;
+            }
+        }
+
+        public void await(long timeoutMillis) {
+            try {
+                mLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    public static class WaitingLoaderCallback extends EmojiCompat.MetadataRepoLoaderCallback {
         final CountDownLatch mLatch;
 
         public WaitingLoaderCallback() {
diff --git a/emoji/core/tests/java/android/support/text/emoji/InitCallbackTest.java b/emoji/core/tests/java/android/support/text/emoji/InitCallbackTest.java
index e11f4da..ec6291d 100644
--- a/emoji/core/tests/java/android/support/text/emoji/InitCallbackTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/InitCallbackTest.java
@@ -15,6 +15,7 @@
  */
 package android.support.text.emoji;
 
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
@@ -57,9 +58,9 @@
     public void testRegisterInitCallback_callsFailCallback() {
         final EmojiCompat.InitCallback initCallback1 = mock(EmojiCompat.InitCallback.class);
         final EmojiCompat.InitCallback initCallback2 = mock(EmojiCompat.InitCallback.class);
-        final EmojiCompat.MetadataLoader loader = mock(EmojiCompat.MetadataLoader.class);
-        doThrow(new RuntimeException("")).when(loader).load(any(EmojiCompat.LoaderCallback
-                .class));
+        final EmojiCompat.MetadataRepoLoader loader = mock(EmojiCompat.MetadataRepoLoader.class);
+        doThrow(new RuntimeException("")).when(loader)
+                .load(any(EmojiCompat.MetadataRepoLoaderCallback.class));
 
         final EmojiCompat.Config config = new TestConfig(loader);
         final EmojiCompat emojiCompat = EmojiCompat.reset(config);
@@ -68,17 +69,17 @@
 
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
-        verify(initCallback1, times(1)).onFailed(any(Throwable.class));
-        verify(initCallback2, times(1)).onFailed(any(Throwable.class));
+        verify(initCallback1, times(1)).onFailed(nullable(Throwable.class));
+        verify(initCallback2, times(1)).onFailed(nullable(Throwable.class));
     }
 
     @Test
     @SdkSuppress(minSdkVersion = 19)
     public void testRegisterInitCallback_callsFailCallback_whenOnFailCalledByLoader() {
         final EmojiCompat.InitCallback initCallback = mock(EmojiCompat.InitCallback.class);
-        final EmojiCompat.MetadataLoader loader = new EmojiCompat.MetadataLoader() {
+        final EmojiCompat.MetadataRepoLoader loader = new EmojiCompat.MetadataRepoLoader() {
             @Override
-            public void load(@NonNull EmojiCompat.LoaderCallback loaderCallback) {
+            public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
                 loaderCallback.onFailed(new RuntimeException(""));
             }
         };
@@ -88,16 +89,16 @@
         emojiCompat.registerInitCallback(initCallback);
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
-        verify(initCallback, times(1)).onFailed(any(Throwable.class));
+        verify(initCallback, times(1)).onFailed(nullable(Throwable.class));
     }
 
     @Test
     @SdkSuppress(minSdkVersion = 19)
     public void testRegisterInitCallback_callsFailCallback_whenMetadataRepoIsNull() {
         final EmojiCompat.InitCallback initCallback = mock(EmojiCompat.InitCallback.class);
-        final EmojiCompat.MetadataLoader loader = new EmojiCompat.MetadataLoader() {
+        final EmojiCompat.MetadataRepoLoader loader = new EmojiCompat.MetadataRepoLoader() {
             @Override
-            public void load(@NonNull EmojiCompat.LoaderCallback loaderCallback) {
+            public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
                 loaderCallback.onLoaded(null);
             }
         };
@@ -107,7 +108,7 @@
         emojiCompat.registerInitCallback(initCallback);
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
-        verify(initCallback, times(1)).onFailed(any(Throwable.class));
+        verify(initCallback, times(1)).onFailed(nullable(Throwable.class));
     }
 
     @Test
@@ -144,9 +145,9 @@
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         verify(callbackUnregister, times(0)).onFailed(any(Throwable.class));
-        verify(callbackConfigUnregister, times(0)).onFailed(any(Throwable.class));
-        verify(callback, times(1)).onFailed(any(Throwable.class));
-        verify(callbackConfig, times(1)).onFailed(any(Throwable.class));
+        verify(callbackConfigUnregister, times(0)).onFailed(nullable(Throwable.class));
+        verify(callback, times(1)).onFailed(nullable(Throwable.class));
+        verify(callbackConfig, times(1)).onFailed(nullable(Throwable.class));
     }
 
     @Test
diff --git a/emoji/core/tests/java/android/support/text/emoji/SoftDeleteTest.java b/emoji/core/tests/java/android/support/text/emoji/SoftDeleteTest.java
index 5a56bda..1a25aa6 100644
--- a/emoji/core/tests/java/android/support/text/emoji/SoftDeleteTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/SoftDeleteTest.java
@@ -70,8 +70,8 @@
     @Test
     public void testDelete_doesNotDelete_whenSelectionIsUndefined() {
         // no selection is set on editable
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 1, 0,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -82,8 +82,8 @@
         Selection.setSelection(mEditable, mTestString.emojiStartIndex(),
                 mTestString.emojiEndIndex() + 1);
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 1, 0,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -93,7 +93,8 @@
     public void testDelete_withNullEditable() {
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, null, 1, 0, false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, null,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -103,7 +104,8 @@
     public void testDelete_withNullInputConnection() {
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(null, mEditable, 1, 0, false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(null, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -114,8 +116,8 @@
     public void testDelete_withInvalidLength() {
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, -1, 0,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                -1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -126,8 +128,8 @@
     public void testDelete_withInvalidAfterLength() {
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 0, -1,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                0 /*beforeLength*/, -1 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji(EMOJI_WITH_ZWJ));
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -138,8 +140,8 @@
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
         // backwards delete 1 character, it will delete the emoji
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 1, 0,
-                false));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals(new TestString().withPrefix().withSuffix().toString(), mEditable.toString());
@@ -150,8 +152,8 @@
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
         // backwards delete 1 character, it will delete the emoji
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 1, 0,
-                true));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, true /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals(new TestString().withPrefix().withSuffix().toString(), mEditable.toString());
@@ -162,8 +164,8 @@
         Selection.setSelection(mEditable, mTestString.emojiStartIndex());
 
         // forward delete 1 character, it will dele the emoji.
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 0, 1,
-                false));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                0 /*beforeLength*/, 1 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals(new TestString().withPrefix().withSuffix().toString(), mEditable.toString());
@@ -174,8 +176,8 @@
         Selection.setSelection(mEditable, mTestString.emojiStartIndex());
 
         // forward delete 1 codepoint, it will delete the emoji.
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 0, 1,
-                false));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                0 /*beforeLength*/, 1 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals(new TestString().withPrefix().withSuffix().toString(), mEditable.toString());
@@ -186,8 +188,8 @@
         // make sure selection at 0 does not do something weird for backward delete
         Selection.setSelection(mEditable, 0);
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 1, 0,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                1 /*beforeLength*/, 0 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji());
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -198,8 +200,8 @@
         // make sure selection at end does not do something weird for forward delete
         Selection.setSelection(mEditable, mTestString.emojiEndIndex());
 
-        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 0, 1,
-                false));
+        assertFalse(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                0 /*beforeLength*/, 1 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, hasEmoji());
         assertEquals(mTestString.toString(), mEditable.toString());
@@ -216,8 +218,8 @@
         Selection.setSelection(mEditable, "abc".length() + EMOJI_FLAG.charCount() / 2);
 
         // delete 4 characters forward, 4 character backwards
-        assertTrue(
-                EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 4, 4, false));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                4 /*beforeLength*/, 4 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals("af", mEditable.toString());
@@ -234,8 +236,8 @@
         Selection.setSelection(mEditable, "abc".length() + EMOJI_FLAG.charCount() / 2);
 
         // delete 3 codepoints forward, 3 codepoints backwards
-        assertTrue(
-                EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 3, 3, true));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                3 /*beforeLength*/, 3 /*afterLength*/, true /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals("af", mEditable.toString());
@@ -251,8 +253,8 @@
         // set the selection in the middle of emoji
         Selection.setSelection(mEditable, "abc".length() + EMOJI_FLAG.charCount() / 2);
 
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 100, 100,
-                false));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                100 /*beforeLength*/, 100 /*afterLength*/, false /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals("", mEditable.toString());
@@ -268,8 +270,8 @@
         // set the selection in the middle of emoji
         Selection.setSelection(mEditable, "abc".length() + EMOJI_FLAG.charCount() / 2);
 
-        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable, 100, 100,
-                true));
+        assertTrue(EmojiCompat.handleDeleteSurroundingText(mInputConnection, mEditable,
+                100 /*beforeLength*/, 100 /*afterLength*/, true /*inCodePoints*/));
 
         assertThat(mEditable, not(hasEmoji()));
         assertEquals("", mEditable.toString());
diff --git a/emoji/core/tests/java/android/support/text/emoji/TestConfigBuilder.java b/emoji/core/tests/java/android/support/text/emoji/TestConfigBuilder.java
index 202b2e4..242d62b 100644
--- a/emoji/core/tests/java/android/support/text/emoji/TestConfigBuilder.java
+++ b/emoji/core/tests/java/android/support/text/emoji/TestConfigBuilder.java
@@ -34,12 +34,12 @@
             super(new TestEmojiDataLoader());
         }
 
-        TestConfig(final EmojiCompat.MetadataLoader metadataLoader) {
+        TestConfig(final EmojiCompat.MetadataRepoLoader metadataLoader) {
             super(metadataLoader);
         }
     }
 
-    public static class WaitingDataLoader implements EmojiCompat.MetadataLoader {
+    public static class WaitingDataLoader implements EmojiCompat.MetadataRepoLoader {
         private final CountDownLatch mLoaderLatch;
         private final CountDownLatch mTestLatch;
         private final boolean mSuccess;
@@ -63,7 +63,7 @@
         }
 
         @Override
-        public void load(@NonNull final EmojiCompat.LoaderCallback loaderCallback) {
+        public void load(@NonNull final EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
             new Thread(new Runnable() {
                 @Override
                 public void run() {
@@ -84,7 +84,7 @@
         }
     }
 
-    public static class TestEmojiDataLoader implements EmojiCompat.MetadataLoader {
+    public static class TestEmojiDataLoader implements EmojiCompat.MetadataRepoLoader {
         static final Object sMetadataRepoLock = new Object();
         // keep a static instance to in order not to slow down the tests
         @GuardedBy("sMetadataRepoLock")
@@ -94,7 +94,7 @@
         }
 
         @Override
-        public void load(@NonNull EmojiCompat.LoaderCallback loaderCallback) {
+        public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
             if (sMetadataRepo == null) {
                 synchronized (sMetadataRepoLock) {
                     if (sMetadataRepo == null) {
diff --git a/emoji/core/tests/java/android/support/text/emoji/util/EmojiMatcher.java b/emoji/core/tests/java/android/support/text/emoji/util/EmojiMatcher.java
index 20f656d..2915acd 100644
--- a/emoji/core/tests/java/android/support/text/emoji/util/EmojiMatcher.java
+++ b/emoji/core/tests/java/android/support/text/emoji/util/EmojiMatcher.java
@@ -21,10 +21,10 @@
 import android.text.Spanned;
 import android.text.TextUtils;
 
-import org.hamcrest.BaseMatcher;
 import org.hamcrest.Description;
 import org.hamcrest.Matcher;
 import org.hamcrest.TypeSafeMatcher;
+import org.mockito.ArgumentMatcher;
 
 /**
  * Utility class that includes matchers specific to emojis and EmojiSpans.
@@ -62,18 +62,18 @@
     }
 
     public static <T extends CharSequence> T sameCharSequence(final T expected) {
-        return argThat(new BaseMatcher<T>() {
+        return argThat(new ArgumentMatcher<T>() {
             @Override
-            public boolean matches(Object o) {
-                if (o instanceof CharSequence && expected.getClass() == o.getClass()) {
-                    return TextUtils.equals(expected, (CharSequence) o);
+            public boolean matches(T o) {
+                if (o instanceof CharSequence) {
+                    return TextUtils.equals(expected, o);
                 }
                 return false;
             }
 
             @Override
-            public void describeTo(Description description) {
-                description.appendText("doesn't match " + expected);
+            public String toString() {
+                return "doesn't match " + expected;
             }
         });
     }
diff --git a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiEditTextHelperTest.java b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiEditTextHelperTest.java
index a2856be..efc7ca0 100644
--- a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiEditTextHelperTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiEditTextHelperTest.java
@@ -123,6 +123,32 @@
 
         mEmojiEditTextHelper.setMaxEmojiCount(1);
 
-        assertEquals(emojiTextWatcher.getMaxEmojiCount(), 1);
+        assertEquals(1, emojiTextWatcher.getMaxEmojiCount());
     }
+
+    @Test
+    public void testSetEmojiReplaceStrategy() {
+        mEditText = mock(EditText.class);
+        mEmojiEditTextHelper = new EmojiEditTextHelper(mEditText);
+
+        //assert the default value
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_DEFAULT,
+                mEmojiEditTextHelper.getEmojiReplaceStrategy());
+
+        // capture TextWatcher
+        final ArgumentCaptor<TextWatcher> argumentCaptor = ArgumentCaptor.forClass(
+                TextWatcher.class);
+        verify(mEditText, times(1)).addTextChangedListener(argumentCaptor.capture());
+        assertThat(argumentCaptor.getValue(), instanceOf(EmojiTextWatcher.class));
+        final EmojiTextWatcher emojiTextWatcher = (EmojiTextWatcher) argumentCaptor.getValue();
+
+        mEmojiEditTextHelper.setEmojiReplaceStrategy(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT);
+
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT,
+                mEmojiEditTextHelper.getEmojiReplaceStrategy());
+
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT,
+                emojiTextWatcher.getEmojiReplaceStrategy());
+    }
+
 }
diff --git a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiExtractTextLayoutTest.java b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiExtractTextLayoutTest.java
new file mode 100644
index 0000000..8e1c6cf
--- /dev/null
+++ b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiExtractTextLayoutTest.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2017 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 android.support.text.emoji.widget;
+
+import static android.support.text.emoji.util.EmojiMatcher.sameCharSequence;
+
+import static junit.framework.TestCase.assertFalse;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.inputmethodservice.InputMethodService;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.SdkSuppress;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.text.emoji.EmojiCompat;
+import android.support.text.emoji.R;
+import android.text.InputType;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.inputmethod.EditorInfo;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class EmojiExtractTextLayoutTest {
+
+    private InputMethodService mInputMethodService;
+
+    @BeforeClass
+    public static void setupEmojiCompat() {
+        EmojiCompat.reset(mock(EmojiCompat.class));
+    }
+
+    @Before
+    public void setup() {
+        mInputMethodService = mock(InputMethodService.class);
+    }
+
+    @Test
+    @UiThreadTest
+    public void testInflate() {
+        final Context context = InstrumentationRegistry.getTargetContext();
+        final EmojiExtractTextLayout layout = (EmojiExtractTextLayout) LayoutInflater.from(context)
+                .inflate(android.support.text.emoji.test.R.layout.extract_view, null);
+
+        final EmojiExtractEditText extractEditText = layout.findViewById(
+                android.R.id.inputExtractEditText);
+        assertNotNull(extractEditText);
+
+        final ViewGroup inputExtractAccessories = layout.findViewById(
+                R.id.inputExtractAccessories);
+        assertNotNull(inputExtractAccessories);
+
+        final ExtractButtonCompat extractButton = inputExtractAccessories.findViewById(
+                R.id.inputExtractAction);
+        assertNotNull(extractButton);
+    }
+
+    @Test
+    @UiThreadTest
+    public void testSetEmojiReplaceStrategy() {
+        final Context context = InstrumentationRegistry.getTargetContext();
+
+        final EmojiExtractTextLayout layout = (EmojiExtractTextLayout) LayoutInflater.from(context)
+                .inflate(android.support.text.emoji.test.R.layout.extract_view_with_attrs, null);
+
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT, layout.getEmojiReplaceStrategy());
+
+        final EmojiExtractEditText extractEditText = layout.findViewById(
+                android.R.id.inputExtractEditText);
+        assertNotNull(extractEditText);
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT,
+                extractEditText.getEmojiReplaceStrategy());
+
+        layout.setEmojiReplaceStrategy(EmojiCompat.REPLACE_STRATEGY_ALL);
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_ALL, layout.getEmojiReplaceStrategy());
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_ALL, extractEditText.getEmojiReplaceStrategy());
+    }
+
+    @Test
+    @UiThreadTest
+    @SdkSuppress(minSdkVersion = 19)
+    public void testSetEmojiReplaceStrategyCallEmojiCompatWithCorrectStrategy() {
+        final Context context = InstrumentationRegistry.getTargetContext();
+
+        final EmojiExtractTextLayout layout = (EmojiExtractTextLayout) LayoutInflater.from(context)
+                .inflate(android.support.text.emoji.test.R.layout.extract_view_with_attrs, null);
+
+        final EmojiExtractEditText extractEditText = layout.findViewById(
+                android.R.id.inputExtractEditText);
+        assertNotNull(layout);
+        assertNotNull(extractEditText);
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT, layout.getEmojiReplaceStrategy());
+
+        final EmojiCompat emojiCompat = mock(EmojiCompat.class);
+        when(emojiCompat.getLoadState()).thenReturn(EmojiCompat.LOAD_STATE_SUCCEEDED);
+        EmojiCompat.reset(emojiCompat);
+
+        final String testString = "anytext";
+        extractEditText.setText(testString);
+
+        verify(emojiCompat, times(1)).process(sameCharSequence(testString), anyInt(), anyInt(),
+                anyInt(), eq(EmojiCompat.REPLACE_STRATEGY_NON_EXISTENT));
+    }
+
+    @Test
+    @UiThreadTest
+    public void testOnUpdateExtractingViews() {
+        final Context context = InstrumentationRegistry.getTargetContext();
+        final EmojiExtractTextLayout layout = (EmojiExtractTextLayout) LayoutInflater.from(context)
+                .inflate(android.support.text.emoji.test.R.layout.extract_view, null);
+
+        final EditorInfo editorInfo = new EditorInfo();
+        editorInfo.actionLabel = "My Action Label";
+        editorInfo.imeOptions = EditorInfo.IME_ACTION_SEND;
+        editorInfo.inputType = InputType.TYPE_CLASS_TEXT;
+
+        when(mInputMethodService.isExtractViewShown()).thenReturn(true);
+
+        final ViewGroup inputExtractAccessories = layout.findViewById(
+                R.id.inputExtractAccessories);
+        inputExtractAccessories.setVisibility(View.GONE);
+
+        final ExtractButtonCompat extractButton = inputExtractAccessories.findViewById(
+                R.id.inputExtractAction);
+
+        layout.onUpdateExtractingViews(mInputMethodService, editorInfo);
+
+        assertEquals(View.VISIBLE, inputExtractAccessories.getVisibility());
+        assertEquals(editorInfo.actionLabel, extractButton.getText());
+        assertTrue(extractButton.hasOnClickListeners());
+    }
+
+    @Test
+    @UiThreadTest
+    public void testOnUpdateExtractingViews_hidesAccessoriesIfNoAction() {
+        final Context context = InstrumentationRegistry.getTargetContext();
+        final EmojiExtractTextLayout layout = (EmojiExtractTextLayout) LayoutInflater.from(context)
+                .inflate(android.support.text.emoji.test.R.layout.extract_view, null);
+
+        final EditorInfo editorInfo = new EditorInfo();
+        editorInfo.imeOptions = EditorInfo.IME_ACTION_NONE;
+        when(mInputMethodService.isExtractViewShown()).thenReturn(true);
+
+        final ViewGroup inputExtractAccessories = layout.findViewById(
+                R.id.inputExtractAccessories);
+        final ExtractButtonCompat extractButton = inputExtractAccessories.findViewById(
+                R.id.inputExtractAction);
+
+        layout.onUpdateExtractingViews(mInputMethodService, editorInfo);
+
+        assertEquals(View.GONE, inputExtractAccessories.getVisibility());
+        assertFalse(extractButton.hasOnClickListeners());
+    }
+}
diff --git a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiInputFilterTest.java b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiInputFilterTest.java
index ca594cf..690a946 100644
--- a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiInputFilterTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiInputFilterTest.java
@@ -68,7 +68,7 @@
     @Test
     public void testFilter_withString() {
         final String testString = "abc";
-        when(mEmojiCompat.process(any(Spannable.class), anyInt(), anyInt()))
+        when(mEmojiCompat.process(any(CharSequence.class), anyInt(), anyInt()))
                 .thenReturn(new SpannableString(testString));
         final CharSequence result = mInputFilter.filter(testString, 0, 1, null, 0, 1);
 
diff --git a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiTextWatcherTest.java b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiTextWatcherTest.java
index 728947c..88549cf 100644
--- a/emoji/core/tests/java/android/support/text/emoji/widget/EmojiTextWatcherTest.java
+++ b/emoji/core/tests/java/android/support/text/emoji/widget/EmojiTextWatcherTest.java
@@ -18,6 +18,7 @@
 
 import static android.support.text.emoji.util.EmojiMatcher.sameCharSequence;
 
+import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
@@ -60,7 +61,7 @@
         mTextWatcher.onTextChanged(testString, 0, 0, 1);
 
         verify(mEmojiCompat, times(1)).process(sameCharSequence(testString), eq(0), eq(1),
-                eq(Integer.MAX_VALUE));
+                eq(Integer.MAX_VALUE), anyInt());
         verify(mEmojiCompat, times(0)).registerInitCallback(any(EmojiCompat.InitCallback.class));
     }
 
@@ -71,7 +72,8 @@
 
         mTextWatcher.onTextChanged(testString, 0, 0, 1);
 
-        verify(mEmojiCompat, times(0)).process(any(Spannable.class), anyInt(), anyInt(), anyInt());
+        verify(mEmojiCompat, times(0)).process(any(Spannable.class), anyInt(), anyInt(), anyInt(),
+                anyInt());
         verify(mEmojiCompat, times(1)).registerInitCallback(any(EmojiCompat.InitCallback.class));
     }
 
@@ -82,7 +84,28 @@
 
         mTextWatcher.onTextChanged(testString, 0, 0, 1);
 
-        verify(mEmojiCompat, times(0)).process(any(Spannable.class), anyInt(), anyInt(), anyInt());
+        verify(mEmojiCompat, times(0)).process(any(Spannable.class), anyInt(), anyInt(), anyInt(),
+                anyInt());
         verify(mEmojiCompat, times(0)).registerInitCallback(any(EmojiCompat.InitCallback.class));
     }
+
+    @Test
+    public void testSetEmojiReplaceStrategy() {
+        final Spannable testString = new SpannableString("abc");
+        when(mEmojiCompat.getLoadState()).thenReturn(EmojiCompat.LOAD_STATE_SUCCEEDED);
+
+        assertEquals(EmojiCompat.REPLACE_STRATEGY_DEFAULT, mTextWatcher.getEmojiReplaceStrategy());
+
+        mTextWatcher.onTextChanged(testString, 0, 0, 1);
+
+        verify(mEmojiCompat, times(1)).process(any(Spannable.class), anyInt(), anyInt(), anyInt(),
+                eq(EmojiCompat.REPLACE_STRATEGY_DEFAULT));
+
+        mTextWatcher.setEmojiReplaceStrategy(EmojiCompat.REPLACE_STRATEGY_ALL);
+
+        mTextWatcher.onTextChanged(testString, 0, 0, 1);
+
+        verify(mEmojiCompat, times(1)).process(any(Spannable.class), anyInt(), anyInt(), anyInt(),
+                eq(EmojiCompat.REPLACE_STRATEGY_ALL));
+    }
 }
diff --git a/emoji/core/tests/res/layout/extract_view.xml b/emoji/core/tests/res/layout/extract_view.xml
new file mode 100644
index 0000000..ba72433
--- /dev/null
+++ b/emoji/core/tests/res/layout/extract_view.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<android.support.text.emoji.widget.EmojiExtractTextLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"/>
\ No newline at end of file
diff --git a/emoji/core/tests/res/layout/extract_view_with_attrs.xml b/emoji/core/tests/res/layout/extract_view_with_attrs.xml
new file mode 100644
index 0000000..0c16e7d
--- /dev/null
+++ b/emoji/core/tests/res/layout/extract_view_with_attrs.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<android.support.text.emoji.widget.EmojiExtractTextLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/emojiExtractTextLayout"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    app:emojiReplaceStrategy="nonExistent"/>
\ No newline at end of file
diff --git a/exifinterface/build.gradle b/exifinterface/build.gradle
index 583ed93..634fd28 100644
--- a/exifinterface/build.gradle
+++ b/exifinterface/build.gradle
@@ -2,9 +2,9 @@
 archivesBaseName = 'exifinterface'
 
 dependencies {
-    compile project(':support-annotations')
+    api project(':support-annotations')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/exifinterface/lint-baseline.xml b/exifinterface/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/exifinterface/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/exifinterface/src/android/support/media/ExifInterface.java b/exifinterface/src/android/support/media/ExifInterface.java
index ec59c63..aa19cbe 100644
--- a/exifinterface/src/android/support/media/ExifInterface.java
+++ b/exifinterface/src/android/support/media/ExifInterface.java
@@ -19,6 +19,7 @@
 import android.content.res.AssetManager;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
+import android.location.Location;
 import android.support.annotation.IntDef;
 import android.support.annotation.NonNull;
 import android.util.Log;
@@ -49,8 +50,10 @@
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.TimeZone;
+import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -389,10 +392,15 @@
     public static final int ORIENTATION_FLIP_VERTICAL = 4;  // upside down mirror
     // flipped about top-left <--> bottom-right axis
     public static final int ORIENTATION_TRANSPOSE = 5;
-    public static final int ORIENTATION_ROTATE_90 = 6;  // rotate 90 cw to right it
+    public static final int ORIENTATION_ROTATE_90 = 6;  // rotate 90 degree clockwise
     // flipped about top-right <--> bottom-left axis
     public static final int ORIENTATION_TRANSVERSE = 7;
-    public static final int ORIENTATION_ROTATE_270 = 8;  // rotate 270 to right it
+    public static final int ORIENTATION_ROTATE_270 = 8;  // rotate 270 degree clockwise
+    private static final List<Integer> ROTATION_ORDER = Arrays.asList(ORIENTATION_NORMAL,
+            ORIENTATION_ROTATE_90, ORIENTATION_ROTATE_180, ORIENTATION_ROTATE_270);
+    private static final List<Integer> FLIPPED_ROTATION_ORDER = Arrays.asList(
+            ORIENTATION_FLIP_HORIZONTAL, ORIENTATION_TRANSVERSE, ORIENTATION_FLIP_VERTICAL,
+            ORIENTATION_TRANSPOSE);
 
     // Constants used for white balance
     public static final int WHITEBALANCE_AUTO = 0;
@@ -401,7 +409,7 @@
     // Maximum size for checking file type signature (see image_type_recognition_lite.cc)
     private static final int SIGNATURE_CHECK_SIZE = 5000;
 
-    private static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff};
+    static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff};
     private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW";
     private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84;
     private static final int RAF_INFO_SIZE = 160;
@@ -437,11 +445,11 @@
     // image metadata from GPS longitude to camera model name.
 
     // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2)
-    private static final short BYTE_ALIGN_II = 0x4949;  // II: Intel order
-    private static final short BYTE_ALIGN_MM = 0x4d4d;  // MM: Motorola order
+    static final short BYTE_ALIGN_II = 0x4949;  // II: Intel order
+    static final short BYTE_ALIGN_MM = 0x4d4d;  // MM: Motorola order
 
     // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2)
-    private static final byte START_CODE = 0x2a; // 42
+    static final byte START_CODE = 0x2a; // 42
     private static final int IFD_OFFSET = 8;
 
     // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".)
@@ -460,12 +468,12 @@
     // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag")
     private static final int IFD_FORMAT_IFD = 13;
     // Names for the data formats for debugging purpose.
-    private static final String[] IFD_FORMAT_NAMES = new String[] {
+    static final String[] IFD_FORMAT_NAMES = new String[] {
             "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT",
             "SLONG", "SRATIONAL", "SINGLE", "DOUBLE"
     };
     // Sizes of the components of each IFD value format
-    private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] {
+    static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] {
             0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1
     };
     private static final byte[] EXIF_ASCII_PREFIX = new byte[] {
@@ -517,6 +525,10 @@
         public final long numerator;
         public final long denominator;
 
+        private Rational(double value) {
+            this((long) (value * 10000), 10000);
+        }
+
         private Rational(long numerator, long denominator) {
             // Handle erroneous case
             if (denominator == 0) {
@@ -903,7 +915,7 @@
     }
 
     // A class for indicating EXIF tag.
-    private static class ExifTag {
+    static class ExifTag {
         public final int number;
         public final String name;
         public final int primaryFormat;
@@ -922,6 +934,24 @@
             this.primaryFormat = primaryFormat;
             this.secondaryFormat = secondaryFormat;
         }
+
+        private boolean isFormatCompatible(int format) {
+            if (primaryFormat == IFD_FORMAT_UNDEFINED || format == IFD_FORMAT_UNDEFINED) {
+                return true;
+            } else if (primaryFormat == format || secondaryFormat == format) {
+                return true;
+            } else if ((primaryFormat == IFD_FORMAT_ULONG || secondaryFormat == IFD_FORMAT_ULONG)
+                    && format == IFD_FORMAT_USHORT) {
+                return true;
+            } else if ((primaryFormat == IFD_FORMAT_SLONG || secondaryFormat == IFD_FORMAT_SLONG)
+                    && format == IFD_FORMAT_SSHORT) {
+                return true;
+            } else if ((primaryFormat == IFD_FORMAT_DOUBLE || secondaryFormat == IFD_FORMAT_DOUBLE)
+                    && format == IFD_FORMAT_SINGLE) {
+                return true;
+            }
+            return false;
+        }
     }
 
     // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
@@ -1150,19 +1180,19 @@
             IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF})
     public @interface IfdType {}
 
-    private static final int IFD_TYPE_PRIMARY = 0;
+    static final int IFD_TYPE_PRIMARY = 0;
     private static final int IFD_TYPE_EXIF = 1;
     private static final int IFD_TYPE_GPS = 2;
     private static final int IFD_TYPE_INTEROPERABILITY = 3;
-    private static final int IFD_TYPE_THUMBNAIL = 4;
-    private static final int IFD_TYPE_PREVIEW = 5;
+    static final int IFD_TYPE_THUMBNAIL = 4;
+    static final int IFD_TYPE_PREVIEW = 5;
     private static final int IFD_TYPE_ORF_MAKER_NOTE = 6;
     private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7;
     private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8;
     private static final int IFD_TYPE_PEF = 9;
 
     // List of Exif tag groups
-    private static final ExifTag[][] EXIF_TAGS = new ExifTag[][] {
+    static final ExifTag[][] EXIF_TAGS = new ExifTag[][] {
             IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS,
             IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS,
             ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS
@@ -1205,11 +1235,11 @@
 
     private static final Charset ASCII = Charset.forName("US-ASCII");
     // Identifier for EXIF APP1 segment in JPEG
-    private static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII);
+    static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII);
     // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with
     // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start
     // of frame(baseline DCT) and the image size info exists in its beginning part.
-    private static final byte MARKER = (byte) 0xff;
+    static final byte MARKER = (byte) 0xff;
     private static final byte MARKER_SOI = (byte) 0xd8;
     private static final byte MARKER_SOF0 = (byte) 0xc0;
     private static final byte MARKER_SOF1 = (byte) 0xc1;
@@ -1225,9 +1255,9 @@
     private static final byte MARKER_SOF14 = (byte) 0xce;
     private static final byte MARKER_SOF15 = (byte) 0xcf;
     private static final byte MARKER_SOS = (byte) 0xda;
-    private static final byte MARKER_APP1 = (byte) 0xe1;
+    static final byte MARKER_APP1 = (byte) 0xe1;
     private static final byte MARKER_COM = (byte) 0xfe;
-    private static final byte MARKER_EOI = (byte) 0xd9;
+    static final byte MARKER_EOI = (byte) 0xd9;
 
     // Supported Image File Types
     private static final int IMAGE_TYPE_UNKNOWN = 0;
@@ -1427,7 +1457,7 @@
     }
 
     /**
-     * Set the value of the specified tag.
+     * Sets the value of the specified tag.
      *
      * @param tag the name of the tag.
      * @param value the value of the tag.
@@ -1446,7 +1476,7 @@
             } else {
                 try {
                     double doubleValue = Double.parseDouble(value);
-                    value = (long) (doubleValue * 10000L) + "/10000";
+                    value = new Rational(doubleValue).toString();
                 } catch (NumberFormatException e) {
                     Log.w(TAG, "Invalid value for " + tag + " : " + value);
                     return;
@@ -1567,6 +1597,122 @@
     }
 
     /**
+     * Resets the {@link #TAG_ORIENTATION} of the image to be {@link #ORIENTATION_NORMAL}.
+     */
+    public void resetOrientation() {
+        setAttribute(TAG_ORIENTATION, Integer.toString(ORIENTATION_NORMAL));
+    }
+
+    /**
+     * Rotates the image by the given degree clockwise. The degree should be a multiple of
+     * 90 (e.g, 90, 180, -90, etc.).
+     *
+     * @param degree The degree of rotation.
+     */
+    public void rotate(int degree) {
+        if (degree % 90 !=0) {
+            throw new IllegalArgumentException("degree should be a multiple of 90");
+        }
+
+        int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+        int currentIndex, newIndex;
+        int resultOrientation;
+        if (ROTATION_ORDER.contains(currentOrientation)) {
+            currentIndex = ROTATION_ORDER.indexOf(currentOrientation);
+            newIndex = (currentIndex + degree / 90) % 4;
+            newIndex += newIndex < 0 ? 4 : 0;
+            resultOrientation = ROTATION_ORDER.get(newIndex);
+        } else if (FLIPPED_ROTATION_ORDER.contains(currentOrientation)) {
+            currentIndex = FLIPPED_ROTATION_ORDER.indexOf(currentOrientation);
+            newIndex = (currentIndex + degree / 90) % 4;
+            newIndex += newIndex < 0 ? 4 : 0;
+            resultOrientation = FLIPPED_ROTATION_ORDER.get(newIndex);
+        } else {
+            resultOrientation = ORIENTATION_UNDEFINED;
+        }
+
+        setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+    }
+
+    /**
+     * Flips the image vertically.
+     */
+    public void flipVertically() {
+        int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+        int resultOrientation;
+        switch (currentOrientation) {
+            case ORIENTATION_FLIP_HORIZONTAL:
+                resultOrientation = ORIENTATION_ROTATE_180;
+                break;
+            case ORIENTATION_ROTATE_180:
+                resultOrientation = ORIENTATION_FLIP_HORIZONTAL;
+                break;
+            case ORIENTATION_FLIP_VERTICAL:
+                resultOrientation = ORIENTATION_NORMAL;
+                break;
+            case ORIENTATION_TRANSPOSE:
+                resultOrientation = ORIENTATION_ROTATE_270;
+                break;
+            case ORIENTATION_ROTATE_90:
+                resultOrientation = ORIENTATION_TRANSVERSE;
+                break;
+            case ORIENTATION_TRANSVERSE:
+                resultOrientation = ORIENTATION_ROTATE_90;
+                break;
+            case ORIENTATION_ROTATE_270:
+                resultOrientation = ORIENTATION_TRANSPOSE;
+                break;
+            case ORIENTATION_NORMAL:
+                resultOrientation = ORIENTATION_FLIP_VERTICAL;
+                break;
+            case ORIENTATION_UNDEFINED:
+            default:
+                resultOrientation = ORIENTATION_UNDEFINED;
+                break;
+        }
+        setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+    }
+
+    /**
+     * Flips the image horizontally.
+     */
+    public void flipHorizontally() {
+        int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+        int resultOrientation;
+        switch (currentOrientation) {
+            case ORIENTATION_FLIP_HORIZONTAL:
+                resultOrientation = ORIENTATION_NORMAL;
+                break;
+            case ORIENTATION_ROTATE_180:
+                resultOrientation = ORIENTATION_FLIP_VERTICAL;
+                break;
+            case ORIENTATION_FLIP_VERTICAL:
+                resultOrientation = ORIENTATION_ROTATE_180;
+                break;
+            case ORIENTATION_TRANSPOSE:
+                resultOrientation = ORIENTATION_ROTATE_90;
+                break;
+            case ORIENTATION_ROTATE_90:
+                resultOrientation = ORIENTATION_TRANSPOSE;
+                break;
+            case ORIENTATION_TRANSVERSE:
+                resultOrientation = ORIENTATION_ROTATE_270;
+                break;
+            case ORIENTATION_ROTATE_270:
+                resultOrientation = ORIENTATION_TRANSVERSE;
+                break;
+            case ORIENTATION_NORMAL:
+                resultOrientation = ORIENTATION_FLIP_HORIZONTAL;
+                break;
+            case ORIENTATION_UNDEFINED:
+            default:
+                resultOrientation = ORIENTATION_UNDEFINED;
+                break;
+        }
+        setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+    }
+
+    /**
      * Update the values of the tags in the tag groups if any value for the tag already was stored.
      *
      * @param tag the name of the tag.
@@ -1899,6 +2045,28 @@
     }
 
     /**
+     * Sets the GPS-related information. It will set GPS processing method, latitude and longitude
+     * values, GPS timestamp, and speed information at the same time.
+     *
+     * @param location the {@link Location} object returned by GPS service.
+     */
+    public void setGpsInfo(Location location) {
+        if (location == null) {
+            return;
+        }
+        setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, location.getProvider());
+        setLatLong(location.getLatitude(), location.getLongitude());
+        setAltitude(location.getAltitude());
+        // Location objects store speeds in m/sec. Translates it to km/hr here.
+        setAttribute(TAG_GPS_SPEED_REF, "K");
+        setAttribute(TAG_GPS_SPEED, new Rational(location.getSpeed()
+                * TimeUnit.HOURS.toSeconds(1) / 1000).toString());
+        String[] dateTime = sFormatter.format(new Date(location.getTime())).split("\\s+");
+        setAttribute(ExifInterface.TAG_GPS_DATESTAMP, dateTime[0]);
+        setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, dateTime[1]);
+    }
+
+    /**
      * Sets the latitude and longitude values.
      *
      * @param latitude the decimal value of latitude. Must be a valid double value between -90.0 and
@@ -1939,6 +2107,27 @@
     }
 
     /**
+     * Sets the altitude in meters.
+     */
+    public void setAltitude(double altitude) {
+        String ref = altitude >= 0 ? "0" : "1";
+        setAttribute(TAG_GPS_ALTITUDE, new Rational(Math.abs(altitude)).toString());
+        setAttribute(TAG_GPS_ALTITUDE_REF, ref);
+    }
+
+    /**
+     * Set the date time value.
+     *
+     * @param timeStamp number of milliseconds since Jan. 1, 1970, midnight local time.
+     * @hide
+     */
+    public void setDateTime(long timeStamp) {
+        long sub = timeStamp % 1000;
+        setAttribute(TAG_DATETIME, sFormatter.format(new Date(timeStamp)));
+        setAttribute(TAG_SUBSEC_TIME, Long.toString(sub));
+    }
+
+    /**
      * Returns number of milliseconds since Jan. 1, 1970, midnight local time.
      * Returns -1 if the date time information if not available.
      * @hide
@@ -2421,16 +2610,16 @@
             readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE);
 
             // Retrieve & update preview image offset & length values
-            ExifAttribute imageLengthAttribute = (ExifAttribute)
+            ExifAttribute imageStartAttribute = (ExifAttribute)
                     mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START);
-            ExifAttribute bitsPerSampleAttribute = (ExifAttribute)
+            ExifAttribute imageLengthAttribute = (ExifAttribute)
                     mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH);
 
-            if (imageLengthAttribute != null && bitsPerSampleAttribute != null) {
+            if (imageStartAttribute != null && imageLengthAttribute != null) {
                 mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT,
-                        imageLengthAttribute);
+                        imageStartAttribute);
                 mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
-                        bitsPerSampleAttribute);
+                        imageLengthAttribute);
             }
 
             // TODO: Check this behavior in other ORF files
@@ -2603,9 +2792,9 @@
     }
 
     private void addDefaultValuesForCompatibility() {
-        // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
+        // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's.
         String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL);
-        if (valueOfDateTimeOriginal != null) {
+        if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) {
             mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME,
                     ExifAttribute.createString(valueOfDateTimeOriginal));
         }
@@ -2684,15 +2873,14 @@
         }
         // See TIFF 6.0 Section 2: TIFF Structure, Figure 1.
         short numberOfDirectoryEntry = dataInputStream.readShort();
+        if (DEBUG) {
+            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
+        }
         if (dataInputStream.mPosition + 12 * numberOfDirectoryEntry > dataInputStream.mLength) {
             // Return if the size of entries is too big.
             return;
         }
 
-        if (DEBUG) {
-            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
-        }
-
         // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory".
         for (short i = 0; i < numberOfDirectoryEntry; ++i) {
             int tagNumber = dataInputStream.readUnsignedShort();
@@ -2716,7 +2904,13 @@
                 Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber);
             } else if (dataFormat <= 0 || dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) {
                 Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat);
+            } else if (!tag.isFormatCompatible(dataFormat)) {
+                Log.w(TAG, "Skip the tag entry since data format (" + IFD_FORMAT_NAMES[dataFormat]
+                        + ") is unexpected for tag: " + tag.name);
             } else {
+                if (dataFormat == IFD_FORMAT_UNDEFINED) {
+                    dataFormat = tag.primaryFormat;
+                }
                 byteCount = (long) numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
                 if (byteCount < 0 || byteCount > Integer.MAX_VALUE) {
                     Log.w(TAG, "Skip the tag entry since the number of components is invalid: "
diff --git a/exifinterface/tests/AndroidManifest.xml b/exifinterface/tests/AndroidManifest.xml
index 142772e..91e9859 100644
--- a/exifinterface/tests/AndroidManifest.xml
+++ b/exifinterface/tests/AndroidManifest.xml
@@ -15,10 +15,9 @@
    limitations under the License.
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.support.media.test">
+          package="android.support.media.test">
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
-    <uses-sdk android:minSdkVersion="9"/>
 </manifest>
\ No newline at end of file
diff --git a/exifinterface/tests/src/android/support/media/ExifInterfaceTest.java b/exifinterface/tests/src/android/support/media/ExifInterfaceTest.java
index ee9e38e..07ba52d 100644
--- a/exifinterface/tests/src/android/support/media/ExifInterfaceTest.java
+++ b/exifinterface/tests/src/android/support/media/ExifInterfaceTest.java
@@ -25,9 +25,11 @@
 
 import android.content.res.TypedArray;
 import android.graphics.Bitmap;
+import android.location.Location;
 import android.os.Environment;
 import android.support.exifinterface.test.R;
 import android.support.test.filters.LargeTest;
+import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.util.Log;
@@ -46,6 +48,9 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Test {@link ExifInterface}.
@@ -66,6 +71,8 @@
 
     private static final String TEST_TEMP_FILE_NAME = "testImage";
     private static final double DELTA = 1e-8;
+    // We translate double to rational in a 1/10000 precision.
+    private static final double RATIONAL_DELTA = 0.0001;
     private static final int TEST_LAT_LONG_VALUES_ARRAY_LENGTH = 8;
     private static final double[] TEST_LATITUDE_VALID_VALUES = new double[]
             {0, 45, 90, -60, 0.00000001, -89.999999999, 14.2465923626, -68.3434534737};
@@ -77,12 +84,97 @@
     private static final double[] TEST_LONGITUDE_INVALID_VALUES = new double[]
             {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 180.0000000001,
                     263.34763236326, -1e10, 347.325252623, -4000.346323236};
+    private static final double[] TEST_ALTITUDE_VALUES = new double[]
+            {0, -2000, 10000, -355.99999999999, 18.02038};
+    private static final int[][] TEST_ROTATION_STATE_MACHINE = {
+            {ExifInterface.ORIENTATION_UNDEFINED, -90, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_UNDEFINED, 0, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_UNDEFINED, 90, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_UNDEFINED, 180, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_UNDEFINED, 270, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_UNDEFINED, 540, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_NORMAL, -90, ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_NORMAL, 0, ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_NORMAL, 90, ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_NORMAL, 180,ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_NORMAL, 270,ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_NORMAL, 540,ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_ROTATE_90, -90, ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_ROTATE_90, 0, ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_ROTATE_90, 90, ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_ROTATE_90, 180,ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_ROTATE_90, 270,ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_ROTATE_90, 540,ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_ROTATE_180, -90, ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_ROTATE_180, 0, ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_ROTATE_180, 90, ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_ROTATE_180, 180,ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_ROTATE_180, 270,ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_ROTATE_180, 540,ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_ROTATE_270, -90, ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_ROTATE_270, 0, ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_ROTATE_270, 90, ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_ROTATE_270, 180,ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_ROTATE_270, 270,ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_ROTATE_270, 540,ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, -90, ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, 0, ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, 90, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, 180,
+                    ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, 270,ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, 540,
+                    ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, -90, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, 0,
+                    ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, 90, ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, 180,
+                    ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, 270, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, 540,
+                    ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_TRANSPOSE, -90, ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_TRANSPOSE, 0, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_TRANSPOSE, 90, ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_TRANSPOSE, 180,ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_TRANSPOSE, 270,ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_TRANSPOSE, 540,ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_TRANSVERSE, -90, ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_TRANSVERSE, 0, ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_TRANSVERSE, 90, ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_TRANSVERSE, 180,ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_TRANSVERSE, 270,ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_TRANSVERSE, 540,ExifInterface.ORIENTATION_TRANSPOSE},
+    };
+    private static final int[][] TEST_FLIP_VERTICALLY_STATE_MACHINE = {
+            {ExifInterface.ORIENTATION_UNDEFINED, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_NORMAL, ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_TRANSPOSE, ExifInterface.ORIENTATION_ROTATE_270},
+            {ExifInterface.ORIENTATION_TRANSVERSE, ExifInterface.ORIENTATION_ROTATE_90}
+    };
+    private static final int[][] TEST_FLIP_HORIZONTALLY_STATE_MACHINE = {
+            {ExifInterface.ORIENTATION_UNDEFINED, ExifInterface.ORIENTATION_UNDEFINED},
+            {ExifInterface.ORIENTATION_NORMAL, ExifInterface.ORIENTATION_FLIP_HORIZONTAL},
+            {ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSPOSE},
+            {ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_FLIP_VERTICAL},
+            {ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSVERSE},
+            {ExifInterface.ORIENTATION_FLIP_VERTICAL, ExifInterface.ORIENTATION_ROTATE_180},
+            {ExifInterface.ORIENTATION_FLIP_HORIZONTAL, ExifInterface.ORIENTATION_NORMAL},
+            {ExifInterface.ORIENTATION_TRANSPOSE, ExifInterface.ORIENTATION_ROTATE_90},
+            {ExifInterface.ORIENTATION_TRANSVERSE, ExifInterface.ORIENTATION_ROTATE_270}
+    };
 
     private static final String[] EXIF_TAGS = {
             ExifInterface.TAG_MAKE,
             ExifInterface.TAG_MODEL,
             ExifInterface.TAG_F_NUMBER,
-            ExifInterface.TAG_DATETIME,
+            ExifInterface.TAG_DATETIME_ORIGINAL,
             ExifInterface.TAG_EXPOSURE_TIME,
             ExifInterface.TAG_FLASH,
             ExifInterface.TAG_FOCAL_LENGTH,
@@ -118,7 +210,7 @@
         public final String make;
         public final String model;
         public final float aperture;
-        public final String datetime;
+        public final String dateTimeOriginal;
         public final float exposureTime;
         public final float flash;
         public final String focalLength;
@@ -161,7 +253,7 @@
             make = getString(typedArray, 7);
             model = getString(typedArray, 8);
             aperture = typedArray.getFloat(9, 0f);
-            datetime = getString(typedArray, 10);
+            dateTimeOriginal = getString(typedArray, 10);
             exposureTime = typedArray.getFloat(11, 0f);
             flash = typedArray.getFloat(12, 0f);
             focalLength = getString(typedArray, 13);
@@ -236,21 +328,122 @@
     }
 
     @Test
-    @SmallTest
+    @MediumTest
     public void testDoNotFailOnCorruptedImage() throws Throwable {
-        // To keep the compatibility with old versions of ExifInterface, even on a corrupted image,
-        // it shouldn't raise any exceptions except an IOException when unable to open a file.
-        byte[] bytes = new byte[1024];
-        try {
-            new ExifInterface(new ByteArrayInputStream(bytes));
-            // Always success
-        } catch (IOException e) {
-            fail("Should not reach here!");
+        // ExifInterface shouldn't raise any exceptions except an IOException when unable to open
+        // a file, even with a corrupted image. Generates 10,000 randomly corrupted image stream
+        // for testing. Uses Epoch date count as random seed so that we can reproduce a broken test.
+        Random random = new Random(System.currentTimeMillis() / 86400);
+        byte[] bytes = new byte[8096];
+        ByteBuffer buffer = ByteBuffer.wrap(bytes);
+        for (int i = 0; i < 10000; i++) {
+            buffer.clear();
+            random.nextBytes(bytes);
+            if (!randomlyCorrupted(random)) {
+                buffer.put(ExifInterface.JPEG_SIGNATURE);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.put(ExifInterface.MARKER_APP1);
+            }
+            buffer.putShort((short) (random.nextInt(100) + 300));
+            if (!randomlyCorrupted(random)) {
+                buffer.put(ExifInterface.IDENTIFIER_EXIF_APP1);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.putShort(ExifInterface.BYTE_ALIGN_MM);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.put((byte) 0);
+                buffer.put(ExifInterface.START_CODE);
+            }
+            buffer.putInt(8);
+
+            // Primary Tags
+            int numberOfDirectory = random.nextInt(8) + 1;
+            if (!randomlyCorrupted(random)) {
+                buffer.putShort((short) numberOfDirectory);
+            }
+            for (int j = 0; j < numberOfDirectory; j++) {
+                generateRandomExifTag(buffer, ExifInterface.IFD_TYPE_PRIMARY, random);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.putInt(buffer.position() - 8);
+            }
+
+            // Thumbnail Tags
+            numberOfDirectory = random.nextInt(8) + 1;
+            if (!randomlyCorrupted(random)) {
+                buffer.putShort((short) numberOfDirectory);
+            }
+            for (int j = 0; j < numberOfDirectory; j++) {
+                generateRandomExifTag(buffer, ExifInterface.IFD_TYPE_THUMBNAIL, random);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.putInt(buffer.position() - 8);
+            }
+
+            // Preview Tags
+            numberOfDirectory = random.nextInt(8) + 1;
+            if (!randomlyCorrupted(random)) {
+                buffer.putShort((short) numberOfDirectory);
+            }
+            for (int j = 0; j < numberOfDirectory; j++) {
+                generateRandomExifTag(buffer, ExifInterface.IFD_TYPE_PREVIEW, random);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.putInt(buffer.position() - 8);
+            }
+
+            if (!randomlyCorrupted(random)) {
+                buffer.put(ExifInterface.MARKER);
+            }
+            if (!randomlyCorrupted(random)) {
+                buffer.put(ExifInterface.MARKER_EOI);
+            }
+
+            try {
+                new ExifInterface(new ByteArrayInputStream(bytes));
+                // Always success
+            } catch (IOException e) {
+                fail("Should not reach here!");
+            }
         }
     }
 
     @Test
     @SmallTest
+    public void testSetGpsInfo() throws IOException {
+        final String provider = "ExifInterfaceTest";
+        final long timestamp = System.currentTimeMillis();
+        final float speedInMeterPerSec = 36.627533f;
+        Location location = new Location(provider);
+        location.setLatitude(TEST_LATITUDE_VALID_VALUES[TEST_LATITUDE_VALID_VALUES.length - 1]);
+        location.setLongitude(TEST_LONGITUDE_VALID_VALUES[TEST_LONGITUDE_VALID_VALUES.length - 1]);
+        location.setAltitude(TEST_ALTITUDE_VALUES[TEST_ALTITUDE_VALUES.length - 1]);
+        location.setSpeed(speedInMeterPerSec);
+        location.setTime(timestamp);
+        ExifInterface exif = createTestExifInterface();
+        exif.setGpsInfo(location);
+
+        double[] latLong = exif.getLatLong();
+        assertNotNull(latLong);
+        assertEquals(TEST_LATITUDE_VALID_VALUES[TEST_LATITUDE_VALID_VALUES.length - 1],
+                latLong[0], DELTA);
+        assertEquals(TEST_LONGITUDE_VALID_VALUES[TEST_LONGITUDE_VALID_VALUES.length - 1],
+                latLong[1], DELTA);
+        assertEquals(TEST_ALTITUDE_VALUES[TEST_ALTITUDE_VALUES.length - 1], exif.getAltitude(0),
+                RATIONAL_DELTA);
+        assertEquals("K", exif.getAttribute(ExifInterface.TAG_GPS_SPEED_REF));
+        assertEquals(speedInMeterPerSec, exif.getAttributeDouble(ExifInterface.TAG_GPS_SPEED, 0.0)
+                * 1000 / TimeUnit.HOURS.toSeconds(1), RATIONAL_DELTA);
+        assertEquals(provider, exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
+        // GPS time's precision is secs.
+        assertEquals(TimeUnit.MILLISECONDS.toSeconds(timestamp),
+                TimeUnit.MILLISECONDS.toSeconds(exif.getGpsDateTime()));
+    }
+
+    @Test
+    @SmallTest
     public void testSetLatLong_withValidValues() throws IOException {
         for (int i = 0; i < TEST_LAT_LONG_VALUES_ARRAY_LENGTH; i++) {
             ExifInterface exif = createTestExifInterface();
@@ -295,6 +488,110 @@
         }
     }
 
+    @Test
+    @SmallTest
+    public void testSetAltitude() throws IOException {
+        for (int i = 0; i < TEST_ALTITUDE_VALUES.length; i++) {
+            ExifInterface exif = createTestExifInterface();
+            exif.setAltitude(TEST_ALTITUDE_VALUES[i]);
+            assertEquals(TEST_ALTITUDE_VALUES[i], exif.getAltitude(Double.NaN), RATIONAL_DELTA);
+        }
+    }
+
+    @Test
+    @SmallTest
+    public void testSetDateTime() throws IOException {
+        final String dateTimeValue = "2017:02:02 22:22:22";
+        final String dateTimeOriginalValue = "2017:01:01 11:11:11";
+
+        File imageFile = new File(
+                Environment.getExternalStorageDirectory(), EXIF_BYTE_ORDER_II_JPEG);
+        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
+        exif.setAttribute(ExifInterface.TAG_DATETIME, dateTimeValue);
+        exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateTimeOriginalValue);
+        exif.saveAttributes();
+
+        // Check that the DATETIME value is not overwritten by DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL));
+
+        // Now remove the DATETIME value.
+        exif.setAttribute(ExifInterface.TAG_DATETIME, null);
+        exif.saveAttributes();
+
+        // When the DATETIME has no value, then it should be set to DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+
+        long currentTimeStamp = System.currentTimeMillis();
+        exif.setDateTime(currentTimeStamp);
+        exif.saveAttributes();
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(currentTimeStamp, exif.getDateTime());
+    }
+
+    @Test
+    @SmallTest
+    public void testRotation() throws IOException {
+        File imageFile = new File(
+                Environment.getExternalStorageDirectory(), EXIF_BYTE_ORDER_II_JPEG);
+        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
+
+        int num;
+        // Test flip vertically.
+        for (num = 0; num < TEST_FLIP_VERTICALLY_STATE_MACHINE.length; num++) {
+            exif.setAttribute(ExifInterface.TAG_ORIENTATION,
+                    Integer.toString(TEST_FLIP_VERTICALLY_STATE_MACHINE[num][0]));
+            exif.flipVertically();
+            exif.saveAttributes();
+            exif = new ExifInterface(imageFile.getAbsolutePath());
+            assertIntTag(exif, ExifInterface.TAG_ORIENTATION,
+                    TEST_FLIP_VERTICALLY_STATE_MACHINE[num][1]);
+
+        }
+
+        // Test flip horizontally.
+        for (num = 0; num < TEST_FLIP_VERTICALLY_STATE_MACHINE.length; num++) {
+            exif.setAttribute(ExifInterface.TAG_ORIENTATION,
+                    Integer.toString(TEST_FLIP_HORIZONTALLY_STATE_MACHINE[num][0]));
+            exif.flipHorizontally();
+            exif.saveAttributes();
+            exif = new ExifInterface(imageFile.getAbsolutePath());
+            assertIntTag(exif, ExifInterface.TAG_ORIENTATION,
+                    TEST_FLIP_HORIZONTALLY_STATE_MACHINE[num][1]);
+
+        }
+
+        // Test rotate by degrees
+        exif.setAttribute(ExifInterface.TAG_ORIENTATION,
+                Integer.toString(ExifInterface.ORIENTATION_NORMAL));
+        try {
+            exif.rotate(108);
+            fail("Rotate with 108 degree should throw IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // Success
+        }
+
+        for (num = 0; num < TEST_ROTATION_STATE_MACHINE.length; num++) {
+            exif.setAttribute(ExifInterface.TAG_ORIENTATION,
+                    Integer.toString(TEST_ROTATION_STATE_MACHINE[num][0]));
+            exif.rotate(TEST_ROTATION_STATE_MACHINE[num][1]);
+            exif.saveAttributes();
+            exif = new ExifInterface(imageFile.getAbsolutePath());
+            assertIntTag(exif, ExifInterface.TAG_ORIENTATION, TEST_ROTATION_STATE_MACHINE[num][2]);
+        }
+
+        // Test reset the rotation.
+        exif.setAttribute(ExifInterface.TAG_ORIENTATION,
+                Integer.toString(ExifInterface.ORIENTATION_FLIP_HORIZONTAL));
+        exif.resetOrientation();
+        exif.saveAttributes();
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertIntTag(exif, ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
+
+    }
+
     private void printExifTagsAndValues(String fileName, ExifInterface exifInterface) {
         // Prints thumbnail information.
         if (exifInterface.hasThumbnail()) {
@@ -390,7 +687,8 @@
         assertStringTag(exifInterface, ExifInterface.TAG_MAKE, expectedValue.make);
         assertStringTag(exifInterface, ExifInterface.TAG_MODEL, expectedValue.model);
         assertFloatTag(exifInterface, ExifInterface.TAG_F_NUMBER, expectedValue.aperture);
-        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME, expectedValue.datetime);
+        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME_ORIGINAL,
+                expectedValue.dateTimeOriginal);
         assertFloatTag(exifInterface, ExifInterface.TAG_EXPOSURE_TIME, expectedValue.exposureTime);
         assertFloatTag(exifInterface, ExifInterface.TAG_FLASH, expectedValue.flash);
         assertStringTag(exifInterface, ExifInterface.TAG_FOCAL_LENGTH, expectedValue.focalLength);
@@ -482,6 +780,31 @@
         // about writing back in here.
     }
 
+    private void generateRandomExifTag(ByteBuffer buffer, int ifdType, Random random) {
+        ExifInterface.ExifTag[] tagGroup = ExifInterface.EXIF_TAGS[ifdType];
+        ExifInterface.ExifTag tag = tagGroup[random.nextInt(tagGroup.length)];
+        if (!randomlyCorrupted(random)) {
+            buffer.putShort((short) tag.number);
+        }
+        int dataFormat = random.nextInt(ExifInterface.IFD_FORMAT_NAMES.length);
+        if (!randomlyCorrupted(random)) {
+            buffer.putShort((short) dataFormat);
+        }
+        buffer.putInt(1);
+        int dataLength = ExifInterface.IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
+        if (dataLength > 4) {
+            buffer.putShort((short) random.nextInt(8096 - dataLength));
+            buffer.position(buffer.position() + 2);
+        } else {
+            buffer.position(buffer.position() + 4);
+        }
+    }
+
+    private boolean randomlyCorrupted(Random random) {
+        // Corrupts somewhere in a possibility of 1/500.
+        return random.nextInt(500) == 0;
+    }
+
     private void closeQuietly(Closeable closeable) {
         if (closeable != null) {
             try {
diff --git a/fragment/build.gradle b/fragment/build.gradle
index f93d020..b50b691 100644
--- a/fragment/build.gradle
+++ b/fragment/build.gradle
@@ -2,19 +2,18 @@
 archivesBaseName = 'support-fragment'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-core-ui')
-    compile project(':support-core-utils')
+    api project(':support-compat')
+    api project(':support-core-ui')
+    api project(':support-core-utils')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/fragment/java/android/support/v4/app/Fragment.java b/fragment/java/android/support/v4/app/Fragment.java
index 1df0f37..f8e3d47 100644
--- a/fragment/java/android/support/v4/app/Fragment.java
+++ b/fragment/java/android/support/v4/app/Fragment.java
@@ -340,6 +340,11 @@
     // getLayoutInflater()
     LayoutInflater mLayoutInflater;
 
+    // Keep track of whether or not this Fragment has run performCreate(). Retained instance
+    // fragments can have mRetaining set to true without going through creation, so we must
+    // track it separately.
+    boolean mIsCreated;
+
     /**
      * State information that has been retrieved from a fragment instance
      * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
@@ -2322,6 +2327,7 @@
         mState = CREATED;
         mCalled = false;
         onCreate(savedInstanceState);
+        mIsCreated = true;
         if (!mCalled) {
             throw new SuperNotCalledException("Fragment " + this
                     + " did not call through to super.onCreate()");
@@ -2583,6 +2589,7 @@
         }
         mState = INITIALIZING;
         mCalled = false;
+        mIsCreated = false;
         onDestroy();
         if (!mCalled) {
             throw new SuperNotCalledException("Fragment " + this
diff --git a/fragment/java/android/support/v4/app/FragmentManager.java b/fragment/java/android/support/v4/app/FragmentManager.java
index c49b69b..288fe57 100644
--- a/fragment/java/android/support/v4/app/FragmentManager.java
+++ b/fragment/java/android/support/v4/app/FragmentManager.java
@@ -662,7 +662,8 @@
     ArrayList<Integer> mAvailBackStackIndices;
 
     ArrayList<OnBackStackChangedListener> mBackStackChangeListeners;
-    private CopyOnWriteArrayList<Pair<FragmentLifecycleCallbacks, Boolean>> mLifecycleCallbacks;
+    private final CopyOnWriteArrayList<Pair<FragmentLifecycleCallbacks, Boolean>>
+            mLifecycleCallbacks = new CopyOnWriteArrayList<>();
 
     int mCurState = Fragment.INITIALIZING;
     FragmentHostCallback mHost;
@@ -1371,7 +1372,7 @@
                         }
                         dispatchOnFragmentAttached(f, mHost.getContext(), false);
 
-                        if (!f.mRetaining) {
+                        if (!f.mIsCreated) {
                             dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false);
                             f.performCreate(f.mSavedFragmentState);
                             dispatchOnFragmentCreated(f, f.mSavedFragmentState, false);
@@ -3350,18 +3351,11 @@
     @Override
     public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb,
             boolean recursive) {
-        if (mLifecycleCallbacks == null) {
-            mLifecycleCallbacks = new CopyOnWriteArrayList<>();
-        }
         mLifecycleCallbacks.add(new Pair<>(cb, recursive));
     }
 
     @Override
     public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) {
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
-
         synchronized (mLifecycleCallbacks) {
             for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) {
                 if (mLifecycleCallbacks.get(i).first == cb) {
@@ -3380,9 +3374,6 @@
                         .dispatchOnFragmentPreAttached(f, context, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentPreAttached(this, f, context);
@@ -3398,9 +3389,6 @@
                         .dispatchOnFragmentAttached(f, context, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentAttached(this, f, context);
@@ -3417,9 +3405,6 @@
                         .dispatchOnFragmentPreCreated(f, savedInstanceState, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentPreCreated(this, f, savedInstanceState);
@@ -3435,9 +3420,6 @@
                         .dispatchOnFragmentCreated(f, savedInstanceState, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentCreated(this, f, savedInstanceState);
@@ -3454,9 +3436,6 @@
                         .dispatchOnFragmentActivityCreated(f, savedInstanceState, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentActivityCreated(this, f, savedInstanceState);
@@ -3473,9 +3452,6 @@
                         .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentViewCreated(this, f, v, savedInstanceState);
@@ -3491,9 +3467,6 @@
                         .dispatchOnFragmentStarted(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentStarted(this, f);
@@ -3509,9 +3482,6 @@
                         .dispatchOnFragmentResumed(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentResumed(this, f);
@@ -3527,9 +3497,6 @@
                         .dispatchOnFragmentPaused(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentPaused(this, f);
@@ -3545,9 +3512,6 @@
                         .dispatchOnFragmentStopped(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentStopped(this, f);
@@ -3563,9 +3527,6 @@
                         .dispatchOnFragmentSaveInstanceState(f, outState, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentSaveInstanceState(this, f, outState);
@@ -3581,9 +3542,6 @@
                         .dispatchOnFragmentViewDestroyed(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentViewDestroyed(this, f);
@@ -3599,9 +3557,6 @@
                         .dispatchOnFragmentDestroyed(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentDestroyed(this, f);
@@ -3617,9 +3572,6 @@
                         .dispatchOnFragmentDetached(f, true);
             }
         }
-        if (mLifecycleCallbacks == null) {
-            return;
-        }
         for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
             if (!onlyRecursive || p.second) {
                 p.first.onFragmentDetached(this, f);
diff --git a/fragment/java/android/support/v4/app/FragmentStatePagerAdapter.java b/fragment/java/android/support/v4/app/FragmentStatePagerAdapter.java
index 7aa3d20..fc27c4f 100644
--- a/fragment/java/android/support/v4/app/FragmentStatePagerAdapter.java
+++ b/fragment/java/android/support/v4/app/FragmentStatePagerAdapter.java
@@ -62,7 +62,7 @@
  *      complete}
  */
 public abstract class FragmentStatePagerAdapter extends PagerAdapter {
-    private static final String TAG = "FragmentStatePagerAdapter";
+    private static final String TAG = "FragmentStatePagerAdapt";
     private static final boolean DEBUG = false;
 
     private final FragmentManager mFragmentManager;
diff --git a/fragment/lint-baseline.xml b/fragment/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/fragment/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/fragment/tests/AndroidManifest.xml b/fragment/tests/AndroidManifest.xml
index bd0a433..e6a520e 100644
--- a/fragment/tests/AndroidManifest.xml
+++ b/fragment/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.fragment.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.VIBRATE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
@@ -29,20 +24,20 @@
     <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
 
     <application
-            android:supportsRtl="true"
-            android:theme="@style/TestActivityTheme">
+        android:supportsRtl="true"
+        android:theme="@style/TestActivityTheme">
         <activity android:name="android.support.v4.app.test.FragmentTestActivity"/>
 
-        <activity android:name="android.support.v4.app.test.EmptyFragmentTestActivity" />
+        <activity android:name="android.support.v4.app.test.EmptyFragmentTestActivity"/>
 
-        <activity android:name="android.support.v4.app.test.FragmentResultActivity" />
+        <activity android:name="android.support.v4.app.test.FragmentResultActivity"/>
 
-        <activity android:name="android.support.v4.app.test.LoaderActivity" />
+        <activity android:name="android.support.v4.app.test.LoaderActivity"/>
 
         <activity android:name="android.support.v4.app.test.NewIntentActivity"
-                  android:launchMode="singleInstance" />
+                  android:launchMode="singleInstance"/>
 
-        <activity android:name="android.support.v4.app.test.NonConfigOnStopActivity" />
+        <activity android:name="android.support.v4.app.test.NonConfigOnStopActivity"/>
     </application>
 
 </manifest>
diff --git a/fragment/tests/java/android/support/v4/app/CtsMockitoUtils.java b/fragment/tests/java/android/support/v4/app/CtsMockitoUtils.java
index c82b61d..1ccb87b 100644
--- a/fragment/tests/java/android/support/v4/app/CtsMockitoUtils.java
+++ b/fragment/tests/java/android/support/v4/app/CtsMockitoUtils.java
@@ -18,6 +18,7 @@
 import android.os.SystemClock;
 
 import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.verification.VerificationModeFactory;
 import org.mockito.internal.verification.api.VerificationData;
 import org.mockito.invocation.Invocation;
 import org.mockito.verification.VerificationMode;
@@ -74,6 +75,11 @@
                     + data.getWanted().toString());
         }
 
+        @Override
+        public VerificationMode description(String description) {
+            return VerificationModeFactory.description(this, description);
+        }
+
         private void markAllInvocationsAsVerified(VerificationData data) {
             for (Invocation invocation : data.getAllInvocations()) {
                 invocation.markVerified();
diff --git a/fragment/tests/java/android/support/v4/app/FragmentLifecycleTest.java b/fragment/tests/java/android/support/v4/app/FragmentLifecycleTest.java
index a312b9b..09f071e 100644
--- a/fragment/tests/java/android/support/v4/app/FragmentLifecycleTest.java
+++ b/fragment/tests/java/android/support/v4/app/FragmentLifecycleTest.java
@@ -1107,6 +1107,86 @@
         }
     }
 
+    /**
+     * When a retained instance fragment is saved while in the back stack, it should go
+     * through onCreate() when it is popped back.
+     */
+    @Test
+    @UiThreadTest
+    public void retainInstanceWithOnCreate() throws Throwable {
+        FragmentController fc = FragmentTestUtil.createController(mActivityRule);
+        FragmentTestUtil.resume(mActivityRule, fc, null);
+        FragmentManager fm = fc.getSupportFragmentManager();
+
+        OnCreateFragment fragment1 = new OnCreateFragment();
+
+        fm.beginTransaction()
+                .add(fragment1, "1")
+                .commit();
+        fm.beginTransaction()
+                .remove(fragment1)
+                .addToBackStack(null)
+                .commit();
+
+        Pair<Parcelable, FragmentManagerNonConfig> savedState =
+                FragmentTestUtil.destroy(mActivityRule, fc);
+        Pair<Parcelable, FragmentManagerNonConfig> restartState =
+                Pair.create(savedState.first, null);
+
+        fc = FragmentTestUtil.createController(mActivityRule);
+        FragmentTestUtil.resume(mActivityRule, fc, restartState);
+
+        // Save again, but keep the state
+        savedState = FragmentTestUtil.destroy(mActivityRule, fc);
+
+        fc = FragmentTestUtil.createController(mActivityRule);
+        FragmentTestUtil.resume(mActivityRule, fc, savedState);
+
+        fm = fc.getSupportFragmentManager();
+
+        fm.popBackStackImmediate();
+        OnCreateFragment fragment2 = (OnCreateFragment) fm.findFragmentByTag("1");
+        assertTrue(fragment2.onCreateCalled);
+        fm.popBackStackImmediate();
+    }
+
+    /**
+     * A retained instance fragment should go through onCreate() once, even through save and
+     * restore.
+     */
+    @Test
+    @UiThreadTest
+    public void retainInstanceOneOnCreate() throws Throwable {
+        FragmentController fc = FragmentTestUtil.createController(mActivityRule);
+        FragmentTestUtil.resume(mActivityRule, fc, null);
+        FragmentManager fm = fc.getSupportFragmentManager();
+
+        OnCreateFragment fragment = new OnCreateFragment();
+
+        fm.beginTransaction()
+                .add(fragment, "fragment")
+                .commit();
+        fm.executePendingTransactions();
+
+        fm.beginTransaction()
+                .remove(fragment)
+                .addToBackStack(null)
+                .commit();
+
+        assertTrue(fragment.onCreateCalled);
+        fragment.onCreateCalled = false;
+
+        Pair<Parcelable, FragmentManagerNonConfig> savedState =
+                FragmentTestUtil.destroy(mActivityRule, fc);
+
+        fc = FragmentTestUtil.createController(mActivityRule);
+        FragmentTestUtil.resume(mActivityRule, fc, savedState);
+        fm = fc.getSupportFragmentManager();
+
+        fm.popBackStackImmediate();
+        assertFalse(fragment.onCreateCalled);
+    }
+
     private void assertAnimationsMatch(FragmentManager fm, int enter, int exit, int popEnter,
             int popExit) {
         FragmentManagerImpl fmImpl = (FragmentManagerImpl) fm;
@@ -1440,4 +1520,18 @@
             }
         }
     }
+
+    public static class OnCreateFragment extends Fragment {
+        public boolean onCreateCalled;
+
+        public OnCreateFragment() {
+            setRetainInstance(true);
+        }
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            onCreateCalled = true;
+        }
+    }
 }
diff --git a/gradle.properties b/gradle.properties
index d1c2c14..9b77c57 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,4 +1,6 @@
 org.gradle.jvmargs=-Xmx4g
 org.gradle.daemon=true
-org.gradle.configureondemand=true
-org.gradle.parallel=true
\ No newline at end of file
+# Disabled due to b/63329112
+# org.gradle.configureondemand=true
+org.gradle.parallel=true
+android.useDexArchive=false
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index ea0d01f..2a386c4 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -3,4 +3,4 @@
 distributionPath=wrapper/dists
 zipStoreBase=GRADLE_USER_HOME
 zipStorePath=wrapper/dists
-distributionUrl=../../../../tools/external/gradle/gradle-3.5-bin.zip
+distributionUrl=../../../../tools/external/gradle/gradle-4.1-milestone-1-bin.zip
diff --git a/graphics/drawable/animated/build.gradle b/graphics/drawable/animated/build.gradle
index 00a3688..5fc9edd 100644
--- a/graphics/drawable/animated/build.gradle
+++ b/graphics/drawable/animated/build.gradle
@@ -2,14 +2,15 @@
 archivesBaseName = 'animated-vector-drawable'
 
 dependencies {
-    compile project(':support-vector-drawable')
-    androidTestCompile (libs.test_runner) {
+    api project(':support-vector-drawable')
+    api project(':support-core-ui')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    compile project(path: ':support-core-ui')
 }
 
 android {
diff --git a/graphics/drawable/animated/lint-baseline.xml b/graphics/drawable/animated/lint-baseline.xml
new file mode 100644
index 0000000..0668235
--- /dev/null
+++ b/graphics/drawable/animated/lint-baseline.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="ResourceType"
+        message="Expected resource of type anim"
+        errorLine1="            parser = resources.getAnimation(id);"
+        errorLine2="                                            ~~">
+        <location
+            file="src/android/support/graphics/drawable/AnimatorInflaterCompat.java"
+            line="130"
+            column="45"/>
+    </issue>
+
+</issues>
diff --git a/graphics/drawable/animated/src/android/support/graphics/drawable/Animatable2Compat.java b/graphics/drawable/animated/src/android/support/graphics/drawable/Animatable2Compat.java
index d9d0f36..232dc81 100644
--- a/graphics/drawable/animated/src/android/support/graphics/drawable/Animatable2Compat.java
+++ b/graphics/drawable/animated/src/android/support/graphics/drawable/Animatable2Compat.java
@@ -25,7 +25,7 @@
 import android.support.annotation.RequiresApi;
 
 /**
- * Abstract class that drawables supporting animations and callbacks should extend in support lib.
+ * Interface that drawables supporting animations and callbacks should extend in support lib.
  */
 public interface Animatable2Compat extends Animatable {
 
@@ -51,7 +51,7 @@
     void clearAnimationCallbacks();
 
     /**
-     * Animation callback interface. Used to notify animation events.
+     * Abstract class for animation callback. Used to notify animation events.
      */
     abstract class AnimationCallback {
         /**
diff --git a/graphics/drawable/animated/tests/AndroidManifest.xml b/graphics/drawable/animated/tests/AndroidManifest.xml
index f6cda49..a43ebd4 100644
--- a/graphics/drawable/animated/tests/AndroidManifest.xml
+++ b/graphics/drawable/animated/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.graphics.drawable.animated.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                    android.support.test.espresso, android.support.test.espresso.idling" />
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <application>
diff --git a/graphics/drawable/static/build.gradle b/graphics/drawable/static/build.gradle
index 996a855..913729a 100644
--- a/graphics/drawable/static/build.gradle
+++ b/graphics/drawable/static/build.gradle
@@ -2,9 +2,10 @@
 archivesBaseName = 'support-vector-drawable'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
-    androidTestCompile (libs.test_runner) {
+    api project(':support-annotations')
+    api project(':support-compat')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/graphics/drawable/static/lint-baseline.xml b/graphics/drawable/static/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/graphics/drawable/static/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/graphics/drawable/static/src/android/support/graphics/drawable/VectorDrawableCompat.java b/graphics/drawable/static/src/android/support/graphics/drawable/VectorDrawableCompat.java
index f9753eb..b68ef1b 100644
--- a/graphics/drawable/static/src/android/support/graphics/drawable/VectorDrawableCompat.java
+++ b/graphics/drawable/static/src/android/support/graphics/drawable/VectorDrawableCompat.java
@@ -16,6 +16,7 @@
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
 
+import android.annotation.SuppressLint;
 import android.content.res.ColorStateList;
 import android.content.res.Resources;
 import android.content.res.Resources.Theme;
@@ -554,7 +555,7 @@
         }
 
         try {
-            final XmlPullParser parser = res.getXml(resId);
+            @SuppressLint("ResourceType") final XmlPullParser parser = res.getXml(resId);
             final AttributeSet attrs = Xml.asAttributeSet(parser);
             int type;
             while ((type = parser.next()) != XmlPullParser.START_TAG &&
@@ -818,7 +819,8 @@
     // We don't support RTL auto mirroring since the getLayoutDirection() is for API 17+.
     private boolean needMirroring() {
         if (Build.VERSION.SDK_INT >= 17) {
-            return isAutoMirrored() && getLayoutDirection() == LayoutDirection.RTL;
+            return isAutoMirrored()
+                    && DrawableCompat.getLayoutDirection(this) == LayoutDirection.RTL;
         } else {
             return false;
         }
diff --git a/graphics/drawable/static/tests/AndroidManifest.xml b/graphics/drawable/static/tests/AndroidManifest.xml
index 68a9bad..2c1faaa 100644
--- a/graphics/drawable/static/tests/AndroidManifest.xml
+++ b/graphics/drawable/static/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.graphics.drawable.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                android.support.test.espresso, android.support.test.espresso.idling" />
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 </manifest>
diff --git a/lifecycle/.gitignore b/lifecycle/.gitignore
new file mode 100644
index 0000000..be4e6f1
--- /dev/null
+++ b/lifecycle/.gitignore
@@ -0,0 +1,4 @@
+local.properties
+maven-repo/
+build/
+*.DS_Store
diff --git a/lifecycle/common/build.gradle b/lifecycle/common/build.gradle
new file mode 100644
index 0000000..ac9b2e2f
--- /dev/null
+++ b/lifecycle/common/build.gradle
@@ -0,0 +1,14 @@
+apply plugin: 'java'
+apply plugin: 'maven'
+
+sourceCompatibility = 1.7
+
+dependencies {
+    testCompile libs.junit
+    testCompile libs.mockito_core
+    compile libs.support.annotations
+}
+
+archivesBaseName = "common"
+
+createAndroidCheckstyle(project)
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/GenericLifecycleObserver.java b/lifecycle/common/src/main/java/android/arch/lifecycle/GenericLifecycleObserver.java
new file mode 100644
index 0000000..a34bfbf
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/GenericLifecycleObserver.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * Internal class that can receive any lifecycle change and dispatch it to the receiver.
+ * @hide
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public interface GenericLifecycleObserver extends LifecycleObserver {
+    /**
+     * Called when a state transition event happens.
+     *
+     * @param source The source of the event
+     * @param event The event
+     */
+    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
+
+    /**
+     * Returns the actual receiver of the event
+     *
+     * @return The actual receiver
+     */
+    Object getReceiver();
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycle.java b/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycle.java
new file mode 100644
index 0000000..fcbd50a
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycle.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.annotation.MainThread;
+
+/**
+ * Defines an object that has an Android Lifecycle. {@link android.support.v4.app.Fragment Fragment}
+ * and {@link android.support.v4.app.FragmentActivity FragmentActivity} classes implement
+ * {@link LifecycleOwner} interface which has the {@link LifecycleOwner#getLifecycle()
+ * getLifecycle} method to access the Lifecycle. You can also implement {@link LifecycleOwner}
+ * in your own classes.
+ * <p>
+ * {@link Event#ON_CREATE}, {@link Event#ON_START}, {@link Event#ON_RESUME} events in this class
+ * are dispatched <b>after</b> the {@link LifecycleOwner}'s related method returns.
+ * {@link Event#ON_PAUSE}, {@link Event#ON_STOP}, {@link Event#ON_DESTROY} events in this class
+ * are dispatched <b>before</b> the {@link LifecycleOwner}'s related method is called.
+ * For instance, {@link Event#ON_START} will be dispatched after
+ * {@link android.app.Activity#onStart onStart} returns, {@link Event#ON_STOP} will be dispatched
+ * before {@link android.app.Activity#onStop onStop} is called.
+ * This gives you certain guarantees on which state the owner is in.
+ * <p>
+ * Lifecycle events are observed using annotations.
+ * <pre>
+ * class TestObserver implements LifecycleObserver {
+ *   {@literal @}OnLifecycleEvent(ON_STOP)
+ *   void onStopped() {}
+ * }
+ * </pre>
+ * <p>
+ * Multiple methods can observe the same event.
+ * <pre>
+ * class TestObserver implements LifecycleObserver {
+ *   {@literal @}OnLifecycleEvent(ON_STOP)
+ *   void onStoppedFirst() {}
+ *   {@literal @}OnLifecycleEvent(ON_STOP)
+ *   void onStoppedSecond() {}
+ * }
+ * </pre>
+ * <p>
+ * Observer methods can receive zero or one argument.
+ * If used, the first argument must be of type {@link LifecycleOwner}.
+ * Methods annotated with {@link Event#ON_ANY} can receive the second argument, which must be
+ * of type {@link Event}.
+ * <pre>
+ * class TestObserver implements LifecycleObserver {
+ *   {@literal @}OnLifecycleEvent(ON_CREATE)
+ *   void onCreated(LifecycleOwner source) {}
+ *   {@literal @}OnLifecycleEvent(ON_ANY)
+ *   void onAny(LifecycleOwner source, Event event) {}
+ * }
+ * </pre>
+ * These additional parameters are provided to allow you to conveniently observe multiple providers
+ * and events without tracking them manually.
+ */
+public abstract class Lifecycle {
+    /**
+     * Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
+     * state.
+     * <p>
+     * The given observer will be brought to the current state of the LifecycleOwner.
+     * For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
+     * will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
+     *
+     * @param observer The observer to notify.
+     */
+    @MainThread
+    public abstract void addObserver(LifecycleObserver observer);
+
+    /**
+     * Removes the given observer from the observers list.
+     * <p>
+     * If this method is called while a state change is being dispatched,
+     * <ul>
+     * <li>If the given observer has not yet received that event, it will not receive it.
+     * <li>If the given observer has more than 1 method that observes the currently dispatched
+     * event and at least one of them received the event, all of them will receive the event and
+     * the removal will happen afterwards.
+     * </ul>
+     *
+     * @param observer The observer to be removed.
+     */
+    @MainThread
+    public abstract void removeObserver(LifecycleObserver observer);
+
+    /**
+     * Returns the current state of the Lifecycle.
+     *
+     * @return The current state of the Lifecycle.
+     */
+    @MainThread
+    public abstract State getCurrentState();
+
+    @SuppressWarnings("WeakerAccess")
+    public enum Event {
+        /**
+         * Constant for onCreate event of the {@link LifecycleOwner}.
+         */
+        ON_CREATE,
+        /**
+         * Constant for onStart event of the {@link LifecycleOwner}.
+         */
+        ON_START,
+        /**
+         * Constant for onResume event of the {@link LifecycleOwner}.
+         */
+        ON_RESUME,
+        /**
+         * Constant for onPause event of the {@link LifecycleOwner}.
+         */
+        ON_PAUSE,
+        /**
+         * Constant for onStop event of the {@link LifecycleOwner}.
+         */
+        ON_STOP,
+        /**
+         * Constant for onDestroy event of the {@link LifecycleOwner}.
+         */
+        ON_DESTROY,
+        /**
+         * An {@link Event Event} constant that can be used to match all events.
+         */
+        ON_ANY
+    }
+
+    /**
+     * Lifecycle states. You can consider the states as the nodes in a graph and
+     * {@link Event}s as the edges between these nodes.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public enum State {
+        /**
+         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
+         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
+         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
+         */
+        DESTROYED,
+
+        /**
+         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
+         * the state when it is constructed but has not received
+         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
+         */
+        INITIALIZED,
+
+        /**
+         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
+         * is reached in two cases:
+         * <ul>
+         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
+         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
+         * </ul>
+         */
+        CREATED,
+
+        /**
+         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
+         * is reached in two cases:
+         * <ul>
+         *     <li>after {@link android.app.Activity#onStart() onStart} call;
+         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
+         * </ul>
+         */
+        STARTED,
+
+        /**
+         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
+         * is reached after {@link android.app.Activity#onResume() onResume} is called.
+         */
+        RESUMED;
+
+        /**
+         * Compares if this State is greater or equal to the given {@code state}.
+         *
+         * @param state State to compare with
+         * @return true if this State is greater or equal to the given {@code state}
+         */
+        public boolean isAtLeast(State state) {
+            return compareTo(state) >= 0;
+        }
+    }
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleObserver.java b/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleObserver.java
new file mode 100644
index 0000000..94670bf
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleObserver.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
+ * {@link OnLifecycleEvent} annotated methods.
+ * <p>
+ * @see Lifecycle Lifecycle - for samples and usage patterns.
+ */
+@SuppressWarnings("WeakerAccess")
+public interface LifecycleObserver {
+
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleOwner.java b/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleOwner.java
new file mode 100644
index 0000000..934cf3a
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/LifecycleOwner.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * A class that has an Android lifecycle. These events can be used by custom components to
+ * handle lifecycle changes without implementing any code inside the Activity or the Fragment.
+ *
+ * @see Lifecycle
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public interface LifecycleOwner {
+    /**
+     * Returns the Lifecycle of the provider.
+     *
+     * @return The lifecycle of the provider.
+     */
+    Lifecycle getLifecycle();
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycling.java b/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycling.java
new file mode 100644
index 0000000..295f731
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/Lifecycling.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Internal class to handle lifecycle conversion etc.
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+class Lifecycling {
+    private static Constructor<? extends GenericLifecycleObserver> sREFLECTIVE;
+
+    static {
+        try {
+            sREFLECTIVE = ReflectiveGenericLifecycleObserver.class
+                    .getDeclaredConstructor(Object.class);
+        } catch (NoSuchMethodException ignored) {
+
+        }
+    }
+
+    private static Map<Class, Constructor<? extends GenericLifecycleObserver>> sCallbackCache =
+            new HashMap<>();
+
+    @NonNull
+    static GenericLifecycleObserver getCallback(Object object) {
+        if (object instanceof GenericLifecycleObserver) {
+            return (GenericLifecycleObserver) object;
+        }
+        //noinspection TryWithIdenticalCatches
+        try {
+            final Class<?> klass = object.getClass();
+            Constructor<? extends GenericLifecycleObserver> cachedConstructor = sCallbackCache.get(
+                    klass);
+            if (cachedConstructor != null) {
+                return cachedConstructor.newInstance(object);
+            }
+            cachedConstructor = getGeneratedAdapterConstructor(klass);
+            if (cachedConstructor != null) {
+                if (!cachedConstructor.isAccessible()) {
+                    cachedConstructor.setAccessible(true);
+                }
+            } else {
+                cachedConstructor = sREFLECTIVE;
+            }
+            sCallbackCache.put(klass, cachedConstructor);
+            return cachedConstructor.newInstance(object);
+        } catch (IllegalAccessException e) {
+            throw new RuntimeException(e);
+        } catch (InstantiationException e) {
+            throw new RuntimeException(e);
+        } catch (InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Nullable
+    private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor(
+            Class<?> klass) {
+        final String fullPackage = klass.getPackage().getName();
+
+        String name = klass.getCanonicalName();
+        // anonymous class bug:35073837
+        if (name == null) {
+            return null;
+        }
+        final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
+                name.substring(fullPackage.length() + 1));
+        try {
+            @SuppressWarnings("unchecked")
+            final Class<? extends GenericLifecycleObserver> aClass =
+                    (Class<? extends GenericLifecycleObserver>) Class.forName(
+                            fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
+            return aClass.getDeclaredConstructor(klass);
+        } catch (ClassNotFoundException e) {
+            final Class<?> superclass = klass.getSuperclass();
+            if (superclass != null) {
+                return getGeneratedAdapterConstructor(superclass);
+            }
+        } catch (NoSuchMethodException e) {
+            // this should not happen
+            throw new RuntimeException(e);
+        }
+        return null;
+    }
+
+    static String getAdapterName(String className) {
+        return className.replace(".", "_") + "_LifecycleAdapter";
+    }
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/OnLifecycleEvent.java b/lifecycle/common/src/main/java/android/arch/lifecycle/OnLifecycleEvent.java
new file mode 100644
index 0000000..9a86b0c
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/OnLifecycleEvent.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@SuppressWarnings("unused")
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+public @interface OnLifecycleEvent {
+    Lifecycle.Event value();
+}
diff --git a/lifecycle/common/src/main/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserver.java b/lifecycle/common/src/main/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserver.java
new file mode 100644
index 0000000..7de32db
--- /dev/null
+++ b/lifecycle/common/src/main/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserver.java
@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.arch.lifecycle.Lifecycle.Event;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * An internal implementation of {@link GenericLifecycleObserver} that relies on reflection.
+ */
+class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
+    private final Object mWrapped;
+    private final CallbackInfo mInfo;
+    @SuppressWarnings("WeakerAccess")
+    static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>();
+
+    ReflectiveGenericLifecycleObserver(Object wrapped) {
+        mWrapped = wrapped;
+        mInfo = getInfo(mWrapped.getClass());
+    }
+
+    @Override
+    public void onStateChanged(LifecycleOwner source, Event event) {
+        invokeCallbacks(mInfo, source, event);
+    }
+
+    private void invokeMethodsForEvent(List<MethodReference> handlers, LifecycleOwner source,
+            Event event) {
+        if (handlers != null) {
+            for (int i = handlers.size() - 1; i >= 0; i--) {
+                MethodReference reference = handlers.get(i);
+                invokeCallback(reference, source, event);
+            }
+        }
+    }
+
+    @SuppressWarnings("ConstantConditions")
+    private void invokeCallbacks(CallbackInfo info, LifecycleOwner source, Event event) {
+        invokeMethodsForEvent(info.mEventToHandlers.get(event), source, event);
+        invokeMethodsForEvent(info.mEventToHandlers.get(Event.ON_ANY), source, event);
+    }
+
+    private void invokeCallback(MethodReference reference, LifecycleOwner source, Event event) {
+        //noinspection TryWithIdenticalCatches
+        try {
+            switch (reference.mCallType) {
+                case CALL_TYPE_NO_ARG:
+                    reference.mMethod.invoke(mWrapped);
+                    break;
+                case CALL_TYPE_PROVIDER:
+                    reference.mMethod.invoke(mWrapped, source);
+                    break;
+                case CALL_TYPE_PROVIDER_WITH_EVENT:
+                    reference.mMethod.invoke(mWrapped, source, event);
+                    break;
+            }
+        } catch (InvocationTargetException e) {
+            throw new RuntimeException("Failed to call observer method", e.getCause());
+        } catch (IllegalAccessException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public Object getReceiver() {
+        return mWrapped;
+    }
+
+    private static CallbackInfo getInfo(Class klass) {
+        CallbackInfo existing = sInfoCache.get(klass);
+        if (existing != null) {
+            return existing;
+        }
+        existing = createInfo(klass);
+        return existing;
+    }
+
+    private static void verifyAndPutHandler(Map<MethodReference, Event> handlers,
+            MethodReference newHandler, Event newEvent, Class klass) {
+        Event event = handlers.get(newHandler);
+        if (event != null && newEvent != event) {
+            Method method = newHandler.mMethod;
+            throw new IllegalArgumentException(
+                    "Method " + method.getName() + " in " + klass.getName()
+                            + " already declared with different @OnLifecycleEvent value: previous"
+                            + " value " + event + ", new value " + newEvent);
+        }
+        if (event == null) {
+            handlers.put(newHandler, newEvent);
+        }
+    }
+
+    private static CallbackInfo createInfo(Class klass) {
+        Class superclass = klass.getSuperclass();
+        Map<MethodReference, Event> handlerToEvent = new HashMap<>();
+        if (superclass != null) {
+            CallbackInfo superInfo = getInfo(superclass);
+            if (superInfo != null) {
+                handlerToEvent.putAll(superInfo.mHandlerToEvent);
+            }
+        }
+
+        Method[] methods = klass.getDeclaredMethods();
+
+        Class[] interfaces = klass.getInterfaces();
+        for (Class intrfc : interfaces) {
+            for (Entry<MethodReference, Event> entry : getInfo(intrfc).mHandlerToEvent.entrySet()) {
+                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
+            }
+        }
+
+        for (Method method : methods) {
+            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
+            if (annotation == null) {
+                continue;
+            }
+            Class<?>[] params = method.getParameterTypes();
+            int callType = CALL_TYPE_NO_ARG;
+            if (params.length > 0) {
+                callType = CALL_TYPE_PROVIDER;
+                if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
+                    throw new IllegalArgumentException(
+                            "invalid parameter type. Must be one and instanceof LifecycleOwner");
+                }
+            }
+            Event event = annotation.value();
+
+            if (params.length > 1) {
+                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
+                if (!params[1].isAssignableFrom(Event.class)) {
+                    throw new IllegalArgumentException(
+                            "invalid parameter type. second arg must be an event");
+                }
+                if (event != Event.ON_ANY) {
+                    throw new IllegalArgumentException(
+                            "Second arg is supported only for ON_ANY value");
+                }
+            }
+            if (params.length > 2) {
+                throw new IllegalArgumentException("cannot have more than 2 params");
+            }
+            MethodReference methodReference = new MethodReference(callType, method);
+            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
+        }
+        CallbackInfo info = new CallbackInfo(handlerToEvent);
+        sInfoCache.put(klass, info);
+        return info;
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    static class CallbackInfo {
+        final Map<Event, List<MethodReference>> mEventToHandlers;
+        final Map<MethodReference, Event> mHandlerToEvent;
+
+        CallbackInfo(Map<MethodReference, Event> handlerToEvent) {
+            mHandlerToEvent = handlerToEvent;
+            mEventToHandlers = new HashMap<>();
+            for (Entry<MethodReference, Event> entry : handlerToEvent.entrySet()) {
+                Event event = entry.getValue();
+                List<MethodReference> methodReferences = mEventToHandlers.get(event);
+                if (methodReferences == null) {
+                    methodReferences = new ArrayList<>();
+                    mEventToHandlers.put(event, methodReferences);
+                }
+                methodReferences.add(entry.getKey());
+            }
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    static class MethodReference {
+        final int mCallType;
+        final Method mMethod;
+
+        MethodReference(int callType, Method method) {
+            mCallType = callType;
+            mMethod = method;
+            mMethod.setAccessible(true);
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+
+            MethodReference that = (MethodReference) o;
+            return mCallType == that.mCallType && mMethod.getName().equals(that.mMethod.getName());
+        }
+
+        @Override
+        public int hashCode() {
+            return 31 * mCallType + mMethod.getName().hashCode();
+        }
+    }
+
+    private static final int CALL_TYPE_NO_ARG = 0;
+    private static final int CALL_TYPE_PROVIDER = 1;
+    private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2;
+}
diff --git a/lifecycle/common/src/test/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserverTest.java b/lifecycle/common/src/test/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserverTest.java
new file mode 100644
index 0000000..68f04e8
--- /dev/null
+++ b/lifecycle/common/src/test/java/android/arch/lifecycle/ReflectiveGenericLifecycleObserverTest.java
@@ -0,0 +1,365 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_ANY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.Lifecycle.State.CREATED;
+import static android.arch.lifecycle.Lifecycle.State.INITIALIZED;
+import static android.arch.lifecycle.Lifecycle.State.RESUMED;
+import static android.arch.lifecycle.Lifecycle.State.STARTED;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Matchers;
+
+@RunWith(JUnit4.class)
+public class ReflectiveGenericLifecycleObserverTest {
+    private LifecycleOwner mOwner;
+    private Lifecycle mLifecycle;
+
+    @Before
+    public void initMocks() {
+        mOwner = mock(LifecycleOwner.class);
+        mLifecycle = mock(Lifecycle.class);
+        when(mOwner.getLifecycle()).thenReturn(mLifecycle);
+    }
+
+    @Test
+    public void anyState() {
+        AnyStateListener obj = mock(AnyStateListener.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        when(mLifecycle.getCurrentState()).thenReturn(STARTED);
+        observer.onStateChanged(mOwner, ON_CREATE);
+        verify(obj).onAnyState(mOwner, ON_CREATE);
+        reset(obj);
+
+        observer.onStateChanged(mOwner, ON_START);
+        verify(obj).onAnyState(mOwner, ON_START);
+        reset(obj);
+
+        observer.onStateChanged(mOwner, ON_RESUME);
+        verify(obj).onAnyState(mOwner, ON_RESUME);
+        reset(obj);
+
+        observer.onStateChanged(mOwner, ON_PAUSE);
+        verify(obj).onAnyState(mOwner, ON_PAUSE);
+        reset(obj);
+
+        observer.onStateChanged(mOwner, ON_STOP);
+        verify(obj).onAnyState(mOwner, ON_STOP);
+        reset(obj);
+
+        observer.onStateChanged(mOwner, ON_DESTROY);
+        verify(obj).onAnyState(mOwner, ON_DESTROY);
+        reset(obj);
+    }
+
+    private static class AnyStateListener implements LifecycleObserver {
+        @OnLifecycleEvent(ON_ANY)
+        void onAnyState(LifecycleOwner owner, Lifecycle.Event event) {
+
+        }
+    }
+
+    @Test
+    public void singleMethod() {
+        CreatedStateListener obj = mock(CreatedStateListener.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        when(mLifecycle.getCurrentState()).thenReturn(CREATED);
+        observer.onStateChanged(mOwner, ON_CREATE);
+        verify(obj).onCreated();
+        verify(obj).onCreated(mOwner);
+    }
+
+    private static class CreatedStateListener implements LifecycleObserver {
+        @OnLifecycleEvent(ON_CREATE)
+        void onCreated() {
+
+        }
+        @SuppressWarnings("UnusedParameters")
+        @OnLifecycleEvent(ON_CREATE)
+        void onCreated(LifecycleOwner provider) {
+
+        }
+    }
+
+    @Test
+    public void eachEvent() {
+        AllMethodsListener obj = mock(AllMethodsListener.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        when(mLifecycle.getCurrentState()).thenReturn(CREATED);
+
+        observer.onStateChanged(mOwner, ON_CREATE);
+        verify(obj).created();
+        reset(obj);
+
+        when(mLifecycle.getCurrentState()).thenReturn(STARTED);
+        observer.onStateChanged(mOwner, ON_START);
+        verify(obj).started();
+        reset(obj);
+
+        when(mLifecycle.getCurrentState()).thenReturn(RESUMED);
+        observer.onStateChanged(mOwner, ON_RESUME);
+        verify(obj).resumed();
+        reset(obj);
+
+        when(mLifecycle.getCurrentState()).thenReturn(STARTED);
+        observer.onStateChanged(mOwner, ON_PAUSE);
+        verify(obj).paused();
+        reset(obj);
+
+        when(mLifecycle.getCurrentState()).thenReturn(CREATED);
+        observer.onStateChanged(mOwner, ON_STOP);
+        verify(obj).stopped();
+        reset(obj);
+
+        when(mLifecycle.getCurrentState()).thenReturn(INITIALIZED);
+        observer.onStateChanged(mOwner, ON_DESTROY);
+        verify(obj).destroyed();
+        reset(obj);
+    }
+
+
+    private static class AllMethodsListener implements LifecycleObserver {
+        @OnLifecycleEvent(ON_CREATE)
+        void created() {}
+
+        @OnLifecycleEvent(ON_START)
+        void started() {}
+
+        @OnLifecycleEvent(ON_RESUME)
+        void resumed() {}
+
+        @OnLifecycleEvent(ON_PAUSE)
+        void paused() {}
+
+        @OnLifecycleEvent(ON_STOP)
+        void stopped() {}
+
+        @OnLifecycleEvent(ON_DESTROY)
+        void destroyed() {
+        }
+    }
+
+    @Test
+    public void testFailingObserver() {
+        class UnprecedentedError extends Error {
+        }
+
+        LifecycleObserver obj = new LifecycleObserver() {
+            @OnLifecycleEvent(ON_START)
+            void started() {
+                throw new UnprecedentedError();
+            }
+        };
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        try {
+            observer.onStateChanged(mOwner, ON_START);
+        } catch (Exception e) {
+            assertThat("exception cause is wrong",
+                    e.getCause() instanceof UnprecedentedError);
+        }
+    }
+
+    @Test
+    public void testPrivateObserverMethods() {
+        class ObserverWithPrivateMethod implements LifecycleObserver {
+            boolean mCalled = false;
+            @OnLifecycleEvent(ON_START)
+            private void started() {
+                mCalled = true;
+            }
+        }
+
+        ObserverWithPrivateMethod obj = mock(ObserverWithPrivateMethod.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        observer.onStateChanged(mOwner, ON_START);
+        assertThat(obj.mCalled, is(true));
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testWrongFirstParam1() {
+        LifecycleObserver observer = new LifecycleObserver() {
+            @OnLifecycleEvent(ON_START)
+            private void started(Lifecycle.Event e) {
+            }
+        };
+        new ReflectiveGenericLifecycleObserver(observer);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testWrongFirstParam2() {
+        LifecycleObserver observer = new LifecycleObserver() {
+            @OnLifecycleEvent(ON_ANY)
+            private void started(Lifecycle l, Lifecycle.Event e) {
+            }
+        };
+        new ReflectiveGenericLifecycleObserver(observer);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testWrongSecondParam() {
+        LifecycleObserver observer = new LifecycleObserver() {
+            @OnLifecycleEvent(ON_START)
+            private void started(LifecycleOwner owner, Lifecycle l) {
+            }
+        };
+        new ReflectiveGenericLifecycleObserver(observer);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testThreeParams() {
+        LifecycleObserver observer = new LifecycleObserver() {
+            @OnLifecycleEvent(ON_ANY)
+            private void started(LifecycleOwner owner, Lifecycle.Event e, int i) {
+            }
+        };
+        new ReflectiveGenericLifecycleObserver(observer);
+    }
+
+    class BaseClass1 implements LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner) {
+        }
+    }
+
+    class DerivedClass1 extends BaseClass1 {
+        @OnLifecycleEvent(ON_STOP)
+        void foo(LifecycleOwner owner) {
+        }
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testInvalidSuper1() {
+        new ReflectiveGenericLifecycleObserver(new DerivedClass1());
+    }
+
+    class BaseClass2 implements LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner) {
+        }
+    }
+
+    class DerivedClass2 extends BaseClass1 {
+        @OnLifecycleEvent(ON_STOP)
+        void foo() {
+        }
+    }
+
+    @Test
+    public void testValidSuper1() {
+        DerivedClass2 obj = mock(DerivedClass2.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        observer.onStateChanged(mock(LifecycleOwner.class), ON_START);
+        verify(obj).foo(Matchers.<LifecycleOwner>any());
+        verify(obj, never()).foo();
+        reset(obj);
+        observer.onStateChanged(mock(LifecycleOwner.class), ON_STOP);
+        verify(obj).foo();
+        verify(obj, never()).foo(Matchers.<LifecycleOwner>any());
+    }
+
+    class BaseClass3 implements LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner) {
+        }
+    }
+
+    interface Interface3 extends LifecycleObserver {
+        @OnLifecycleEvent(ON_STOP)
+        void foo(LifecycleOwner owner);
+    }
+
+    class DerivedClass3 extends BaseClass3 implements Interface3 {
+        @Override
+        public void foo(LifecycleOwner owner) {
+        }
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testInvalidSuper2() {
+        new ReflectiveGenericLifecycleObserver(new DerivedClass3());
+    }
+
+    class BaseClass4 implements LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner) {
+        }
+    }
+
+    interface Interface4 extends LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner);
+    }
+
+    class DerivedClass4 extends BaseClass4 implements Interface4 {
+        @Override
+        @OnLifecycleEvent(ON_START)
+        public void foo(LifecycleOwner owner) {
+        }
+
+        @OnLifecycleEvent(ON_START)
+        public void foo() {
+        }
+    }
+
+    @Test
+    public void testValidSuper2() {
+        DerivedClass4 obj = mock(DerivedClass4.class);
+        ReflectiveGenericLifecycleObserver observer = new ReflectiveGenericLifecycleObserver(obj);
+        observer.onStateChanged(mock(LifecycleOwner.class), ON_START);
+        verify(obj).foo(Matchers.<LifecycleOwner>any());
+        verify(obj).foo();
+    }
+
+    interface InterfaceStart extends LifecycleObserver {
+        @OnLifecycleEvent(ON_START)
+        void foo(LifecycleOwner owner);
+    }
+
+    interface InterfaceStop extends LifecycleObserver {
+        @OnLifecycleEvent(ON_STOP)
+        void foo(LifecycleOwner owner);
+    }
+
+    class DerivedClass5 implements InterfaceStart, InterfaceStop {
+        @Override
+        public void foo(LifecycleOwner owner) {
+        }
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testInvalidSuper3() {
+        new ReflectiveGenericLifecycleObserver(new DerivedClass5());
+    }
+}
diff --git a/lifecycle/compiler/build.gradle b/lifecycle/compiler/build.gradle
new file mode 100644
index 0000000..f0d2a60
--- /dev/null
+++ b/lifecycle/compiler/build.gradle
@@ -0,0 +1,27 @@
+apply plugin: 'kotlin'
+apply plugin: 'maven'
+apply plugin: 'checkstyle'
+
+sourceSets {
+    test.java.srcDirs += 'src/tests/kotlin'
+}
+
+// Temporary hack to stop AS to adding two guavas into test's classpath
+configurations.all {
+    resolutionStrategy {
+        force libs.guava
+    }
+}
+
+dependencies {
+    compile project(":lifecycle:common")
+    compile libs.kotlin.stdlib
+    compile libs.auto_common
+    compile libs.javapoet
+    testCompile libs.google_compile_testing
+    testCompile files(org.gradle.internal.jvm.Jvm.current().getToolsJar())
+}
+
+archivesBaseName = "compiler"
+
+createKotlinCheckstyle(project)
diff --git a/lifecycle/compiler/reset_results.py b/lifecycle/compiler/reset_results.py
new file mode 100644
index 0000000..994f20d
--- /dev/null
+++ b/lifecycle/compiler/reset_results.py
@@ -0,0 +1,62 @@
+#!/usr/bin/python
+
+#
+# Copyright 2017, 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.
+#
+
+""" Run this script when you need to update test-data/expected."""
+import sys
+
+if len(sys.argv) != 2:
+    print("You need to specify the only one param: file with test failures")
+    sys.exit()
+
+with open(sys.argv[1]) as f:
+    content = f.readlines()
+
+with open("src/tests/test-data/expected/license.txt") as license:
+    licenseLines = license.readlines()
+
+
+def writeToFile(fileName, lines):
+    file = open("src/tests/test-data/expected/" + fileName, "w")
+    for line in lines:
+        file.write(line)
+
+    file.close()
+
+
+state = 0
+filename = ""
+expected = "Expected file:"
+fileLines = []
+for line in content:
+    if (state == 0 and line.startswith(expected)):
+        state = 1
+        filename  = line[line.rfind("/") + 1 : len(line) - 2]
+        print(filename)
+
+    if state == 1 and line.startswith("Actual Source:"):
+        state = 2
+        continue
+
+    if state == 2:
+        fileLines.append(line)
+
+    if state == 2 and line.rstrip() == "}":
+        writeToFile(filename, licenseLines + fileLines[1:])
+        state = 0
+        fileLines = []
+
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/ErrorMessages.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/ErrorMessages.kt
new file mode 100644
index 0000000..8dac863
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/ErrorMessages.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+object ErrorMessages {
+    const val TOO_MANY_ARGS = "callback method cannot have more than 2 parameters"
+    const val TOO_MANY_ARGS_NOT_ON_ANY = "only callback annotated with ON_ANY " +
+            "can have 2 parameters"
+    const val INVALID_SECOND_ARGUMENT = "2nd argument of a callback method" +
+            " must be Lifecycle.Event and represent the current event"
+    const val INVALID_FIRST_ARGUMENT = "1st argument of a callback method must be " +
+            "a LifecycleOwner which represents the source of the event"
+    const val INVALID_METHOD_MODIFIER = "method marked with OnLifecycleEvent annotation can " +
+            "not be private"
+    const val INVALID_CLASS_MODIFIER = "class containing OnLifecycleEvent methods can not be " +
+            "private"
+    const val INVALID_STATE_OVERRIDE_METHOD = "overridden method must handle the same " +
+            "onState changes as original method"
+    const val INVALID_ENCLOSING_ELEMENT =
+            "Parent of OnLifecycleEvent should be a class or interface"
+    const val INVALID_ANNOTATED_ELEMENT = "OnLifecycleEvent can only be added to methods"
+
+}
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/LifecycleProcessor.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/LifecycleProcessor.kt
new file mode 100644
index 0000000..81bcc95
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/LifecycleProcessor.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import javax.annotation.processing.AbstractProcessor
+import javax.annotation.processing.RoundEnvironment
+import javax.annotation.processing.SupportedAnnotationTypes
+import javax.annotation.processing.SupportedSourceVersion
+import javax.lang.model.SourceVersion
+import javax.lang.model.element.TypeElement
+
+@SupportedAnnotationTypes("android.arch.lifecycle.OnLifecycleEvent")
+@SupportedSourceVersion(SourceVersion.RELEASE_7)
+class LifecycleProcessor : AbstractProcessor() {
+    override fun process(annotations: MutableSet<out TypeElement>,
+                         roundEnv: RoundEnvironment): Boolean {
+        val input = collectAndVerifyInput(processingEnv, roundEnv)
+        writeModels(transformToOutput(processingEnv, input), processingEnv.filer)
+        return true
+    }
+}
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/elements_ext.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/elements_ext.kt
new file mode 100644
index 0000000..eedb3af
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/elements_ext.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import com.google.auto.common.MoreElements
+import javax.lang.model.element.Element
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.PackageElement
+
+fun Element.getPackage(): PackageElement = MoreElements.getPackage(this)
+
+fun Element.getPackageQName() = getPackage().qualifiedName.toString()
+
+fun ExecutableElement.name() = simpleName.toString()
+
+fun ExecutableElement.isPackagePrivate() = !modifiers.any {
+    it == Modifier.PUBLIC || it == Modifier.PROTECTED || it == Modifier.PRIVATE
+}
+
+fun ExecutableElement.isProtected() = modifiers.contains(Modifier.PROTECTED)
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/input_collector.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/input_collector.kt
new file mode 100644
index 0000000..5183df5
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/input_collector.kt
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import android.arch.lifecycle.model.EventMethod
+import android.arch.lifecycle.model.LifecycleObserverInfo
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import javax.annotation.processing.ProcessingEnvironment
+import javax.annotation.processing.RoundEnvironment
+import javax.lang.model.element.Element
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.TypeElement
+import javax.lang.model.element.VariableElement
+import javax.tools.Diagnostic
+
+fun collectAndVerifyInput(processingEnv: ProcessingEnvironment,
+                          roundEnv: RoundEnvironment): Map<TypeElement, LifecycleObserverInfo> {
+    val validator = Validator(processingEnv)
+
+    return roundEnv.getElementsAnnotatedWith(OnLifecycleEvent::class.java).map { elem ->
+        if (elem.kind != ElementKind.METHOD) {
+            validator.printErrorMessage(ErrorMessages.INVALID_ANNOTATED_ELEMENT, elem)
+            null
+        } else {
+            val enclosingElement = elem.enclosingElement
+            val onState = elem.getAnnotation(OnLifecycleEvent::class.java)
+            val method = MoreElements.asExecutable(elem)
+            if (validator.validateClass(enclosingElement)
+                    && validator.validateMethod(method, onState.value)) {
+                EventMethod(method, onState, MoreElements.asType(enclosingElement))
+            } else {
+                null
+            }
+        }
+    }
+            .filterNotNull()
+            .groupBy { MoreElements.asType(it.method.enclosingElement) }
+            .mapValues { entry -> LifecycleObserverInfo(entry.key, entry.value) }
+
+}
+
+class Validator(val processingEnv: ProcessingEnvironment) {
+
+    fun printErrorMessage(msg: CharSequence, elem: Element) {
+        processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, msg, elem)
+    }
+
+    fun validateParam(param: VariableElement,
+                      expectedType: Class<*>, errorMsg: String): Boolean {
+        if (!MoreTypes.isTypeOf(expectedType, param.asType())) {
+            printErrorMessage(errorMsg, param)
+            return false
+        }
+        return true
+    }
+
+    fun validateMethod(method: ExecutableElement, event: Lifecycle.Event): Boolean {
+        if (Modifier.PRIVATE in method.modifiers) {
+            printErrorMessage(ErrorMessages.INVALID_METHOD_MODIFIER, method)
+            return false
+        }
+        val params = method.parameters
+        if ((params.size > 2)) {
+            printErrorMessage(ErrorMessages.TOO_MANY_ARGS, method)
+            return false
+        }
+
+        if (params.size == 2 && event != Lifecycle.Event.ON_ANY) {
+            printErrorMessage(ErrorMessages.TOO_MANY_ARGS_NOT_ON_ANY, method)
+            return false
+        }
+
+        if (params.size == 2 && !validateParam(params[1], Lifecycle.Event::class.java,
+                ErrorMessages.INVALID_SECOND_ARGUMENT)) {
+            return false
+        }
+
+        if (params.size > 0) {
+            return validateParam(params[0], LifecycleOwner::class.java,
+                    ErrorMessages.INVALID_FIRST_ARGUMENT)
+        }
+        return true
+    }
+
+    fun validateClass(classElement: Element): Boolean {
+        if (classElement.kind != ElementKind.CLASS && classElement.kind != ElementKind.INTERFACE) {
+            printErrorMessage(ErrorMessages.INVALID_ENCLOSING_ELEMENT, classElement)
+            return false
+        }
+        if (Modifier.PRIVATE in classElement.modifiers) {
+            printErrorMessage(ErrorMessages.INVALID_CLASS_MODIFIER, classElement)
+            return false
+        }
+        return true
+    }
+}
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/AdapterClass.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/AdapterClass.kt
new file mode 100644
index 0000000..1e76fa8
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/AdapterClass.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.model
+
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.TypeElement
+
+data class AdapterClass(val type: TypeElement,
+                        val calls: List<EventMethodCall>,
+                        val syntheticMethods: Set<ExecutableElement>)
\ No newline at end of file
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/EventMethod.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/EventMethod.kt
new file mode 100644
index 0000000..a3d4712
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/EventMethod.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.model
+
+import android.arch.lifecycle.OnLifecycleEvent
+import android.arch.lifecycle.getPackageQName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.TypeElement
+
+data class EventMethod(val method: ExecutableElement,
+                       val onLifecycleEvent: OnLifecycleEvent,
+                       val type: TypeElement) {
+
+    fun packageName() = type.getPackageQName()
+}
+
+data class EventMethodCall(val method: EventMethod, val syntheticAccess: TypeElement? = null)
\ No newline at end of file
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/LifecycleObserverInfo.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/LifecycleObserverInfo.kt
new file mode 100644
index 0000000..d8bc364
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/model/LifecycleObserverInfo.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.model
+
+import javax.lang.model.element.TypeElement
+
+data class LifecycleObserverInfo(
+        val type: TypeElement,
+        val methods: List<EventMethod>)
\ No newline at end of file
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/transformation.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/transformation.kt
new file mode 100644
index 0000000..66fabf7
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/transformation.kt
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import android.arch.lifecycle.model.AdapterClass
+import android.arch.lifecycle.model.EventMethod
+import android.arch.lifecycle.model.EventMethodCall
+import android.arch.lifecycle.model.LifecycleObserverInfo
+import com.google.auto.common.MoreTypes
+import com.google.common.collect.HashMultimap
+import java.util.LinkedList
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.NoType
+import javax.lang.model.type.TypeMirror
+import javax.tools.Diagnostic
+
+
+private fun superObservers(world: Map<TypeElement, LifecycleObserverInfo>,
+                           observer: LifecycleObserverInfo): List<LifecycleObserverInfo> {
+    val stack = LinkedList<TypeMirror>()
+    stack += observer.type.interfaces.reversed()
+    stack += observer.type.superclass
+    val result = mutableListOf<LifecycleObserverInfo>()
+    while (stack.isNotEmpty()) {
+        val typeMirror = stack.removeLast()
+        if (typeMirror is NoType) {
+            continue
+        }
+        val type = MoreTypes.asTypeElement(typeMirror)
+        val currentObserver = world[type]
+        if (currentObserver != null) {
+            result.add(currentObserver)
+        } else {
+            stack += type.interfaces.reversed()
+            stack += type.superclass
+        }
+    }
+    return result
+}
+
+private fun mergeAndVerifyMethods(processingEnv: ProcessingEnvironment,
+                                  type: TypeElement,
+                                  classMethods: List<EventMethod>,
+                                  parentMethods: List<EventMethod>): List<EventMethod> {
+    // need to update parent methods like that because:
+    // 1. visibility can be expanded
+    // 2. we want to preserve order
+    val updatedParentMethods = parentMethods.map { parentMethod ->
+        val overrideMethod = classMethods.find { (method) ->
+            processingEnv.elementUtils.overrides(method, parentMethod.method, type)
+        }
+        if (overrideMethod != null) {
+            if (overrideMethod.onLifecycleEvent != parentMethod.onLifecycleEvent) {
+                processingEnv.messager.printMessage(Diagnostic.Kind.ERROR,
+                        ErrorMessages.INVALID_STATE_OVERRIDE_METHOD, overrideMethod.method)
+            }
+            overrideMethod
+        } else {
+            parentMethod
+        }
+    }
+    return updatedParentMethods + classMethods.filterNot { updatedParentMethods.contains(it) }
+}
+
+fun flattenObservers(processingEnv: ProcessingEnvironment,
+                     world: Map<TypeElement, LifecycleObserverInfo>): List<LifecycleObserverInfo> {
+    val flattened: MutableMap<LifecycleObserverInfo, LifecycleObserverInfo> = mutableMapOf()
+    val superObservers = world.mapValues { superObservers(world, it.value) }
+
+    fun traverse(observer: LifecycleObserverInfo) {
+        if (observer in flattened) {
+            return
+        }
+        val observers = superObservers[observer.type]!!
+        if (observers.isEmpty()) {
+            flattened[observer] = observer
+            return
+        }
+        observers.filter { it !in flattened }.forEach(::traverse)
+        val methods = observers
+                .map(flattened::get)
+                .fold(emptyList<EventMethod>()) { list, parentObserver ->
+                    mergeAndVerifyMethods(processingEnv, observer.type, parentObserver!!.methods, list)
+                }
+
+        flattened[observer] = LifecycleObserverInfo(observer.type,
+                mergeAndVerifyMethods(processingEnv, observer.type, observer.methods, methods))
+    }
+
+    world.values.forEach(::traverse)
+    return flattened.values.toList()
+}
+
+fun transformToOutput(processingEnv: ProcessingEnvironment,
+                      world: Map<TypeElement, LifecycleObserverInfo>): List<AdapterClass> {
+    val flatObservers = flattenObservers(processingEnv, world)
+    val syntheticMethods = HashMultimap.create<TypeElement, EventMethodCall>()
+    val adapterCalls = flatObservers.map { (type, methods) ->
+        val calls = methods.map { eventMethod ->
+            val executable = eventMethod.method
+            if (type.getPackageQName() != eventMethod.packageName()
+                    && (executable.isPackagePrivate() || executable.isProtected())) {
+                EventMethodCall(eventMethod, eventMethod.type)
+            } else {
+                EventMethodCall(eventMethod)
+            }
+        }
+        calls.filter { it.syntheticAccess != null }.forEach { eventMethod ->
+            syntheticMethods.put(eventMethod.method.type, eventMethod)
+        }
+        type to calls
+    }.toMap()
+
+    return adapterCalls.map { (type, calls) ->
+        val methods = syntheticMethods.get(type) ?: setOf()
+        val synthetic = methods.map { eventMethod -> eventMethod!!.method.method }.toSet()
+        AdapterClass(type, calls, synthetic)
+    }
+}
diff --git a/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/writer.kt b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/writer.kt
new file mode 100644
index 0000000..1cd20ed
--- /dev/null
+++ b/lifecycle/compiler/src/main/kotlin/android/arch/lifecycle/writer.kt
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import android.arch.lifecycle.model.AdapterClass
+import android.arch.lifecycle.model.EventMethodCall
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.JavaFile
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.annotation.processing.Filer
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.TypeElement
+
+fun writeModels(infos: List<AdapterClass>, filer: Filer) {
+    infos.forEach({ adapter -> writeAdapter(adapter, filer) })
+}
+
+private val LIFECYCLE_OWNER = ClassName.get(LifecycleOwner::class.java)
+private val LIFECYCLE_EVENT = Lifecycle.Event::class.java
+
+private val T = "\$T"
+private val N = "\$N"
+private val L = "\$L"
+
+private fun writeAdapter(adapter: AdapterClass, filer: Filer) {
+    val ownerParam = ParameterSpec.builder(LIFECYCLE_OWNER, "owner").build()
+    val eventParam = ParameterSpec.builder(ClassName.get(LIFECYCLE_EVENT), "event").build()
+    val receiverName = "mReceiver"
+    val receiverField = FieldSpec.builder(ClassName.get(adapter.type), receiverName,
+            Modifier.FINAL).build()
+
+    val dispatchMethodBuilder = MethodSpec.methodBuilder("onStateChanged")
+            .returns(TypeName.VOID)
+            .addParameter(ownerParam)
+            .addParameter(eventParam)
+            .addModifiers(Modifier.PUBLIC)
+            .addAnnotation(Override::class.java)
+    val dispatchMethod = dispatchMethodBuilder.apply {
+        adapter.calls
+                .groupBy { (eventMethod) -> eventMethod.onLifecycleEvent.value }
+                .forEach { entry ->
+                    val event = entry.key
+                    val calls = entry.value
+                    if (event == Lifecycle.Event.ON_ANY) {
+                        writeMethodCalls(eventParam, calls, ownerParam, receiverField)
+                    } else {
+                        beginControlFlow("if ($N == $T.$L)", eventParam, LIFECYCLE_EVENT, event)
+                                .writeMethodCalls(eventParam, calls, ownerParam, receiverField)
+                        endControlFlow()
+                    }
+                }
+    }.build()
+
+    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+    val getWrappedMethod = MethodSpec.methodBuilder("getReceiver")
+            .returns(ClassName.get(Object::class.java))
+            .addModifiers(Modifier.PUBLIC)
+            .addStatement("return $N", receiverField)
+            .build()
+
+    val receiverParam = ParameterSpec.builder(
+            ClassName.get(adapter.type), "receiver").build()
+
+    val syntheticMethods = adapter.syntheticMethods.map {
+        val method = MethodSpec.methodBuilder(syntheticName(it))
+                .returns(TypeName.VOID)
+                .addModifiers(Modifier.PUBLIC)
+                .addModifiers(Modifier.STATIC)
+                .addParameter(receiverParam)
+        if (it.parameters.size >= 1) {
+            method.addParameter(ownerParam)
+        }
+        if (it.parameters.size == 2) {
+            method.addParameter(eventParam)
+        }
+
+        val count = it.parameters.size
+        val paramString = generateParamString(count)
+        method.addStatement("$N.$L($paramString)", receiverParam, it.name(),
+                *takeParams(count, ownerParam, eventParam))
+        method.build()
+    }
+
+    val constructor = MethodSpec.constructorBuilder()
+            .addParameter(receiverParam)
+            .addStatement("this.$N = $N", receiverField, receiverParam)
+            .build()
+
+    val adapterName = getAdapterName(adapter.type)
+    val adapterTypeSpec = TypeSpec.classBuilder(adapterName)
+            .addModifiers(Modifier.PUBLIC)
+            .addSuperinterface(ClassName.get(GenericLifecycleObserver::class.java))
+            .addField(receiverField)
+            .addMethod(constructor)
+            .addMethod(dispatchMethod)
+            .addMethod(getWrappedMethod)
+            .addMethods(syntheticMethods)
+            .build()
+    JavaFile.builder(adapter.type.getPackageQName(), adapterTypeSpec)
+            .build().writeTo(filer)
+}
+
+private fun MethodSpec.Builder.writeMethodCalls(eventParam: ParameterSpec,
+                                                calls: List<EventMethodCall>,
+                                                ownerParam: ParameterSpec,
+                                                receiverField: FieldSpec) {
+    calls.forEach { (method, syntheticAccess) ->
+        val count = method.method.parameters.size
+        if (syntheticAccess == null) {
+            val paramString = generateParamString(count)
+            addStatement("$N.$L($paramString)", receiverField,
+                    method.method.name(),
+                    *takeParams(count, ownerParam, eventParam))
+
+        } else {
+            val originalType = syntheticAccess
+            val paramString = generateParamString(count + 1)
+            val className = ClassName.get(originalType.getPackageQName(),
+                    getAdapterName(originalType))
+            addStatement("$T.$L($paramString)", className,
+                    syntheticName(method.method),
+                    *takeParams(count + 1, receiverField, ownerParam,
+                            eventParam))
+        }
+    }
+}
+
+private fun syntheticName(method: ExecutableElement) = "__synthetic_" + method.simpleName
+
+private fun takeParams(count: Int, vararg params: Any) = params.take(count).toTypedArray()
+
+private fun generateParamString(count: Int) = (0..(count - 1)).joinToString(",") { N }
+
+private fun getAdapterName(type: TypeElement): String {
+    val packageElement = type.getPackage()
+    val qName = type.qualifiedName.toString()
+    val partialName = if (packageElement.isUnnamed) qName else qName.substring(
+            packageElement.qualifiedName.toString().length + 1)
+    return Lifecycling.getAdapterName(partialName)
+}
diff --git a/lifecycle/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/lifecycle/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 0000000..cdabd71
--- /dev/null
+++ b/lifecycle/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1 @@
+android.arch.lifecycle.LifecycleProcessor
diff --git a/lifecycle/compiler/src/main/resources/NOTICE.txt b/lifecycle/compiler/src/main/resources/NOTICE.txt
new file mode 100644
index 0000000..28a4a72
--- /dev/null
+++ b/lifecycle/compiler/src/main/resources/NOTICE.txt
@@ -0,0 +1,1077 @@
+List of 3rd party licenses:
+-----------------------------------------------------------------------------
+* javapoet.jar (com.squareup:javapoet:1.8.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* kotlin-stdlib.jar (org.jetbrains.kotlin:kotlin-stdlib:1.1.1)
+
+ ****** NOTICE:
+   =========================================================================
+   ==  NOTICE file corresponding to the section 4 d of                    ==
+   ==  the Apache License, Version 2.0,                                   ==
+   ==  in this case for the Kotlin Compiler distribution.                 ==
+   =========================================================================
+
+   Kotlin Compiler
+   Copyright 2010-2015 JetBrains s.r.o and respective authors and developers
+
+ ****** LICENSE:
+/*
+ * Copyright 2010-2017 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* auto-common.jar (com.google.auto:auto-common:0.6)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* annotations.jar (org.jetbrains:annotations:13.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* guava.jar (com.google.guava:guava:18.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
diff --git a/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/InvalidCasesTest.kt b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/InvalidCasesTest.kt
new file mode 100644
index 0000000..3e502d3
--- /dev/null
+++ b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/InvalidCasesTest.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import android.arch.lifecycle.utils.processClass
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+@RunWith(Parameterized::class)
+class InvalidCasesTest(val name: String, val errorMsg: String) {
+    companion object {
+        @JvmStatic
+        @Parameterized.Parameters(name = "failingCase({0})")
+        fun data() : Collection<Array<Any>> = listOf(
+                arrayOf<Any>("foo.InvalidFirstArg1", ErrorMessages.INVALID_FIRST_ARGUMENT),
+                arrayOf<Any>("foo.InvalidFirstArg2", ErrorMessages.INVALID_FIRST_ARGUMENT),
+                arrayOf<Any>("foo.InvalidSecondArg", ErrorMessages.INVALID_SECOND_ARGUMENT),
+                arrayOf<Any>("foo.TooManyArgs1", ErrorMessages.TOO_MANY_ARGS),
+                arrayOf<Any>("foo.TooManyArgs2", ErrorMessages.TOO_MANY_ARGS_NOT_ON_ANY),
+                arrayOf<Any>("foo.InvalidMethodModifier",
+                        ErrorMessages.INVALID_METHOD_MODIFIER),
+                arrayOf<Any>("foo.InvalidClassModifier", ErrorMessages.INVALID_CLASS_MODIFIER),
+                arrayOf<Any>("foo.InvalidInheritance1",
+                        ErrorMessages.INVALID_STATE_OVERRIDE_METHOD),
+                arrayOf<Any>("foo.InvalidInheritance2",
+                        ErrorMessages.INVALID_STATE_OVERRIDE_METHOD)
+        )
+    }
+
+    @Test
+    fun shouldFailWithError() {
+        processClass(name).failsToCompile().withErrorContaining(errorMsg)
+    }
+}
diff --git a/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/ValidCasesTest.kt b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/ValidCasesTest.kt
new file mode 100644
index 0000000..66429a2
--- /dev/null
+++ b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/ValidCasesTest.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle
+
+import android.arch.lifecycle.utils.load
+import android.arch.lifecycle.utils.processClass
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class ValidCasesTest {
+    @Test
+    fun testTest() {
+        processClass("foo.Bar").compilesWithoutError()
+    }
+
+    @Test
+    fun testOnAny() {
+        processClass("foo.OnAnyMethod").compilesWithoutError().and().generatesSources(
+                load("foo.OnAnyMethod_LifecycleAdapter", "expected")
+        )
+    }
+
+    @Test
+    fun testInheritance() {
+        processClass("foo.InheritanceOk1").compilesWithoutError()
+    }
+
+    @Test
+    fun testInheritance2() {
+        processClass("foo.InheritanceOk2").compilesWithoutError().and().generatesSources(
+                load("foo.InheritanceOk2Base_LifecycleAdapter", "expected"),
+                load("foo.InheritanceOk2Derived_LifecycleAdapter", "expected")
+        )
+    }
+
+    @Test
+    fun testInheritance3() {
+        processClass("foo.InheritanceOk3").compilesWithoutError().and().generatesSources(
+                load("foo.InheritanceOk3Base_LifecycleAdapter", "expected"),
+                load("foo.InheritanceOk3Derived_LifecycleAdapter", "expected")
+        )
+    }
+
+    @Test
+    fun testNoPackageClass() {
+        processClass("NoPackageOk").compilesWithoutError()
+    }
+
+    @Test
+    fun testInterface1(){
+        processClass("foo.InterfaceOk1").compilesWithoutError()
+    }
+
+    @Test
+    fun testInterface2() {
+        processClass("foo.InterfaceOk2").compilesWithoutError().and().generatesSources(
+                load("foo.InterfaceOk2Base_LifecycleAdapter", "expected"),
+                load("foo.InterfaceOk2Derived_LifecycleAdapter", "expected"),
+                load("foo.InterfaceOk2Interface_LifecycleAdapter", "expected")
+        )
+    }
+
+    @Test
+    fun testInheritanceDifferentPackages1() {
+        processClass("foo.DifferentPackagesBase1",
+                "bar.DifferentPackagesDerived1").compilesWithoutError().and().generatesSources(
+                load("foo.DifferentPackagesBase1_LifecycleAdapter", "expected"),
+                load("bar.DifferentPackagesDerived1_LifecycleAdapter", "expected")
+        )
+    }
+
+    @Test
+    fun testInheritanceDifferentPackages2() {
+        processClass("foo.DifferentPackagesBase2",
+                "bar.DifferentPackagesDerived2").compilesWithoutError().and().generatesSources(
+                load("foo.DifferentPackagesBase2_LifecycleAdapter", "expected"),
+                load("bar.DifferentPackagesDerived2_LifecycleAdapter", "expected")
+        )
+    }
+}
diff --git a/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/utils/TestUtils.kt b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/utils/TestUtils.kt
new file mode 100644
index 0000000..d3b13c2
--- /dev/null
+++ b/lifecycle/compiler/src/tests/kotlin/android/arch/lifecycle/utils/TestUtils.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.utils
+
+import android.arch.lifecycle.LifecycleProcessor
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourceSubjectFactory
+import com.google.testing.compile.JavaSourcesSubject
+import java.io.File
+import java.nio.charset.Charset
+import javax.tools.JavaFileObject
+
+fun load(fullClassName: String, folder: String): JavaFileObject {
+    val folderPath = "src/tests/test-data/${if (folder.isEmpty()) "" else folder + "/"}"
+    val split = fullClassName.split(".")
+    val code = File("$folderPath/${split.last()}.java").readText(Charset.defaultCharset())
+    return JavaFileObjects.forSourceString(fullClassName, code)
+}
+
+fun processClass(className: String, vararg fullClassNames: String): CompileTester {
+    val javaFiles = fullClassNames.map { load(it, "") }.toTypedArray()
+    val processedWith = JavaSourcesSubject.assertThat(load(className, ""), *javaFiles)
+            .processedWith(LifecycleProcessor())
+    return checkNotNull(processedWith)
+}
diff --git a/lifecycle/compiler/src/tests/test-data/Bar.java b/lifecycle/compiler/src/tests/test-data/Bar.java
new file mode 100644
index 0000000..773948e
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/Bar.java
@@ -0,0 +1,40 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class Bar {
+    @OnLifecycleEvent(ON_START)
+    public void doOnStart() {
+    }
+
+    @OnLifecycleEvent(ON_STOP)
+    public void doOnStop1Arg(LifecycleOwner provider) {
+    }
+
+    @OnLifecycleEvent(ON_STOP)
+    public void doOnStop2Args(LifecycleOwner provider) {
+    }
+
+    public static class Inner1 {
+        @OnLifecycleEvent(ON_START)
+        public void doOnStart() {
+        }
+
+        public static class Inner2 {
+            @OnLifecycleEvent(ON_START)
+            public void doOnStart() {
+            }
+
+            public static class Inner3 {
+                @OnLifecycleEvent(ON_START)
+                public void doOnStart() {
+                }
+            }
+        }
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase1.java b/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase1.java
new file mode 100644
index 0000000..cc9d5d5
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase1.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class DifferentPackagesBase1 {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop(LifecycleOwner provider){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase2.java b/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase2.java
new file mode 100644
index 0000000..e31921a
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/DifferentPackagesBase2.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class DifferentPackagesPreBase2 {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop(LifecycleOwner provider){}
+}
+
+public class DifferentPackagesBase2 extends DifferentPackagesPreBase2 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived1.java b/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived1.java
new file mode 100644
index 0000000..8ad4c91
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived1.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 bar;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+import foo.DifferentPackagesBase1;
+
+public class DifferentPackagesDerived1 extends DifferentPackagesBase1 {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop2(LifecycleOwner provider){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived2.java b/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived2.java
new file mode 100644
index 0000000..648f628
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/DifferentPackagesDerived2.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 bar;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+import foo.DifferentPackagesBase2;
+
+public class DifferentPackagesDerived2 extends DifferentPackagesBase2 {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop2(LifecycleOwner provider){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/IGNORE_CHECKSTYLE b/lifecycle/compiler/src/tests/test-data/IGNORE_CHECKSTYLE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/IGNORE_CHECKSTYLE
diff --git a/lifecycle/compiler/src/tests/test-data/InheritanceOk1.java b/lifecycle/compiler/src/tests/test-data/InheritanceOk1.java
new file mode 100644
index 0000000..79c2151
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InheritanceOk1.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class Base1 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider) {
+    }
+}
+
+class Proxy extends Base1 {
+}
+
+class Derived1 extends Proxy {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop2(LifecycleOwner provider) {
+    }
+}
+
+class Derived2 extends Proxy {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop2(LifecycleOwner provider) {
+    }
+}
+
+class Base2 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider) {
+    }
+}
+
+class Derived3 extends Base2 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop2(LifecycleOwner provider) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InheritanceOk2.java b/lifecycle/compiler/src/tests/test-data/InheritanceOk2.java
new file mode 100644
index 0000000..31f0a41
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InheritanceOk2.java
@@ -0,0 +1,19 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class InheritanceOk2Base {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider) {
+    }
+}
+
+class InheritanceOk2Derived extends InheritanceOk2Base {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop2(LifecycleOwner provider) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InheritanceOk3.java b/lifecycle/compiler/src/tests/test-data/InheritanceOk3.java
new file mode 100644
index 0000000..50c4623
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InheritanceOk3.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class InheritanceOk3Base {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider) {
+    }
+}
+
+class InheritanceOk3Derived extends InheritanceOk3Base {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InterfaceOk1.java b/lifecycle/compiler/src/tests/test-data/InterfaceOk1.java
new file mode 100644
index 0000000..3584f6d
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InterfaceOk1.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+interface InterfaceOk1 {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop(LifecycleOwner provider);
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InterfaceOk2.java b/lifecycle/compiler/src/tests/test-data/InterfaceOk2.java
new file mode 100644
index 0000000..58688d3
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InterfaceOk2.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class InterfaceOk2Base {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop1(LifecycleOwner provider) {
+    }
+}
+
+interface InterfaceOk2Interface {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop2(LifecycleOwner provider);
+}
+
+class InterfaceOk2Proxy extends InterfaceOk2Base {
+}
+
+class InterfaceOk2Derived extends InterfaceOk2Proxy implements InterfaceOk2Interface {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop3(LifecycleOwner provider) {
+    }
+
+    public void onStop2(LifecycleOwner provider) {}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidClassModifier.java b/lifecycle/compiler/src/tests/test-data/InvalidClassModifier.java
new file mode 100644
index 0000000..4c30bb6
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidClassModifier.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class InvalidClassModifier {
+    private static class Inner {
+        @OnLifecycleEvent(ON_STOP)
+        private void onStop() {
+        }
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidFirstArg1.java b/lifecycle/compiler/src/tests/test-data/InvalidFirstArg1.java
new file mode 100644
index 0000000..26bfc23
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidFirstArg1.java
@@ -0,0 +1,12 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class InvalidFirstArg1 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(Event event) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidFirstArg2.java b/lifecycle/compiler/src/tests/test-data/InvalidFirstArg2.java
new file mode 100644
index 0000000..459c316
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidFirstArg2.java
@@ -0,0 +1,12 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_ANY;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class InvalidFirstArg2 {
+    @OnLifecycleEvent(ON_ANY)
+    public void onStop(Event e2, Event event) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidInheritance1.java b/lifecycle/compiler/src/tests/test-data/InvalidInheritance1.java
new file mode 100644
index 0000000..69f6bb2
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidInheritance1.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class Base {
+    @OnLifecycleEvent(ON_STOP)
+    void foo() {
+    }
+}
+
+class Derived extends Base {
+    @OnLifecycleEvent(ON_START)
+    void foo() {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidInheritance2.java b/lifecycle/compiler/src/tests/test-data/InvalidInheritance2.java
new file mode 100644
index 0000000..b714e47
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidInheritance2.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+interface Base {
+    @OnLifecycleEvent(ON_STOP)
+    void foo();
+}
+
+class Derived implements Base {
+    @OnLifecycleEvent(ON_START)
+    public void foo(){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidMethodModifier.java b/lifecycle/compiler/src/tests/test-data/InvalidMethodModifier.java
new file mode 100644
index 0000000..6540333
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidMethodModifier.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2016 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class InvalidMethodModifier {
+    @OnLifecycleEvent(ON_STOP)
+    private void onStop() {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/InvalidSecondArg.java b/lifecycle/compiler/src/tests/test-data/InvalidSecondArg.java
new file mode 100644
index 0000000..e98d915
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/InvalidSecondArg.java
@@ -0,0 +1,12 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_ANY;
+
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class InvalidSecondArg {
+    @OnLifecycleEvent(ON_ANY)
+    public void onStop(LifecycleOwner provider, Object lastEvent) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/NoPackageOk.java b/lifecycle/compiler/src/tests/test-data/NoPackageOk.java
new file mode 100644
index 0000000..a00283d
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/NoPackageOk.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+class NoPackageOk {
+    @OnLifecycleEvent(ON_STOP)
+    void onStop(LifecycleOwner provider){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/OnAnyMethod.java b/lifecycle/compiler/src/tests/test-data/OnAnyMethod.java
new file mode 100644
index 0000000..f03f1cd
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/OnAnyMethod.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_ANY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class OnAnyMethod {
+
+    @OnLifecycleEvent(ON_STOP)
+    void onStop(LifecycleOwner provider){}
+
+    @OnLifecycleEvent(ON_ANY)
+    void any(LifecycleOwner provider){}
+
+
+    @OnLifecycleEvent(ON_ANY)
+    void any(LifecycleOwner provider, Event event){}
+}
diff --git a/lifecycle/compiler/src/tests/test-data/TooManyArgs1.java b/lifecycle/compiler/src/tests/test-data/TooManyArgs1.java
new file mode 100644
index 0000000..0d65098
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/TooManyArgs1.java
@@ -0,0 +1,13 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_ANY;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class TooManyArgs1 {
+    @OnLifecycleEvent(ON_ANY)
+    public void onAny(LifecycleOwner provider, Event event, int x) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/TooManyArgs2.java b/lifecycle/compiler/src/tests/test-data/TooManyArgs2.java
new file mode 100644
index 0000000..f332d0b
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/TooManyArgs2.java
@@ -0,0 +1,13 @@
+package foo;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+
+public class TooManyArgs2 {
+    @OnLifecycleEvent(ON_STOP)
+    public void onStop(LifecycleOwner provider, Event event) {
+    }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase1_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase1_LifecycleAdapter.java
new file mode 100644
index 0000000..0728bf5
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase1_LifecycleAdapter.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class DifferentPackagesBase1_LifecycleAdapter implements GenericLifecycleObserver {
+  final DifferentPackagesBase1 mReceiver;
+
+  DifferentPackagesBase1_LifecycleAdapter(DifferentPackagesBase1 receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+
+  public static void __synthetic_onStop(DifferentPackagesBase1 receiver, LifecycleOwner owner) {
+    receiver.onStop(owner);
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase2_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase2_LifecycleAdapter.java
new file mode 100644
index 0000000..cb6d6d3
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesBase2_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class DifferentPackagesBase2_LifecycleAdapter implements GenericLifecycleObserver {
+  final DifferentPackagesBase2 mReceiver;
+
+  DifferentPackagesBase2_LifecycleAdapter(DifferentPackagesBase2 receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived1_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived1_LifecycleAdapter.java
new file mode 100644
index 0000000..fe6dd24
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived1_LifecycleAdapter.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 bar;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import foo.DifferentPackagesBase1_LifecycleAdapter;
+import java.lang.Object;
+import java.lang.Override;
+
+public class DifferentPackagesDerived1_LifecycleAdapter implements GenericLifecycleObserver {
+  final DifferentPackagesDerived1 mReceiver;
+
+  DifferentPackagesDerived1_LifecycleAdapter(DifferentPackagesDerived1 receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      DifferentPackagesBase1_LifecycleAdapter.__synthetic_onStop(mReceiver,owner);
+      mReceiver.onStop2(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived2_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived2_LifecycleAdapter.java
new file mode 100644
index 0000000..261dce1
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/DifferentPackagesDerived2_LifecycleAdapter.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2017 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 bar;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class DifferentPackagesDerived2_LifecycleAdapter implements GenericLifecycleObserver {
+  final DifferentPackagesDerived2 mReceiver;
+
+  DifferentPackagesDerived2_LifecycleAdapter(DifferentPackagesDerived2 receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+      mReceiver.onStop2(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Base_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Base_LifecycleAdapter.java
new file mode 100644
index 0000000..3712e48
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Base_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InheritanceOk2Base_LifecycleAdapter implements GenericLifecycleObserver {
+  final InheritanceOk2Base mReceiver;
+
+  InheritanceOk2Base_LifecycleAdapter(InheritanceOk2Base receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Derived_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Derived_LifecycleAdapter.java
new file mode 100644
index 0000000..1549387
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk2Derived_LifecycleAdapter.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InheritanceOk2Derived_LifecycleAdapter implements GenericLifecycleObserver {
+  final InheritanceOk2Derived mReceiver;
+
+  InheritanceOk2Derived_LifecycleAdapter(InheritanceOk2Derived receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+      mReceiver.onStop2(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Base_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Base_LifecycleAdapter.java
new file mode 100644
index 0000000..1647443
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Base_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InheritanceOk3Base_LifecycleAdapter implements GenericLifecycleObserver {
+  final InheritanceOk3Base mReceiver;
+
+  InheritanceOk3Base_LifecycleAdapter(InheritanceOk3Base receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Derived_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Derived_LifecycleAdapter.java
new file mode 100644
index 0000000..e41b9eb
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InheritanceOk3Derived_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InheritanceOk3Derived_LifecycleAdapter implements GenericLifecycleObserver {
+  final InheritanceOk3Derived mReceiver;
+
+  InheritanceOk3Derived_LifecycleAdapter(InheritanceOk3Derived receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Base_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Base_LifecycleAdapter.java
new file mode 100644
index 0000000..22de775
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Base_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InterfaceOk2Base_LifecycleAdapter implements GenericLifecycleObserver {
+  final InterfaceOk2Base mReceiver;
+
+  InterfaceOk2Base_LifecycleAdapter(InterfaceOk2Base receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop1(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Derived_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Derived_LifecycleAdapter.java
new file mode 100644
index 0000000..9ba0461
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Derived_LifecycleAdapter.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InterfaceOk2Derived_LifecycleAdapter implements GenericLifecycleObserver {
+  final InterfaceOk2Derived mReceiver;
+
+  InterfaceOk2Derived_LifecycleAdapter(InterfaceOk2Derived receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop1(owner);
+      mReceiver.onStop2(owner);
+      mReceiver.onStop3(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Interface_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Interface_LifecycleAdapter.java
new file mode 100644
index 0000000..a7fba29
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/InterfaceOk2Interface_LifecycleAdapter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class InterfaceOk2Interface_LifecycleAdapter implements GenericLifecycleObserver {
+  final InterfaceOk2Interface mReceiver;
+
+  InterfaceOk2Interface_LifecycleAdapter(InterfaceOk2Interface receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop2(owner);
+    }
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/OnAnyMethod_LifecycleAdapter.java b/lifecycle/compiler/src/tests/test-data/expected/OnAnyMethod_LifecycleAdapter.java
new file mode 100644
index 0000000..dc59207
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/OnAnyMethod_LifecycleAdapter.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 foo;
+
+import android.arch.lifecycle.GenericLifecycleObserver;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import java.lang.Object;
+import java.lang.Override;
+
+public class OnAnyMethod_LifecycleAdapter implements GenericLifecycleObserver {
+  final OnAnyMethod mReceiver;
+
+  OnAnyMethod_LifecycleAdapter(OnAnyMethod receiver) {
+    this.mReceiver = receiver;
+  }
+
+  @Override
+  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
+    if (event == Lifecycle.Event.ON_STOP) {
+      mReceiver.onStop(owner);
+    }
+    mReceiver.any(owner);
+    mReceiver.any(owner,event);
+  }
+
+  public Object getReceiver() {
+    return mReceiver;
+  }
+}
diff --git a/lifecycle/compiler/src/tests/test-data/expected/license.txt b/lifecycle/compiler/src/tests/test-data/expected/license.txt
new file mode 100644
index 0000000..a538eb5
--- /dev/null
+++ b/lifecycle/compiler/src/tests/test-data/expected/license.txt
@@ -0,0 +1,15 @@
+/*
+ * Copyright (C) 2017 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.
+ */
diff --git a/lifecycle/extensions/.gitignore b/lifecycle/extensions/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/lifecycle/extensions/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/lifecycle/extensions/build.gradle b/lifecycle/extensions/build.gradle
new file mode 100644
index 0000000..4facb68
--- /dev/null
+++ b/lifecycle/extensions/build.gradle
@@ -0,0 +1,58 @@
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+
+    buildTypes.all {
+        consumerProguardFiles 'proguard-rules.pro'
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+}
+dependencies {
+    compile project(":lifecycle:common")
+    compile project(":lifecycle:runtime")
+    compile project(":arch:common")
+    compile project(":arch:runtime")
+    compile libs.support.fragments
+
+    testCompile project(":arch:core-testing")
+    testCompile libs.junit
+    testCompile libs.mockito_core
+
+    testCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile libs.support.app_compat
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+}
+
+createAndroidCheckstyle(project)
+
+//noinspection GroovyUnusedAssignment
+archivesBaseName = "extensions"
diff --git a/lifecycle/extensions/proguard-rules.pro b/lifecycle/extensions/proguard-rules.pro
new file mode 100644
index 0000000..a24a5d3
--- /dev/null
+++ b/lifecycle/extensions/proguard-rules.pro
@@ -0,0 +1,7 @@
+-keep class * extends android.arch.lifecycle.ViewModel {
+    <init>();
+}
+
+-keep class * extends android.arch.lifecycle.AndroidViewModel {
+    <init>(android.app.Application);
+}
\ No newline at end of file
diff --git a/lifecycle/extensions/src/androidTest/AndroidManifest.xml b/lifecycle/extensions/src/androidTest/AndroidManifest.xml
new file mode 100644
index 0000000..08e1de6
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.lifecycle.extensions.test">
+
+    <application>
+        <activity android:name="android.arch.lifecycle.viewmodeltest.ViewModelActivity"
+                  android:theme="@style/Base.Theme.AppCompat">
+        </activity>
+        <activity android:name="android.arch.lifecycle.EmptyActivity"/>
+        <activity android:name="android.arch.lifecycle.activity.FragmentLifecycleActivity"
+            android:theme="@style/Base.Theme.AppCompat"/>
+        <activity android:name="android.arch.lifecycle.activity.EmptyActivity"/>
+        <service android:name="android.arch.lifecycle.service.TestService"/>
+    </application>
+
+</manifest>
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/EmptyActivity.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/EmptyActivity.java
new file mode 100644
index 0000000..738bd66
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/EmptyActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.v4.app.FragmentActivity;
+
+public class EmptyActivity extends FragmentActivity {
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentLifecycleInActivityTest.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentLifecycleInActivityTest.java
new file mode 100644
index 0000000..70a4465
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentLifecycleInActivityTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.app.Instrumentation;
+import android.arch.lifecycle.activity.FragmentLifecycleActivity;
+import android.content.Intent;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.v4.app.Fragment;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
+
+@MediumTest
+@RunWith(Parameterized.class)
+public class FragmentLifecycleInActivityTest {
+
+    private static final long TIMEOUT = 2; //sec
+
+    @Rule
+    public ActivityTestRule<FragmentLifecycleActivity> mActivityRule =
+            new ActivityTestRule<>(FragmentLifecycleActivity.class, false, false);
+
+    private Instrumentation mInstrumentation;
+
+    @SuppressWarnings("WeakerAccess")
+    @Parameterized.Parameter
+    public boolean mNested;
+
+    @Parameterized.Parameters(name = "nested_{0}")
+    public static Object[][] params() {
+        return new Object[][]{new Object[]{false}, new Object[]{true}};
+    }
+
+    @Before
+    public void getInstrumentation() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+    }
+
+    private void reset() {
+        mActivityRule.getActivity().resetEvents();
+    }
+
+    @Test
+    public void testFullEvents() throws Throwable {
+        final FragmentLifecycleActivity activity = launchActivity();
+        waitForIdle();
+        assertEvents(ON_CREATE, ON_START, ON_RESUME);
+        reset();
+        finishActivity(activity);
+        assertEvents(ON_PAUSE, ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testStopStart() throws Throwable {
+        final FragmentLifecycleActivity activity = launchActivity();
+        waitForIdle();
+        assertEvents(ON_CREATE, ON_START, ON_RESUME);
+        reset();
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mInstrumentation.callActivityOnPause(activity);
+                mInstrumentation.callActivityOnStop(activity);
+            }
+        });
+        waitForIdle();
+        assertEvents(ON_PAUSE, ON_STOP);
+        reset();
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mInstrumentation.callActivityOnStart(activity);
+                mInstrumentation.callActivityOnResume(activity);
+            }
+        });
+        waitForIdle();
+        assertEvents(ON_START, ON_RESUME);
+    }
+
+    private FragmentLifecycleActivity launchActivity() throws Throwable {
+        Intent intent = FragmentLifecycleActivity.intentFor(mInstrumentation.getTargetContext(),
+                mNested);
+        final FragmentLifecycleActivity activity = mActivityRule.launchActivity(intent);
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                Fragment main = activity.getSupportFragmentManager()
+                        .findFragmentByTag(FragmentLifecycleActivity.MAIN_TAG);
+                assertThat("test sanity", main, notNullValue());
+                Fragment nestedFragment = main.getChildFragmentManager()
+                        .findFragmentByTag(FragmentLifecycleActivity.NESTED_TAG);
+                assertThat("test sanity", nestedFragment != null, is(mNested));
+            }
+        });
+        assertThat(activity.getObservedOwner(), instanceOf(
+                mNested ? FragmentLifecycleActivity.NestedFragment.class
+                        : FragmentLifecycleActivity.MainFragment.class
+        ));
+        return activity;
+    }
+
+    private void waitForIdle() {
+        mInstrumentation.waitForIdleSync();
+    }
+
+    private void finishActivity(final FragmentLifecycleActivity activity)
+            throws InterruptedException {
+        mInstrumentation.runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                activity.finish();
+            }
+        });
+        assertThat(activity.awaitForDestruction(TIMEOUT, TimeUnit.SECONDS), is(true));
+    }
+
+    private void assertEvents(Lifecycle.Event... events) {
+        assertThat(mActivityRule.getActivity().getLoggedEvents(), is(Arrays.asList(events)));
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentOperationsLifecycleTest.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentOperationsLifecycleTest.java
new file mode 100644
index 0000000..be062cb
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/FragmentOperationsLifecycleTest.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+
+import static java.util.Arrays.asList;
+
+import android.arch.lifecycle.activity.EmptyActivity;
+import android.arch.lifecycle.extensions.test.R;
+import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.app.FragmentManager;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class FragmentOperationsLifecycleTest {
+
+    @Rule
+    public ActivityTestRule<EmptyActivity> mActivityTestRule = new ActivityTestRule<>(
+            EmptyActivity.class);
+
+    @Test
+    @UiThreadTest
+    public void addRemoveFragment() {
+        EmptyActivity activity = mActivityTestRule.getActivity();
+        LifecycleFragment fragment = new LifecycleFragment();
+        FragmentManager fm = activity.getSupportFragmentManager();
+        fm.beginTransaction().add(fragment, "tag").commitNow();
+        CollectingObserver observer = observeAndCollectIn(fragment);
+        assertThat(observer.getEventsAndReset(), is(asList(ON_CREATE, ON_START, ON_RESUME)));
+        fm.beginTransaction().remove(fragment).commitNow();
+        assertThat(observer.getEventsAndReset(), is(asList(ON_PAUSE, ON_STOP, ON_DESTROY)));
+        fm.beginTransaction().add(fragment, "tag").commitNow();
+        assertThat(observer.getEventsAndReset(), is(asList(ON_CREATE, ON_START, ON_RESUME)));
+    }
+
+    @Test
+    @UiThreadTest
+    public void fragmentInBackstack() {
+        EmptyActivity activity = mActivityTestRule.getActivity();
+        LifecycleFragment fragment1 = new LifecycleFragment();
+        FragmentManager fm = activity.getSupportFragmentManager();
+        fm.beginTransaction().add(R.id.fragment_container, fragment1, "tag").addToBackStack(null)
+                .commit();
+        fm.executePendingTransactions();
+        CollectingObserver observer1 = observeAndCollectIn(fragment1);
+        assertThat(observer1.getEventsAndReset(), is(asList(ON_CREATE, ON_START, ON_RESUME)));
+
+        LifecycleFragment fragment2 = new LifecycleFragment();
+        fm.beginTransaction().replace(R.id.fragment_container, fragment2).addToBackStack(null)
+                .commit();
+        fm.executePendingTransactions();
+
+        CollectingObserver observer2 = observeAndCollectIn(fragment2);
+        assertThat(observer1.getEventsAndReset(), is(asList(ON_PAUSE, ON_STOP)));
+        assertThat(observer2.getEventsAndReset(), is(asList(ON_CREATE, ON_START, ON_RESUME)));
+
+        assertThat(fm.popBackStackImmediate(), is(true));
+        assertThat(observer1.getEventsAndReset(), is(asList(ON_START, ON_RESUME)));
+        assertThat(observer2.getEventsAndReset(), is(asList(ON_PAUSE, ON_STOP, ON_DESTROY)));
+
+        assertThat(fm.popBackStackImmediate(), is(true));
+        assertThat(observer1.getEventsAndReset(), is(asList(ON_PAUSE, ON_STOP, ON_DESTROY)));
+    }
+
+    private static CollectingObserver observeAndCollectIn(LifecycleFragment fragment) {
+        CollectingObserver observer = new CollectingObserver();
+        fragment.getLifecycle().addObserver(observer);
+        return observer;
+    }
+
+    private static class CollectingObserver implements LifecycleObserver {
+        final List<Lifecycle.Event> mCollectedEvents = new ArrayList<>();
+
+        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
+        public void anyEvent(LifecycleOwner owner, Lifecycle.Event event) {
+            mCollectedEvents.add(event);
+        }
+
+        List<Lifecycle.Event> getEventsAndReset() {
+            ArrayList<Lifecycle.Event> events = new ArrayList<>(mCollectedEvents);
+            mCollectedEvents.clear();
+            return events;
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ServiceLifecycleTest.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ServiceLifecycleTest.java
new file mode 100644
index 0000000..fe0a306
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ServiceLifecycleTest.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.service.TestService;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ServiceConnection;
+import android.os.IBinder;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.content.LocalBroadcastManager;
+
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class ServiceLifecycleTest {
+
+    private static final int RETRY_NUMBER = 5;
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(1);
+
+    private Intent mServiceIntent;
+
+    private volatile List<Event> mLoggerEvents;
+    private EventLogger mLogger;
+
+    @Before
+    public void setUp() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        mServiceIntent = new Intent(context, TestService.class);
+        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction(TestService.ACTION_LOG_EVENT);
+
+        // Overcautiousness: each EventLogger has its own events list, so one bad test won't spoil
+        // others.
+        mLoggerEvents = new ArrayList<>();
+        mLogger = new EventLogger(mLoggerEvents);
+        localBroadcastManager.registerReceiver(mLogger, intentFilter);
+
+    }
+
+    @After
+    public void tearDown() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
+        localBroadcastManager.unregisterReceiver(mLogger);
+        mLogger = null;
+        mLoggerEvents = null;
+    }
+
+    @Test
+    public void testUnboundedService() throws TimeoutException, InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        context.startService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+        context.stopService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START, ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testBoundedService() throws TimeoutException, InterruptedException {
+        ServiceConnection connection = bindToService();
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+        InstrumentationRegistry.getTargetContext().unbindService(connection);
+        awaitAndAssertEvents(ON_CREATE, ON_START, ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testStartBindUnbindStop() throws InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        context.startService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        ServiceConnection connection = bindToService();
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // still the same events
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.unbindService(connection);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // service is still started (stopServices/stopSelf weren't called)
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.stopService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START, ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testStartBindStopUnbind() throws InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        context.startService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        ServiceConnection connection = bindToService();
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // still the same events
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.stopService(mServiceIntent);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // service is still bound
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.unbindService(connection);
+        awaitAndAssertEvents(ON_CREATE, ON_START,
+                ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testBindStartUnbindStop() throws InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        ServiceConnection connection = bindToService();
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+
+        context.startService(mServiceIntent);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // still the same events
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.unbindService(connection);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // service is still started (stopServices/stopSelf weren't called)
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.stopService(mServiceIntent);
+        awaitAndAssertEvents(ON_CREATE, ON_START,
+                ON_STOP, ON_DESTROY);
+    }
+
+    @Test
+    public void testBindStartStopUnbind() throws InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        ServiceConnection connection = bindToService();
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.startService(mServiceIntent);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // still the same events
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.stopService(mServiceIntent);
+        // Precaution: give a chance to dispatch events
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
+        // service is still bound
+        awaitAndAssertEvents(ON_CREATE, ON_START);
+
+        context.unbindService(connection);
+        awaitAndAssertEvents(ON_CREATE, ON_START,
+                ON_STOP, ON_DESTROY);
+    }
+
+    // can't use ServiceTestRule because it proxies connection, so we can't use unbindService method
+    private ServiceConnection bindToService() throws InterruptedException {
+        Context context = InstrumentationRegistry.getTargetContext();
+        final CountDownLatch latch = new CountDownLatch(1);
+        ServiceConnection connection = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                latch.countDown();
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+
+            }
+        };
+
+        boolean success = context.bindService(mServiceIntent, connection, Context.BIND_AUTO_CREATE);
+        assertThat(success, is(true));
+        boolean awaited = latch.await(TIMEOUT, TimeUnit.MILLISECONDS);
+        assertThat(awaited, is(true));
+        return connection;
+    }
+
+    private void awaitAndAssertEvents(Event... events) throws InterruptedException {
+        //noinspection SynchronizeOnNonFinalField
+        synchronized (mLoggerEvents) {
+            int retryCount = 0;
+            while (mLoggerEvents.size() < events.length && retryCount++ < RETRY_NUMBER) {
+                mLoggerEvents.wait(TIMEOUT);
+            }
+            assertThat(mLoggerEvents, is(Arrays.asList(events)));
+        }
+    }
+
+    private static class EventLogger extends BroadcastReceiver {
+        private final List<Event> mLoggerEvents;
+
+        private EventLogger(List<Event> loggerEvents) {
+            mLoggerEvents = loggerEvents;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            synchronized (mLoggerEvents) {
+                mLoggerEvents.add((Event) intent.getSerializableExtra(TestService.EXTRA_KEY_EVENT));
+                mLoggerEvents.notifyAll();
+            }
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTest.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTest.java
new file mode 100644
index 0000000..98ce027
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTest.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.app.Instrumentation;
+import android.arch.lifecycle.viewmodeltest.TestViewModel;
+import android.arch.lifecycle.viewmodeltest.ViewModelActivity;
+import android.arch.lifecycle.viewmodeltest.ViewModelActivity.ViewModelFragment;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class ViewModelTest {
+    private static final int TIMEOUT = 2; // secs
+
+    @Rule
+    public ActivityTestRule<ViewModelActivity> mActivityRule =
+            new ActivityTestRule<>(ViewModelActivity.class);
+
+    @Test
+    public void ensureSameViewHolders() throws Throwable {
+        final TestViewModel[] activityModel = new TestViewModel[1];
+        final TestViewModel[] defaultActivityModel = new TestViewModel[1];
+        final TestViewModel[] fragment1Model = new TestViewModel[1];
+        final TestViewModel[] fragment2Model = new TestViewModel[1];
+        final ViewModelActivity[] viewModelActivity = new ViewModelActivity[1];
+        viewModelActivity[0] = mActivityRule.getActivity();
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ViewModelFragment fragment1 = getFragment(viewModelActivity[0],
+                        ViewModelActivity.FRAGMENT_TAG_1);
+                ViewModelFragment fragment2 = getFragment(viewModelActivity[0],
+                        ViewModelActivity.FRAGMENT_TAG_2);
+                assertThat(fragment1, notNullValue());
+                assertThat(fragment2, notNullValue());
+                assertThat(fragment1.activityModel, is(fragment2.activityModel));
+                assertThat(fragment1.fragmentModel, not(is(fragment2.activityModel)));
+                assertThat(mActivityRule.getActivity().activityModel, is(fragment1.activityModel));
+                activityModel[0] = mActivityRule.getActivity().activityModel;
+                defaultActivityModel[0] = mActivityRule.getActivity().defaultActivityModel;
+                assertThat(defaultActivityModel[0], not(is(activityModel[0])));
+                fragment1Model[0] = fragment1.fragmentModel;
+                fragment2Model[0] = fragment2.fragmentModel;
+            }
+        });
+        viewModelActivity[0] = recreateActivity();
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ViewModelFragment fragment1 = getFragment(viewModelActivity[0],
+                        ViewModelActivity.FRAGMENT_TAG_1);
+                ViewModelFragment fragment2 = getFragment(viewModelActivity[0],
+                        ViewModelActivity.FRAGMENT_TAG_2);
+                assertThat(fragment1, notNullValue());
+                assertThat(fragment2, notNullValue());
+
+                assertThat(fragment1.activityModel, is(activityModel[0]));
+                assertThat(fragment2.activityModel, is(activityModel[0]));
+                assertThat(fragment1.fragmentModel, is(fragment1Model[0]));
+                assertThat(fragment2.fragmentModel, is(fragment2Model[0]));
+                assertThat(fragment1.defaultActivityModel, is(defaultActivityModel[0]));
+                assertThat(fragment2.defaultActivityModel, is(defaultActivityModel[0]));
+                assertThat(mActivityRule.getActivity().activityModel, is(activityModel[0]));
+                assertThat(mActivityRule.getActivity().defaultActivityModel,
+                        is(defaultActivityModel[0]));
+            }
+        });
+    }
+
+    @Test
+    @UiThreadTest
+    public void testGetApplication() {
+        TestViewModel activityModel = mActivityRule.getActivity().activityModel;
+        assertThat(activityModel.getApplication(),
+                is(InstrumentationRegistry.getTargetContext().getApplicationContext()));
+    }
+
+    @Test
+    public void testOnClear() throws Throwable {
+        final ViewModelActivity activity = mActivityRule.getActivity();
+        final CountDownLatch latch = new CountDownLatch(1);
+        final LifecycleObserver observer = new LifecycleObserver() {
+            @SuppressWarnings("unused")
+            @OnLifecycleEvent(ON_RESUME)
+            void onResume() {
+                try {
+                    final FragmentManager manager = activity.getSupportFragmentManager();
+                    LifecycleFragment fragment = new LifecycleFragment();
+                    manager.beginTransaction().add(fragment, "temp").commitNow();
+                    ViewModel1 vm = ViewModelProviders.of(fragment).get(ViewModel1.class);
+                    assertThat(vm.mCleared, is(false));
+                    manager.beginTransaction().remove(fragment).commitNow();
+                    assertThat(vm.mCleared, is(true));
+                } finally {
+                    latch.countDown();
+                }
+            }
+        };
+
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                activity.getLifecycle().addObserver(observer);
+            }
+        });
+        assertThat(latch.await(TIMEOUT, TimeUnit.SECONDS), is(true));
+    }
+
+    private ViewModelFragment getFragment(FragmentActivity activity, String tag) {
+        return (ViewModelFragment) activity.getSupportFragmentManager()
+                .findFragmentByTag(tag);
+    }
+
+    private ViewModelActivity recreateActivity() throws Throwable {
+        Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
+                ViewModelActivity.class.getCanonicalName(), null, false);
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        instrumentation.addMonitor(monitor);
+        final ViewModelActivity previous = mActivityRule.getActivity();
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                previous.recreate();
+            }
+        });
+        ViewModelActivity result;
+
+        // this guarantee that we will reinstall monitor between notifications about onDestroy
+        // and onCreate
+        //noinspection SynchronizationOnLocalVariableOrMethodParameter
+        synchronized (monitor) {
+            do {
+                // the documentation says "Block until an Activity is created
+                // that matches this monitor." This statement is true, but there are some other
+                // true statements like: "Block until an Activity is destroyed" or
+                // "Block until an Activity is resumed"...
+
+                // this call will release synchronization monitor's monitor
+                result = (ViewModelActivity) monitor.waitForActivityWithTimeout(4000);
+                if (result == null) {
+                    throw new RuntimeException("Timeout. Failed to recreate an activity");
+                }
+            } while (result == previous);
+        }
+        return result;
+    }
+
+    public static class ViewModel1 extends ViewModel {
+        boolean mCleared = false;
+
+        @Override
+        protected void onCleared() {
+            mCleared = true;
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTestInTransaction.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTestInTransaction.java
new file mode 100644
index 0000000..3832b3b
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/ViewModelTestInTransaction.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.app.Fragment;
+
+import android.arch.lifecycle.viewmodeltest.TestViewModel;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class ViewModelTestInTransaction {
+
+    @Rule
+    public ActivityTestRule<EmptyActivity> mActivityRule =
+            new ActivityTestRule<>(EmptyActivity.class);
+
+    @Test
+    @UiThreadTest
+    public void testViewModelInTransactionActivity() {
+        EmptyActivity activity = mActivityRule.getActivity();
+        TestFragment fragment = new TestFragment();
+        activity.getSupportFragmentManager().beginTransaction().add(fragment, "tag").commitNow();
+        TestViewModel viewModel = ViewModelProviders.of(activity).get(TestViewModel.class);
+        assertThat(viewModel, is(fragment.mViewModel));
+    }
+
+    @Test
+    @UiThreadTest
+    public void testViewModelInTransactionFragment() {
+        EmptyActivity activity = mActivityRule.getActivity();
+        ParentFragment parent = new ParentFragment();
+        activity.getSupportFragmentManager().beginTransaction().add(parent, "parent").commitNow();
+        assertThat(parent.mExecuted, is(true));
+    }
+
+
+    public static class ParentFragment extends Fragment {
+
+        private boolean mExecuted;
+
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            TestFragment fragment = new TestFragment();
+            getChildFragmentManager().beginTransaction().add(fragment, "tag").commitNow();
+            TestViewModel viewModel = ViewModelProviders.of(this).get(TestViewModel.class);
+            assertThat(viewModel, is(fragment.mViewModel));
+            mExecuted = true;
+        }
+    }
+
+    public static class TestFragment extends Fragment {
+
+        TestViewModel mViewModel;
+
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            Fragment parentFragment = getParentFragment();
+            ViewModelProvider provider = parentFragment != null
+                    ? ViewModelProviders.of(parentFragment) : ViewModelProviders.of(getActivity());
+            mViewModel = provider.get(TestViewModel.class);
+            assertThat(mViewModel, notNullValue());
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/EmptyActivity.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/EmptyActivity.java
new file mode 100644
index 0000000..017fff4
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/EmptyActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.activity;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+
+import android.arch.lifecycle.LifecycleActivity;
+import android.arch.lifecycle.extensions.test.R;
+
+public class EmptyActivity extends LifecycleActivity {
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/FragmentLifecycleActivity.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/FragmentLifecycleActivity.java
new file mode 100644
index 0000000..f4485e8
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/activity/FragmentLifecycleActivity.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.activity;
+
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleFragment;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+import android.arch.lifecycle.extensions.test.R;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v7.app.AppCompatActivity;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class FragmentLifecycleActivity extends AppCompatActivity {
+    public static final String NESTED_TAG = "nested_fragment";
+    public static final String MAIN_TAG = "main_fragment";
+    private static final String EXTRA_NESTED = "nested";
+
+    private final List<Lifecycle.Event> mLoggedEvents = Collections
+            .synchronizedList(new ArrayList<Lifecycle.Event>());
+    private LifecycleOwner mObservedOwner;
+    private final CountDownLatch mDestroyLatch = new CountDownLatch(1);
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+        MainFragment fragment;
+        fragment = new MainFragment();
+        boolean nested = getIntent().getBooleanExtra(EXTRA_NESTED, false);
+        if (nested) {
+            fragment.mNestedFragment = new NestedFragment();
+        }
+        observe(nested ? fragment.mNestedFragment : fragment);
+        getSupportFragmentManager().beginTransaction()
+                .add(R.id.fragment_container, fragment, MAIN_TAG)
+                .commit();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mDestroyLatch.countDown();
+    }
+
+    public void resetEvents() {
+        mLoggedEvents.clear();
+    }
+
+    public static class MainFragment extends LifecycleFragment {
+        @Nullable
+        LifecycleFragment mNestedFragment;
+
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            if (mNestedFragment != null) {
+                getChildFragmentManager().beginTransaction()
+                        .add(mNestedFragment, NESTED_TAG)
+                        .commit();
+            }
+        }
+    }
+
+    public static class NestedFragment extends LifecycleFragment {
+    }
+
+    public static Intent intentFor(Context context, boolean nested) {
+        Intent intent = new Intent(context, FragmentLifecycleActivity.class);
+        intent.putExtra(EXTRA_NESTED, nested);
+        return intent;
+    }
+
+    public void observe(LifecycleOwner provider) {
+        mObservedOwner = provider;
+        provider.getLifecycle().addObserver(new LifecycleObserver() {
+            @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
+            public void anyEvent(LifecycleOwner owner, Lifecycle.Event event) {
+                mLoggedEvents.add(event);
+            }
+        });
+    }
+
+    public List<Lifecycle.Event> getLoggedEvents() {
+        return mLoggedEvents;
+    }
+
+    public LifecycleOwner getObservedOwner() {
+        return mObservedOwner;
+    }
+
+    public boolean awaitForDestruction(long timeout, TimeUnit timeUnit)
+            throws InterruptedException {
+        return mDestroyLatch.await(timeout, timeUnit);
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/service/TestService.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/service/TestService.java
new file mode 100644
index 0000000..fcf06cc
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/service/TestService.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.service;
+
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.LifecycleService;
+import android.arch.lifecycle.OnLifecycleEvent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.support.annotation.Nullable;
+import android.support.v4.content.LocalBroadcastManager;
+
+public class TestService extends LifecycleService {
+
+    public static final String ACTION_LOG_EVENT = "ACTION_LOG_EVENT";
+    public static final String EXTRA_KEY_EVENT = "EXTRA_KEY_EVENT";
+
+    private final IBinder mBinder = new Binder();
+
+    public TestService() {
+        getLifecycle().addObserver(new LifecycleObserver() {
+            @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
+            public void anyEvent(LifecycleOwner owner, Lifecycle.Event event) {
+                Context context = (TestService) owner;
+                Intent intent = new Intent(ACTION_LOG_EVENT);
+                intent.putExtra(EXTRA_KEY_EVENT, event);
+                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
+            }
+        });
+    }
+
+    @Nullable
+    @Override
+    public IBinder onBind(Intent intent) {
+        super.onBind(intent);
+        return mBinder;
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/TestViewModel.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/TestViewModel.java
new file mode 100644
index 0000000..ec3550c
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/TestViewModel.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.viewmodeltest;
+
+import android.app.Application;
+
+import android.arch.lifecycle.AndroidViewModel;
+
+public class TestViewModel extends AndroidViewModel {
+
+    public TestViewModel(Application application) {
+        super(application);
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/ViewModelActivity.java b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/ViewModelActivity.java
new file mode 100644
index 0000000..5ef9f16
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/java/android/arch/lifecycle/viewmodeltest/ViewModelActivity.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.viewmodeltest;
+
+import android.arch.lifecycle.extensions.test.R;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+
+import android.arch.lifecycle.LifecycleActivity;
+import android.arch.lifecycle.LifecycleFragment;
+import android.arch.lifecycle.ViewModelProviders;
+
+public class ViewModelActivity extends LifecycleActivity {
+    public static final String KEY_FRAGMENT_MODEL = "fragment-model";
+    public static final String KEY_ACTIVITY_MODEL = "activity-model";
+    public static final String FRAGMENT_TAG_1 = "f1";
+    public static final String FRAGMENT_TAG_2 = "f2";
+
+    public TestViewModel activityModel;
+    public TestViewModel defaultActivityModel;
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_view_model);
+        if (savedInstanceState == null) {
+            getSupportFragmentManager().beginTransaction()
+                    .add(R.id.fragment_container, new ViewModelFragment(), FRAGMENT_TAG_1)
+                    .add(new ViewModelFragment(), FRAGMENT_TAG_2)
+                    .commit();
+        }
+        activityModel = ViewModelProviders.of(this).get(KEY_ACTIVITY_MODEL, TestViewModel.class);
+        defaultActivityModel = ViewModelProviders.of(this).get(TestViewModel.class);
+    }
+
+    public static class ViewModelFragment extends LifecycleFragment {
+        public TestViewModel fragmentModel;
+        public TestViewModel activityModel;
+        public TestViewModel defaultActivityModel;
+
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            fragmentModel = ViewModelProviders.of(this).get(KEY_FRAGMENT_MODEL,
+                    TestViewModel.class);
+            activityModel = ViewModelProviders.of(getActivity()).get(KEY_ACTIVITY_MODEL,
+                    TestViewModel.class);
+            defaultActivityModel = ViewModelProviders.of(getActivity()).get(TestViewModel.class);
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/androidTest/res/layout/activity_main.xml b/lifecycle/extensions/src/androidTest/res/layout/activity_main.xml
new file mode 100644
index 0000000..305bccc
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/res/layout/activity_main.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/activity_main"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="android.arch.lifecycle.activity.FragmentLifecycleActivity">
+    <FrameLayout android:id="@+id/fragment_container"
+                 android:layout_width="match_parent"
+                 android:layout_height="match_parent"></FrameLayout>
+</RelativeLayout>
diff --git a/lifecycle/extensions/src/androidTest/res/layout/activity_view_model.xml b/lifecycle/extensions/src/androidTest/res/layout/activity_view_model.xml
new file mode 100644
index 0000000..eace2e9
--- /dev/null
+++ b/lifecycle/extensions/src/androidTest/res/layout/activity_view_model.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+    <FrameLayout android:id="@+id/fragment_container"
+                 android:layout_width="match_parent"
+                 android:layout_height="match_parent"></FrameLayout>
+</RelativeLayout>
diff --git a/lifecycle/extensions/src/main/AndroidManifest.xml b/lifecycle/extensions/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..f7698eb
--- /dev/null
+++ b/lifecycle/extensions/src/main/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.lifecycle.extensions">
+    <application>
+        <provider android:authorities="${applicationId}.lifecycle-trojan"
+            android:multiprocess="true"
+            android:exported="false"
+            android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider"/>
+    </application>
+</manifest>
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/AndroidViewModel.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/AndroidViewModel.java
new file mode 100644
index 0000000..2c7e173
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/AndroidViewModel.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Application;
+
+/**
+ * Application context aware {@link ViewModel}.
+ * <p>
+ * Subclasses must have a constructor which accepts {@link Application} as the only parameter.
+ * <p>
+ */
+public class AndroidViewModel extends ViewModel {
+    private Application mApplication;
+
+    public AndroidViewModel(Application application) {
+        mApplication = application;
+    }
+
+    /**
+     * Return the application.
+     */
+    public <T extends Application> T getApplication() {
+        return (T) mApplication;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ComputableLiveData.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ComputableLiveData.java
new file mode 100644
index 0000000..fe18243
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ComputableLiveData.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.VisibleForTesting;
+import android.support.annotation.WorkerThread;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * A LiveData class that can be invalidated & computed on demand.
+ * <p>
+ * This is an internal class for now, might be public if we see the necessity.
+ *
+ * @param <T> The type of the live data
+ * @hide internal
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class ComputableLiveData<T> {
+
+    private final LiveData<T> mLiveData;
+
+    private AtomicBoolean mInvalid = new AtomicBoolean(true);
+    private AtomicBoolean mComputing = new AtomicBoolean(false);
+
+    /**
+     * Creates a computable live data which is computed when there are active observers.
+     * <p>
+     * It can also be invalidated via {@link #invalidate()} which will result in a call to
+     * {@link #compute()} if there are active observers (or when they start observing)
+     */
+    @SuppressWarnings("WeakerAccess")
+    public ComputableLiveData() {
+        mLiveData = new LiveData<T>() {
+            @Override
+            protected void onActive() {
+                // TODO if we make this class public, we should accept an executor
+                AppToolkitTaskExecutor.getInstance().executeOnDiskIO(mRefreshRunnable);
+            }
+        };
+    }
+
+    /**
+     * Returns the LiveData managed by this class.
+     *
+     * @return A LiveData that is controlled by ComputableLiveData.
+     */
+    @SuppressWarnings("WeakerAccess")
+    @NonNull
+    public LiveData<T> getLiveData() {
+        return mLiveData;
+    }
+
+    @VisibleForTesting
+    final Runnable mRefreshRunnable = new Runnable() {
+        @WorkerThread
+        @Override
+        public void run() {
+            boolean computed;
+            do {
+                computed = false;
+                // compute can happen only in 1 thread but no reason to lock others.
+                if (mComputing.compareAndSet(false, true)) {
+                    // as long as it is invalid, keep computing.
+                    try {
+                        T value = null;
+                        while (mInvalid.compareAndSet(true, false)) {
+                            computed = true;
+                            value = compute();
+                        }
+                        if (computed) {
+                            mLiveData.postValue(value);
+                        }
+                    } finally {
+                        // release compute lock
+                        mComputing.set(false);
+                    }
+                }
+                // check invalid after releasing compute lock to avoid the following scenario.
+                // Thread A runs compute()
+                // Thread A checks invalid, it is false
+                // Main thread sets invalid to true
+                // Thread B runs, fails to acquire compute lock and skips
+                // Thread A releases compute lock
+                // We've left invalid in set state. The check below recovers.
+            } while (computed && mInvalid.get());
+        }
+    };
+
+    // invalidation check always happens on the main thread
+    @VisibleForTesting
+    final Runnable mInvalidationRunnable = new Runnable() {
+        @MainThread
+        @Override
+        public void run() {
+            boolean isActive = mLiveData.hasActiveObservers();
+            if (mInvalid.compareAndSet(false, true)) {
+                if (isActive) {
+                    // TODO if we make this class public, we should accept an executor.
+                    AppToolkitTaskExecutor.getInstance().executeOnDiskIO(mRefreshRunnable);
+                }
+            }
+        }
+    };
+
+    /**
+     * Invalidates the LiveData.
+     * <p>
+     * When there are active observers, this will trigger a call to {@link #compute()}.
+     */
+    public void invalidate() {
+        AppToolkitTaskExecutor.getInstance().executeOnMainThread(mInvalidationRunnable);
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @WorkerThread
+    protected abstract T compute();
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/EmptyActivityLifecycleCallbacks.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/EmptyActivityLifecycleCallbacks.java
new file mode 100644
index 0000000..ed41f2d
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/EmptyActivityLifecycleCallbacks.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Activity;
+import android.app.Application;
+import android.os.Bundle;
+
+class EmptyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
+    @Override
+    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+    }
+
+    @Override
+    public void onActivityStarted(Activity activity) {
+    }
+
+    @Override
+    public void onActivityResumed(Activity activity) {
+    }
+
+    @Override
+    public void onActivityPaused(Activity activity) {
+    }
+
+    @Override
+    public void onActivityStopped(Activity activity) {
+    }
+
+    @Override
+    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
+    }
+
+    @Override
+    public void onActivityDestroyed(Activity activity) {
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/HolderFragment.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/HolderFragment.java
new file mode 100644
index 0000000..100d10a
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/HolderFragment.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Activity;
+import android.app.Application.ActivityLifecycleCallbacks;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+import android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks;
+import android.util.Log;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class HolderFragment extends Fragment {
+    private static final String LOG_TAG = "ViewModelStores";
+
+    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static final String HOLDER_TAG =
+            "android.arch.lifecycle.state.StateProviderHolderFragment";
+
+    private ViewModelStore mViewModelStore = new ViewModelStore();
+
+    public HolderFragment() {
+        setRetainInstance(true);
+    }
+
+    @Override
+    public void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        sHolderFragmentManager.holderFragmentCreated(this);
+    }
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        mViewModelStore.clear();
+    }
+
+    public ViewModelStore getViewModelStore() {
+        return mViewModelStore;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static HolderFragment holderFragmentFor(FragmentActivity activity) {
+        return sHolderFragmentManager.holderFragmentFor(activity);
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static HolderFragment holderFragmentFor(Fragment fragment) {
+        return sHolderFragmentManager.holderFragmentFor(fragment);
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    static class HolderFragmentManager {
+        private Map<Activity, HolderFragment> mNotCommittedActivityHolders = new HashMap<>();
+        private Map<Fragment, HolderFragment> mNotCommittedFragmentHolders = new HashMap<>();
+
+        private ActivityLifecycleCallbacks mActivityCallbacks =
+                new EmptyActivityLifecycleCallbacks() {
+                    @Override
+                    public void onActivityDestroyed(Activity activity) {
+                        HolderFragment fragment = mNotCommittedActivityHolders.remove(activity);
+                        if (fragment != null) {
+                            Log.e(LOG_TAG, "Failed to save a ViewModel for " + activity);
+                        }
+                    }
+                };
+
+        private boolean mActivityCallbacksIsAdded = false;
+
+        private FragmentLifecycleCallbacks mParentDestroyedCallback =
+                new FragmentLifecycleCallbacks() {
+                    @Override
+                    public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) {
+                        super.onFragmentDestroyed(fm, parentFragment);
+                        HolderFragment fragment = mNotCommittedFragmentHolders.remove(
+                                parentFragment);
+                        if (fragment != null) {
+                            Log.e(LOG_TAG, "Failed to save a ViewModel for " + parentFragment);
+                        }
+                    }
+                };
+
+        void holderFragmentCreated(Fragment holderFragment) {
+            Fragment parentFragment = holderFragment.getParentFragment();
+            if (parentFragment != null) {
+                mNotCommittedFragmentHolders.remove(parentFragment);
+                parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks(
+                        mParentDestroyedCallback);
+            } else {
+                mNotCommittedActivityHolders.remove(holderFragment.getActivity());
+            }
+        }
+
+        private static HolderFragment findHolderFragment(FragmentManager manager) {
+            if (manager.isDestroyed()) {
+                throw new IllegalStateException("Can't access ViewModels from onDestroy");
+            }
+
+            Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG);
+            if (fragmentByTag != null && !(fragmentByTag instanceof HolderFragment)) {
+                throw new IllegalStateException("Unexpected "
+                        + "fragment instance was returned by HOLDER_TAG");
+            }
+            return (HolderFragment) fragmentByTag;
+        }
+
+        private static HolderFragment createHolderFragment(FragmentManager fragmentManager) {
+            HolderFragment holder = new HolderFragment();
+            fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
+            return holder;
+        }
+
+        HolderFragment holderFragmentFor(FragmentActivity activity) {
+            FragmentManager fm = activity.getSupportFragmentManager();
+            HolderFragment holder = findHolderFragment(fm);
+            if (holder != null) {
+                return holder;
+            }
+            holder = mNotCommittedActivityHolders.get(activity);
+            if (holder != null) {
+                return holder;
+            }
+
+            if (!mActivityCallbacksIsAdded) {
+                mActivityCallbacksIsAdded = true;
+                activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
+            }
+            holder = createHolderFragment(fm);
+            mNotCommittedActivityHolders.put(activity, holder);
+            return holder;
+        }
+
+        HolderFragment holderFragmentFor(Fragment parentFragment) {
+            FragmentManager fm = parentFragment.getChildFragmentManager();
+            HolderFragment holder = findHolderFragment(fm);
+            if (holder != null) {
+                return holder;
+            }
+            holder = mNotCommittedFragmentHolders.get(parentFragment);
+            if (holder != null) {
+                return holder;
+            }
+
+            parentFragment.getFragmentManager()
+                    .registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false);
+            holder = createHolderFragment(fm);
+            mNotCommittedFragmentHolders.put(parentFragment, holder);
+            return holder;
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleActivity.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleActivity.java
new file mode 100644
index 0000000..196a8d7
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleActivity.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.v4.app.FragmentActivity;
+
+/**
+ * Activity that implements {@link LifecycleOwner}.
+ * <p>
+ * This class is a temporary implementation detail until Lifecycles are integrated with support
+ * library.
+ */
+public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {
+
+    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
+
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mRegistry;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleDispatcher.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleDispatcher.java
new file mode 100644
index 0000000..9fdec95
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleDispatcher.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.Lifecycle.State.CREATED;
+
+import android.app.Activity;
+import android.app.Application;
+import android.arch.lifecycle.Lifecycle.State;
+import android.content.Context;
+import android.os.Bundle;
+import android.support.annotation.VisibleForTesting;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * When initialized, it hooks into the Activity callback of the Application and observes
+ * Activities. It is responsible to hook in child-fragments to activities and fragments to report
+ * their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle
+ * providers related to an activity as soon it is not safe to run a fragment transaction in this
+ * activity.
+ */
+class LifecycleDispatcher {
+
+    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+            + ".LifecycleDispatcher.report_fragment_tag";
+
+    private static AtomicBoolean sInitialized = new AtomicBoolean(false);
+
+    static void init(Context context) {
+        if (sInitialized.getAndSet(true)) {
+            return;
+        }
+        ((Application) context.getApplicationContext())
+                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
+        private final FragmentCallback mFragmentCallback;
+
+        DispatcherActivityCallback() {
+            mFragmentCallback = new FragmentCallback();
+        }
+
+        @Override
+        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+            if (activity instanceof FragmentActivity) {
+                ((FragmentActivity) activity).getSupportFragmentManager()
+                        .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
+            }
+            ReportFragment.injectIfNeededIn(activity);
+        }
+
+        @Override
+        public void onActivityStopped(Activity activity) {
+            if (activity instanceof FragmentActivity) {
+                markState((FragmentActivity) activity, CREATED);
+            }
+        }
+
+        @Override
+        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
+            if (activity instanceof FragmentActivity) {
+                markState((FragmentActivity) activity, CREATED);
+            }
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    public static class DestructionReportFragment extends Fragment {
+        @Override
+        public void onPause() {
+            super.onPause();
+            dispatch(ON_PAUSE);
+        }
+
+        @Override
+        public void onStop() {
+            super.onStop();
+            dispatch(ON_STOP);
+        }
+
+        @Override
+        public void onDestroy() {
+            super.onDestroy();
+            dispatch(ON_DESTROY);
+        }
+
+        protected void dispatch(Lifecycle.Event event) {
+            dispatchIfLifecycleOwner(getParentFragment(), event);
+        }
+    }
+
+    private static void markState(FragmentManager manager, State state) {
+        Collection<Fragment> fragments = manager.getFragments();
+        if (fragments == null) {
+            return;
+        }
+        for (Fragment fragment : fragments) {
+            if (fragment == null) {
+                continue;
+            }
+            markStateIn(fragment, state);
+            if (fragment.isAdded()) {
+                markState(fragment.getChildFragmentManager(), state);
+            }
+        }
+    }
+
+    private static void markStateIn(Object object, State state) {
+        if (object instanceof LifecycleRegistryOwner) {
+            LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
+            registry.markState(state);
+        }
+    }
+
+    private static void markState(FragmentActivity activity, State state) {
+        markStateIn(activity, state);
+        markState(activity.getSupportFragmentManager(), state);
+    }
+
+    private static void dispatchIfLifecycleOwner(Fragment fragment, Lifecycle.Event event) {
+        if (fragment instanceof LifecycleRegistryOwner) {
+            ((LifecycleRegistryOwner) fragment).getLifecycle().handleLifecycleEvent(event);
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {
+
+        @Override
+        public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
+            dispatchIfLifecycleOwner(f, ON_CREATE);
+
+            if (!(f instanceof LifecycleRegistryOwner)) {
+                return;
+            }
+
+            if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
+                f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
+                        REPORT_FRAGMENT_TAG).commit();
+            }
+        }
+
+        @Override
+        public void onFragmentStarted(FragmentManager fm, Fragment f) {
+            dispatchIfLifecycleOwner(f, ON_START);
+        }
+
+        @Override
+        public void onFragmentResumed(FragmentManager fm, Fragment f) {
+            dispatchIfLifecycleOwner(f, ON_RESUME);
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleFragment.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleFragment.java
new file mode 100644
index 0000000..d8dbf38
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleFragment.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.v4.app.Fragment;
+
+/**
+ * A fragment that is also a {@link LifecycleOwner}.
+ * <p>
+ * This class is a temporary implementation detail until Lifecycles are integrated with support
+ * library.
+ */
+// This class will be removed once we integrate with Fragment library.
+public class LifecycleFragment extends Fragment implements LifecycleRegistryOwner {
+    LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
+
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleRuntimeTrojanProvider.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleRuntimeTrojanProvider.java
new file mode 100644
index 0000000..ac278c0
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleRuntimeTrojanProvider.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+/**
+ * Internal class to initialize Lifecycles.
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class LifecycleRuntimeTrojanProvider extends ContentProvider {
+    @Override
+    public boolean onCreate() {
+        LifecycleDispatcher.init(getContext());
+        ProcessLifecycleOwner.init(getContext());
+        return true;
+    }
+
+    @Nullable
+    @Override
+    public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1,
+            String s1) {
+        return null;
+    }
+
+    @Nullable
+    @Override
+    public String getType(@NonNull Uri uri) {
+        return null;
+    }
+
+    @Nullable
+    @Override
+    public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
+        return null;
+    }
+
+    @Override
+    public int delete(@NonNull Uri uri, String s, String[] strings) {
+        return 0;
+    }
+
+    @Override
+    public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) {
+        return 0;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleService.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleService.java
new file mode 100644
index 0000000..adc4ffc
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LifecycleService.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.support.annotation.CallSuper;
+import android.support.annotation.Nullable;
+
+/**
+ * A Service that is also a {@link LifecycleOwner}.
+ */
+public class LifecycleService extends Service implements LifecycleOwner {
+
+    private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
+
+    @CallSuper
+    @Override
+    public void onCreate() {
+        mDispatcher.onServicePreSuperOnCreate();
+        super.onCreate();
+    }
+
+    @CallSuper
+    @Nullable
+    @Override
+    public IBinder onBind(Intent intent) {
+        mDispatcher.onServicePreSuperOnBind();
+        return null;
+    }
+
+    @SuppressWarnings("deprecation")
+    @CallSuper
+    @Override
+    public void onStart(Intent intent, int startId) {
+        mDispatcher.onServicePreSuperOnStart();
+        super.onStart(intent, startId);
+    }
+
+    // this method is added only to annotate it with @CallSuper.
+    // In usual service super.onStartCommand is no-op, but in LifecycleService
+    // it results in mDispatcher.onServicePreSuperOnStart() call, because
+    // super.onStartCommand calls onStart().
+    @CallSuper
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        return super.onStartCommand(intent, flags, startId);
+    }
+
+    @CallSuper
+    @Override
+    public void onDestroy() {
+        mDispatcher.onServicePreSuperOnDestroy();
+        super.onDestroy();
+    }
+
+    @Override
+    public Lifecycle getLifecycle() {
+        return mDispatcher.getLifecycle();
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/LiveData.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LiveData.java
new file mode 100644
index 0000000..d689442
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/LiveData.java
@@ -0,0 +1,413 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.State.DESTROYED;
+import static android.arch.lifecycle.Lifecycle.State.STARTED;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.internal.SafeIterableMap;
+import android.arch.lifecycle.Lifecycle.State;
+import android.support.annotation.MainThread;
+import android.support.annotation.Nullable;
+
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * LiveData is a data holder class that can be observed within a given lifecycle.
+ * This means that an {@link Observer} can be added in a pair with a {@link LifecycleOwner}, and
+ * this observer will be notified about modifications of the wrapped data only if the paired
+ * LifecycleOwner is in active state. LifecycleOwner is considered as active, if its state is
+ * {@link Lifecycle.State#STARTED} or {@link Lifecycle.State#RESUMED}. An observer added via
+ * {@link #observeForever(Observer)} is considered as always active and thus will be always notified
+ * about modifications. For those observers, you should manually call
+ * {@link #removeObserver(Observer)}.
+ *
+ * <p> An observer added with a Lifecycle will be automatically removed if the corresponding
+ * Lifecycle moves to {@link Lifecycle.State#DESTROYED} state. This is especially useful for
+ * activities and fragments where they can safely observe LiveData and not worry about leaks:
+ * they will be instantly unsubscribed when they are destroyed.
+ *
+ * <p>
+ * In addition, LiveData has {@link LiveData#onActive()} and {@link LiveData#onInactive()} methods
+ * to get notified when number of active {@link Observer}s change between 0 and 1.
+ * This allows LiveData to release any heavy resources when it does not have any Observers that
+ * are actively observing.
+ * <p>
+ * This class is designed to hold individual data fields of {@link ViewModel},
+ * but can also be used for sharing data between different modules in your application
+ * in a decoupled fashion.
+ *
+ * @param <T> The type of data hold by this instance
+ * @see ViewModel
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+// TODO: Thread checks are too strict right now, we may consider automatically moving them to main
+// thread.
+public abstract class LiveData<T> {
+    private final Object mDataLock = new Object();
+    static final int START_VERSION = -1;
+    private static final Object NOT_SET = new Object();
+
+    private static final LifecycleOwner ALWAYS_ON = new LifecycleOwner() {
+
+        private LifecycleRegistry mRegistry = init();
+
+        private LifecycleRegistry init() {
+            LifecycleRegistry registry = new LifecycleRegistry(this);
+            registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
+            registry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+            registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
+            return registry;
+        }
+
+        @Override
+        public Lifecycle getLifecycle() {
+            return mRegistry;
+        }
+    };
+
+    private SafeIterableMap<Observer<T>, LifecycleBoundObserver> mObservers =
+            new SafeIterableMap<>();
+
+    // how many observers are in active state
+    private int mActiveCount = 0;
+    private Object mData = NOT_SET;
+    // when setData is called, we set the pending data and actual data swap happens on the main
+    // thread
+    private volatile Object mPendingData = NOT_SET;
+    private int mVersion = START_VERSION;
+
+    private boolean mDispatchingValue;
+    @SuppressWarnings("FieldCanBeLocal")
+    private boolean mDispatchInvalidated;
+    private final Runnable mPostValueRunnable = new Runnable() {
+        @Override
+        public void run() {
+            Object newValue;
+            synchronized (mDataLock) {
+                newValue = mPendingData;
+                mPendingData = NOT_SET;
+            }
+            //noinspection unchecked
+            setValue((T) newValue);
+        }
+    };
+
+    private void considerNotify(LifecycleBoundObserver observer) {
+        if (!observer.active) {
+            return;
+        }
+        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
+        //
+        // we still first check observer.active to keep it as the entrance for events. So even if
+        // the observer moved to an active state, if we've not received that event, we better not
+        // notify for a more predictable notification order.
+        if (!isActiveState(observer.owner.getLifecycle().getCurrentState())) {
+            return;
+        }
+        if (observer.lastVersion >= mVersion) {
+            return;
+        }
+        observer.lastVersion = mVersion;
+        //noinspection unchecked
+        observer.observer.onChanged((T) mData);
+    }
+
+    private void dispatchingValue(@Nullable LifecycleBoundObserver initiator) {
+        if (mDispatchingValue) {
+            mDispatchInvalidated = true;
+            return;
+        }
+        mDispatchingValue = true;
+        do {
+            mDispatchInvalidated = false;
+            if (initiator != null) {
+                considerNotify(initiator);
+                initiator = null;
+            } else {
+                for (Iterator<Map.Entry<Observer<T>, LifecycleBoundObserver>> iterator =
+                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
+                    considerNotify(iterator.next().getValue());
+                    if (mDispatchInvalidated) {
+                        break;
+                    }
+                }
+            }
+        } while (mDispatchInvalidated);
+        mDispatchingValue = false;
+    }
+
+    /**
+     * Adds the given observer to the observers list within the lifespan of the given
+     * owner. The events are dispatched on the main thread. If LiveData already has data
+     * set, it will be delivered to the observer.
+     * <p>
+     * The observer will only receive events if the owner is in {@link Lifecycle.State#STARTED}
+     * or {@link Lifecycle.State#RESUMED} state (active).
+     * <p>
+     * If the owner moves to the {@link Lifecycle.State#DESTROYED} state, the observer will
+     * automatically be removed.
+     * <p>
+     * When data changes while the {@code owner} is not active, it will not receive any updates.
+     * If it becomes active again, it will receive the last available data automatically.
+     * <p>
+     * LiveData keeps a strong reference to the observer and the owner as long as the
+     * given LifecycleOwner is not destroyed. When it is destroyed, LiveData removes references to
+     * the observer &amp; the owner.
+     * <p>
+     * If the given owner is already in {@link Lifecycle.State#DESTROYED} state, LiveData
+     * ignores the call.
+     * <p>
+     * If the given owner, observer tuple is already in the list, the call is ignored.
+     * If the observer is already in the list with another owner, LiveData throws an
+     * {@link IllegalArgumentException}.
+     *
+     * @param owner    The LifecycleOwner which controls the observer
+     * @param observer The observer that will receive the events
+     */
+    @MainThread
+    public void observe(LifecycleOwner owner, Observer<T> observer) {
+        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
+            // ignore
+            return;
+        }
+        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
+        LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
+        if (existing != null && existing.owner != wrapper.owner) {
+            throw new IllegalArgumentException("Cannot add the same observer"
+                    + " with different lifecycles");
+        }
+        if (existing != null) {
+            return;
+        }
+        owner.getLifecycle().addObserver(wrapper);
+        wrapper.activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
+    }
+
+    /**
+     * Adds the given observer to the observers list. This call is similar to
+     * {@link LiveData#observe(LifecycleOwner, Observer)} with a LifecycleOwner, which
+     * is always active. This means that the given observer will receive all events and will never
+     * be automatically removed. You should manually call {@link #removeObserver(Observer)} to stop
+     * observing this LiveData.
+     * While LiveData has one of such observers, it will be considered
+     * as active.
+     * <p>
+     * If the observer was already added with an owner to this LiveData, LiveData throws an
+     * {@link IllegalArgumentException}.
+     *
+     * @param observer The observer that will receive the events
+     */
+    @MainThread
+    public void observeForever(Observer<T> observer) {
+        observe(ALWAYS_ON, observer);
+    }
+
+    /**
+     * Removes the given observer from the observers list.
+     *
+     * @param observer The Observer to receive events.
+     */
+    @MainThread
+    public void removeObserver(final Observer<T> observer) {
+        assertMainThread("removeObserver");
+        LifecycleBoundObserver removed = mObservers.remove(observer);
+        if (removed == null) {
+            return;
+        }
+        removed.owner.getLifecycle().removeObserver(removed);
+        removed.activeStateChanged(false);
+    }
+
+    /**
+     * Removes all observers that are tied to the given {@link LifecycleOwner}.
+     *
+     * @param owner The {@code LifecycleOwner} scope for the observers to be removed.
+     */
+    @MainThread
+    public void removeObservers(final LifecycleOwner owner) {
+        assertMainThread("removeObservers");
+        for (Map.Entry<Observer<T>, LifecycleBoundObserver> entry : mObservers) {
+            if (entry.getValue().owner == owner) {
+                removeObserver(entry.getKey());
+            }
+        }
+    }
+
+    /**
+     * Posts a task to a main thread to set the given value. So if you have a following code
+     * executed in the main thread:
+     * <pre class="prettyprint">
+     * liveData.postValue("a");
+     * liveData.setValue("b");
+     * </pre>
+     * The value "b" would be set at first and later the main thread would override it with
+     * the value "a".
+     * <p>
+     * If you called this method multiple times before a main thread executed a posted task, only
+     * the last value would be dispatched.
+     *
+     * @param value The new value
+     */
+    protected void postValue(T value) {
+        boolean postTask;
+        synchronized (mDataLock) {
+            postTask = mPendingData == NOT_SET;
+            mPendingData = value;
+        }
+        if (!postTask) {
+            return;
+        }
+        AppToolkitTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
+    }
+
+    /**
+     * Sets the value. If there are active observers, the value will be dispatched to them.
+     * <p>
+     * This method must be called from the main thread. If you need set a value from a background
+     * thread, you can use {@link #postValue(Object)}
+     *
+     * @param value The new value
+     */
+    @MainThread
+    protected void setValue(T value) {
+        assertMainThread("setValue");
+        mVersion++;
+        mData = value;
+        dispatchingValue(null);
+    }
+
+    /**
+     * Returns the current value.
+     * Note that calling this method on a background thread does not guarantee that the latest
+     * value set will be received.
+     *
+     * @return the current value
+     */
+    @Nullable
+    public T getValue() {
+        // we do not return pending data here to be able to serve a consistent view to the main
+        // thread.
+        Object data = mData;
+        if (mData != NOT_SET) {
+            //noinspection unchecked
+            return (T) mData;
+        }
+        return null;
+    }
+
+    int getVersion() {
+        return mVersion;
+    }
+
+    /**
+     * Called when the number of active observers change to 1 from 0.
+     * <p>
+     * This callback can be used to know that this LiveData is being used thus should be kept
+     * up to date.
+     */
+    protected void onActive() {
+
+    }
+
+    /**
+     * Called when the number of active observers change from 1 to 0.
+     * <p>
+     * This does not mean that there are no observers left, there may still be observers but their
+     * lifecycle states aren't {@link Lifecycle.State#STARTED} or {@link Lifecycle.State#RESUMED}
+     * (like an Activity in the back stack).
+     * <p>
+     * You can check if there are observers via {@link #hasObservers()}.
+     */
+    protected void onInactive() {
+
+    }
+
+    /**
+     * Returns true if this LiveData has observers.
+     *
+     * @return true if this LiveData has observers
+     */
+    public boolean hasObservers() {
+        return mObservers.size() > 0;
+    }
+
+    /**
+     * Returns true if this LiveData has active observers.
+     *
+     * @return true if this LiveData has active observers
+     */
+    public boolean hasActiveObservers() {
+        return mActiveCount > 0;
+    }
+
+    class LifecycleBoundObserver implements LifecycleObserver {
+        public final LifecycleOwner owner;
+        public final Observer<T> observer;
+        public boolean active;
+        public int lastVersion = START_VERSION;
+
+        LifecycleBoundObserver(LifecycleOwner owner, Observer<T> observer) {
+            this.owner = owner;
+            this.observer = observer;
+        }
+
+        @SuppressWarnings("unused")
+        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
+        void onStateChange() {
+            if (owner.getLifecycle().getCurrentState() == DESTROYED) {
+                removeObserver(observer);
+                return;
+            }
+            // immediately set active state, so we'd never dispatch anything to inactive
+            // owner
+            activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
+
+        }
+
+        void activeStateChanged(boolean newActive) {
+            if (newActive == active) {
+                return;
+            }
+            active = newActive;
+            boolean wasInactive = LiveData.this.mActiveCount == 0;
+            LiveData.this.mActiveCount += active ? 1 : -1;
+            if (wasInactive && active) {
+                onActive();
+            }
+            if (LiveData.this.mActiveCount == 0 && !active) {
+                onInactive();
+            }
+            if (active) {
+                dispatchingValue(this);
+            }
+        }
+    }
+
+    static boolean isActiveState(State state) {
+        return state.isAtLeast(STARTED);
+    }
+
+    private void assertMainThread(String methodName) {
+        if (!AppToolkitTaskExecutor.getInstance().isMainThread()) {
+            throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
+                    + " thread");
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/MediatorLiveData.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/MediatorLiveData.java
new file mode 100644
index 0000000..a7d090b
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/MediatorLiveData.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.arch.core.internal.SafeIterableMap;
+import android.support.annotation.CallSuper;
+import android.support.annotation.MainThread;
+import android.support.annotation.Nullable;
+
+import java.util.Map;
+
+/**
+ * {@link LiveData} subclass which may observer other {@code LiveData} objects and react on
+ * {@code OnChanged} events from them.
+ * <p>
+ * This class correctly propagates its active/inactive states down to source {@code LiveData}
+ * objects.
+ *
+ * @param <T> The type of data hold by this instance
+ */
+@SuppressWarnings("WeakerAccess")
+public class MediatorLiveData<T> extends MutableLiveData<T> {
+    private SafeIterableMap<LiveData<?>, Source<?>> mSources = new SafeIterableMap<>();
+
+    /**
+     * Starts to listen the given {@code source} LiveData, {@code onChanged} observer will be called
+     * when {@code source} value was changed.
+     * <p>
+     * {@code onChanged} callback will be called only when this {@code MediatorLiveData} is active.
+     * <p> If the given LiveData is already added as a source but with a different Observer,
+     * {@link IllegalArgumentException} will be thrown.
+     *
+     * @param source    the {@code LiveData} to listen to
+     * @param onChanged The observer that will receive the events
+     * @param <S>       The type of data hold by {@code source} LiveData
+     */
+    @MainThread
+    public <S> void addSource(LiveData<S> source, Observer<S> onChanged) {
+        Source<S> e = new Source<>(source, onChanged);
+        Source<?> existing = mSources.putIfAbsent(source, e);
+        if (existing != null && existing.mObserver != onChanged) {
+            throw new IllegalArgumentException(
+                    "This source was already added with the different observer");
+        }
+        if (existing != null) {
+            return;
+        }
+        if (hasActiveObservers()) {
+            e.plug();
+        }
+    }
+
+    /**
+     * Stops to listen the given {@code LiveData}.
+     *
+     * @param toRemote {@code LiveData} to stop to listen
+     * @param <S>      the type of data hold by {@code source} LiveData
+     */
+    @MainThread
+    public <S> void removeSource(LiveData<S> toRemote) {
+        Source<?> source = mSources.remove(toRemote);
+        if (source != null) {
+            source.unplug();
+        }
+    }
+
+    @CallSuper
+    @Override
+    protected void onActive() {
+        for (Map.Entry<LiveData<?>, Source<?>> source : mSources) {
+            source.getValue().plug();
+        }
+    }
+
+    @CallSuper
+    @Override
+    protected void onInactive() {
+        for (Map.Entry<LiveData<?>, Source<?>> source : mSources) {
+            source.getValue().unplug();
+        }
+    }
+
+    private static class Source<V> {
+        final LiveData<V> mLiveData;
+        final Observer<V> mObserver;
+        int mVersion = START_VERSION;
+
+        Source(LiveData<V> liveData, final Observer<V> observer) {
+            mLiveData = liveData;
+            mObserver = new Observer<V>() {
+                @Override
+                public void onChanged(@Nullable V v) {
+                    if (mVersion != mLiveData.getVersion()) {
+                        mVersion = mLiveData.getVersion();
+                        observer.onChanged(v);
+                    }
+                }
+            };
+        }
+
+        void plug() {
+            mLiveData.observeForever(mObserver);
+        }
+
+        void unplug() {
+            mLiveData.removeObserver(mObserver);
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/MutableLiveData.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/MutableLiveData.java
new file mode 100644
index 0000000..ecd7752
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/MutableLiveData.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
+ *
+ * @param <T> The type of data hold by this instance
+ */
+@SuppressWarnings("WeakerAccess")
+public class MutableLiveData<T> extends LiveData<T> {
+    @Override
+    public void postValue(T value) {
+        super.postValue(value);
+    }
+
+    @Override
+    public void setValue(T value) {
+        super.setValue(value);
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/Observer.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/Observer.java
new file mode 100644
index 0000000..0e36775
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/Observer.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.annotation.Nullable;
+
+/**
+ * A simple callback that can receive from {@link LiveData}.
+ *
+ * @param <T> The type of the parameter
+ *
+ * @see LiveData LiveData - for a usage description.
+ */
+public interface Observer<T> {
+    /**
+     * Called when the data is changed.
+     * @param t  The new data
+     */
+    void onChanged(@Nullable T t);
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ProcessLifecycleOwner.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ProcessLifecycleOwner.java
new file mode 100644
index 0000000..e2a1256
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ProcessLifecycleOwner.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Activity;
+import android.app.Application;
+import android.arch.lifecycle.ReportFragment.ActivityInitializationListener;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.annotation.VisibleForTesting;
+
+/**
+ * Class that provides lifecycle for the whole application process.
+ * <p>
+ * You can consider this LifecycleOwner as the composite of all of your Activities, except that
+ * {@link Lifecycle.Event#ON_CREATE} will be dispatched once and {@link Lifecycle.Event#ON_DESTROY}
+ * will never be dispatched. Other lifecycle events will be dispatched with following rules:
+ * ProcessLifecycleOwner will dispatch {@link Lifecycle.Event#ON_START},
+ * {@link Lifecycle.Event#ON_RESUME} events, as a first activity moves through these events.
+ * {@link Lifecycle.Event#ON_PAUSE}, {@link Lifecycle.Event#ON_STOP}, events will be dispatched with
+ * a <b>delay</b> after a last activity
+ * passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner
+ * won't send any events if activities are destroyed and recreated due to a
+ * configuration change.
+ *
+ * <p>
+ * It is useful for use cases where you would like to react on your app coming to the foreground or
+ * going to the background and you don't need a milliseconds accuracy in receiving lifecycle
+ * events.
+ */
+@SuppressWarnings("WeakerAccess")
+public class ProcessLifecycleOwner implements LifecycleOwner {
+
+    @VisibleForTesting
+    static final long TIMEOUT_MS = 700; //mls
+
+    // ground truth counters
+    private int mStartedCounter = 0;
+    private int mResumedCounter = 0;
+
+    private boolean mPauseSent = true;
+    private boolean mStopSent = true;
+
+    private Handler mHandler;
+    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
+
+    private Runnable mDelayedPauseRunnable = new Runnable() {
+        @Override
+        public void run() {
+            dispatchPauseIfNeeded();
+            dispatchStopIfNeeded();
+        }
+    };
+
+    private ActivityInitializationListener mInitializationListener =
+            new ActivityInitializationListener() {
+                @Override
+                public void onCreate() {
+                }
+
+                @Override
+                public void onStart() {
+                    activityStarted();
+                }
+
+                @Override
+                public void onResume() {
+                    activityResumed();
+                }
+            };
+
+    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
+
+    /**
+     * The LifecycleOwner for the whole application process. Note that if your application
+     * has multiple processes, this provider does not know about other processes.
+     *
+     * @return {@link LifecycleOwner} for the whole application.
+     */
+    public static LifecycleOwner get() {
+        return sInstance;
+    }
+
+    static void init(Context context) {
+        sInstance.attach(context);
+    }
+
+    void activityStarted() {
+        mStartedCounter++;
+        if (mStartedCounter == 1 && mStopSent) {
+            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+            mStopSent = false;
+        }
+    }
+
+    void activityResumed() {
+        mResumedCounter++;
+        if (mResumedCounter == 1) {
+            if (mPauseSent) {
+                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
+                mPauseSent = false;
+            } else {
+                mHandler.removeCallbacks(mDelayedPauseRunnable);
+            }
+        }
+    }
+
+    void activityPaused() {
+        mResumedCounter--;
+        if (mResumedCounter == 0) {
+            mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
+        }
+    }
+
+    void activityStopped() {
+        mStartedCounter--;
+        dispatchStopIfNeeded();
+    }
+
+    private void dispatchPauseIfNeeded() {
+        if (mResumedCounter == 0) {
+            mPauseSent = true;
+            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
+        }
+    }
+
+    private void dispatchStopIfNeeded() {
+        if (mStartedCounter == 0 && mPauseSent) {
+            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+            mStopSent = true;
+        }
+    }
+
+    private ProcessLifecycleOwner() {
+    }
+
+    void attach(Context context) {
+        mHandler = new Handler();
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
+        Application app = (Application) context.getApplicationContext();
+        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
+            @Override
+            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+                ReportFragment  .get(activity).setProcessListener(mInitializationListener);
+            }
+
+            @Override
+            public void onActivityPaused(Activity activity) {
+                activityPaused();
+            }
+
+            @Override
+            public void onActivityStopped(Activity activity) {
+                activityStopped();
+            }
+        });
+    }
+
+    @Override
+    public Lifecycle getLifecycle() {
+        return mRegistry;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ServiceLifecycleDispatcher.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ServiceLifecycleDispatcher.java
new file mode 100644
index 0000000..6067d7b
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ServiceLifecycleDispatcher.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.Handler;
+import android.support.annotation.NonNull;
+
+/**
+ * Helper class to dispatch lifecycle events for a service. Use it only if it is impossible
+ * to use {@link LifecycleService}.
+ */
+@SuppressWarnings("WeakerAccess")
+public class ServiceLifecycleDispatcher {
+    private final LifecycleRegistry mRegistry;
+    private final Handler mHandler;
+    private DispatchRunnable mLastDispatchRunnable;
+
+    /**
+     * @param provider {@link LifecycleOwner} for a service, usually it is a service itself
+     */
+    public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
+        mRegistry = new LifecycleRegistry(provider);
+        mHandler = new Handler();
+    }
+
+    private void postDispatchRunnable(Lifecycle.Event event) {
+        if (mLastDispatchRunnable != null) {
+            mLastDispatchRunnable.run();
+        }
+        mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
+        mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
+    }
+
+    /**
+     * Must be a first call in {@link Service#onCreate()} method, even before super.onCreate call.
+     */
+    public void onServicePreSuperOnCreate() {
+        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
+    }
+
+    /**
+     * Must be a first call in {@link Service#onBind(Intent)} method, even before super.onBind
+     * call.
+     */
+    public void onServicePreSuperOnBind() {
+        postDispatchRunnable(Lifecycle.Event.ON_START);
+    }
+
+    /**
+     * Must be a first call in {@link Service#onStart(Intent, int)} or
+     * {@link Service#onStartCommand(Intent, int, int)} methods, even before
+     * a corresponding super call.
+     */
+    public void onServicePreSuperOnStart() {
+        postDispatchRunnable(Lifecycle.Event.ON_START);
+    }
+
+    /**
+     * Must be a first call in {@link Service#onDestroy()} method, even before super.OnDestroy
+     * call.
+     */
+    public void onServicePreSuperOnDestroy() {
+        postDispatchRunnable(Lifecycle.Event.ON_STOP);
+        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
+    }
+
+    /**
+     * @return {@link Lifecycle} for the given {@link LifecycleOwner}
+     */
+    public Lifecycle getLifecycle() {
+        return mRegistry;
+    }
+
+    static class DispatchRunnable implements Runnable {
+        private final LifecycleRegistry mRegistry;
+        final Lifecycle.Event mEvent;
+        private boolean mWasExecuted = false;
+
+        DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
+            mRegistry = registry;
+            mEvent = event;
+        }
+
+        @Override
+        public void run() {
+            if (!mWasExecuted) {
+                mRegistry.handleLifecycleEvent(mEvent);
+                mWasExecuted = true;
+            }
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/Transformations.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/Transformations.java
new file mode 100644
index 0000000..c316563
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/Transformations.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.arch.core.util.Function;
+import android.support.annotation.MainThread;
+import android.support.annotation.Nullable;
+
+/**
+ * Transformations for a {@link LiveData} class.
+ */
+@SuppressWarnings("WeakerAccess")
+public class Transformations {
+
+    private Transformations() {
+    }
+
+    /**
+     * Applies the given function on the main thread to each value emitted by {@code source}
+     * LiveData and returns LiveData, which emits resulting values.
+     * <p>
+     * The given function {@code func} will be executed on the main thread.
+     *
+     * @param source a {@code LiveData} to listen to
+     * @param func   a function to apply
+     * @param <X>    a type of {@code source} LiveData
+     * @param <Y>    a type of resulting LiveData.
+     * @return a LiveData which emits resulting values
+     */
+    @MainThread
+    public static <X, Y> LiveData<Y> map(LiveData<X> source, final Function<X, Y> func) {
+        final MediatorLiveData<Y> result = new MediatorLiveData<>();
+        result.addSource(source, new Observer<X>() {
+            @Override
+            public void onChanged(@Nullable X x) {
+                result.setValue(func.apply(x));
+            }
+        });
+        return result;
+    }
+
+    /**
+     * Creates a LiveData, let's name it {@code swLiveData}, which follows next flow:
+     * it reacts on changes of {@code trigger} LiveData, applies the given function to new value of
+     * {@code trigger} LiveData and sets resulting LiveData as a "backing" LiveData
+     * to {@code swLiveData}.
+     * "Backing" LiveData means, that all events emitted by it will retransmitted
+     * by {@code swLiveData}.
+     * <p>
+     * If the given function returns null, then {@code swLiveData} is not "backed" by any other
+     * LiveData.
+     * <p>
+     * The given function {@code func} will be executed on the main thread.
+     *
+     * @param trigger a {@code LiveData} to listen to
+     * @param func    a function which creates "backing" LiveData
+     * @param <X>     a type of {@code source} LiveData
+     * @param <Y>     a type of resulting LiveData
+     */
+    @MainThread
+    public static <X, Y> LiveData<Y> switchMap(LiveData<X> trigger,
+            final Function<X, LiveData<Y>> func) {
+        final MediatorLiveData<Y> result = new MediatorLiveData<>();
+        result.addSource(trigger, new Observer<X>() {
+            LiveData<Y> mSource;
+
+            @Override
+            public void onChanged(@Nullable X x) {
+                LiveData<Y> newLiveData = func.apply(x);
+                if (mSource == newLiveData) {
+                    return;
+                }
+                if (mSource != null) {
+                    result.removeSource(mSource);
+                }
+                mSource = newLiveData;
+                if (mSource != null) {
+                    result.addSource(mSource, new Observer<Y>() {
+                        @Override
+                        public void onChanged(@Nullable Y y) {
+                            result.setValue(y);
+                        }
+                    });
+                }
+            }
+        });
+        return result;
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModel.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModel.java
new file mode 100644
index 0000000..0310c46
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModel.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * ViewModel is a class that is responsible for preparing and managing the data for
+ * an {@link android.app.Activity Activity} or a {@link android.support.v4.app.Fragment Fragment}.
+ * It also handles the communication of the Activity / Fragment with the rest of the application
+ * (e.g. calling the business logic classes).
+ * <p>
+ * A ViewModel is always created in association with a scope (an fragment or an activity) and will
+ * be retained as long as the scope is alive. E.g. if it is an Activity, until it is
+ * finished.
+ * <p>
+ * In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a
+ * configuration change (e.g. rotation). The new instance of the owner will just re-connected to the
+ * existing ViewModel.
+ * <p>
+ * The purpose of the ViewModel is to acquire and keep the information that is necessary for an
+ * Activity or a Fragment. The Activity or the Fragment should be able to observe changes in the
+ * ViewModel. ViewModels usually expose this information via {@link LiveData} or Android Data
+ * Binding. You can also use any observability construct from you favorite framework.
+ * <p>
+ * ViewModel's only responsibility is to manage the data for the UI. It <b>should never</b> access
+ * your view hierarchy or hold a reference back to the Activity or the Fragment.
+ * <p>
+ * Typical usage from an Activity standpoint would be:
+ * <pre>
+ * public class UserActivity extends Activity {
+ *
+ *     {@literal @}Override
+ *     protected void onCreate(Bundle savedInstanceState) {
+ *         super.onCreate(savedInstanceState);
+ *         setContentView(R.layout.user_activity_layout);
+ *         final UserModel viewModel = ViewModelProviders.of(this).get(UserModel.class);
+ *         viewModel.userLiveData.observer(this, new Observer<User>() {
+ *            {@literal @}Override
+ *             public void onChanged(@Nullable User data) {
+ *                 // update ui.
+ *             }
+ *         });
+ *         findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
+ *             {@literal @}Override
+ *             public void onClick(View v) {
+ *                  viewModel.doAction();
+ *             }
+ *         });
+ *     }
+ * }
+ * </pre>
+ *
+ * ViewModel would be:
+ * <pre>
+ * public class UserModel extends ViewModel {
+ *     public final LiveData&lt;User&gt; userLiveData = new LiveData<>();
+ *
+ *     public UserModel() {
+ *         // trigger user load.
+ *     }
+ *
+ *     void doAction() {
+ *         // depending on the action, do necessary business logic calls and update the
+ *         // userLiveData.
+ *     }
+ * }
+ * </pre>
+ *
+ * <p>
+ * ViewModels can also be used as a communication layer between different Fragments of an Activity.
+ * Each Fragment can acquire the ViewModel using the same key via their Activity. This allows
+ * communication between Fragments in a de-coupled fashion such that they never need to talk to
+ * the other Fragment directly.
+ * <pre>
+ * public class MyFragment extends Fragment {
+ *     public void onStart() {
+ *         UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
+ *     }
+ * }
+ * </pre>
+ * </>
+ */
+public abstract class ViewModel {
+    /**
+     * This method will be called when this ViewModel is no longer used and will be destroyed.
+     * <p>
+     * It is useful when ViewModel observes some data and you need to clear this subscription to
+     * prevent a leak of this ViewModel.
+     */
+    @SuppressWarnings("WeakerAccess")
+    protected void onCleared() {
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProvider.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProvider.java
new file mode 100644
index 0000000..7ef591f
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProvider.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+
+/**
+ * An utility class that provides {@code ViewModels} for a scope.
+ * <p>
+ * Default {@code ViewModelProvider} for an {@code Activity} or a {@code Fragment} can be obtained
+ * from {@link android.arch.lifecycle.ViewModelProviders} class.
+ */
+@SuppressWarnings("WeakerAccess")
+public class ViewModelProvider {
+
+    private static final String DEFAULT_KEY =
+            "android.arch.lifecycle.ViewModelProvider.DefaultKey";
+
+    /**
+     * Implementations of {@code Factory} interface are responsible to instantiate ViewModels.
+     */
+    public interface Factory {
+        /**
+         * Creates a new instance of the given {@code Class}.
+         * <p>
+         *
+         * @param modelClass a {@code Class} whose instance is requested
+         * @param <T>        The type parameter for the ViewModel.
+         * @return a newly created ViewModel
+         */
+        <T extends ViewModel> T create(Class<T> modelClass);
+    }
+
+    private final Factory mFactory;
+    private final ViewModelStore mViewModelStore;
+
+    /**
+     * Creates {@code ViewModelProvider}, which will create {@code ViewModels} via the given
+     * {@code Factory} and retain them in a store of the given {@code ViewModelStoreOwner}.
+     *
+     * @param owner   a {@code ViewModelStoreOwner} whose {@link ViewModelStore} will be used to
+     *                retain {@code ViewModels}
+     * @param factory a {@code Factory} which will be used to instantiate
+     *                new {@code ViewModels}
+     */
+    public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
+        this(owner.getViewModelStore(), factory);
+    }
+
+    /**
+     * Creates {@code ViewModelProvider}, which will create {@code ViewModels} via the given
+     * {@code Factory} and retain them in the given {@code store}.
+     *
+     * @param store   {@code ViewModelStore} where ViewModels will be stored.
+     * @param factory factory a {@code Factory} which will be used to instantiate
+     *                new {@code ViewModels}
+     */
+    public ViewModelProvider(ViewModelStore store, Factory factory) {
+        mFactory = factory;
+        this.mViewModelStore = store;
+    }
+
+    /**
+     * Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or
+     * an activity), associated with this {@code ViewModelProvider}.
+     * <p>
+     * The created ViewModel is associated with the given scope and will be retained
+     * as long as the scope is alive (e.g. if it is an activity, until it is
+     * finished or process is killed).
+     *
+     * @param modelClass The class of the ViewModel to create an instance of it if it is not
+     *                   present.
+     * @param <T>        The type parameter for the ViewModel.
+     * @return A ViewModel that is an instance of the given type {@code T}.
+     */
+    public <T extends ViewModel> T get(Class<T> modelClass) {
+        String canonicalName = modelClass.getCanonicalName();
+        if (canonicalName == null) {
+            throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
+        }
+        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
+    }
+
+    /**
+     * Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or
+     * an activity), associated with this {@code ViewModelProvider}.
+     * <p>
+     * The created ViewModel is associated with the given scope and will be retained
+     * as long as the scope is alive (e.g. if it is an activity, until it is
+     * finished or process is killed).
+     *
+     * @param key        The key to use to identify the ViewModel.
+     * @param modelClass The class of the ViewModel to create an instance of it if it is not
+     *                   present.
+     * @param <T>        The type parameter for the ViewModel.
+     * @return A ViewModel that is an instance of the given type {@code T}.
+     */
+    @NonNull
+    @MainThread
+    public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
+        ViewModel viewModel = mViewModelStore.get(key);
+
+        if (modelClass.isInstance(viewModel)) {
+            //noinspection unchecked
+            return (T) viewModel;
+        } else {
+            //noinspection StatementWithEmptyBody
+            if (viewModel != null) {
+                // TODO: log a warning.
+            }
+        }
+
+        viewModel = mFactory.create(modelClass);
+        mViewModelStore.put(key, viewModel);
+        //noinspection unchecked
+        return (T) viewModel;
+    }
+
+    /**
+     * Simple factory, which calls empty constructor on the give class.
+     */
+    public static class NewInstanceFactory implements Factory {
+
+        @Override
+        public <T extends ViewModel> T create(Class<T> modelClass) {
+            //noinspection TryWithIdenticalCatches
+            try {
+                return modelClass.newInstance();
+            } catch (InstantiationException e) {
+                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+            } catch (IllegalAccessException e) {
+                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+            }
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProviders.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProviders.java
new file mode 100644
index 0000000..f64365b
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelProviders.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.annotation.SuppressLint;
+import android.app.Application;
+import android.arch.lifecycle.ViewModelProvider.Factory;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentActivity;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Utilities methods for {@link ViewModelStore} class.
+ */
+public class ViewModelProviders {
+
+    @SuppressLint("StaticFieldLeak")
+    private static DefaultFactory sDefaultFactory;
+
+    private static void initializeFactoryIfNeeded(Application application) {
+        if (sDefaultFactory == null) {
+            sDefaultFactory = new DefaultFactory(application);
+        }
+    }
+
+    /**
+     * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given
+     * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}.
+     * <p>
+     * It uses {@link DefaultFactory} to instantiate new ViewModels.
+     *
+     * @param fragment a fragment, in whose scope ViewModels should be retained
+     * @return a ViewModelProvider instance
+     */
+    @MainThread
+    public static ViewModelProvider of(@NonNull Fragment fragment) {
+        FragmentActivity activity = fragment.getActivity();
+        if (activity == null) {
+            throw new IllegalArgumentException(
+                    "Can't create ViewModelProvider for detached fragment");
+        }
+        initializeFactoryIfNeeded(activity.getApplication());
+        return new ViewModelProvider(ViewModelStores.of(fragment), sDefaultFactory);
+    }
+
+    /**
+     * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
+     * is alive. More detailed explanation is in {@link ViewModel}.
+     * <p>
+     * It uses {@link DefaultFactory} to instantiate new ViewModels.
+     *
+     * @param activity an activity, in whose scope ViewModels should be retained
+     * @return a ViewModelProvider instance
+     */
+    @MainThread
+    public static ViewModelProvider of(@NonNull FragmentActivity activity) {
+        initializeFactoryIfNeeded(activity.getApplication());
+        return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
+    }
+
+    /**
+     * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given
+     * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}.
+     * <p>
+     * It uses the given {@link Factory} to instantiate new ViewModels.
+     *
+     * @param fragment a fragment, in whose scope ViewModels should be retained
+     * @param factory  a {@code Factory} to instantiate new ViewModels
+     * @return a ViewModelProvider instance
+     */
+    @MainThread
+    public static ViewModelProvider of(@NonNull Fragment fragment, @NonNull Factory factory) {
+        return new ViewModelProvider(ViewModelStores.of(fragment), factory);
+    }
+
+    /**
+     * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
+     * is alive. More detailed explanation is in {@link ViewModel}.
+     * <p>
+     * It uses the given {@link Factory} to instantiate new ViewModels.
+     *
+     * @param activity an activity, in whose scope ViewModels should be retained
+     * @param factory  a {@code Factory} to instantiate new ViewModels
+     * @return a ViewModelProvider instance
+     */
+    @MainThread
+    public static ViewModelProvider of(@NonNull FragmentActivity activity,
+            @NonNull Factory factory) {
+        return new ViewModelProvider(ViewModelStores.of(activity), factory);
+    }
+
+    /**
+     * {@link Factory} which may create {@link AndroidViewModel} and
+     * {@link ViewModel}, which have an empty constructor.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public static class DefaultFactory extends ViewModelProvider.NewInstanceFactory {
+
+        private Application mApplication;
+
+        /**
+         * Creates a {@code DefaultFactory}
+         *
+         * @param application an application to pass in {@link AndroidViewModel}
+         */
+        public DefaultFactory(@NonNull Application application) {
+            mApplication = application;
+        }
+
+        @Override
+        public <T extends ViewModel> T create(Class<T> modelClass) {
+            if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
+                //noinspection TryWithIdenticalCatches
+                try {
+                    return modelClass.getConstructor(Application.class).newInstance(mApplication);
+                } catch (NoSuchMethodException e) {
+                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+                } catch (IllegalAccessException e) {
+                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+                } catch (InstantiationException e) {
+                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+                } catch (InvocationTargetException e) {
+                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
+                }
+            }
+            return super.create(modelClass);
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStore.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStore.java
new file mode 100644
index 0000000..a1864bb
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStore.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import java.util.HashMap;
+
+/**
+ * Class to store {@code ViewModels}.
+ * <p>
+ * An instance of {@code ViewModelStore} must be retained through configuration changes:
+ * if an owner of this {@code ViewModelStore} is destroyed and recreated due to configuration
+ * changes, new instance of an owner should still have the same old instance of
+ * {@code ViewModelStore}.
+ * <p>
+ * If an owner of this {@code ViewModelStore} is destroyed and is not going to be recreated,
+ * then it should call {@link #clear()} on this {@code ViewModelStore}, so {@code ViewModels} would
+ * be notified that they are no longer used.
+ * <p>
+ * {@link android.arch.lifecycle.ViewModelStores} provides a {@code ViewModelStore} for
+ * activities and fragments.
+ */
+public class ViewModelStore {
+
+    private final HashMap<String, ViewModel> mMap = new HashMap<>();
+
+    final void put(String key, ViewModel viewModel) {
+        ViewModel oldViewModel = mMap.get(key);
+        if (oldViewModel != null) {
+            oldViewModel.onCleared();
+        }
+        mMap.put(key, viewModel);
+    }
+
+    final ViewModel get(String key) {
+        return mMap.get(key);
+    }
+
+    /**
+     *  Clears internal storage and notifies ViewModels that they are no longer used.
+     */
+    public final void clear() {
+        for (ViewModel vm : mMap.values()) {
+            vm.onCleared();
+        }
+        mMap.clear();
+    }
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStoreOwner.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStoreOwner.java
new file mode 100644
index 0000000..5058305
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStoreOwner.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * A scope that owns {@link ViewModelStore}.
+ * <p>
+ * A responsibility of an implementation of this interface is to retain owned ViewModelStore
+ * during the configuration changes and call {@link ViewModelStore#clear()}, when this scope is
+ * going to be destroyed.
+ */
+@SuppressWarnings("WeakerAccess")
+public interface ViewModelStoreOwner {
+    /**
+     * Returns owned {@link ViewModelStore}
+     *
+     * @return a {@code ViewModelStore}
+     */
+    ViewModelStore getViewModelStore();
+}
diff --git a/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStores.java b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStores.java
new file mode 100644
index 0000000..8c17dd9
--- /dev/null
+++ b/lifecycle/extensions/src/main/java/android/arch/lifecycle/ViewModelStores.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.HolderFragment.holderFragmentFor;
+
+import android.support.annotation.MainThread;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentActivity;
+
+/**
+ * Factory methods for {@link ViewModelStore} class.
+ */
+@SuppressWarnings("WeakerAccess")
+public class ViewModelStores {
+
+    private ViewModelStores() {
+    }
+
+    /**
+     * Returns the {@link ViewModelStore} of the given activity.
+     *
+     * @param activity an activity whose {@code ViewModelStore} is requested
+     * @return a {@code ViewModelStore}
+     */
+    @MainThread
+    public static ViewModelStore of(FragmentActivity activity) {
+        return holderFragmentFor(activity).getViewModelStore();
+    }
+
+    /**
+     * Returns the {@link ViewModelStore} of the given fragment.
+     *
+     * @param fragment a fragment whose {@code ViewModelStore} is requested
+     * @return a {@code ViewModelStore}
+     */
+    @MainThread
+    public static ViewModelStore of(Fragment fragment) {
+        return holderFragmentFor(fragment).getViewModelStore();
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/ComputableLiveDataTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ComputableLiveDataTest.java
new file mode 100644
index 0000000..0a3fbed
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ComputableLiveDataTest.java
@@ -0,0 +1,215 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.TaskExecutor;
+import android.arch.core.executor.TaskExecutorWithFakeMainThread;
+import android.arch.lifecycle.util.InstantTaskExecutor;
+import android.support.annotation.Nullable;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Collections;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@RunWith(JUnit4.class)
+public class ComputableLiveDataTest {
+    private TaskExecutor mTaskExecutor;
+    private TestLifecycleOwner mLifecycleOwner;
+
+    @Before
+    public void setup() {
+        mLifecycleOwner = new TestLifecycleOwner();
+    }
+
+    @Before
+    public void swapExecutorDelegate() {
+        mTaskExecutor = spy(new InstantTaskExecutor());
+        AppToolkitTaskExecutor.getInstance().setDelegate(mTaskExecutor);
+    }
+
+    @After
+    public void removeExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    @Test
+    public void noComputeWithoutObservers() {
+        final TestComputable computable = new TestComputable();
+        verify(mTaskExecutor, never()).executeOnDiskIO(computable.mRefreshRunnable);
+        verify(mTaskExecutor, never()).executeOnDiskIO(computable.mInvalidationRunnable);
+    }
+
+    @Test
+    public void noConcurrentCompute() throws InterruptedException {
+        TaskExecutorWithFakeMainThread executor = new TaskExecutorWithFakeMainThread(2);
+        AppToolkitTaskExecutor.getInstance().setDelegate(executor);
+        try {
+            // # of compute calls
+            final Semaphore computeCounter = new Semaphore(0);
+            // available permits for computation
+            final Semaphore computeLock = new Semaphore(0);
+            final TestComputable computable = new TestComputable(1, 2) {
+                @Override
+                protected Integer compute() {
+                    try {
+                        computeCounter.release(1);
+                        computeLock.tryAcquire(1, 20, TimeUnit.SECONDS);
+                    } catch (InterruptedException e) {
+                        throw new AssertionError(e);
+                    }
+                    return super.compute();
+                }
+            };
+            final ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
+            //noinspection unchecked
+            Observer<Integer> observer = mock(Observer.class);
+            computable.getLiveData().observeForever(observer);
+            verify(observer, never()).onChanged(anyInt());
+            // wait for first compute call
+            assertThat(computeCounter.tryAcquire(1, 2, TimeUnit.SECONDS), is(true));
+            // re-invalidate while in compute
+            computable.invalidate();
+            computable.invalidate();
+            computable.invalidate();
+            computable.invalidate();
+            // ensure another compute call does not arrive
+            assertThat(computeCounter.tryAcquire(1, 2, TimeUnit.SECONDS), is(false));
+            // allow computation to finish
+            computeLock.release(2);
+            // wait for the second result, first will be skipped due to invalidation during compute
+            verify(observer, timeout(2000)).onChanged(captor.capture());
+            assertThat(captor.getAllValues(), is(Collections.singletonList(2)));
+            reset(observer);
+            // allow all computations to run, there should not be any.
+            computeLock.release(100);
+            // unfortunately, Mockito.after is not available in 1.9.5
+            executor.drainTasks(2);
+            // assert no other results arrive
+            verify(observer, never()).onChanged(anyInt());
+        } finally {
+            AppToolkitTaskExecutor.getInstance().setDelegate(null);
+        }
+    }
+
+    @Test
+    public void addingObserverShouldTriggerAComputation() {
+        TestComputable computable = new TestComputable(1);
+        mLifecycleOwner.handleEvent(Lifecycle.Event.ON_CREATE);
+        final AtomicInteger mValue = new AtomicInteger(-1);
+        computable.getLiveData().observe(mLifecycleOwner, new Observer<Integer>() {
+            @Override
+            public void onChanged(@Nullable Integer integer) {
+                //noinspection ConstantConditions
+                mValue.set(integer);
+            }
+        });
+        verify(mTaskExecutor, never()).executeOnDiskIO(any(Runnable.class));
+        assertThat(mValue.get(), is(-1));
+        mLifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        verify(mTaskExecutor).executeOnDiskIO(computable.mRefreshRunnable);
+        assertThat(mValue.get(), is(1));
+    }
+
+    @Test
+    public void invalidationShouldNotReTriggerComputationIfObserverIsInActive() {
+        TestComputable computable = new TestComputable(1, 2);
+        mLifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        final AtomicInteger mValue = new AtomicInteger(-1);
+        computable.getLiveData().observe(mLifecycleOwner, new Observer<Integer>() {
+            @Override
+            public void onChanged(@Nullable Integer integer) {
+                //noinspection ConstantConditions
+                mValue.set(integer);
+            }
+        });
+        assertThat(mValue.get(), is(1));
+        mLifecycleOwner.handleEvent(Lifecycle.Event.ON_STOP);
+        computable.invalidate();
+        reset(mTaskExecutor);
+        verify(mTaskExecutor, never()).executeOnDiskIO(computable.mRefreshRunnable);
+        assertThat(mValue.get(), is(1));
+    }
+
+    @Test
+    public void invalidationShouldReTriggerQueryIfObserverIsActive() {
+        TestComputable computable = new TestComputable(1, 2);
+        mLifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        final AtomicInteger mValue = new AtomicInteger(-1);
+        computable.getLiveData().observe(mLifecycleOwner, new Observer<Integer>() {
+            @Override
+            public void onChanged(@Nullable Integer integer) {
+                //noinspection ConstantConditions
+                mValue.set(integer);
+            }
+        });
+        assertThat(mValue.get(), is(1));
+        computable.invalidate();
+        assertThat(mValue.get(), is(2));
+    }
+
+    static class TestComputable extends ComputableLiveData<Integer> {
+        final int[] mValues;
+        AtomicInteger mValueCounter;
+
+        TestComputable(int... values) {
+            mValueCounter = new AtomicInteger();
+            mValues = values;
+        }
+
+        @Override
+        protected Integer compute() {
+            return mValues[mValueCounter.getAndIncrement()];
+        }
+    }
+
+    static class TestLifecycleOwner implements LifecycleOwner {
+        private LifecycleRegistry mLifecycle;
+
+        TestLifecycleOwner() {
+            mLifecycle = new LifecycleRegistry(this);
+        }
+
+        @Override
+        public Lifecycle getLifecycle() {
+            return mLifecycle;
+        }
+
+        void handleEvent(Lifecycle.Event event) {
+            mLifecycle.handleLifecycleEvent(event);
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/DispatcherActivityCallbackTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/DispatcherActivityCallbackTest.java
new file mode 100644
index 0000000..1431089
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/DispatcherActivityCallbackTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.FragmentTransaction;
+import android.os.Bundle;
+import android.support.test.filters.SmallTest;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+@SmallTest
+public class DispatcherActivityCallbackTest {
+    @Test
+    public void onCreateFrameworkActivity() {
+        LifecycleDispatcher.DispatcherActivityCallback callback =
+                new LifecycleDispatcher.DispatcherActivityCallback();
+        Activity activity = mock(Activity.class);
+        checkReportFragment(callback, activity);
+    }
+
+    @Test
+    public void onCreateFragmentActivity() {
+        LifecycleDispatcher.DispatcherActivityCallback callback =
+                new LifecycleDispatcher.DispatcherActivityCallback();
+        FragmentActivity activity = mock(FragmentActivity.class);
+        FragmentManager fragmentManager = mock(FragmentManager.class);
+        when(activity.getSupportFragmentManager()).thenReturn(fragmentManager);
+
+        checkReportFragment(callback, activity);
+
+        verify(activity).getSupportFragmentManager();
+        verify(fragmentManager).registerFragmentLifecycleCallbacks(
+                any(FragmentManager.FragmentLifecycleCallbacks.class), eq(true));
+    }
+
+    @SuppressLint("CommitTransaction")
+    private void checkReportFragment(LifecycleDispatcher.DispatcherActivityCallback callback,
+            Activity activity) {
+        android.app.FragmentManager fm = mock(android.app.FragmentManager.class);
+        FragmentTransaction transaction = mock(FragmentTransaction.class);
+        when(activity.getFragmentManager()).thenReturn(fm);
+        when(fm.beginTransaction()).thenReturn(transaction);
+        when(transaction.add(any(Fragment.class), anyString())).thenReturn(transaction);
+        callback.onActivityCreated(activity, mock(Bundle.class));
+        verify(activity).getFragmentManager();
+        verify(fm).beginTransaction();
+        verify(transaction).add(any(ReportFragment.class), anyString());
+        verify(transaction).commit();
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/LiveDataTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/LiveDataTest.java
new file mode 100644
index 0000000..f401e1c
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/LiveDataTest.java
@@ -0,0 +1,437 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.util.InstantTaskExecutor;
+import android.support.annotation.Nullable;
+import android.support.test.filters.SmallTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+@SuppressWarnings({"unchecked"})
+@SmallTest
+public class LiveDataTest {
+    private PublicLiveData<String> mLiveData;
+    private LifecycleOwner mOwner;
+    private LifecycleRegistry mRegistry;
+    private MethodExec mActiveObserversChanged;
+    private boolean mInObserver;
+
+    @Before
+    public void init() {
+        mLiveData = new PublicLiveData<>();
+        mOwner = mock(LifecycleOwner.class);
+        mRegistry = new LifecycleRegistry(mOwner);
+        when(mOwner.getLifecycle()).thenReturn(mRegistry);
+        mActiveObserversChanged = mock(MethodExec.class);
+        mLiveData.activeObserversChanged = mActiveObserversChanged;
+        mInObserver = false;
+    }
+
+    @Before
+    public void swapExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(new InstantTaskExecutor());
+    }
+
+    @After
+    public void removeExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    @Test
+    public void testObserverToggle() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, observer);
+
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+
+        mLiveData.removeObserver(observer);
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+        assertThat(mLiveData.hasObservers(), is(false));
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+    }
+
+    @Test
+    public void testActiveObserverToggle() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, observer);
+
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(mActiveObserversChanged).onCall(true);
+        assertThat(mLiveData.hasActiveObservers(), is(true));
+        reset(mActiveObserversChanged);
+
+        mRegistry.handleLifecycleEvent(ON_STOP);
+        verify(mActiveObserversChanged).onCall(false);
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+        assertThat(mLiveData.hasObservers(), is(true));
+
+        reset(mActiveObserversChanged);
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(mActiveObserversChanged).onCall(true);
+        assertThat(mLiveData.hasActiveObservers(), is(true));
+        assertThat(mLiveData.hasObservers(), is(true));
+
+        reset(mActiveObserversChanged);
+        mLiveData.removeObserver(observer);
+        verify(mActiveObserversChanged).onCall(false);
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+        assertThat(mLiveData.hasObservers(), is(false));
+
+        verifyNoMoreInteractions(mActiveObserversChanged);
+    }
+
+    @Test
+    public void testReAddSameObserverTuple() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, observer);
+        mLiveData.observe(mOwner, observer);
+        assertThat(mLiveData.hasObservers(), is(true));
+    }
+
+    @Test
+    public void testAdd2ObserversWithSameOwnerAndRemove() {
+        Observer<String> o1 = (Observer<String>) mock(Observer.class);
+        Observer<String> o2 = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, o1);
+        mLiveData.observe(mOwner, o2);
+        assertThat(mLiveData.hasObservers(), is(true));
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(mActiveObserversChanged).onCall(true);
+        mLiveData.setValue("a");
+        verify(o1).onChanged("a");
+        verify(o2).onChanged("a");
+
+        mLiveData.removeObservers(mOwner);
+
+        assertThat(mLiveData.hasObservers(), is(false));
+        assertThat(mRegistry.getObserverCount(), is(0));
+    }
+
+    @Test
+    public void testAddSameObserverIn2LifecycleOwners() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        LifecycleOwner owner2 = mock(LifecycleOwner.class);
+        LifecycleRegistry registry2 = new LifecycleRegistry(owner2);
+        when(owner2.getLifecycle()).thenReturn(registry2);
+
+        mLiveData.observe(mOwner, observer);
+        Throwable throwable = null;
+        try {
+            mLiveData.observe(owner2, observer);
+        } catch (Throwable t) {
+            throwable = t;
+        }
+        assertThat(throwable, instanceOf(IllegalArgumentException.class));
+        //noinspection ConstantConditions
+        assertThat(throwable.getMessage(),
+                is("Cannot add the same observer with different lifecycles"));
+    }
+
+    @Test
+    public void testRemoveDestroyedObserver() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, observer);
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(mActiveObserversChanged).onCall(true);
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(true));
+
+        reset(mActiveObserversChanged);
+
+        mRegistry.handleLifecycleEvent(ON_DESTROY);
+        assertThat(mLiveData.hasObservers(), is(false));
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+        verify(mActiveObserversChanged).onCall(false);
+    }
+
+    @Test
+    public void testInactiveRegistry() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mRegistry.handleLifecycleEvent(ON_DESTROY);
+        mLiveData.observe(mOwner, observer);
+        assertThat(mLiveData.hasObservers(), is(false));
+    }
+
+    @Test
+    public void testNotifyActiveInactive() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mRegistry.handleLifecycleEvent(ON_CREATE);
+        mLiveData.observe(mOwner, observer);
+        mLiveData.setValue("a");
+        verify(observer, never()).onChanged(anyString());
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(observer).onChanged("a");
+
+        mLiveData.setValue("b");
+        verify(observer).onChanged("b");
+
+        mRegistry.handleLifecycleEvent(ON_STOP);
+        mLiveData.setValue("c");
+        verify(observer, never()).onChanged("c");
+
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(observer).onChanged("c");
+
+        reset(observer);
+        mRegistry.handleLifecycleEvent(ON_STOP);
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(observer, never()).onChanged(anyString());
+    }
+
+    @Test
+    public void testStopObservingOwner_onDestroy() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mRegistry.handleLifecycleEvent(ON_CREATE);
+        mLiveData.observe(mOwner, observer);
+        assertThat(mRegistry.getObserverCount(), is(1));
+        mRegistry.handleLifecycleEvent(ON_DESTROY);
+        assertThat(mRegistry.getObserverCount(), is(0));
+    }
+
+    @Test
+    public void testStopObservingOwner_onStopObserving() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mRegistry.handleLifecycleEvent(ON_CREATE);
+        mLiveData.observe(mOwner, observer);
+        assertThat(mRegistry.getObserverCount(), is(1));
+
+        mLiveData.removeObserver(observer);
+        assertThat(mRegistry.getObserverCount(), is(0));
+    }
+
+    @Test
+    public void testActiveChangeInCallback() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        Observer<String> observer1 = spy(new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                mRegistry.handleLifecycleEvent(ON_STOP);
+                assertThat(mLiveData.hasObservers(), is(true));
+                assertThat(mLiveData.hasActiveObservers(), is(false));
+            }
+        });
+        final Observer observer2 = mock(Observer.class);
+        mLiveData.observe(mOwner, observer1);
+        mLiveData.observe(mOwner, observer2);
+        mLiveData.setValue("bla");
+        verify(observer1).onChanged(anyString());
+        verify(observer2, Mockito.never()).onChanged(anyString());
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(false));
+    }
+
+    @Test
+    public void testActiveChangeInCallback2() {
+        Observer<String> observer1 = spy(new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                assertThat(mInObserver, is(false));
+                mInObserver = true;
+                mRegistry.handleLifecycleEvent(ON_START);
+                assertThat(mLiveData.hasActiveObservers(), is(true));
+                mInObserver = false;
+            }
+        });
+        final Observer observer2 = spy(new FailReentranceObserver());
+        mLiveData.observeForever(observer1);
+        mLiveData.observe(mOwner, observer2);
+        mLiveData.setValue("bla");
+        verify(observer1).onChanged(anyString());
+        verify(observer2).onChanged(anyString());
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(true));
+    }
+
+    @Test
+    public void testObserverRemovalInCallback() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        Observer<String> observer = spy(new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                assertThat(mLiveData.hasObservers(), is(true));
+                mLiveData.removeObserver(this);
+                assertThat(mLiveData.hasObservers(), is(false));
+            }
+        });
+        mLiveData.observe(mOwner, observer);
+        mLiveData.setValue("bla");
+        verify(observer).onChanged(anyString());
+        assertThat(mLiveData.hasObservers(), is(false));
+    }
+
+    @Test
+    public void testObserverAdditionInCallback() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        final Observer observer2 = spy(new FailReentranceObserver());
+        Observer<String> observer1 = spy(new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                assertThat(mInObserver, is(false));
+                mInObserver = true;
+                mLiveData.observe(mOwner, observer2);
+                assertThat(mLiveData.hasObservers(), is(true));
+                assertThat(mLiveData.hasActiveObservers(), is(true));
+                mInObserver = false;
+            }
+        });
+        mLiveData.observe(mOwner, observer1);
+        mLiveData.setValue("bla");
+        verify(observer1).onChanged(anyString());
+        verify(observer2).onChanged(anyString());
+        assertThat(mLiveData.hasObservers(), is(true));
+        assertThat(mLiveData.hasActiveObservers(), is(true));
+    }
+
+    @Test
+    public void testObserverWithoutLifecycleOwner() {
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.setValue("boring");
+        mLiveData.observeForever(observer);
+        verify(mActiveObserversChanged).onCall(true);
+        verify(observer).onChanged("boring");
+        mLiveData.setValue("tihs");
+        verify(observer).onChanged("tihs");
+        mLiveData.removeObserver(observer);
+        verify(mActiveObserversChanged).onCall(false);
+        mLiveData.setValue("boring");
+        reset(observer);
+        verify(observer, never()).onChanged(anyString());
+    }
+
+    @Test
+    public void testSetValueDuringSetValue() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        final Observer observer1 = spy(new Observer<String>() {
+            @Override
+            public void onChanged(String o) {
+                assertThat(mInObserver, is(false));
+                mInObserver = true;
+                if (o.equals(("bla"))) {
+                    mLiveData.setValue("gt");
+                }
+                mInObserver = false;
+            }
+        });
+        final Observer observer2 = spy(new FailReentranceObserver());
+        mLiveData.observe(mOwner, observer1);
+        mLiveData.observe(mOwner, observer2);
+        mLiveData.setValue("bla");
+        verify(observer1, Mockito.atMost(2)).onChanged("gt");
+        verify(observer2, Mockito.atMost(2)).onChanged("gt");
+    }
+
+    @Test
+    public void testDataChangeDuringStateChange() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        mRegistry.addObserver(new LifecycleObserver() {
+            @OnLifecycleEvent(ON_STOP)
+            public void onStop() {
+                // change data in onStop, observer should not be called!
+                mLiveData.setValue("b");
+            }
+        });
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        mLiveData.setValue("a");
+        mLiveData.observe(mOwner, observer);
+        verify(observer).onChanged("a");
+        mRegistry.handleLifecycleEvent(ON_PAUSE);
+        mRegistry.handleLifecycleEvent(ON_STOP);
+        verify(observer, never()).onChanged("b");
+
+        mRegistry.handleLifecycleEvent(ON_RESUME);
+        verify(observer).onChanged("b");
+    }
+
+    @Test
+    public void testNotCallInactiveWithObserveForever() {
+        mRegistry.handleLifecycleEvent(ON_START);
+        Observer<String> observer = (Observer<String>) mock(Observer.class);
+        Observer<String> observer2 = (Observer<String>) mock(Observer.class);
+        mLiveData.observe(mOwner, observer);
+        mLiveData.observeForever(observer2);
+        verify(mActiveObserversChanged).onCall(true);
+        reset(mActiveObserversChanged);
+        mRegistry.handleLifecycleEvent(ON_STOP);
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+        mRegistry.handleLifecycleEvent(ON_START);
+        verify(mActiveObserversChanged, never()).onCall(anyBoolean());
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    static class PublicLiveData<T> extends LiveData<T> {
+        // cannot spy due to internal calls
+        public MethodExec activeObserversChanged;
+
+        @Override
+        protected void onActive() {
+            if (activeObserversChanged != null) {
+                activeObserversChanged.onCall(true);
+            }
+        }
+
+        @Override
+        protected void onInactive() {
+            if (activeObserversChanged != null) {
+                activeObserversChanged.onCall(false);
+            }
+        }
+    }
+
+    private class FailReentranceObserver<T> implements Observer<T> {
+        @Override
+        public void onChanged(@Nullable T t) {
+            assertThat(mInObserver, is(false));
+        }
+    }
+
+    interface MethodExec {
+        void onCall(boolean value);
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/MediatorLiveDataTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/MediatorLiveDataTest.java
new file mode 100644
index 0000000..f522230
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/MediatorLiveDataTest.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.util.InstantTaskExecutor;
+import android.support.annotation.Nullable;
+import android.support.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@SuppressWarnings("unchecked")
+@SmallTest
+@RunWith(JUnit4.class)
+public class MediatorLiveDataTest {
+
+    private LifecycleOwner mOwner;
+    private LifecycleRegistry mRegistry;
+    private MediatorLiveData<String> mMediator;
+    private LiveData<String> mSource;
+    private boolean mSourceActive;
+
+    @Before
+    public void setup() {
+        mOwner = mock(LifecycleOwner.class);
+        mRegistry = new LifecycleRegistry(mOwner);
+        when(mOwner.getLifecycle()).thenReturn(mRegistry);
+        mMediator = new MediatorLiveData<>();
+        mSource = new LiveData<String>() {
+            @Override
+            protected void onActive() {
+                mSourceActive = true;
+            }
+
+            @Override
+            protected void onInactive() {
+                mSourceActive = false;
+            }
+        };
+        mSourceActive = false;
+        mMediator.observe(mOwner, mock(Observer.class));
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+    }
+
+    @Before
+    public void swapExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(new InstantTaskExecutor());
+    }
+
+    @Test
+    public void testSingleDelivery() {
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        mSource.setValue("flatfoot");
+        verify(observer).onChanged("flatfoot");
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        reset(observer);
+        verify(observer, never()).onChanged(any());
+    }
+
+    @Test
+    public void testChangeWhileInactive() {
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        mMediator.observe(mOwner, mock(Observer.class));
+        mSource.setValue("one");
+        verify(observer).onChanged("one");
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        reset(observer);
+        mSource.setValue("flatfoot");
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+        verify(observer).onChanged("flatfoot");
+    }
+
+
+    @Test
+    public void testAddSourceToActive() {
+        mSource.setValue("flatfoot");
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        verify(observer).onChanged("flatfoot");
+    }
+
+    @Test
+    public void testAddSourceToInActive() {
+        mSource.setValue("flatfoot");
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        verify(observer, never()).onChanged(any());
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+        verify(observer).onChanged("flatfoot");
+    }
+
+    @Test
+    public void testRemoveSource() {
+        mSource.setValue("flatfoot");
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        verify(observer).onChanged("flatfoot");
+        mMediator.removeSource(mSource);
+        reset(observer);
+        mSource.setValue("failure");
+        verify(observer, never()).onChanged(any());
+    }
+
+    @Test
+    public void testSourceInactive() {
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        assertThat(mSourceActive, is(true));
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        assertThat(mSourceActive, is(false));
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+        assertThat(mSourceActive, is(true));
+    }
+
+    @Test
+    public void testNoLeakObserver() {
+        // Imitates a destruction of a ViewModel: a listener of LiveData is destroyed,
+        // a reference to MediatorLiveData is cleaned up. In this case we shouldn't leak
+        // MediatorLiveData as an observer of mSource.
+        assertThat(mSource.hasObservers(), is(false));
+        Observer observer = mock(Observer.class);
+        mMediator.addSource(mSource, observer);
+        assertThat(mSource.hasObservers(), is(true));
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
+        mMediator = null;
+        assertThat(mSource.hasObservers(), is(false));
+    }
+
+    @Test
+    public void testMultipleSources() {
+        Observer observer1 = mock(Observer.class);
+        mMediator.addSource(mSource, observer1);
+        MutableLiveData<Integer> source2 = new MutableLiveData<>();
+        Observer observer2 = mock(Observer.class);
+        mMediator.addSource(source2, observer2);
+        mSource.setValue("flatfoot");
+        verify(observer1).onChanged("flatfoot");
+        verify(observer2, never()).onChanged(any());
+        reset(observer1, observer2);
+        source2.setValue(1703);
+        verify(observer1, never()).onChanged(any());
+        verify(observer2).onChanged(1703);
+        reset(observer1, observer2);
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        mSource.setValue("failure");
+        source2.setValue(0);
+        verify(observer1, never()).onChanged(any());
+        verify(observer2, never()).onChanged(any());
+    }
+
+    @Test
+    public void removeSourceDuringOnActive() {
+        // to trigger ConcurrentModificationException,
+        // we have to call remove from a collection during "for" loop.
+        // ConcurrentModificationException is thrown from next() method of an iterator
+        // so this modification shouldn't be at the last iteration,
+        // because if it is a last iteration, then next() wouldn't be called.
+        // And the last: an order of an iteration over sources is not defined,
+        // so I have to call it remove operation  from all observers.
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        Observer<String> removingObserver = new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                mMediator.removeSource(mSource);
+            }
+        };
+        mMediator.addSource(mSource, removingObserver);
+        MutableLiveData<String> source2 = new MutableLiveData<>();
+        source2.setValue("nana");
+        mMediator.addSource(source2, removingObserver);
+        mSource.setValue("petjack");
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void reAddSameSourceWithDifferentObserver() {
+        mMediator.addSource(mSource, mock(Observer.class));
+        mMediator.addSource(mSource, mock(Observer.class));
+    }
+
+    @Test
+    public void addSourceDuringOnActive() {
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
+        mSource.setValue("a");
+        mMediator.addSource(mSource, new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                MutableLiveData<String> source = new MutableLiveData<>();
+                source.setValue("b");
+                mMediator.addSource(source, new Observer<String>() {
+                    @Override
+                    public void onChanged(@Nullable String s) {
+                        mMediator.setValue("c");
+                    }
+                });
+            }
+        });
+        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+        assertThat(mMediator.getValue(), is("c"));
+    }
+
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/ThreadedLiveDataTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ThreadedLiveDataTest.java
new file mode 100644
index 0000000..e578546
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ThreadedLiveDataTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.JunitTaskExecutorRule;
+import android.arch.core.executor.TaskExecutor;
+import android.support.annotation.Nullable;
+import android.support.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@SmallTest
+public class ThreadedLiveDataTest {
+
+    private static final int TIMEOUT_SECS = 3;
+
+    @Rule
+    public JunitTaskExecutorRule mTaskExecutorRule = new JunitTaskExecutorRule(1, false);
+
+    private LiveData<String> mLiveData;
+    private LifecycleOwner mLifecycleOwner;
+    private LifecycleRegistry mRegistry;
+
+    @Before
+    public void init() {
+        mLiveData = new MutableLiveData<>();
+        mLifecycleOwner = mock(LifecycleOwner.class);
+        mRegistry = new LifecycleRegistry(mLifecycleOwner);
+        when(mLifecycleOwner.getLifecycle()).thenReturn(mRegistry);
+    }
+
+    @Test
+    public void testPostValue() throws InterruptedException {
+        final TaskExecutor taskExecutor = mTaskExecutorRule.getTaskExecutor();
+        final CountDownLatch finishTestLatch = new CountDownLatch(1);
+        final Observer<String> observer = new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String newValue) {
+                try {
+                    assertThat(taskExecutor.isMainThread(), is(true));
+                    assertThat(newValue, is("success"));
+                } finally {
+                    finishTestLatch.countDown();
+                }
+            }
+        };
+        taskExecutor.executeOnMainThread(new Runnable() {
+            @Override
+            public void run() {
+                mRegistry.handleLifecycleEvent(ON_START);
+                mLiveData.observe(mLifecycleOwner, observer);
+                final CountDownLatch latch = new CountDownLatch(1);
+                taskExecutor.executeOnDiskIO(new Runnable() {
+                    @Override
+                    public void run() {
+                        mLiveData.postValue("fail");
+                        mLiveData.postValue("success");
+                        latch.countDown();
+                    }
+                });
+                try {
+                    assertThat(latch.await(TIMEOUT_SECS, TimeUnit.SECONDS), is(true));
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        });
+        assertThat(finishTestLatch.await(TIMEOUT_SECS, TimeUnit.SECONDS), is(true));
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/TransformationsTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/TransformationsTest.java
new file mode 100644
index 0000000..8c808ed
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/TransformationsTest.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.util.Function;
+import android.arch.lifecycle.util.InstantTaskExecutor;
+import android.support.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@SuppressWarnings("unchecked")
+@SmallTest
+@RunWith(JUnit4.class)
+public class TransformationsTest {
+
+    private LifecycleOwner mOwner;
+
+    @Before
+    public void swapExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(new InstantTaskExecutor());
+    }
+
+    @Before
+    public void setup() {
+        mOwner = mock(LifecycleOwner.class);
+        LifecycleRegistry registry = new LifecycleRegistry(mOwner);
+        when(mOwner.getLifecycle()).thenReturn(registry);
+        registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
+        registry.handleLifecycleEvent(Lifecycle.Event.ON_START);
+    }
+
+    @Test
+    public void testMap() {
+        LiveData<String> source = new MutableLiveData<>();
+        LiveData<Integer> mapped = Transformations.map(source, new Function<String, Integer>() {
+            @Override
+            public Integer apply(String input) {
+                return input.length();
+            }
+        });
+        Observer<Integer> observer = mock(Observer.class);
+        mapped.observe(mOwner, observer);
+        source.setValue("four");
+        verify(observer).onChanged(4);
+    }
+
+    @Test
+    public void testSwitchMap() {
+        LiveData<Integer> trigger = new MutableLiveData<>();
+        final LiveData<String> first = new MutableLiveData<>();
+        final LiveData<String> second = new MutableLiveData<>();
+        LiveData<String> result = Transformations.switchMap(trigger,
+                new Function<Integer, LiveData<String>>() {
+                    @Override
+                    public LiveData<String> apply(Integer input) {
+                        if (input == 1) {
+                            return first;
+                        } else {
+                            return second;
+                        }
+                    }
+                });
+
+        Observer<String> observer = mock(Observer.class);
+        result.observe(mOwner, observer);
+        verify(observer, never()).onChanged(anyString());
+        first.setValue("first");
+        trigger.setValue(1);
+        verify(observer).onChanged("first");
+        second.setValue("second");
+        reset(observer);
+        verify(observer, never()).onChanged(anyString());
+        trigger.setValue(2);
+        verify(observer).onChanged("second");
+        reset(observer);
+        first.setValue("failure");
+        verify(observer, never()).onChanged(anyString());
+    }
+
+    @Test
+    public void testSwitchMap2() {
+        LiveData<Integer> trigger = new MutableLiveData<>();
+        final LiveData<String> first = new MutableLiveData<>();
+        final LiveData<String> second = new MutableLiveData<>();
+        LiveData<String> result = Transformations.switchMap(trigger,
+                new Function<Integer, LiveData<String>>() {
+                    @Override
+                    public LiveData<String> apply(Integer input) {
+                        if (input == 1) {
+                            return first;
+                        } else {
+                            return second;
+                        }
+                    }
+                });
+
+        Observer<String> observer = mock(Observer.class);
+        result.observe(mOwner, observer);
+
+        verify(observer, never()).onChanged(anyString());
+        trigger.setValue(1);
+        verify(observer, never()).onChanged(anyString());
+        first.setValue("fi");
+        verify(observer).onChanged("fi");
+        first.setValue("rst");
+        verify(observer).onChanged("rst");
+
+        second.setValue("second");
+        reset(observer);
+        verify(observer, never()).onChanged(anyString());
+        trigger.setValue(2);
+        verify(observer).onChanged("second");
+        reset(observer);
+        first.setValue("failure");
+        verify(observer, never()).onChanged(anyString());
+    }
+
+    @Test
+    public void testNoRedispatchSwitchMap() {
+        LiveData<Integer> trigger = new MutableLiveData<>();
+        final LiveData<String> first = new MutableLiveData<>();
+        LiveData<String> result = Transformations.switchMap(trigger,
+                new Function<Integer, LiveData<String>>() {
+                    @Override
+                    public LiveData<String> apply(Integer input) {
+                        return first;
+                    }
+                });
+
+        Observer<String> observer = mock(Observer.class);
+        result.observe(mOwner, observer);
+        verify(observer, never()).onChanged(anyString());
+        first.setValue("first");
+        trigger.setValue(1);
+        verify(observer).onChanged("first");
+        reset(observer);
+        trigger.setValue(2);
+        verify(observer, never()).onChanged(anyString());
+    }
+
+    @Test
+    public void testSwitchMapToNull() {
+        LiveData<Integer> trigger = new MutableLiveData<>();
+        final LiveData<String> first = new MutableLiveData<>();
+        LiveData<String> result = Transformations.switchMap(trigger,
+                new Function<Integer, LiveData<String>>() {
+                    @Override
+                    public LiveData<String> apply(Integer input) {
+                        if (input == 1) {
+                            return first;
+                        } else {
+                            return null;
+                        }
+                    }
+                });
+
+        Observer<String> observer = mock(Observer.class);
+        result.observe(mOwner, observer);
+        verify(observer, never()).onChanged(anyString());
+        first.setValue("first");
+        trigger.setValue(1);
+        verify(observer).onChanged("first");
+        reset(observer);
+
+        trigger.setValue(2);
+        verify(observer, never()).onChanged(anyString());
+        assertThat(first.hasObservers(), is(false));
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelProviderTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelProviderTest.java
new file mode 100644
index 0000000..61760fc
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelProviderTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.lifecycle.ViewModelProvider.NewInstanceFactory;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ViewModelProviderTest {
+
+    private ViewModelProvider mViewModelProvider;
+
+    @Before
+    public void setup() {
+        mViewModelProvider = new ViewModelProvider(new ViewModelStore(), new NewInstanceFactory());
+    }
+
+    @Test
+    public void twoViewModelsWithSameKey() throws Throwable {
+        String key = "the_key";
+        ViewModel1 vm1 = mViewModelProvider.get(key, ViewModel1.class);
+        assertThat(vm1.mCleared, is(false));
+        ViewModel2 vw2 = mViewModelProvider.get(key, ViewModel2.class);
+        assertThat(vw2, notNullValue());
+        assertThat(vm1.mCleared, is(true));
+    }
+
+
+    @Test
+    public void localViewModel() throws Throwable {
+        class VM extends ViewModel1 {
+        }
+        try {
+            mViewModelProvider.get(VM.class);
+            Assert.fail();
+        } catch (IllegalArgumentException ignored) {
+        }
+    }
+
+    @Test
+    public void twoViewModels() {
+        ViewModel1 model1 = mViewModelProvider.get(ViewModel1.class);
+        ViewModel2 model2 = mViewModelProvider.get(ViewModel2.class);
+        assertThat(mViewModelProvider.get(ViewModel1.class), is(model1));
+        assertThat(mViewModelProvider.get(ViewModel2.class), is(model2));
+    }
+
+    @Test
+    public void testOwnedBy() {
+        final ViewModelStore store = new ViewModelStore();
+        ViewModelStoreOwner owner = new ViewModelStoreOwner() {
+            @Override
+            public ViewModelStore getViewModelStore() {
+                return store;
+            }
+        };
+        ViewModelProvider provider = new ViewModelProvider(owner, new NewInstanceFactory());
+        ViewModel1 viewModel = provider.get(ViewModel1.class);
+        assertThat(viewModel, is(provider.get(ViewModel1.class)));
+    }
+
+    public static class ViewModel1 extends ViewModel {
+        boolean mCleared;
+
+        @Override
+        protected void onCleared() {
+            mCleared = true;
+        }
+    }
+
+    public static class ViewModel2 extends ViewModel {
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelStoreTest.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelStoreTest.java
new file mode 100644
index 0000000..cfeefb7
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/ViewModelStoreTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ViewModelStoreTest {
+
+    @Test
+    public void testClear() {
+        ViewModelStore store = new ViewModelStore();
+        TestViewModel viewModel1 = new TestViewModel();
+        TestViewModel viewModel2 = new TestViewModel();
+        store.put("a", viewModel1);
+        store.put("b", viewModel2);
+        assertThat(viewModel1.mCleared, is(false));
+        assertThat(viewModel2.mCleared, is(false));
+        store.clear();
+        assertThat(viewModel1.mCleared, is(true));
+        assertThat(viewModel2.mCleared, is(true));
+        assertThat(store.get("a"), nullValue());
+        assertThat(store.get("b"), nullValue());
+    }
+
+    static class TestViewModel extends ViewModel {
+        boolean mCleared = false;
+
+        @Override
+        protected void onCleared() {
+            mCleared = true;
+        }
+    }
+}
diff --git a/lifecycle/extensions/src/test/java/android/arch/lifecycle/util/InstantTaskExecutor.java b/lifecycle/extensions/src/test/java/android/arch/lifecycle/util/InstantTaskExecutor.java
new file mode 100644
index 0000000..52318fd
--- /dev/null
+++ b/lifecycle/extensions/src/test/java/android/arch/lifecycle/util/InstantTaskExecutor.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.util;
+
+import android.arch.core.executor.TaskExecutor;
+
+public class InstantTaskExecutor extends TaskExecutor {
+    @Override
+    public void executeOnDiskIO(Runnable runnable) {
+        runnable.run();
+    }
+
+    @Override
+    public void postToMainThread(Runnable runnable) {
+        runnable.run();
+    }
+
+    @Override
+    public boolean isMainThread() {
+        return true;
+    }
+}
diff --git a/lifecycle/gradle.properties b/lifecycle/gradle.properties
new file mode 100644
index 0000000..88d2a75
--- /dev/null
+++ b/lifecycle/gradle.properties
@@ -0,0 +1,17 @@
+#
+# Copyright (C) 2016 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.
+#
+
+org.gradle.jvmargs=-Xmx3000M
\ No newline at end of file
diff --git a/lifecycle/gradle/wrapper/gradle-wrapper.jar b/lifecycle/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
--- /dev/null
+++ b/lifecycle/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/lifecycle/gradle/wrapper/gradle-wrapper.properties b/lifecycle/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..467c103
--- /dev/null
+++ b/lifecycle/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Dec 28 10:00:20 PST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-all.zip
diff --git a/lifecycle/gradlew b/lifecycle/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/lifecycle/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/lifecycle/gradlew.bat b/lifecycle/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/lifecycle/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/lifecycle/integration-tests/test-app/src/androidTest/java/com/android/support/lifecycle/LiveDataTransactionTest.java b/lifecycle/integration-tests/test-app/src/androidTest/java/com/android/support/lifecycle/LiveDataTransactionTest.java
new file mode 100644
index 0000000..443662a
--- /dev/null
+++ b/lifecycle/integration-tests/test-app/src/androidTest/java/com/android/support/lifecycle/LiveDataTransactionTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2017 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.android.support.lifecycle;
+
+import static android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks;
+
+import static com.android.support.lifecycle.testapp.LiveDataTestActivity.LIVE_DATA_VALUE;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+
+import android.os.Bundle;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentManager;
+
+import com.android.support.lifecycle.testapp.LiveDataTestActivity;
+
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+
+@SmallTest
+public class LiveDataTransactionTest {
+
+    @Rule
+    public ActivityTestRule<LiveDataTestActivity> mActivityTestRule =
+            new ActivityTestRule<>(LiveDataTestActivity.class);
+
+    private boolean mVisited;
+
+    @Test
+    public void transactionInOnStateChanged() throws Throwable {
+        LiveDataTestActivity activity = mActivityTestRule.getActivity();
+
+        activity.getSupportFragmentManager().registerFragmentLifecycleCallbacks(
+                new FragmentLifecycleCallbacks() {
+                    @Override
+                    public void onFragmentCreated(FragmentManager fm, Fragment f,
+                            Bundle savedInstanceState) {
+                    }
+                }, true);
+        mActivityTestRule.runOnUiThread(() -> {
+            assertThat(activity.fragmentsNumber,  /** 2^MAX_DEPTH - 1 */ is(31));
+            activity.viewModel.liveData.observe(activity,
+                    s -> Assert.fail("savedInstance state triggered an update"));
+        });
+        LiveDataTestActivity newActivity = TestUtils.recreateActivity(activity,
+                mActivityTestRule);
+        TestUtils.waitTillResumed(newActivity, mActivityTestRule);
+        mActivityTestRule.runOnUiThread(() -> {
+            newActivity.viewModel.liveData.observe(newActivity,
+                    s -> {
+                        assertThat(s, is(LIVE_DATA_VALUE));
+                        mVisited = true;
+                    });
+            assertThat(newActivity.fragmentsNumber, /** 2 * (2^MAX_DEPTH - 1) + 1 */is(63));
+            assertThat(mVisited, is(true));
+        });
+    }
+
+}
diff --git a/lifecycle/integration-tests/test-app/src/main/java/com/android/support/lifecycle/testapp/LiveDataTestActivity.java b/lifecycle/integration-tests/test-app/src/main/java/com/android/support/lifecycle/testapp/LiveDataTestActivity.java
new file mode 100644
index 0000000..5bbd368
--- /dev/null
+++ b/lifecycle/integration-tests/test-app/src/main/java/com/android/support/lifecycle/testapp/LiveDataTestActivity.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2017 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.android.support.lifecycle.testapp;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+
+import com.android.support.lifecycle.LifecycleActivity;
+import com.android.support.lifecycle.LifecycleFragment;
+import com.android.support.lifecycle.LifecycleProvider;
+import com.android.support.lifecycle.LiveData;
+import com.android.support.lifecycle.ViewModel;
+import com.android.support.lifecycle.ViewModelStore;
+
+/**
+ * activity for LiveDataTransactionTest
+ */
+public class LiveDataTestActivity extends LifecycleActivity {
+
+    public static final String LIVE_DATA_VALUE = "saveInstanceState";
+    private static final int MAX_DEPTH = 5;
+    private static final String VM_TAG = "test";
+
+    /** view model*/
+    public LiveDataViewModel viewModel;
+    /** counter of created  */
+    public int fragmentsNumber;
+
+    /** ViewModel class */
+    public static class LiveDataViewModel extends ViewModel {
+        public LiveData<String> liveData = new LiveData<>();
+    }
+
+    /** Counting Fragment */
+    public static class CountingFragment extends LifecycleFragment {
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ((LiveDataTestActivity) getActivity()).fragmentsNumber++;
+        }
+    }
+
+    /** a fragment which injects new fragment on new value of livedata */
+    public static class InternalFragment extends CountingFragment {
+
+        int mDepth = MAX_DEPTH;
+
+        @Override
+        public void onCreate(@Nullable Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            LiveDataViewModel liveDataViewModel = ViewModelStore.get(
+                    (LifecycleProvider) getActivity(), VM_TAG, LiveDataViewModel.class);
+            liveDataViewModel.liveData.observe(this, s ->
+                    getChildFragmentManager().beginTransaction().add(new CountingFragment(),
+                            s).commitNow());
+
+            if (mDepth == MAX_DEPTH) {
+                return;
+            }
+            InternalFragment aFragment = new InternalFragment();
+            aFragment.mDepth = mDepth + 1;
+            InternalFragment bFragment = new InternalFragment();
+            bFragment.mDepth = mDepth + 1;
+            getChildFragmentManager().beginTransaction()
+                    .add(aFragment, getTag() + "_" + mDepth + "_a")
+                    .add(bFragment, getTag() + "_" + mDepth + "_b")
+                    .commitNow();
+        }
+    }
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        viewModel = ViewModelStore.get(this, VM_TAG, LiveDataViewModel.class);
+        viewModel.liveData.observe(this, s ->
+                getSupportFragmentManager().beginTransaction().add(new CountingFragment(),
+                        s).commit());
+        String tag = "0_a";
+        if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
+            InternalFragment internalFragment = new InternalFragment();
+            internalFragment.mDepth = 1;
+            getSupportFragmentManager().beginTransaction().add(internalFragment, tag).commitNow();
+        }
+    }
+
+    @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        viewModel.liveData.setValue(LIVE_DATA_VALUE);
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/.gitignore b/lifecycle/integration-tests/testapp/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/lifecycle/integration-tests/testapp/build.gradle b/lifecycle/integration-tests/testapp/build.gradle
new file mode 100644
index 0000000..b0da333
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/build.gradle
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+apply plugin: 'com.android.application'
+
+project.ext.noDocs = true
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        applicationId "android.arch.lifecycle.testapp"
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_8
+        targetCompatibility JavaVersion.VERSION_1_8
+    }
+    buildTypes {
+        // test coverage does not work w/ jack
+        debug {
+            testCoverageEnabled = false
+        }
+        release {
+            testCoverageEnabled = false
+        }
+    }
+}
+
+dependencies {
+    compile fileTree(dir: 'libs', include: ['*.jar'])
+    // IJ canont figure out transitive dependencies so need to declare them.
+    compile project(":lifecycle:common")
+    compile project(":lifecycle:runtime")
+    compile project(":lifecycle:extensions")
+    annotationProcessor project(":lifecycle:compiler")
+    androidTestAnnotationProcessor project(":lifecycle:compiler")
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+    testCompile libs.junit
+}
+createAndroidCheckstyle(project)
+
+tasks['check'].dependsOn(tasks['connectedCheck'])
+
+uploadArchives.enabled = false
diff --git a/lifecycle/integration-tests/testapp/proguard-rules.pro b/lifecycle/integration-tests/testapp/proguard-rules.pro
new file mode 100644
index 0000000..575c04e
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/proguard-rules.pro
@@ -0,0 +1,25 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/sergeyv/Library/Android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ActivityFullLifecycleTest.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ActivityFullLifecycleTest.java
new file mode 100644
index 0000000..ee4e661
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ActivityFullLifecycleTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.testapp.TestEvent.ACTIVITY_CALLBACK;
+import static android.arch.lifecycle.testapp.TestEvent.LIFECYCLE_EVENT;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+
+import android.app.Activity;
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.testapp.CollectingActivity;
+import android.arch.lifecycle.testapp.FrameworkLifecycleRegistryActivity;
+import android.arch.lifecycle.testapp.FullLifecycleTestActivity;
+import android.arch.lifecycle.testapp.SupportLifecycleRegistryActivity;
+import android.arch.lifecycle.testapp.TestEvent;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.util.Pair;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@SmallTest
+@RunWith(Parameterized.class)
+public class ActivityFullLifecycleTest {
+    @Rule
+    public ActivityTestRule activityTestRule =
+            new ActivityTestRule<>(FullLifecycleTestActivity.class);
+
+    @Parameterized.Parameters
+    public static Class[] params() {
+        return new Class[]{FullLifecycleTestActivity.class,
+                SupportLifecycleRegistryActivity.class,
+                FrameworkLifecycleRegistryActivity.class};
+    }
+
+    public ActivityFullLifecycleTest(Class<? extends Activity> activityClass) {
+        //noinspection unchecked
+        activityTestRule = new ActivityTestRule(activityClass);
+    }
+
+
+    @Test
+    public void testFullLifecycle() throws InterruptedException {
+        Activity activity = activityTestRule.getActivity();
+        List<Pair<TestEvent, Event>> results = ((CollectingActivity) activity)
+                .waitForCollectedEvents();
+
+        Event[] expectedEvents =
+                new Event[]{ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY};
+
+        List<Pair<TestEvent, Event>> expected = new ArrayList<>();
+        boolean beforeResume = true;
+        for (Event i : expectedEvents) {
+            if (beforeResume) {
+                expected.add(new Pair<>(ACTIVITY_CALLBACK, i));
+                expected.add(new Pair<>(LIFECYCLE_EVENT, i));
+            } else {
+                expected.add(new Pair<>(LIFECYCLE_EVENT, i));
+                expected.add(new Pair<>(ACTIVITY_CALLBACK, i));
+            }
+            if (i == ON_RESUME) {
+                beforeResume = false;
+            }
+        }
+        assertThat(results, is(expected));
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/FragmentInBackStackLifecycleTest.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/FragmentInBackStackLifecycleTest.java
new file mode 100644
index 0000000..3397f5f
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/FragmentInBackStackLifecycleTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.TestUtils.recreateActivity;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.iterableWithSize;
+
+import static java.util.Arrays.asList;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.testapp.EmptyActivity;
+import android.arch.lifecycle.testapp.R;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class FragmentInBackStackLifecycleTest {
+    @Rule
+    public ActivityTestRule<EmptyActivity> activityTestRule = new ActivityTestRule<>(
+            EmptyActivity.class);
+
+    @Test
+    public void test() throws Throwable {
+        final ArrayList<Event> collectedEvents = new ArrayList<>();
+        LifecycleObserver collectingObserver = new LifecycleObserver() {
+            @OnLifecycleEvent(Event.ON_ANY)
+            void onAny(LifecycleOwner owner, Event event) {
+                collectedEvents.add(event);
+            }
+        };
+        final FragmentActivity activity = activityTestRule.getActivity();
+        activityTestRule.runOnUiThread(() -> {
+            FragmentManager fm = activity.getSupportFragmentManager();
+            LifecycleFragment fragment = new LifecycleFragment();
+            fm.beginTransaction().add(R.id.fragment_container, fragment, "tag").addToBackStack(null)
+                    .commit();
+            fm.executePendingTransactions();
+
+            fragment.getLifecycle().addObserver(collectingObserver);
+            LifecycleFragment fragment2 = new LifecycleFragment();
+            fm.beginTransaction().replace(R.id.fragment_container, fragment2).addToBackStack(null)
+                    .commit();
+            fm.executePendingTransactions();
+            assertThat(collectedEvents, is(asList(ON_CREATE, ON_START, ON_RESUME,
+                    ON_PAUSE, ON_STOP)));
+            collectedEvents.clear();
+        });
+        EmptyActivity newActivity = recreateActivity(activityTestRule.getActivity(),
+                activityTestRule);
+
+        assertThat(collectedEvents, is(asList(ON_DESTROY)));
+        collectedEvents.clear();
+        EmptyActivity lastActivity = recreateActivity(newActivity, activityTestRule);
+        activityTestRule.runOnUiThread(() -> {
+            FragmentManager fm = lastActivity.getSupportFragmentManager();
+            LifecycleFragment fragment = (LifecycleFragment) fm.findFragmentByTag("tag");
+            fragment.getLifecycle().addObserver(collectingObserver);
+            assertThat(collectedEvents, iterableWithSize(0));
+            fm.popBackStackImmediate();
+            assertThat(collectedEvents, is(asList(ON_CREATE, ON_START, ON_RESUME)));
+        });
+    }
+
+
+}
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ProcessOwnerTest.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ProcessOwnerTest.java
new file mode 100644
index 0000000..e80e11c
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/ProcessOwnerTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.TestUtils.waitTillResumed;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+
+import android.app.Instrumentation;
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.testapp.NavigationDialogActivity;
+import android.arch.lifecycle.testapp.NavigationTestActivityFirst;
+import android.arch.lifecycle.testapp.NavigationTestActivitySecond;
+import android.content.Context;
+import android.content.Intent;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class ProcessOwnerTest {
+
+    @Rule
+    public ActivityTestRule<NavigationTestActivityFirst> activityTestRule =
+            new ActivityTestRule<>(NavigationTestActivityFirst.class);
+
+    static class ProcessObserver implements LifecycleObserver {
+        volatile boolean mChangedState;
+
+        @OnLifecycleEvent(Event.ON_ANY)
+        void onEvent() {
+            mChangedState = true;
+        }
+    }
+
+    private ProcessObserver mObserver = new ProcessObserver();
+
+    @After
+    public void tearDown() {
+        try {
+            // reassure that our observer is removed.
+            removeProcessObserver(mObserver);
+        } catch (Throwable throwable) {
+            throwable.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testNavigation() throws Throwable {
+        LifecycleActivity firstActivity = setupObserverOnResume();
+        Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
+                NavigationTestActivitySecond.class.getCanonicalName(), null, false);
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        instrumentation.addMonitor(monitor);
+
+        Intent intent = new Intent(firstActivity, NavigationTestActivitySecond.class);
+        firstActivity.finish();
+        firstActivity.startActivity(intent);
+
+        LifecycleActivity secondActivity = (LifecycleActivity) monitor.waitForActivity();
+        assertThat("Failed to navigate", secondActivity, notNullValue());
+        checkProcessObserverSilent(secondActivity);
+    }
+
+    @Test
+    public void testRecreation() throws Throwable {
+        LifecycleActivity activity = setupObserverOnResume();
+        LifecycleActivity recreated = TestUtils.recreateActivity(activity, activityTestRule);
+        assertThat("Failed to recreate", recreated, notNullValue());
+        checkProcessObserverSilent(recreated);
+    }
+
+    @Test
+    public void testPressHomeButton() throws Throwable {
+        setupObserverOnResume();
+
+        Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
+                NavigationDialogActivity.class.getCanonicalName(), null, false);
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        instrumentation.addMonitor(monitor);
+
+        NavigationTestActivityFirst activity = activityTestRule.getActivity();
+        activity.startActivity(new Intent(activity, NavigationDialogActivity.class));
+        LifecycleActivity dialogActivity = (LifecycleActivity) monitor.waitForActivity();
+        checkProcessObserverSilent(dialogActivity);
+
+        List<Event> events = Collections.synchronizedList(new ArrayList<>());
+
+        LifecycleObserver collectingObserver = new LifecycleObserver() {
+            @OnLifecycleEvent(Event.ON_ANY)
+            public void onStateChanged(LifecycleOwner provider, Event event) {
+                events.add(event);
+            }
+        };
+        addProcessObserver(collectingObserver);
+        events.clear();
+        assertThat(activity.moveTaskToBack(true), is(true));
+        Thread.sleep(ProcessLifecycleOwner.TIMEOUT_MS * 2);
+        assertThat(events.toArray(), is(new Event[]{ON_PAUSE, ON_STOP}));
+        events.clear();
+        Context context = InstrumentationRegistry.getContext();
+        context.startActivity(new Intent(activity, NavigationDialogActivity.class)
+                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+        waitTillResumed(dialogActivity, activityTestRule);
+        assertThat(events.toArray(), is(new Event[]{ON_START, ON_RESUME}));
+        removeProcessObserver(collectingObserver);
+        dialogActivity.finish();
+    }
+
+    private LifecycleActivity setupObserverOnResume() throws Throwable {
+        LifecycleActivity firstActivity = activityTestRule.getActivity();
+        waitTillResumed(firstActivity, activityTestRule);
+        addProcessObserver(mObserver);
+        mObserver.mChangedState = false;
+        return firstActivity;
+    }
+
+    private void addProcessObserver(LifecycleObserver observer) throws Throwable {
+        activityTestRule.runOnUiThread(() ->
+                ProcessLifecycleOwner.get().getLifecycle().addObserver(observer));
+    }
+
+    private void removeProcessObserver(LifecycleObserver observer) throws Throwable {
+        activityTestRule.runOnUiThread(() ->
+                ProcessLifecycleOwner.get().getLifecycle().removeObserver(observer));
+    }
+
+    private void checkProcessObserverSilent(LifecycleActivity activity) throws Throwable {
+        waitTillResumed(activity, activityTestRule);
+        assertThat(mObserver.mChangedState, is(false));
+        activityTestRule.runOnUiThread(() ->
+                ProcessLifecycleOwner.get().getLifecycle().removeObserver(mObserver));
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SimpleAppFullLifecycleTest.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SimpleAppFullLifecycleTest.java
new file mode 100644
index 0000000..44d1e8a
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SimpleAppFullLifecycleTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.State.CREATED;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.isIn;
+import static org.hamcrest.Matchers.notNullValue;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.Lifecycle.State;
+import android.arch.lifecycle.testapp.SimpleAppLifecycleTestActivity;
+import android.arch.lifecycle.testapp.SimpleAppLifecycleTestActivity.TestEventType;
+import android.support.test.filters.LargeTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.Pair;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class SimpleAppFullLifecycleTest {
+
+    @SuppressWarnings("unchecked")
+    private static final Pair[] EXPECTED_EVENTS_CONSTRUCTION =
+            new Pair[] {
+                new Pair(TestEventType.PROCESS_EVENT, Event.ON_CREATE),
+                new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_CREATE),
+                new Pair(TestEventType.PROCESS_EVENT, Event.ON_START),
+                new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_START),
+                new Pair(TestEventType.PROCESS_EVENT, Event.ON_RESUME),
+                new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_RESUME),
+            };
+
+    @SuppressWarnings("unchecked")
+    private static final Pair[] EXPECTED_EVENTS_DESTRUCTION =
+            new Pair[]{
+
+                    new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_PAUSE),
+                    new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_STOP),
+                    new Pair(TestEventType.ACTIVITY_EVENT, Event.ON_DESTROY),
+
+                    new Pair(TestEventType.PROCESS_EVENT, Event.ON_PAUSE),
+                    new Pair(TestEventType.PROCESS_EVENT, Event.ON_STOP),
+            };
+    @Rule
+    public ActivityTestRule<SimpleAppLifecycleTestActivity> activityTestRule =
+            new ActivityTestRule<>(SimpleAppLifecycleTestActivity.class, false, false);
+
+    @Before
+    public void setup() {
+        // cool down period, so application state will become DESTROYED
+        try {
+            Thread.sleep(ProcessLifecycleOwner.TIMEOUT_MS * 2);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        SimpleAppLifecycleTestActivity.startProcessObserver();
+    }
+
+    @After
+    public void tearDown() {
+        SimpleAppLifecycleTestActivity.stopProcessObserver();
+    }
+
+    @Test
+    public void testFullLifecycle() throws InterruptedException {
+        State currentState = ProcessLifecycleOwner.get().getLifecycle().getCurrentState();
+        assertThat(currentState, is(CREATED));
+        activityTestRule.launchActivity(null);
+        List<Pair<TestEventType, Event>> events = SimpleAppLifecycleTestActivity.awaitForEvents();
+        assertThat("Failed to await for events", events, notNullValue());
+        //noinspection ConstantConditions
+        assertThat(events.subList(0, 6).toArray(), is(EXPECTED_EVENTS_CONSTRUCTION));
+
+        // TODO: bug 35122523
+        for (Pair<TestEventType, Event> event: events.subList(6, 11)) {
+            assertThat(event, isIn(EXPECTED_EVENTS_DESTRUCTION));
+        }
+    }
+
+}
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SynchronousActivityLifecycleTest.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SynchronousActivityLifecycleTest.java
new file mode 100644
index 0000000..141d612
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/SynchronousActivityLifecycleTest.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+
+import android.app.Activity;
+import android.app.Application;
+import android.app.Instrumentation;
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.testapp.LifecycleTestActivity;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.os.Build;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.UiThreadTestRule;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.reflect.Method;
+
+/**
+ * It tests that an event is dispatched immediately after a call of corresponding OnXXX method
+ * during an execution of performXXX
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class SynchronousActivityLifecycleTest {
+
+    @Rule
+    public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
+
+    @Test
+    public void testOnCreateCall() throws Throwable {
+        testSynchronousCall(Event.ON_CREATE,
+                activity -> {
+                },
+                activity -> getInstrumentation().callActivityOnCreate(activity, null));
+    }
+
+    @Test
+    public void testOnStartCall() throws Throwable {
+        testSynchronousCall(Lifecycle.Event.ON_START,
+                activity -> getInstrumentation().callActivityOnCreate(activity, null),
+                SynchronousActivityLifecycleTest::performStart);
+    }
+
+    @Test
+    public void testOnResumeCall() throws Throwable {
+        testSynchronousCall(Lifecycle.Event.ON_RESUME,
+                activity -> {
+                    getInstrumentation().callActivityOnCreate(activity, null);
+                    performStart(activity);
+                },
+                SynchronousActivityLifecycleTest::performResume);
+    }
+
+    @Test
+    public void testOnStopCall() throws Throwable {
+        testSynchronousCall(Lifecycle.Event.ON_STOP,
+                activity -> {
+                    getInstrumentation().callActivityOnCreate(activity, null);
+                    performStart(activity);
+                },
+                SynchronousActivityLifecycleTest::performStop);
+    }
+
+    @Test
+    public void testOnDestroyCall() throws Throwable {
+        testSynchronousCall(Lifecycle.Event.ON_DESTROY,
+                activity -> getInstrumentation().callActivityOnCreate(activity, null),
+                activity -> getInstrumentation().callActivityOnDestroy(activity));
+    }
+
+    public void testSynchronousCall(Event event, ActivityCall preInit, ActivityCall call)
+            throws Throwable {
+        uiThreadTestRule.runOnUiThread(() -> {
+            Intent intent = new Intent();
+            ComponentName cn = new ComponentName(LifecycleTestActivity.class.getPackage().getName(),
+                    LifecycleTestActivity.class.getName());
+            intent.setComponent(cn);
+            Instrumentation instrumentation = getInstrumentation();
+            try {
+                Application app =
+                        (Application) instrumentation.getTargetContext().getApplicationContext();
+                LifecycleTestActivity testActivity =
+                        (LifecycleTestActivity) instrumentation.newActivity(
+                                LifecycleTestActivity.class, instrumentation.getTargetContext(),
+                                null, app, intent, new ActivityInfo(), "bla", null, null, null);
+                preInit.call(testActivity);
+                TestObserver testObserver = new TestObserver(testActivity, event);
+                testActivity.getLifecycle().addObserver(testObserver);
+                testObserver.unmute();
+                call.call(testActivity);
+
+                assertThat(testObserver.mEventReceived, is(true));
+            } catch (Exception e) {
+                throw new Error(e);
+            }
+        });
+    }
+
+    // Instrumentation.callOnActivityCreate calls performCreate on mActivity,
+    // but Instrumentation.callOnActivityStart calls onStart instead of performStart. ¯\_(ツ)_/¯
+    private static void performStart(Activity activity) {
+        try {
+            Method m = Activity.class.getDeclaredMethod("performStart");
+            m.setAccessible(true);
+            m.invoke(activity);
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+    private static void performResume(Activity activity) {
+        try {
+            Method m = Activity.class.getDeclaredMethod("performResume");
+            m.setAccessible(true);
+            m.invoke(activity);
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+
+    private static void performStop(Activity activity) {
+        try {
+            if (Build.VERSION.SDK_INT >= 24) {
+                Method m = Activity.class.getDeclaredMethod("performStop", boolean.class);
+                m.setAccessible(true);
+                m.invoke(activity, false);
+            } else {
+                Method m = Activity.class.getDeclaredMethod("performStop");
+                m.setAccessible(true);
+                m.invoke(activity);
+            }
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+    private static class TestObserver implements GenericLifecycleObserver {
+        private final LifecycleTestActivity mActivity;
+        private final Event mExpectedEvent;
+        boolean mEventReceived = false;
+        boolean mMuted = true;
+
+        private TestObserver(LifecycleTestActivity activity, Event expectedEvent) {
+            this.mActivity = activity;
+            this.mExpectedEvent = expectedEvent;
+        }
+
+        void unmute() {
+            mMuted = false;
+        }
+
+        @Override
+        public void onStateChanged(LifecycleOwner lifecycleOwner, Event event) {
+            if (mMuted) {
+                return;
+            }
+            assertThat(event, is(mExpectedEvent));
+            assertThat(mActivity.mLifecycleCallFinished, is(true));
+            mEventReceived = true;
+        }
+
+        @Override
+        public Object getReceiver() {
+            return null;
+        }
+    }
+
+    private interface ActivityCall {
+        void call(Activity activity);
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/TestUtils.java b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/TestUtils.java
new file mode 100644
index 0000000..c5a520f
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/androidTest/java/android/arch/lifecycle/TestUtils.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.State.RESUMED;
+
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.app.Instrumentation.ActivityMonitor;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.rule.ActivityTestRule;
+
+import java.util.concurrent.CountDownLatch;
+
+public class TestUtils {
+
+    private static final long TIMEOUT_MS = 2000;
+
+    @SuppressWarnings("unchecked")
+    public static <T extends Activity> T recreateActivity(final T activity, ActivityTestRule rule)
+            throws Throwable {
+        ActivityMonitor monitor = new ActivityMonitor(
+                activity.getClass().getCanonicalName(), null, false);
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        instrumentation.addMonitor(monitor);
+        rule.runOnUiThread(activity::recreate);
+        T result;
+
+        // this guarantee that we will reinstall monitor between notifications about onDestroy
+        // and onCreate
+        //noinspection SynchronizationOnLocalVariableOrMethodParameter
+        synchronized (monitor) {
+            do {
+                // the documetation says "Block until an Activity is created
+                // that matches this monitor." This statement is true, but there are some other
+                // true statements like: "Block until an Activity is destoyed" or
+                // "Block until an Activity is resumed"...
+
+                // this call will release synchronization monitor's monitor
+                result = (T) monitor.waitForActivityWithTimeout(TIMEOUT_MS);
+                if (result == null) {
+                    throw new RuntimeException("Timeout. Failed to recreate an activity");
+                }
+            } while (result == activity);
+        }
+        return result;
+    }
+
+    static void waitTillResumed(final LifecycleActivity a, ActivityTestRule<?> activityRule)
+            throws Throwable {
+        final CountDownLatch latch = new CountDownLatch(1);
+        activityRule.runOnUiThread(() -> {
+            Lifecycle.State currentState = a.getLifecycle().getCurrentState();
+            if (currentState == RESUMED) {
+                latch.countDown();
+            }
+            a.getLifecycle().addObserver(new LifecycleObserver() {
+                @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
+                public void onStateChanged(LifecycleOwner provider) {
+                    latch.countDown();
+                    provider.getLifecycle().removeObserver(this);
+                }
+            });
+        });
+        latch.await();
+    }
+
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/AndroidManifest.xml b/lifecycle/integration-tests/testapp/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..bf88f97
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/AndroidManifest.xml
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+  ~ Copyright (C) 2016 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.
+  -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools" package="android.arch.lifecycle.testapp">
+
+    <application android:allowBackup="true" android:label="Test App" android:supportsRtl="true"
+        tools:ignore="AllowBackup,GoogleAppIndexingWarning,MissingApplicationIcon">
+        <activity android:name="android.arch.lifecycle.testapp.MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <activity android:name="android.arch.lifecycle.testapp.LifecycleTestActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="android.arch.lifecycle.testapp.FullLifecycleTestActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="android.arch.lifecycle.testapp.SupportLifecycleRegistryActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="android.arch.lifecycle.testapp.FrameworkLifecycleRegistryActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity
+            android:name="android.arch.lifecycle.testapp.SimpleAppLifecycleTestActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="android.arch.lifecycle.testapp.NavigationTestActivityFirst"
+            android:launchMode="singleTask">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity
+            android:name="android.arch.lifecycle.testapp.EmptyActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name=".NavigationTestActivitySecond" />
+        <activity android:name=".NavigationDialogActivity"
+            android:launchMode="singleTask"
+            android:theme="@android:style/Theme.DeviceDefault.Dialog" />
+    </application>
+</manifest>
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/CollectingActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/CollectingActivity.java
new file mode 100644
index 0000000..6e243b6
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/CollectingActivity.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.Lifecycle;
+import android.util.Pair;
+
+import java.util.List;
+
+/**
+ * For activities that collect their events.
+ */
+public interface CollectingActivity {
+    long TIMEOUT = 5;
+
+    /**
+     * Return collected events
+     *
+     * @return The list of collected events.
+     * @throws InterruptedException
+     */
+    List<Pair<TestEvent, Lifecycle.Event>> waitForCollectedEvents() throws InterruptedException;
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/EmptyActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/EmptyActivity.java
new file mode 100644
index 0000000..68a82e1
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/EmptyActivity.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v4.app.FragmentActivity;
+
+/**
+ * empty activity
+ */
+public class EmptyActivity extends FragmentActivity {
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.empty_activity_layout);
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FrameworkLifecycleRegistryActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FrameworkLifecycleRegistryActivity.java
new file mode 100644
index 0000000..d8f4fb3
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FrameworkLifecycleRegistryActivity.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import static android.arch.lifecycle.testapp.TestEvent.ACTIVITY_CALLBACK;
+
+import android.app.Activity;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LifecycleRegistryOwner;
+import android.os.Bundle;
+import android.util.Pair;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * LifecycleRegistryOwner that extends framework activity.
+ */
+public class FrameworkLifecycleRegistryActivity extends Activity implements
+        LifecycleRegistryOwner, CollectingActivity {
+    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
+
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+
+    private List<Pair<TestEvent, Lifecycle.Event>> mCollectedEvents = new ArrayList<>();
+    private TestObserver mTestObserver = new TestObserver(mCollectedEvents);
+    private CountDownLatch mLatch = new CountDownLatch(1);
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_CREATE));
+        getLifecycle().addObserver(mTestObserver);
+    }
+
+    @Override
+    protected void onStart() {
+        super.onStart();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_START));
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_RESUME));
+        finish();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_DESTROY));
+        mLatch.countDown();
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_STOP));
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_PAUSE));
+    }
+
+    /**
+     * awaits for all events and returns them.
+     */
+    @Override
+    public List<Pair<TestEvent, Lifecycle.Event>> waitForCollectedEvents()
+            throws InterruptedException {
+        mLatch.await(TIMEOUT, TimeUnit.SECONDS);
+        return mCollectedEvents;
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FullLifecycleTestActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FullLifecycleTestActivity.java
new file mode 100644
index 0000000..5972b16
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/FullLifecycleTestActivity.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.testapp;
+
+import static android.arch.lifecycle.testapp.TestEvent.ACTIVITY_CALLBACK;
+
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleActivity;
+import android.os.Bundle;
+import android.util.Pair;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Activity for testing full lifecycle
+ */
+public class FullLifecycleTestActivity extends LifecycleActivity implements CollectingActivity {
+
+    private List<Pair<TestEvent, Lifecycle.Event>> mCollectedEvents = new ArrayList<>();
+    private TestObserver mTestObserver = new TestObserver(mCollectedEvents);
+    private CountDownLatch mLatch = new CountDownLatch(1);
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_CREATE));
+        getLifecycle().addObserver(mTestObserver);
+    }
+
+    @Override
+    protected void onStart() {
+        super.onStart();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_START));
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_RESUME));
+        finish();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_DESTROY));
+        mLatch.countDown();
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_STOP));
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Lifecycle.Event.ON_PAUSE));
+    }
+
+    /**
+     * awaits for all events and returns them.
+     */
+    @Override
+    public List<Pair<TestEvent, Lifecycle.Event>> waitForCollectedEvents()
+            throws InterruptedException {
+        mLatch.await(TIMEOUT, TimeUnit.SECONDS);
+        return mCollectedEvents;
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/LifecycleTestActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/LifecycleTestActivity.java
new file mode 100644
index 0000000..093ec7f
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/LifecycleTestActivity.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.LifecycleActivity;
+import android.os.Bundle;
+
+/**
+ * Activity for testing events by themselves
+ */
+public class LifecycleTestActivity extends LifecycleActivity {
+
+    /**
+     * identifies that
+     */
+    public boolean mLifecycleCallFinished;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        mLifecycleCallFinished = false;
+        super.onCreate(savedInstanceState);
+        mLifecycleCallFinished = true;
+    }
+
+    @Override
+    protected void onStart() {
+        mLifecycleCallFinished = false;
+        super.onStart();
+        mLifecycleCallFinished = true;
+    }
+
+    @Override
+    protected void onResume() {
+        mLifecycleCallFinished = false;
+        super.onResume();
+        mLifecycleCallFinished = true;
+    }
+
+    @Override
+    protected void onPause() {
+        mLifecycleCallFinished = false;
+        super.onPause();
+        mLifecycleCallFinished = true;
+    }
+
+    @Override
+    protected void onStop() {
+        mLifecycleCallFinished = false;
+        super.onStop();
+        mLifecycleCallFinished = true;
+    }
+
+    @Override
+    protected void onDestroy() {
+        mLifecycleCallFinished = false;
+        super.onDestroy();
+        mLifecycleCallFinished = true;
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/MainActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/MainActivity.java
new file mode 100644
index 0000000..b9d5914
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/MainActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.testapp;
+
+import android.os.Bundle;
+import android.support.v4.app.FragmentActivity;
+
+/**
+ * Simple test activity
+ */
+public class MainActivity extends FragmentActivity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity);
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationDialogActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationDialogActivity.java
new file mode 100644
index 0000000..709bd8d
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationDialogActivity.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.LifecycleActivity;
+
+/**
+ *  an activity with Dialog theme.
+ */
+public class NavigationDialogActivity extends LifecycleActivity {
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivityFirst.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivityFirst.java
new file mode 100644
index 0000000..f1847c9
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivityFirst.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.LifecycleActivity;
+
+/**
+ * Activity for ProcessOwnerTest
+ */
+public class NavigationTestActivityFirst extends LifecycleActivity {
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivitySecond.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivitySecond.java
new file mode 100644
index 0000000..221e927
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/NavigationTestActivitySecond.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.LifecycleActivity;
+
+/**
+ * Activity for ProcessOwnerTest
+ */
+public class NavigationTestActivitySecond extends LifecycleActivity {
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SimpleAppLifecycleTestActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SimpleAppLifecycleTestActivity.java
new file mode 100644
index 0000000..6d61c5e
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SimpleAppLifecycleTestActivity.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleActivity;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+import android.arch.lifecycle.ProcessLifecycleOwner;
+import android.os.Bundle;
+import android.util.Pair;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Activity for SimpleAppFullLifecycleTest
+ */
+public class SimpleAppLifecycleTestActivity extends LifecycleActivity {
+
+    public enum TestEventType {
+        PROCESS_EVENT,
+        ACTIVITY_EVENT
+    }
+
+    private static final long TIMEOUT_SECS = 10; // secs
+
+    static class TestObserver implements LifecycleObserver {
+
+        private TestEventType mType;
+
+        TestObserver(TestEventType type) {
+            mType = type;
+        }
+
+        @SuppressWarnings("unused")
+        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
+        void onEvent(LifecycleOwner provider, Lifecycle.Event event) {
+            sCollectedEvents.add(new Pair<>(mType, event));
+            sLatch.countDown();
+        }
+    }
+
+    static List<Pair<TestEventType, Lifecycle.Event>> sCollectedEvents = new ArrayList<>();
+    static CountDownLatch sLatch = new CountDownLatch(11);
+
+    /**
+     * start process observer
+     */
+    public static void startProcessObserver() {
+        ProcessLifecycleOwner.get().getLifecycle().addObserver(sProcessObserver);
+    }
+
+    /**
+     * stop process observer
+     */
+    public static void stopProcessObserver() {
+        ProcessLifecycleOwner.get().getLifecycle().removeObserver(sProcessObserver);
+    }
+
+    private static TestObserver sProcessObserver = new TestObserver(TestEventType.PROCESS_EVENT);
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getLifecycle().addObserver(new TestObserver(TestEventType.ACTIVITY_EVENT));
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        finish();
+    }
+
+    /**
+     * returns collected events
+     */
+    public static List<Pair<TestEventType, Lifecycle.Event>> awaitForEvents()
+            throws InterruptedException {
+        boolean success = sLatch.await(TIMEOUT_SECS, TimeUnit.SECONDS);
+        return success ? sCollectedEvents : null;
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SupportLifecycleRegistryActivity.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SupportLifecycleRegistryActivity.java
new file mode 100644
index 0000000..c46c6d3
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/SupportLifecycleRegistryActivity.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import static android.arch.lifecycle.testapp.TestEvent.ACTIVITY_CALLBACK;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LifecycleRegistryOwner;
+import android.os.Bundle;
+import android.support.v4.app.FragmentActivity;
+import android.util.Pair;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * LifecycleRegistryOwner that extends FragmentActivity.
+ */
+public class SupportLifecycleRegistryActivity extends FragmentActivity implements
+        LifecycleRegistryOwner, CollectingActivity {
+    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+
+    private List<Pair<TestEvent, Event>> mCollectedEvents = new ArrayList<>();
+    private TestObserver mTestObserver = new TestObserver(mCollectedEvents);
+    private CountDownLatch mLatch = new CountDownLatch(1);
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_CREATE));
+        getLifecycle().addObserver(mTestObserver);
+    }
+
+    @Override
+    protected void onStart() {
+        super.onStart();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_START));
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_RESUME));
+        finish();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_DESTROY));
+        mLatch.countDown();
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_STOP));
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        mCollectedEvents.add(new Pair<>(ACTIVITY_CALLBACK, Event.ON_PAUSE));
+    }
+
+    /**
+     * awaits for all events and returns them.
+     */
+    @Override
+    public List<Pair<TestEvent, Event>> waitForCollectedEvents() throws InterruptedException {
+        mLatch.await(TIMEOUT, TimeUnit.SECONDS);
+        return mCollectedEvents;
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestEvent.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestEvent.java
new file mode 100644
index 0000000..0929f84
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestEvent.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+public enum TestEvent {
+    ACTIVITY_CALLBACK,
+    LIFECYCLE_EVENT
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestObserver.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestObserver.java
new file mode 100644
index 0000000..c611239
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/TestObserver.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle.testapp;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.testapp.TestEvent.LIFECYCLE_EVENT;
+
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.OnLifecycleEvent;
+import android.util.Pair;
+
+import java.util.List;
+
+class TestObserver implements LifecycleObserver {
+    private final List<Pair<TestEvent, Event>> mCollectedEvents;
+
+    TestObserver(List<Pair<TestEvent, Event>> collectedEvents) {
+        mCollectedEvents = collectedEvents;
+    }
+
+    @OnLifecycleEvent(ON_CREATE)
+    public void create(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_CREATE));
+    }
+
+    @OnLifecycleEvent(ON_START)
+    public void start(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_START));
+    }
+
+    @OnLifecycleEvent(ON_RESUME)
+    public void resume(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_RESUME));
+    }
+    @OnLifecycleEvent(ON_PAUSE)
+    public void pause(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_PAUSE));
+    }
+
+    @OnLifecycleEvent(ON_STOP)
+    public void stop(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_STOP));
+    }
+
+    @OnLifecycleEvent(ON_DESTROY)
+    public void destroy(LifecycleOwner pr) {
+        mCollectedEvents.add(new Pair<>(LIFECYCLE_EVENT, ON_DESTROY));
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/UsualFragment.java b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/UsualFragment.java
new file mode 100644
index 0000000..fb6cae0
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/java/android/arch/lifecycle/testapp/UsualFragment.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2016 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 android.arch.lifecycle.testapp;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+/**
+ * Simple fragment which does nothing.
+ */
+public class UsualFragment extends Fragment {
+
+    @Nullable
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        return new View(getContext());
+    }
+}
diff --git a/lifecycle/integration-tests/testapp/src/main/res/layout/activity.xml b/lifecycle/integration-tests/testapp/src/main/res/layout/activity.xml
new file mode 100644
index 0000000..a4e9513
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/res/layout/activity.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+    <FrameLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/root">
+        <fragment
+            android:id="@+id/main_fragment"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:tag="fragment_tag"
+            android:name="android.arch.lifecycle.testapp.UsualFragment"
+            tools:context="android.arch.lifecycle.testapp.MainActivity">
+        </fragment>
+    </FrameLayout>
+</FrameLayout>
diff --git a/lifecycle/integration-tests/testapp/src/main/res/layout/empty_activity_layout.xml b/lifecycle/integration-tests/testapp/src/main/res/layout/empty_activity_layout.xml
new file mode 100644
index 0000000..d476848
--- /dev/null
+++ b/lifecycle/integration-tests/testapp/src/main/res/layout/empty_activity_layout.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/activity_main"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="android.arch.lifecycle.activity.FragmentLifecycleActivity">
+    <FrameLayout
+        android:id="@+id/fragment_container"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent" />
+</RelativeLayout>
diff --git a/lifecycle/reactivestreams/.gitignore b/lifecycle/reactivestreams/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/lifecycle/reactivestreams/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/lifecycle/reactivestreams/build.gradle b/lifecycle/reactivestreams/build.gradle
new file mode 100644
index 0000000..67da2ca
--- /dev/null
+++ b/lifecycle/reactivestreams/build.gradle
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+sourceCompatibility = '1.7'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+}
+
+allprojects {
+    dependencies {
+        compile project(":arch:common")
+        compile project(":lifecycle:common")
+        compile project(":lifecycle:extensions")
+        compile project(":lifecycle:runtime")
+        compile libs.support.annotations
+        compile libs.reactive_streams
+
+        testCompile libs.junit
+        testCompile libs.rx_java
+
+        testCompile(libs.test_runner) {
+            exclude module: 'support-annotations'
+        }
+        androidTestCompile libs.support.app_compat
+    }
+}
+
+createAndroidCheckstyle(project)
+
+archivesBaseName = "reactivestreams"
diff --git a/lifecycle/reactivestreams/proguard-rules.pro b/lifecycle/reactivestreams/proguard-rules.pro
new file mode 100644
index 0000000..b7210d1
--- /dev/null
+++ b/lifecycle/reactivestreams/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/yboyar/android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
diff --git a/lifecycle/reactivestreams/src/androidTest/AndroidManifest.xml b/lifecycle/reactivestreams/src/androidTest/AndroidManifest.xml
new file mode 100644
index 0000000..722f480
--- /dev/null
+++ b/lifecycle/reactivestreams/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.lifecycle.reactivestreams.test">
+
+    <application>
+        <activity android:name="android.arch.lifecycle.viewmodeltest.ViewModelActivity"
+                  android:theme="@style/Base.Theme.AppCompat">
+        </activity>
+    </application>
+
+</manifest>
diff --git a/lifecycle/reactivestreams/src/main/AndroidManifest.xml b/lifecycle/reactivestreams/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..2210041
--- /dev/null
+++ b/lifecycle/reactivestreams/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.lifecycle.reactivestreams">
+</manifest>
diff --git a/lifecycle/reactivestreams/src/main/java/android/arch/lifecycle/LiveDataReactiveStreams.java b/lifecycle/reactivestreams/src/main/java/android/arch/lifecycle/LiveDataReactiveStreams.java
new file mode 100644
index 0000000..0be0149
--- /dev/null
+++ b/lifecycle/reactivestreams/src/main/java/android/arch/lifecycle/LiveDataReactiveStreams.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.support.annotation.Nullable;
+
+import org.reactivestreams.Publisher;
+import org.reactivestreams.Subscriber;
+import org.reactivestreams.Subscription;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * Adapts {@link LiveData} input and output to the ReactiveStreams spec.
+ */
+@SuppressWarnings("WeakerAccess")
+public final class LiveDataReactiveStreams {
+    private LiveDataReactiveStreams() {
+    }
+
+    /**
+     * Adapts the given {@link LiveData} stream to a ReactiveStreams {@link Publisher}.
+     *
+     * <p>
+     * By using a good publisher implementation such as RxJava 2.x Flowables, most consumers will
+     * be able to let the library deal with backpressure using operators and not need to worry about
+     * ever manually calling {@link Subscription#request}.
+     *
+     * <p>
+     * On subscription to the publisher, the observer will attach to the given {@link LiveData}.
+     * Once {@link Subscription#request) is called on the subscription object, an observer will be
+     * connected to the data stream. Calling request(Long.MAX_VALUE) is equivalent to creating an
+     * unbounded stream with no backpressure. If request with a finite count reaches 0, the observer
+     * will buffer the latest item and emit it to the subscriber when data is again requested. Any
+     * other items emitted during the time there was no backpressure requested will be dropped.
+     */
+    public static <T> Publisher<T> toPublisher(
+            final LifecycleOwner lifecycle, final LiveData<T> liveData) {
+
+        return new Publisher<T>() {
+            boolean mObserving;
+            boolean mCanceled;
+            long mRequested;
+            @Nullable
+            T mLatest;
+
+            @Override
+            public void subscribe(final Subscriber<? super T> subscriber) {
+                final Observer<T> observer = new Observer<T>() {
+                    @Override
+                    public void onChanged(@Nullable T t) {
+                        if (mCanceled) {
+                            return;
+                        }
+                        if (mRequested > 0) {
+                            mLatest = null;
+                            subscriber.onNext(t);
+                            if (mRequested != Long.MAX_VALUE) {
+                                mRequested--;
+                            }
+                        } else {
+                            mLatest = t;
+                        }
+                    }
+                };
+
+                subscriber.onSubscribe(new Subscription() {
+                    @Override
+                    public void request(final long n) {
+                        if (n < 0 || mCanceled) {
+                            return;
+                        }
+                        AppToolkitTaskExecutor.getInstance().executeOnMainThread(new Runnable() {
+                            @Override
+                            public void run() {
+                                if (mCanceled) {
+                                    return;
+                                }
+                                // Prevent overflowage.
+                                mRequested = mRequested + n >= mRequested
+                                        ? mRequested + n : Long.MAX_VALUE;
+                                if (!mObserving) {
+                                    mObserving = true;
+                                    liveData.observe(lifecycle, observer);
+                                } else if (mLatest != null) {
+                                    observer.onChanged(mLatest);
+                                    mLatest = null;
+                                }
+                            }
+                        });
+                    }
+
+                    @Override
+                    public void cancel() {
+                        if (mCanceled) {
+                            return;
+                        }
+                        AppToolkitTaskExecutor.getInstance().executeOnMainThread(new Runnable() {
+                            @Override
+                            public void run() {
+                                if (mCanceled) {
+                                    return;
+                                }
+                                if (mObserving) {
+                                    liveData.removeObserver(observer);
+                                    mObserving = false;
+                                }
+                                mLatest = null;
+                                mCanceled = true;
+                            }
+                        });
+                    }
+                });
+            }
+
+        };
+    }
+
+    /**
+     * Creates an Observable {@link LiveData} stream from a ReactiveStreams publisher.
+     */
+    public static <T> LiveData<T> fromPublisher(final Publisher<T> publisher) {
+        MutableLiveData<T> liveData = new MutableLiveData<>();
+        // Since we don't have a way to directly observe cancels, weakly hold the live data.
+        final WeakReference<MutableLiveData<T>> liveDataRef = new WeakReference<>(liveData);
+
+        publisher.subscribe(new Subscriber<T>() {
+            @Override
+            public void onSubscribe(Subscription s) {
+                // Don't worry about backpressure. If the stream is too noisy then backpressure can
+                // be handled upstream.
+                s.request(Long.MAX_VALUE);
+            }
+
+            @Override
+            public void onNext(final T t) {
+                final LiveData<T> liveData = liveDataRef.get();
+                if (liveData != null) {
+                    liveData.postValue(t);
+                }
+            }
+
+            @Override
+            public void onError(Throwable t) {
+                // Errors should be handled upstream, so propagate as a crash.
+                throw new RuntimeException(t);
+            }
+
+            @Override
+            public void onComplete() {
+            }
+        });
+
+        return liveData;
+    }
+
+}
diff --git a/lifecycle/reactivestreams/src/test/java/android/arch/lifecycle/LiveDataReactiveStreamsTest.java b/lifecycle/reactivestreams/src/test/java/android/arch/lifecycle/LiveDataReactiveStreamsTest.java
new file mode 100644
index 0000000..87fba27
--- /dev/null
+++ b/lifecycle/reactivestreams/src/test/java/android/arch/lifecycle/LiveDataReactiveStreamsTest.java
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.State.RESUMED;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.TaskExecutor;
+import android.support.annotation.Nullable;
+import android.support.test.filters.SmallTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.reactivestreams.Subscriber;
+import org.reactivestreams.Subscription;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import io.reactivex.Flowable;
+import io.reactivex.disposables.Disposable;
+import io.reactivex.functions.Consumer;
+import io.reactivex.processors.PublishProcessor;
+import io.reactivex.processors.ReplayProcessor;
+import io.reactivex.schedulers.TestScheduler;
+import io.reactivex.subjects.AsyncSubject;
+
+@SmallTest
+public class LiveDataReactiveStreamsTest {
+    private static final Lifecycle sLifecycle = new Lifecycle() {
+        @Override
+        public void addObserver(LifecycleObserver observer) {
+        }
+
+        @Override
+        public void removeObserver(LifecycleObserver observer) {
+        }
+
+        @Override
+        public State getCurrentState() {
+            return RESUMED;
+        }
+    };
+    private static final LifecycleOwner S_LIFECYCLE_OWNER = new LifecycleOwner() {
+
+        @Override
+        public Lifecycle getLifecycle() {
+            return sLifecycle;
+        }
+
+    };
+
+    private final List<String> mLiveDataOutput = new ArrayList<>();
+    private final Observer<String> mObserver = new Observer<String>() {
+        @Override
+        public void onChanged(@Nullable String s) {
+            mLiveDataOutput.add(s);
+        }
+    };
+
+    private final ReplayProcessor<String> mOutputProcessor = ReplayProcessor.create();
+
+    private static final TestScheduler sBackgroundScheduler = new TestScheduler();
+    private Thread mTestThread;
+
+    @Before
+    public void init() {
+        mTestThread = Thread.currentThread();
+        AppToolkitTaskExecutor.getInstance().setDelegate(new TaskExecutor() {
+
+            @Override
+            public void executeOnDiskIO(Runnable runnable) {
+                throw new IllegalStateException();
+            }
+
+            @Override
+            public void postToMainThread(Runnable runnable) {
+                // Wrong implementation, but it is fine for test
+                runnable.run();
+            }
+
+            @Override
+            public boolean isMainThread() {
+                return Thread.currentThread() == mTestThread;
+            }
+
+        });
+    }
+
+    @After
+    public void removeExecutorDelegate() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    @Test
+    public void convertsFromPublisher() {
+        PublishProcessor<String> processor = PublishProcessor.create();
+        LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);
+
+        liveData.observe(S_LIFECYCLE_OWNER, mObserver);
+
+        processor.onNext("foo");
+        processor.onNext("bar");
+        processor.onNext("baz");
+
+        assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
+    }
+
+    @Test
+    public void convertsFromPublisherWithMultipleObservers() {
+        final List<String> output2 = new ArrayList<>();
+        PublishProcessor<String> processor = PublishProcessor.create();
+        LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);
+
+        liveData.observe(S_LIFECYCLE_OWNER, mObserver);
+
+        processor.onNext("foo");
+        processor.onNext("bar");
+
+        // The second mObserver should only get the newest value and any later values.
+        liveData.observe(S_LIFECYCLE_OWNER, new Observer<String>() {
+            @Override
+            public void onChanged(@Nullable String s) {
+                output2.add(s);
+            }
+        });
+
+        processor.onNext("baz");
+
+        assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
+        assertThat(output2, is(Arrays.asList("bar", "baz")));
+    }
+
+    @Test
+    public void convertsFromAsyncPublisher() {
+        Flowable<String> input = Flowable.just("foo")
+                .concatWith(Flowable.just("bar", "baz").observeOn(sBackgroundScheduler));
+        LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(input);
+
+        liveData.observe(S_LIFECYCLE_OWNER, mObserver);
+
+        assertThat(mLiveDataOutput, is(Collections.singletonList("foo")));
+        sBackgroundScheduler.triggerActions();
+        assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
+    }
+
+    @Test
+    public void convertsToPublisherWithSyncData() {
+        MutableLiveData<String> liveData = new MutableLiveData<>();
+        liveData.setValue("foo");
+        assertThat(liveData.getValue(), is("foo"));
+
+        Flowable.fromPublisher(LiveDataReactiveStreams.toPublisher(S_LIFECYCLE_OWNER, liveData))
+                .subscribe(mOutputProcessor);
+
+        liveData.setValue("bar");
+        liveData.setValue("baz");
+
+        assertThat(
+                mOutputProcessor.getValues(new String[]{}),
+                is(new String[] {"foo", "bar", "baz"}));
+    }
+
+    @Test
+    public void convertingToPublisherIsCancelable() {
+        MutableLiveData<String> liveData = new MutableLiveData<>();
+        liveData.setValue("foo");
+        assertThat(liveData.getValue(), is("foo"));
+
+        Disposable disposable = Flowable
+                .fromPublisher(LiveDataReactiveStreams.toPublisher(S_LIFECYCLE_OWNER, liveData))
+                .subscribe(new Consumer<String>() {
+                    @Override
+                    public void accept(String s) throws Exception {
+                        mLiveDataOutput.add(s);
+                    }
+                });
+
+        liveData.setValue("bar");
+        liveData.setValue("baz");
+
+        assertThat(liveData.hasObservers(), is(true));
+        disposable.dispose();
+
+        liveData.setValue("fizz");
+        liveData.setValue("buzz");
+
+        assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
+        // Canceling disposable should also remove livedata mObserver.
+        assertThat(liveData.hasObservers(), is(false));
+    }
+
+    @Test
+    public void convertsToPublisherWithBackpressure() {
+        MutableLiveData<String> liveData = new MutableLiveData<>();
+
+        final AsyncSubject<Subscription> subscriptionSubject = AsyncSubject.create();
+
+        Flowable.fromPublisher(LiveDataReactiveStreams.toPublisher(S_LIFECYCLE_OWNER, liveData))
+                .subscribe(new Subscriber<String>() {
+                    @Override
+                    public void onSubscribe(Subscription s) {
+                        subscriptionSubject.onNext(s);
+                        subscriptionSubject.onComplete();
+                    }
+
+                    @Override
+                    public void onNext(String s) {
+                        mOutputProcessor.onNext(s);
+                    }
+
+                    @Override
+                    public void onError(Throwable t) {
+                        throw new RuntimeException(t);
+                    }
+
+                    @Override
+                    public void onComplete() {
+                    }
+                });
+
+        // Subscription should have happened synchronously. If it didn't, this will deadlock.
+        final Subscription subscription = subscriptionSubject.blockingSingle();
+
+        subscription.request(1);
+        assertThat(mOutputProcessor.getValues(new String[]{}), is(new String[] {}));
+
+        liveData.setValue("foo");
+        assertThat(mOutputProcessor.getValues(new String[]{}), is(new String[] {"foo"}));
+
+        subscription.request(2);
+        liveData.setValue("baz");
+        liveData.setValue("fizz");
+
+        assertThat(
+                mOutputProcessor.getValues(new String[]{}),
+                is(new String[] {"foo", "baz", "fizz"}));
+
+        // 'nyan' will be dropped as there is nothing currently requesting a stream.
+        liveData.setValue("nyan");
+        liveData.setValue("cat");
+
+        assertThat(
+                mOutputProcessor.getValues(new String[]{}),
+                is(new String[] {"foo", "baz", "fizz"}));
+
+        // When a new request comes in, the latest value will be pushed.
+        subscription.request(1);
+        assertThat(
+                mOutputProcessor.getValues(new String[]{}),
+                is(new String[] {"foo", "baz", "fizz", "cat"}));
+    }
+
+    @Test
+    public void convertsToPublisherWithAsyncData() {
+        MutableLiveData<String> liveData = new MutableLiveData<>();
+
+        Flowable.fromPublisher(LiveDataReactiveStreams.toPublisher(S_LIFECYCLE_OWNER, liveData))
+                .observeOn(sBackgroundScheduler)
+                .subscribe(mOutputProcessor);
+
+        liveData.setValue("foo");
+
+        assertThat(mOutputProcessor.getValues(new String[]{}), is(new String[] {}));
+        sBackgroundScheduler.triggerActions();
+        assertThat(mOutputProcessor.getValues(new String[]{}), is(new String[] {"foo"}));
+
+        liveData.setValue("bar");
+        liveData.setValue("baz");
+
+        assertThat(mOutputProcessor.getValues(new String[]{}), is(new String[] {"foo"}));
+        sBackgroundScheduler.triggerActions();
+        assertThat(mOutputProcessor.getValues(
+                new String[]{}),
+                is(new String[] {"foo", "bar", "baz"}));
+    }
+}
diff --git a/lifecycle/runtime/.gitignore b/lifecycle/runtime/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/lifecycle/runtime/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/lifecycle/runtime/build.gradle b/lifecycle/runtime/build.gradle
new file mode 100644
index 0000000..3eb40e4
--- /dev/null
+++ b/lifecycle/runtime/build.gradle
@@ -0,0 +1,48 @@
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+
+    buildTypes.all {
+        consumerProguardFiles 'proguard-rules.pro'
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+}
+
+dependencies {
+    compile project(":lifecycle:common")
+    compile project(":arch:common")
+    // necessary for IJ to resolve dependencies.
+    compile libs.support.annotations
+
+    testCompile libs.junit
+    testCompile libs.mockito_core
+
+    testCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+}
+
+createAndroidCheckstyle(project)
+
+archivesBaseName = "runtime"
diff --git a/lifecycle/runtime/proguard-rules.pro b/lifecycle/runtime/proguard-rules.pro
new file mode 100644
index 0000000..25f3e87
--- /dev/null
+++ b/lifecycle/runtime/proguard-rules.pro
@@ -0,0 +1,16 @@
+-keepattributes *Annotation*
+
+-keepclassmembers enum android.arch.lifecycle.Lifecycle$Event {
+    <fields>;
+}
+
+-keep class * implements android.arch.lifecycle.LifecycleObserver {
+}
+
+-keep class * implements android.arch.lifecycle.GenericLifecycleObserver {
+    <init>(...);
+}
+
+-keepclassmembers class ** {
+    @android.arch.lifecycle.OnLifecycleEvent *;
+}
\ No newline at end of file
diff --git a/lifecycle/runtime/src/main/AndroidManifest.xml b/lifecycle/runtime/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..274a076
--- /dev/null
+++ b/lifecycle/runtime/src/main/AndroidManifest.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.lifecycle">
+</manifest>
diff --git a/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistry.java b/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistry.java
new file mode 100644
index 0000000..b83e6b8
--- /dev/null
+++ b/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistry.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+import static android.arch.lifecycle.Lifecycle.State.CREATED;
+import static android.arch.lifecycle.Lifecycle.State.DESTROYED;
+import static android.arch.lifecycle.Lifecycle.State.INITIALIZED;
+import static android.arch.lifecycle.Lifecycle.State.RESUMED;
+import static android.arch.lifecycle.Lifecycle.State.STARTED;
+
+import android.arch.core.internal.FastSafeIterableMap;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map.Entry;
+
+/**
+ * An implementation of {@link Lifecycle} that can handle multiple observers.
+ * <p>
+ * It is used by Fragments and Support Library Activities. You can also directly use it if you have
+ * a custom LifecycleOwner.
+ */
+public class LifecycleRegistry extends Lifecycle {
+
+    /**
+     * Custom list that keeps observers and can handle removals / additions during traversal.
+     *
+     * Invariant: at any moment of time for observer1 & observer2:
+     * if addition_order(observer1) < addition_order(observer2), then
+     * state(observer1) >= state(observer2),
+     */
+    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
+            new FastSafeIterableMap<>();
+    /**
+     * Current state
+     */
+    private State mState;
+    /**
+     * The provider that owns this Lifecycle.
+     */
+    private final LifecycleOwner mLifecycleOwner;
+
+    private int mAddingObserverCounter = 0;
+
+    private boolean mHandlingEvent = false;
+    private boolean mNewEventOccurred = false;
+
+    // we have to keep it for cases:
+    // void onStart() {
+    //     mRegistry.removeObserver(this);
+    //     mRegistry.add(newObserver);
+    // }
+    // newObserver should be brought only to CREATED state during the execution of
+    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
+    // is no longer in the map.
+    private ArrayList<State> mParentStates = new ArrayList<>();
+
+    /**
+     * Creates a new LifecycleRegistry for the given provider.
+     * <p>
+     * You should usually create this inside your LifecycleOwner class's constructor and hold
+     * onto the same instance.
+     *
+     * @param provider The owner LifecycleOwner
+     */
+    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
+        mLifecycleOwner = provider;
+        mState = INITIALIZED;
+    }
+
+    /**
+     * Only marks the current state as the given value. It doesn't dispatch any event to its
+     * listeners.
+     *
+     * @param state new state
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void markState(State state) {
+        mState = state;
+    }
+
+    /**
+     * Sets the current state and notifies the observers.
+     * <p>
+     * Note that if the {@code currentState} is the same state as the last call to this method,
+     * calling this method has no effect.
+     *
+     * @param event The event that was received
+     */
+    public void handleLifecycleEvent(Lifecycle.Event event) {
+        mState = getStateAfter(event);
+        if (mHandlingEvent || mAddingObserverCounter != 0) {
+            mNewEventOccurred = true;
+            // we will figure out what to do on upper level.
+            return;
+        }
+        mHandlingEvent = true;
+        sync();
+        mHandlingEvent = false;
+    }
+
+    private boolean isSynced() {
+        if (mObserverMap.size() == 0) {
+            return true;
+        }
+        State eldestObserverState = mObserverMap.eldest().getValue().mState;
+        State newestObserverState = mObserverMap.newest().getValue().mState;
+        return eldestObserverState == newestObserverState && mState == newestObserverState;
+    }
+
+    private State calculateTargetState(LifecycleObserver observer) {
+        Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
+
+        State siblingState = previous != null ? previous.getValue().mState : null;
+        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
+                : null;
+        return min(min(mState, siblingState), parentState);
+    }
+
+    @Override
+    public void addObserver(LifecycleObserver observer) {
+        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
+        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
+        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
+
+        if (previous != null) {
+            return;
+        }
+
+        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
+
+        State targetState = calculateTargetState(observer);
+        mAddingObserverCounter++;
+        while ((statefulObserver.mState.compareTo(targetState) < 0
+                && mObserverMap.contains(observer))) {
+            pushParentState(statefulObserver.mState);
+            statefulObserver.dispatchEvent(mLifecycleOwner, upEvent(statefulObserver.mState));
+            popParentState();
+            // mState / subling may have been changed recalculate
+            targetState = calculateTargetState(observer);
+        }
+
+        if (!isReentrance) {
+            // we do sync only on the top level.
+            sync();
+        }
+        mAddingObserverCounter--;
+    }
+
+    private void popParentState() {
+        mParentStates.remove(mParentStates.size() - 1);
+    }
+
+    private void pushParentState(State state) {
+        mParentStates.add(state);
+    }
+
+    @Override
+    public void removeObserver(LifecycleObserver observer) {
+        // we consciously decided not to send destruction events here in opposition to addObserver.
+        // Our reasons for that:
+        // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
+        // actually occurred but earlier.
+        // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
+        // event. If removeObserver method sends destruction events, then a clean up routine becomes
+        // more cumbersome. More specific example of that is: your LifecycleObserver listens for
+        // a web connection, in the usual routine in OnStop method you report to a server that a
+        // session has just ended and you close the connection. Now let's assume now that you
+        // lost an internet and as a result you removed this observer. If you get destruction
+        // events in removeObserver, you should have a special case in your onStop method that
+        // checks if your web connection died and you shouldn't try to report anything to a server.
+        mObserverMap.remove(observer);
+    }
+
+    /**
+     * The number of observers.
+     *
+     * @return The number of observers.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public int getObserverCount() {
+        return mObserverMap.size();
+    }
+
+    @Override
+    public State getCurrentState() {
+        return mState;
+    }
+
+    static State getStateAfter(Event event) {
+        switch (event) {
+            case ON_CREATE:
+            case ON_STOP:
+                return CREATED;
+            case ON_START:
+            case ON_PAUSE:
+                return STARTED;
+            case ON_RESUME:
+                return RESUMED;
+            case ON_DESTROY:
+                return DESTROYED;
+            case ON_ANY:
+                break;
+        }
+        throw new IllegalArgumentException("Unexpected event value " + event);
+    }
+
+    private static Event downEvent(State state) {
+        switch (state) {
+            case INITIALIZED:
+                throw new IllegalArgumentException();
+            case CREATED:
+                return ON_DESTROY;
+            case STARTED:
+                return ON_STOP;
+            case RESUMED:
+                return ON_PAUSE;
+            case DESTROYED:
+                throw new IllegalArgumentException();
+        }
+        throw new IllegalArgumentException("Unexpected state value " + state);
+    }
+
+    private static Event upEvent(State state) {
+        switch (state) {
+            case INITIALIZED:
+            case DESTROYED:
+                return ON_CREATE;
+            case CREATED:
+                return ON_START;
+            case STARTED:
+                return ON_RESUME;
+            case RESUMED:
+                throw new IllegalArgumentException();
+        }
+        throw new IllegalArgumentException("Unexpected state value " + state);
+    }
+
+    private void forwardPass() {
+        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
+                mObserverMap.iteratorWithAdditions();
+        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
+            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
+            ObserverWithState observer = entry.getValue();
+            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
+                    && mObserverMap.contains(entry.getKey()))) {
+                pushParentState(observer.mState);
+                observer.dispatchEvent(mLifecycleOwner, upEvent(observer.mState));
+                popParentState();
+            }
+        }
+    }
+
+    private void backwardPass() {
+        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
+                mObserverMap.descendingIterator();
+        while (descendingIterator.hasNext() && !mNewEventOccurred) {
+            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
+            ObserverWithState observer = entry.getValue();
+            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
+                    && mObserverMap.contains(entry.getKey()))) {
+                Event event = downEvent(observer.mState);
+                pushParentState(getStateAfter(event));
+                observer.dispatchEvent(mLifecycleOwner, event);
+                popParentState();
+            }
+        }
+    }
+
+    // happens only on the top of stack (never in reentrance),
+    // so it doesn't have to take in account parents
+    private void sync() {
+        while (!isSynced()) {
+            mNewEventOccurred = false;
+            // no need to check eldest for nullability, because isSynced does it for us.
+            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
+                backwardPass();
+            }
+            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
+            if (!mNewEventOccurred && newest != null
+                    && mState.compareTo(newest.getValue().mState) > 0) {
+                forwardPass();
+            }
+        }
+        mNewEventOccurred = false;
+    }
+
+    static State min(@NonNull State state1, @Nullable State state2) {
+        return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
+    }
+
+    static class ObserverWithState {
+        State mState;
+        GenericLifecycleObserver mLifecycleObserver;
+
+        ObserverWithState(LifecycleObserver observer, State initialState) {
+            mLifecycleObserver = Lifecycling.getCallback(observer);
+            mState = initialState;
+        }
+
+        void dispatchEvent(LifecycleOwner owner, Event event) {
+            State newState = getStateAfter(event);
+            mState = min(mState, newState);
+            mLifecycleObserver.onStateChanged(owner, event);
+            mState = newState;
+        }
+    }
+}
diff --git a/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistryOwner.java b/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistryOwner.java
new file mode 100644
index 0000000..634cfc3
--- /dev/null
+++ b/lifecycle/runtime/src/main/java/android/arch/lifecycle/LifecycleRegistryOwner.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+/**
+ * Specialization of {@link LifecycleOwner} that explicitly returns {@link LifecycleRegistry}.
+ * <p>
+ * This method may be used if an object which updates state of {@link Lifecycle} doesn't own it.
+ * <p>
+ * This class is a temporary implementation detail until Lifecycles are integrated with support
+ * library.
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public interface LifecycleRegistryOwner extends LifecycleOwner {
+    @Override
+    LifecycleRegistry getLifecycle();
+}
diff --git a/lifecycle/runtime/src/main/java/android/arch/lifecycle/ReportFragment.java b/lifecycle/runtime/src/main/java/android/arch/lifecycle/ReportFragment.java
new file mode 100644
index 0000000..490028c
--- /dev/null
+++ b/lifecycle/runtime/src/main/java/android/arch/lifecycle/ReportFragment.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.os.Bundle;
+import android.support.annotation.RestrictTo;
+
+/**
+ * Internal class that dispatches initialization events.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class ReportFragment extends Fragment {
+
+    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+            + ".LifecycleDispatcher.report_fragment_tag";
+
+    public static void injectIfNeededIn(Activity activity) {
+        // ProcessLifecycleOwner should always correctly work and some activities may not extend
+        // FragmentActivity from support lib, so we use framework fragments for activities
+        android.app.FragmentManager manager = activity.getFragmentManager();
+        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
+            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
+            // Hopefully, we are the first to make a transaction.
+            manager.executePendingTransactions();
+        }
+    }
+
+    static ReportFragment get(Activity activity) {
+        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
+                REPORT_FRAGMENT_TAG);
+    }
+
+    private ActivityInitializationListener mProcessListener;
+
+    private void dispatchCreate(ActivityInitializationListener listener) {
+        if (listener != null) {
+            listener.onCreate();
+        }
+    }
+
+    private void dispatchStart(ActivityInitializationListener listener) {
+        if (listener != null) {
+            listener.onStart();
+        }
+    }
+
+    private void dispatchResume(ActivityInitializationListener listener) {
+        if (listener != null) {
+            listener.onResume();
+        }
+    }
+
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+        dispatchCreate(mProcessListener);
+        dispatch(Lifecycle.Event.ON_CREATE);
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        dispatchStart(mProcessListener);
+        dispatch(Lifecycle.Event.ON_START);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        dispatchResume(mProcessListener);
+        dispatch(Lifecycle.Event.ON_RESUME);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        dispatch(Lifecycle.Event.ON_PAUSE);
+    }
+
+    @Override
+    public void onStop() {
+        super.onStop();
+        dispatch(Lifecycle.Event.ON_STOP);
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        dispatch(Lifecycle.Event.ON_DESTROY);
+        // just want to be sure that we won't leak reference to an activity
+        mProcessListener = null;
+    }
+
+    private void dispatch(Lifecycle.Event event) {
+        if (getActivity() instanceof LifecycleRegistryOwner) {
+            ((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
+        }
+    }
+
+    void setProcessListener(ActivityInitializationListener processListener) {
+        mProcessListener = processListener;
+    }
+
+    interface ActivityInitializationListener {
+        void onCreate();
+
+        void onStart();
+
+        void onResume();
+    }
+}
diff --git a/lifecycle/runtime/src/test/java/android/arch/lifecycle/LifecycleRegistryTest.java b/lifecycle/runtime/src/test/java/android/arch/lifecycle/LifecycleRegistryTest.java
new file mode 100644
index 0000000..ef498ee
--- /dev/null
+++ b/lifecycle/runtime/src/test/java/android/arch/lifecycle/LifecycleRegistryTest.java
@@ -0,0 +1,608 @@
+/*
+ * Copyright (C) 2017 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 android.arch.lifecycle;
+
+import static android.arch.lifecycle.Lifecycle.Event.ON_CREATE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_DESTROY;
+import static android.arch.lifecycle.Lifecycle.Event.ON_PAUSE;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static android.arch.lifecycle.Lifecycle.Event.ON_START;
+import static android.arch.lifecycle.Lifecycle.Event.ON_STOP;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.support.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.InOrder;
+
+@RunWith(JUnit4.class)
+@SmallTest
+public class LifecycleRegistryTest {
+    private LifecycleOwner mLifecycleOwner;
+    private Lifecycle mLifecycle;
+    private LifecycleRegistry mRegistry;
+
+    @Before
+    public void init() {
+        mLifecycleOwner = mock(LifecycleOwner.class);
+        mLifecycle = mock(Lifecycle.class);
+        when(mLifecycleOwner.getLifecycle()).thenReturn(mLifecycle);
+        mRegistry = new LifecycleRegistry(mLifecycleOwner);
+    }
+
+    @Test
+    public void addRemove() {
+        LifecycleObserver observer = mock(LifecycleObserver.class);
+        mRegistry.addObserver(observer);
+        assertThat(mRegistry.getObserverCount(), is(1));
+        mRegistry.removeObserver(observer);
+        assertThat(mRegistry.getObserverCount(), is(0));
+    }
+
+    @Test
+    public void addGenericAndObserve() {
+        GenericLifecycleObserver generic = mock(GenericLifecycleObserver.class);
+        mRegistry.addObserver(generic);
+        dispatchEvent(ON_CREATE);
+        verify(generic).onStateChanged(mLifecycleOwner, ON_CREATE);
+        reset(generic);
+        dispatchEvent(ON_CREATE);
+        verify(generic, never()).onStateChanged(mLifecycleOwner, ON_CREATE);
+    }
+
+    @Test
+    public void addRegularClass() {
+        TestObserver testObserver = mock(TestObserver.class);
+        mRegistry.addObserver(testObserver);
+        dispatchEvent(ON_START);
+        verify(testObserver, never()).onStop();
+        dispatchEvent(ON_STOP);
+        verify(testObserver).onStop();
+    }
+
+    @Test
+    public void add2RemoveOne() {
+        TestObserver observer1 = mock(TestObserver.class);
+        TestObserver observer2 = mock(TestObserver.class);
+        TestObserver observer3 = mock(TestObserver.class);
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        mRegistry.addObserver(observer3);
+
+        dispatchEvent(ON_CREATE);
+
+        verify(observer1).onCreate();
+        verify(observer2).onCreate();
+        verify(observer3).onCreate();
+        reset(observer1, observer2, observer3);
+
+        mRegistry.removeObserver(observer2);
+        dispatchEvent(ON_START);
+
+        verify(observer1).onStart();
+        verify(observer2, never()).onStart();
+        verify(observer3).onStart();
+    }
+
+    @Test
+    public void removeWhileTraversing() {
+        final TestObserver observer2 = mock(TestObserver.class);
+        TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            public void onCreate() {
+                mRegistry.removeObserver(observer2);
+            }
+        });
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        dispatchEvent(ON_CREATE);
+        verify(observer2, never()).onCreate();
+        verify(observer1).onCreate();
+    }
+
+    @Test
+    public void constructionOrder() {
+        fullyInitializeRegistry();
+        final TestObserver observer = mock(TestObserver.class);
+        mRegistry.addObserver(observer);
+        InOrder inOrder = inOrder(observer);
+        inOrder.verify(observer).onCreate();
+        inOrder.verify(observer).onStart();
+        inOrder.verify(observer).onResume();
+    }
+
+    @Test
+    public void constructionDestruction1() {
+        fullyInitializeRegistry();
+        final TestObserver observer = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                dispatchEvent(ON_PAUSE);
+            }
+        });
+        mRegistry.addObserver(observer);
+        InOrder constructionOrder = inOrder(observer);
+        constructionOrder.verify(observer).onCreate();
+        constructionOrder.verify(observer).onStart();
+        constructionOrder.verify(observer, never()).onResume();
+    }
+
+    @Test
+    public void constructionDestruction2() {
+        fullyInitializeRegistry();
+        final TestObserver observer = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                dispatchEvent(ON_PAUSE);
+                dispatchEvent(ON_STOP);
+                dispatchEvent(ON_DESTROY);
+            }
+        });
+        mRegistry.addObserver(observer);
+        InOrder orderVerifier = inOrder(observer);
+        orderVerifier.verify(observer).onCreate();
+        orderVerifier.verify(observer).onStart();
+        orderVerifier.verify(observer).onStop();
+        orderVerifier.verify(observer).onDestroy();
+        orderVerifier.verify(observer, never()).onResume();
+    }
+
+    @Test
+    public void twoObserversChangingState() {
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onCreate() {
+                dispatchEvent(ON_START);
+            }
+        });
+        final TestObserver observer2 = mock(TestObserver.class);
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        dispatchEvent(ON_CREATE);
+        verify(observer1, times(1)).onCreate();
+        verify(observer2, times(1)).onCreate();
+        verify(observer1, times(1)).onStart();
+        verify(observer2, times(1)).onStart();
+    }
+
+    @Test
+    public void addDuringTraversing() {
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            public void onStart() {
+                mRegistry.addObserver(observer3);
+            }
+        });
+        final TestObserver observer2 = mock(TestObserver.class);
+
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+
+        dispatchEvent(ON_CREATE);
+        dispatchEvent(ON_START);
+
+        InOrder inOrder = inOrder(observer1, observer2, observer3);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer3).onStart();
+    }
+
+    @Test
+    public void addDuringAddition() {
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer2 = spy(new TestObserver() {
+            @Override
+            public void onCreate() {
+                mRegistry.addObserver(observer3);
+            }
+        });
+
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            public void onResume() {
+                mRegistry.addObserver(observer2);
+            }
+        });
+
+        mRegistry.addObserver(observer1);
+
+        dispatchEvent(ON_CREATE);
+        dispatchEvent(ON_START);
+        dispatchEvent(ON_RESUME);
+
+        InOrder inOrder = inOrder(observer1, observer2, observer3);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer2).onResume();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer3).onResume();
+    }
+
+    @Test
+    public void subscribeToDead() {
+        dispatchEvent(ON_CREATE);
+        final TestObserver observer1 = mock(TestObserver.class);
+        mRegistry.addObserver(observer1);
+        verify(observer1).onCreate();
+        dispatchEvent(ON_DESTROY);
+        verify(observer1).onDestroy();
+        final TestObserver observer2 = mock(TestObserver.class);
+        mRegistry.addObserver(observer2);
+        verify(observer2, never()).onCreate();
+        reset(observer1);
+        dispatchEvent(ON_CREATE);
+        verify(observer1).onCreate();
+        verify(observer2).onCreate();
+    }
+
+    @Test
+    public void downEvents() {
+        fullyInitializeRegistry();
+        final TestObserver observer1 = mock(TestObserver.class);
+        final TestObserver observer2 = mock(TestObserver.class);
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        InOrder orderVerifier = inOrder(observer1, observer2);
+        dispatchEvent(ON_PAUSE);
+        orderVerifier.verify(observer2).onPause();
+        orderVerifier.verify(observer1).onPause();
+        dispatchEvent(ON_STOP);
+        orderVerifier.verify(observer2).onStop();
+        orderVerifier.verify(observer1).onStop();
+        dispatchEvent(ON_DESTROY);
+        orderVerifier.verify(observer2).onDestroy();
+        orderVerifier.verify(observer1).onDestroy();
+    }
+
+    @Test
+    public void downEventsAddition() {
+        dispatchEvent(ON_CREATE);
+        dispatchEvent(ON_START);
+        final TestObserver observer1 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer2 = spy(new TestObserver() {
+            @Override
+            void onStop() {
+                mRegistry.addObserver(observer3);
+            }
+        });
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        InOrder orderVerifier = inOrder(observer1, observer2, observer3);
+        dispatchEvent(ON_STOP);
+        orderVerifier.verify(observer2).onStop();
+        orderVerifier.verify(observer3).onCreate();
+        orderVerifier.verify(observer1).onStop();
+        dispatchEvent(ON_DESTROY);
+        orderVerifier.verify(observer3).onDestroy();
+        orderVerifier.verify(observer2).onDestroy();
+        orderVerifier.verify(observer1).onDestroy();
+    }
+
+    @Test
+    public void downEventsRemoveAll() {
+        fullyInitializeRegistry();
+        final TestObserver observer1 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer2 = spy(new TestObserver() {
+            @Override
+            void onStop() {
+                mRegistry.removeObserver(observer3);
+                mRegistry.removeObserver(this);
+                mRegistry.removeObserver(observer1);
+                assertThat(mRegistry.getObserverCount(), is(0));
+            }
+        });
+        mRegistry.addObserver(observer1);
+        mRegistry.addObserver(observer2);
+        mRegistry.addObserver(observer3);
+        InOrder orderVerifier = inOrder(observer1, observer2, observer3);
+        dispatchEvent(ON_PAUSE);
+        orderVerifier.verify(observer3).onPause();
+        orderVerifier.verify(observer2).onPause();
+        orderVerifier.verify(observer1).onPause();
+        dispatchEvent(ON_STOP);
+        orderVerifier.verify(observer3).onStop();
+        orderVerifier.verify(observer2).onStop();
+        orderVerifier.verify(observer1, never()).onStop();
+        dispatchEvent(ON_PAUSE);
+        orderVerifier.verify(observer3, never()).onPause();
+        orderVerifier.verify(observer2, never()).onPause();
+        orderVerifier.verify(observer1, never()).onPause();
+    }
+
+    @Test
+    public void deadParentInAddition() {
+        fullyInitializeRegistry();
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+
+        TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.removeObserver(this);
+                assertThat(mRegistry.getObserverCount(), is(0));
+                mRegistry.addObserver(observer2);
+                mRegistry.addObserver(observer3);
+            }
+        });
+
+        mRegistry.addObserver(observer1);
+
+        InOrder inOrder = inOrder(observer1, observer2, observer3);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer2).onResume();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer3).onResume();
+    }
+
+    @Test
+    public void deadParentWhileTraversing() {
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+        TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.removeObserver(this);
+                assertThat(mRegistry.getObserverCount(), is(0));
+                mRegistry.addObserver(observer2);
+                mRegistry.addObserver(observer3);
+            }
+        });
+        InOrder inOrder = inOrder(observer1, observer2, observer3);
+        mRegistry.addObserver(observer1);
+        dispatchEvent(ON_CREATE);
+        dispatchEvent(ON_START);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer3).onStart();
+    }
+
+    @Test
+    public void removeCascade() {
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer4 = mock(TestObserver.class);
+
+        final TestObserver observer2 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.removeObserver(this);
+            }
+        });
+
+        TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onResume() {
+                mRegistry.removeObserver(this);
+                mRegistry.addObserver(observer2);
+                mRegistry.addObserver(observer3);
+                mRegistry.addObserver(observer4);
+            }
+        });
+        fullyInitializeRegistry();
+        mRegistry.addObserver(observer1);
+        InOrder inOrder = inOrder(observer1, observer2, observer3, observer4);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer4).onCreate();
+        inOrder.verify(observer4).onStart();
+        inOrder.verify(observer3).onResume();
+        inOrder.verify(observer4).onResume();
+    }
+
+    @Test
+    public void changeStateDuringDescending() {
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onPause() {
+                // but tonight I bounce back
+                mRegistry.handleLifecycleEvent(ON_RESUME);
+                mRegistry.addObserver(observer2);
+            }
+        });
+        fullyInitializeRegistry();
+        mRegistry.addObserver(observer1);
+        mRegistry.handleLifecycleEvent(ON_PAUSE);
+        InOrder inOrder = inOrder(observer1, observer2);
+        inOrder.verify(observer1).onPause();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer2).onResume();
+    }
+
+    @Test
+    public void siblingLimitationCheck() {
+        fullyInitializeRegistry();
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.addObserver(observer2);
+            }
+
+            @Override
+            void onResume() {
+                mRegistry.addObserver(observer3);
+            }
+        });
+        mRegistry.addObserver(observer1);
+        InOrder inOrder = inOrder(observer1, observer2, observer3);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer2).onStart();
+        inOrder.verify(observer2).onResume();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer3).onResume();
+    }
+
+    @Test
+    public void siblingRemovalLimitationCheck1() {
+        fullyInitializeRegistry();
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer3 = mock(TestObserver.class);
+        final TestObserver observer4 = mock(TestObserver.class);
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.addObserver(observer2);
+            }
+
+            @Override
+            void onResume() {
+                mRegistry.removeObserver(observer2);
+                mRegistry.addObserver(observer3);
+                mRegistry.addObserver(observer4);
+            }
+        });
+        mRegistry.addObserver(observer1);
+        InOrder inOrder = inOrder(observer1, observer2, observer3, observer4);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer4).onCreate();
+        inOrder.verify(observer4).onStart();
+        inOrder.verify(observer3).onResume();
+        inOrder.verify(observer4).onResume();
+    }
+
+    @Test
+    public void siblingRemovalLimitationCheck2() {
+        fullyInitializeRegistry();
+        final TestObserver observer2 = mock(TestObserver.class);
+        final TestObserver observer3 = spy(new TestObserver() {
+            @Override
+            void onCreate() {
+                mRegistry.removeObserver(observer2);
+            }
+        });
+        final TestObserver observer4 = mock(TestObserver.class);
+        final TestObserver observer1 = spy(new TestObserver() {
+            @Override
+            void onStart() {
+                mRegistry.addObserver(observer2);
+            }
+
+            @Override
+            void onResume() {
+                mRegistry.addObserver(observer3);
+                mRegistry.addObserver(observer4);
+            }
+        });
+
+        mRegistry.addObserver(observer1);
+        InOrder inOrder = inOrder(observer1, observer2, observer3, observer4);
+        inOrder.verify(observer1).onCreate();
+        inOrder.verify(observer1).onStart();
+        inOrder.verify(observer2).onCreate();
+        inOrder.verify(observer1).onResume();
+        inOrder.verify(observer3).onCreate();
+        inOrder.verify(observer3).onStart();
+        inOrder.verify(observer4).onCreate();
+        inOrder.verify(observer4).onStart();
+        inOrder.verify(observer3).onResume();
+        inOrder.verify(observer4).onResume();
+    }
+
+    @Test
+    public void sameObserverReAddition() {
+        TestObserver observer = mock(TestObserver.class);
+        mRegistry.addObserver(observer);
+        mRegistry.removeObserver(observer);
+        mRegistry.addObserver(observer);
+        dispatchEvent(ON_CREATE);
+        verify(observer).onCreate();
+    }
+
+    private void dispatchEvent(Lifecycle.Event event) {
+        when(mLifecycle.getCurrentState()).thenReturn(LifecycleRegistry.getStateAfter(event));
+        mRegistry.handleLifecycleEvent(event);
+    }
+
+    private void fullyInitializeRegistry() {
+        dispatchEvent(ON_CREATE);
+        dispatchEvent(ON_START);
+        dispatchEvent(ON_RESUME);
+    }
+
+    private abstract class TestObserver implements LifecycleObserver {
+        @OnLifecycleEvent(ON_CREATE)
+        void onCreate() {
+        }
+
+        @OnLifecycleEvent(ON_START)
+        void onStart() {
+        }
+
+        @OnLifecycleEvent(ON_RESUME)
+        void onResume() {
+        }
+
+        @OnLifecycleEvent(ON_PAUSE)
+        void onPause() {
+        }
+
+        @OnLifecycleEvent(ON_STOP)
+        void onStop() {
+        }
+
+        @OnLifecycleEvent(ON_DESTROY)
+        void onDestroy() {
+        }
+    }
+}
diff --git a/makeFlatfootRepo.sh b/makeFlatfootRepo.sh
new file mode 100755
index 0000000..1e5e817
--- /dev/null
+++ b/makeFlatfootRepo.sh
@@ -0,0 +1,3 @@
+# temporary script to make flatfoot repo, next to the support repo
+cd lifecycle && ./gradlew uploadArchives --info
+cd ../room && ./gradlew uploadArchives --info
diff --git a/media-compat/api21/android/support/v4/media/session/MediaSessionCompatApi21.java b/media-compat/api21/android/support/v4/media/session/MediaSessionCompatApi21.java
index ad9727d..698e37d 100644
--- a/media-compat/api21/android/support/v4/media/session/MediaSessionCompatApi21.java
+++ b/media-compat/api21/android/support/v4/media/session/MediaSessionCompatApi21.java
@@ -167,6 +167,7 @@
         void onStop();
         void onSeekTo(long position);
         void onSetRating(Object ratingObject);
+        void onSetRating(Object ratingObject, Bundle extras);
         void onCustomAction(String action, Bundle extras);
     }
 
diff --git a/media-compat/build.gradle b/media-compat/build.gradle
index edc51d7..f4e3839 100644
--- a/media-compat/build.gradle
+++ b/media-compat/build.gradle
@@ -2,19 +2,18 @@
 archivesBaseName = 'support-media-compat'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
+    api project(':support-annotations')
+    api project(':support-compat')
 
-    androidTestCompile(libs.test_runner) {
+    androidTestImplementation(libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile(libs.espresso_core) {
+    androidTestImplementation(libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile(libs.mockito_core)
-    androidTestCompile(libs.dexmaker)
-    androidTestCompile(libs.dexmaker_mockito)
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
@@ -33,6 +32,7 @@
                 'java'
         ]
         main.aidl.srcDirs = ['java']
+        main.res.srcDirs 'res', 'res-public'
     }
 
     buildTypes.all {
diff --git a/media-compat/java/android/support/v4/media/MediaBrowserCompat.java b/media-compat/java/android/support/v4/media/MediaBrowserCompat.java
index 98d6452..7116464 100644
--- a/media-compat/java/android/support/v4/media/MediaBrowserCompat.java
+++ b/media-compat/java/android/support/v4/media/MediaBrowserCompat.java
@@ -24,7 +24,8 @@
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_REMOVE_SUBSCRIPTION;
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_SEARCH;
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_SEND_CUSTOM_ACTION;
-import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER;
+import static android.support.v4.media.MediaBrowserProtocol
+        .CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER;
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_VERSION_CURRENT;
 import static android.support.v4.media.MediaBrowserProtocol.DATA_CALLBACK_TOKEN;
 import static android.support.v4.media.MediaBrowserProtocol.DATA_CUSTOM_ACTION;
@@ -69,7 +70,6 @@
 import android.support.v4.media.session.IMediaSession;
 import android.support.v4.media.session.MediaControllerCompat.TransportControls;
 import android.support.v4.media.session.MediaSessionCompat;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.os.ResultReceiver;
 import android.support.v4.util.ArrayMap;
 import android.text.TextUtils;
@@ -181,7 +181,7 @@
             ConnectionCallback callback, Bundle rootHints) {
         // To workaround an issue of {@link #unsubscribe(String, SubscriptionCallback)} on API 24
         // and 25 devices, use the support library version of implementation on those devices.
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             mImpl = new MediaBrowserImplApi24(context, serviceComponent, callback, rootHints);
         } else if (Build.VERSION.SDK_INT >= 23) {
             mImpl = new MediaBrowserImplApi23(context, serviceComponent, callback, rootHints);
@@ -676,7 +676,7 @@
         WeakReference<Subscription> mSubscriptionRef;
 
         public SubscriptionCallback() {
-            if (BuildCompat.isAtLeastO()) {
+            if (Build.VERSION.SDK_INT >= 26) {
                 mSubscriptionCallbackObj =
                         MediaBrowserCompatApi24.createSubscriptionCallback(new StubApi24());
                 mToken = null;
@@ -945,9 +945,10 @@
         void subscribe(@NonNull String parentId, Bundle options,
                 @NonNull SubscriptionCallback callback);
         void unsubscribe(@NonNull String parentId, SubscriptionCallback callback);
-        void getItem(final @NonNull String mediaId, @NonNull final ItemCallback cb);
+        void getItem(@NonNull String mediaId, @NonNull ItemCallback cb);
         void search(@NonNull String query, Bundle extras, @NonNull SearchCallback callback);
-        void sendCustomAction(String action, Bundle extras, final CustomActionCallback callback);
+        void sendCustomAction(@NonNull String action, Bundle extras,
+                @Nullable CustomActionCallback callback);
     }
 
     interface MediaBrowserServiceCallbackImpl {
@@ -1163,7 +1164,7 @@
                 mSubscriptions.put(parentId, sub);
             }
             Bundle copiedOptions = options == null ? null : new Bundle(options);
-            sub.putCallback(copiedOptions, callback);
+            sub.putCallback(mContext, copiedOptions, callback);
 
             // If we are connected, tell the service that we are watching. If we aren't
             // connected, the service will be told when we connect.
@@ -1289,12 +1290,14 @@
             } catch (RemoteException e) {
                 Log.i(TAG, "Remote error sending a custom action: action=" + action + ", extras="
                         + extras, e);
-                mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        callback.onError(action, extras, null);
-                    }
-                });
+                if (callback != null) {
+                    mHandler.post(new Runnable() {
+                        @Override
+                        public void run() {
+                            callback.onError(action, extras, null);
+                        }
+                    });
+                }
             }
         }
 
@@ -1387,7 +1390,7 @@
             }
 
             // Tell the app.
-            SubscriptionCallback subscriptionCallback = subscription.getCallback(options);
+            SubscriptionCallback subscriptionCallback = subscription.getCallback(mContext, options);
             if (subscriptionCallback != null) {
                 if (options == null) {
                     if (list == null) {
@@ -1574,6 +1577,7 @@
     @RequiresApi(21)
     static class MediaBrowserImplApi21 implements MediaBrowserImpl, MediaBrowserServiceCallbackImpl,
             ConnectionCallback.ConnectionCallbackInternal {
+        final Context mContext;
         protected final Object mBrowserObj;
         protected final Bundle mRootHints;
         protected final CallbackHandler mHandler = new CallbackHandler(this);
@@ -1585,6 +1589,7 @@
 
         public MediaBrowserImplApi21(Context context, ComponentName serviceComponent,
                 ConnectionCallback callback, Bundle rootHints) {
+            mContext = context;
             if (rootHints == null) {
                 rootHints = new Bundle();
             }
@@ -1655,7 +1660,7 @@
             }
             callback.setSubscription(sub);
             Bundle copiedOptions = options == null ? null : new Bundle(options);
-            sub.putCallback(copiedOptions, callback);
+            sub.putCallback(mContext, copiedOptions, callback);
 
             if (mServiceBinderWrapper == null) {
                 // TODO: When MediaBrowser is connected to framework's MediaBrowserService,
@@ -1803,8 +1808,8 @@
         }
 
         @Override
-        public void sendCustomAction(final String action, final Bundle extras,
-                final CustomActionCallback callback) {
+        public void sendCustomAction(@NonNull final String action, final Bundle extras,
+                @Nullable final CustomActionCallback callback) {
             if (!isConnected()) {
                 throw new IllegalStateException("Cannot send a custom action (" + action + ") with "
                         + "extras " + extras + " because the browser is not connected to the "
@@ -1812,12 +1817,14 @@
             }
             if (mServiceBinderWrapper == null) {
                 Log.i(TAG, "The connected service doesn't support sendCustomAction.");
-                mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        callback.onError(action, extras, null);
-                    }
-                });
+                if (callback != null) {
+                    mHandler.post(new Runnable() {
+                        @Override
+                        public void run() {
+                            callback.onError(action, extras, null);
+                        }
+                    });
+                }
             }
 
             ResultReceiver receiver = new CustomActionResultReceiver(action, extras, callback,
@@ -1828,12 +1835,14 @@
             } catch (RemoteException e) {
                 Log.i(TAG, "Remote error sending a custom action: action=" + action + ", extras="
                         + extras, e);
-                mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        callback.onError(action, extras, null);
-                    }
-                });
+                if (callback != null) {
+                    mHandler.post(new Runnable() {
+                        @Override
+                        public void run() {
+                            callback.onError(action, extras, null);
+                        }
+                    });
+                }
             }
         }
 
@@ -1903,7 +1912,7 @@
             }
 
             // Tell the app.
-            SubscriptionCallback subscriptionCallback = subscription.getCallback(options);
+            SubscriptionCallback subscriptionCallback = subscription.getCallback(mContext, options);
             if (subscriptionCallback != null) {
                 if (options == null) {
                     if (list == null) {
@@ -1991,7 +2000,10 @@
             return mCallbacks;
         }
 
-        public SubscriptionCallback getCallback(Bundle options) {
+        public SubscriptionCallback getCallback(Context context, Bundle options) {
+            if (options != null) {
+                options.setClassLoader(context.getClassLoader());
+            }
             for (int i = 0; i < mOptionsList.size(); ++i) {
                 if (MediaBrowserCompatUtils.areSameOptions(mOptionsList.get(i), options)) {
                     return mCallbacks.get(i);
@@ -2000,7 +2012,10 @@
             return null;
         }
 
-        public void putCallback(Bundle options, SubscriptionCallback callback) {
+        public void putCallback(Context context, Bundle options, SubscriptionCallback callback) {
+            if (options != null) {
+                options.setClassLoader(context.getClassLoader());
+            }
             for (int i = 0; i < mOptionsList.size(); ++i) {
                 if (MediaBrowserCompatUtils.areSameOptions(mOptionsList.get(i), options)) {
                     mCallbacks.set(i, callback);
diff --git a/media-compat/java/android/support/v4/media/MediaBrowserServiceCompat.java b/media-compat/java/android/support/v4/media/MediaBrowserServiceCompat.java
index 12617b7..7c4c761 100644
--- a/media-compat/java/android/support/v4/media/MediaBrowserServiceCompat.java
+++ b/media-compat/java/android/support/v4/media/MediaBrowserServiceCompat.java
@@ -25,7 +25,8 @@
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_REMOVE_SUBSCRIPTION;
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_SEARCH;
 import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_SEND_CUSTOM_ACTION;
-import static android.support.v4.media.MediaBrowserProtocol.CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER;
+import static android.support.v4.media.MediaBrowserProtocol
+        .CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER;
 import static android.support.v4.media.MediaBrowserProtocol.DATA_CALLBACK_TOKEN;
 import static android.support.v4.media.MediaBrowserProtocol.DATA_CALLING_UID;
 import static android.support.v4.media.MediaBrowserProtocol.DATA_CUSTOM_ACTION;
@@ -68,7 +69,6 @@
 import android.support.v4.app.BundleCompat;
 import android.support.v4.media.session.IMediaSession;
 import android.support.v4.media.session.MediaSessionCompat;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.os.ResultReceiver;
 import android.support.v4.util.ArrayMap;
 import android.support.v4.util.Pair;
@@ -977,7 +977,7 @@
     @Override
     public void onCreate() {
         super.onCreate();
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             mImpl = new MediaBrowserServiceImplApi24();
         } else if (Build.VERSION.SDK_INT >= 23) {
             mImpl = new MediaBrowserServiceImplApi23();
diff --git a/media-compat/java/android/support/v4/media/app/NotificationCompat.java b/media-compat/java/android/support/v4/media/app/NotificationCompat.java
new file mode 100644
index 0000000..be1d423
--- /dev/null
+++ b/media-compat/java/android/support/v4/media/app/NotificationCompat.java
@@ -0,0 +1,502 @@
+/*
+ * Copyright (C) 2017 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 android.support.v4.media.app;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+import static android.support.v4.app.NotificationCompat.COLOR_DEFAULT;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.media.session.MediaSession;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.support.annotation.RequiresApi;
+import android.support.annotation.RestrictTo;
+import android.support.mediacompat.R;
+import android.support.v4.app.BundleCompat;
+import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
+import android.support.v4.media.session.MediaSessionCompat;
+import android.view.View;
+import android.widget.RemoteViews;
+
+/**
+ * Class containing media specfic {@link android.support.v4.app.NotificationCompat.Style styles}
+ * that you can use with {@link android.support.v4.app.NotificationCompat.Builder#setStyle}.
+ */
+public class NotificationCompat {
+
+    private NotificationCompat() {
+    }
+
+    /**
+     * Notification style for media playback notifications.
+     *
+     * In the expanded form, up to 5
+     * {@link android.support.v4.app.NotificationCompat.Action actions} specified with
+     * {@link android.support.v4.app.NotificationCompat.Builder
+     * #addAction(int, CharSequence, PendingIntent) addAction} will be shown as icon-only
+     * pushbuttons, suitable for transport controls. The Bitmap given to
+     * {@link android.support.v4.app.NotificationCompat.Builder
+     * #setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will
+     * be treated as album artwork.
+     *
+     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
+     * content view; by providing action indices to
+     * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed
+     * in the standard view alongside the usual content.
+     *
+     * Notifications created with MediaStyle will have their category set to
+     * {@link android.support.v4.app.NotificationCompat#CATEGORY_TRANSPORT CATEGORY_TRANSPORT}
+     * unless you set a different category using
+     * {@link android.support.v4.app.NotificationCompat.Builder#setCategory(String)
+     * setCategory()}.
+     *
+     * Finally, if you attach a {@link MediaSession.Token} using
+     * {@link android.support.v4.media.app.NotificationCompat.MediaStyle#setMediaSession}, the
+     * System UI can identify this as a notification representing an active media session and
+     * respond accordingly (by showing album artwork in the lockscreen, for example).
+     *
+     * To use this style with your Notification, feed it to
+     * {@link android.support.v4.app.NotificationCompat.Builder#setStyle} like so:
+     * <pre class="prettyprint">
+     * Notification noti = new NotificationCompat.Builder()
+     *     .setSmallIcon(R.drawable.ic_stat_player)
+     *     .setContentTitle(&quot;Track title&quot;)
+     *     .setContentText(&quot;Artist - Album&quot;)
+     *     .setLargeIcon(albumArtBitmap))
+     *     .setStyle(<b>new NotificationCompat.MediaStyle()</b>
+     *         .setMediaSession(mySession))
+     *     .build();
+     * </pre>
+     *
+     * @see Notification#bigContentView
+     */
+    public static class MediaStyle extends android.support.v4.app.NotificationCompat.Style {
+
+        /**
+         * Extracts a {@link MediaSessionCompat.Token} from the extra values
+         * in the {@link MediaStyle} {@link Notification notification}.
+         *
+         * @param notification The notification to extract a {@link MediaSessionCompat.Token} from.
+         * @return The {@link MediaSessionCompat.Token} in the {@code notification} if it contains,
+         *         null otherwise.
+         */
+        public static MediaSessionCompat.Token getMediaSession(Notification notification) {
+            Bundle extras = android.support.v4.app.NotificationCompat.getExtras(notification);
+            if (extras != null) {
+                if (Build.VERSION.SDK_INT >= 21) {
+                    Object tokenInner = extras.getParcelable(
+                            android.support.v4.app.NotificationCompat.EXTRA_MEDIA_SESSION);
+                    if (tokenInner != null) {
+                        return MediaSessionCompat.Token.fromToken(tokenInner);
+                    }
+                } else {
+                    IBinder tokenInner = BundleCompat.getBinder(extras,
+                            android.support.v4.app.NotificationCompat.EXTRA_MEDIA_SESSION);
+                    if (tokenInner != null) {
+                        Parcel p = Parcel.obtain();
+                        p.writeStrongBinder(tokenInner);
+                        p.setDataPosition(0);
+                        MediaSessionCompat.Token token =
+                                MediaSessionCompat.Token.CREATOR.createFromParcel(p);
+                        p.recycle();
+                        return token;
+                    }
+                }
+            }
+            return null;
+        }
+
+        private static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
+        private static final int MAX_MEDIA_BUTTONS = 5;
+
+        int[] mActionsToShowInCompact = null;
+        MediaSessionCompat.Token mToken;
+        boolean mShowCancelButton;
+        PendingIntent mCancelButtonIntent;
+
+        public MediaStyle() {
+        }
+
+        public MediaStyle(android.support.v4.app.NotificationCompat.Builder builder) {
+            setBuilder(builder);
+        }
+
+        /**
+         * Requests up to 3 actions (by index in the order of addition) to be shown in the compact
+         * notification view.
+         *
+         * @param actions the indices of the actions to show in the compact notification view
+         */
+        public MediaStyle setShowActionsInCompactView(int...actions) {
+            mActionsToShowInCompact = actions;
+            return this;
+        }
+
+        /**
+         * Attaches a {@link MediaSessionCompat.Token} to this Notification
+         * to provide additional playback information and control to the SystemUI.
+         */
+        public MediaStyle setMediaSession(MediaSessionCompat.Token token) {
+            mToken = token;
+            return this;
+        }
+
+        /**
+         * Sets whether a cancel button at the top right should be shown in the notification on
+         * platforms before Lollipop.
+         *
+         * <p>Prior to Lollipop, there was a bug in the framework which prevented the developer to
+         * make a notification dismissable again after having used the same notification as the
+         * ongoing notification for a foreground service. When the notification was posted by
+         * {@link android.app.Service#startForeground}, but then the service exited foreground mode
+         * via {@link android.app.Service#stopForeground}, without removing the notification, the
+         * notification stayed ongoing, and thus not dismissable.
+         *
+         * <p>This is a common scenario for media notifications, as this is exactly the service
+         * lifecycle that happens when playing/pausing media. Thus, a workaround is provided by the
+         * support library: Instead of making the notification ongoing depending on the playback
+         * state, the support library provides the ability to add an explicit cancel button to the
+         * notification.
+         *
+         * <p>Note that the notification is enforced to be ongoing if a cancel button is shown to
+         * provide a consistent user experience.
+         *
+         * <p>Also note that this method is a no-op when running on Lollipop and later.
+         *
+         * @param show whether to show a cancel button
+         */
+        public MediaStyle setShowCancelButton(boolean show) {
+            if (Build.VERSION.SDK_INT < 21) {
+                mShowCancelButton = show;
+            }
+            return this;
+        }
+
+        /**
+         * Sets the pending intent to be sent when the cancel button is pressed. See {@link
+         * #setShowCancelButton}.
+         *
+         * @param pendingIntent the intent to be sent when the cancel button is pressed
+         */
+        public MediaStyle setCancelButtonIntent(PendingIntent pendingIntent) {
+            mCancelButtonIntent = pendingIntent;
+            return this;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 21) {
+                builder.getBuilder().setStyle(
+                        fillInMediaStyle(new Notification.MediaStyle()));
+            } else if (mShowCancelButton) {
+                builder.getBuilder().setOngoing(true);
+            }
+        }
+
+        @RequiresApi(21)
+        Notification.MediaStyle fillInMediaStyle(Notification.MediaStyle style) {
+            if (mActionsToShowInCompact != null) {
+                style.setShowActionsInCompactView(mActionsToShowInCompact);
+            }
+            if (mToken != null) {
+                style.setMediaSession((MediaSession.Token) mToken.getToken());
+            }
+            return style;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 21) {
+                // No custom content view required
+                return null;
+            }
+            return generateContentView();
+        }
+
+        RemoteViews generateContentView() {
+            RemoteViews view = applyStandardTemplate(false /* showSmallIcon */,
+                    getContentViewLayoutResource(), true /* fitIn1U */);
+
+            final int numActions = mBuilder.mActions.size();
+            final int numActionsInCompact = mActionsToShowInCompact == null
+                    ? 0
+                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
+            view.removeAllViews(R.id.media_actions);
+            if (numActionsInCompact > 0) {
+                for (int i = 0; i < numActionsInCompact; i++) {
+                    if (i >= numActions) {
+                        throw new IllegalArgumentException(String.format(
+                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
+                                i, numActions - 1));
+                    }
+
+                    final android.support.v4.app.NotificationCompat.Action action =
+                            mBuilder.mActions.get(mActionsToShowInCompact[i]);
+                    final RemoteViews button = generateMediaActionButton(action);
+                    view.addView(R.id.media_actions, button);
+                }
+            }
+            if (mShowCancelButton) {
+                view.setViewVisibility(R.id.end_padder, View.GONE);
+                view.setViewVisibility(R.id.cancel_action, View.VISIBLE);
+                view.setOnClickPendingIntent(R.id.cancel_action, mCancelButtonIntent);
+                view.setInt(R.id.cancel_action, "setAlpha", mBuilder.mContext
+                        .getResources().getInteger(R.integer.cancel_button_image_alpha));
+            } else {
+                view.setViewVisibility(R.id.end_padder, View.VISIBLE);
+                view.setViewVisibility(R.id.cancel_action, View.GONE);
+            }
+            return view;
+        }
+
+        private RemoteViews generateMediaActionButton(
+                android.support.v4.app.NotificationCompat.Action action) {
+            final boolean tombstone = (action.getActionIntent() == null);
+            RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(),
+                    R.layout.notification_media_action);
+            button.setImageViewResource(R.id.action0, action.getIcon());
+            if (!tombstone) {
+                button.setOnClickPendingIntent(R.id.action0, action.getActionIntent());
+            }
+            if (Build.VERSION.SDK_INT >= 15) {
+                button.setContentDescription(R.id.action0, action.getTitle());
+            }
+            return button;
+        }
+
+        int getContentViewLayoutResource() {
+            return R.layout.notification_template_media;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeBigContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 21) {
+                // No custom content view required
+                return null;
+            }
+            return generateBigContentView();
+        }
+
+        RemoteViews generateBigContentView() {
+            final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
+            RemoteViews big = applyStandardTemplate(false /* showSmallIcon */,
+                    getBigContentViewLayoutResource(actionCount), false /* fitIn1U */);
+
+            big.removeAllViews(R.id.media_actions);
+            if (actionCount > 0) {
+                for (int i = 0; i < actionCount; i++) {
+                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
+                    big.addView(R.id.media_actions, button);
+                }
+            }
+            if (mShowCancelButton) {
+                big.setViewVisibility(R.id.cancel_action, View.VISIBLE);
+                big.setInt(R.id.cancel_action, "setAlpha", mBuilder.mContext
+                        .getResources().getInteger(R.integer.cancel_button_image_alpha));
+                big.setOnClickPendingIntent(R.id.cancel_action, mCancelButtonIntent);
+            } else {
+                big.setViewVisibility(R.id.cancel_action, View.GONE);
+            }
+            return big;
+        }
+
+        int getBigContentViewLayoutResource(int actionCount) {
+            return actionCount <= 3
+                    ? R.layout.notification_template_big_media_narrow
+                    : R.layout.notification_template_big_media;
+        }
+    }
+
+    /**
+     * Notification style for media custom views that are decorated by the system.
+     *
+     * <p>Instead of providing a media notification that is completely custom, a developer can set
+     * this style and still obtain system decorations like the notification header with the expand
+     * affordance and actions.
+     *
+     * <p>Use {@link android.support.v4.app.NotificationCompat.Builder
+     * #setCustomContentView(RemoteViews)},
+     * {@link android.support.v4.app.NotificationCompat.Builder
+     * #setCustomBigContentView(RemoteViews)} and
+     * {@link android.support.v4.app.NotificationCompat.Builder
+     * #setCustomHeadsUpContentView(RemoteViews)} to set the
+     * corresponding custom views to display.
+     *
+     * <p>To use this style with your Notification, feed it to
+     * {@link android.support.v4.app.NotificationCompat.Builder
+     * #setStyle(android.support.v4.app.NotificationCompat.Style)} like so:
+     * <pre class="prettyprint">
+     * Notification noti = new NotificationCompat.Builder()
+     *     .setSmallIcon(R.drawable.ic_stat_player)
+     *     .setLargeIcon(albumArtBitmap))
+     *     .setCustomContentView(contentView)
+     *     .setStyle(<b>new NotificationCompat.DecoratedMediaCustomViewStyle()</b>
+     *          .setMediaSession(mySession))
+     *     .build();
+     * </pre>
+     *
+     * <p>If you are using this style, consider using the corresponding styles like
+     * {@link android.support.mediacompat.R.style#TextAppearance_Compat_Notification_Media} or
+     * {@link
+     * android.support.mediacompat.R.style#TextAppearance_Compat_Notification_Title_Media} in
+     * your custom views in order to get the correct styling on each platform version.
+     *
+     * @see android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle
+     * @see MediaStyle
+     */
+    public static class DecoratedMediaCustomViewStyle extends MediaStyle {
+
+        public DecoratedMediaCustomViewStyle() {
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public void apply(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                builder.getBuilder().setStyle(
+                        fillInMediaStyle(new Notification.DecoratedMediaCustomViewStyle()));
+            } else {
+                super.apply(builder);
+            }
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom content view required
+                return null;
+            }
+            boolean hasContentView = mBuilder.getContentView() != null;
+            if (Build.VERSION.SDK_INT >= 21) {
+                // If we are on L/M the media notification will only be colored if the expanded
+                // version is of media style, so we have to create a custom view for the collapsed
+                // version as well in that case.
+                boolean createCustomContent = hasContentView
+                        || mBuilder.getBigContentView() != null;
+                if (createCustomContent) {
+                    RemoteViews contentView = generateContentView();
+                    if (hasContentView) {
+                        buildIntoRemoteViews(contentView, mBuilder.getContentView());
+                    }
+                    setBackgroundColor(contentView);
+                    return contentView;
+                }
+            } else {
+                RemoteViews contentView = generateContentView();
+                if (hasContentView) {
+                    buildIntoRemoteViews(contentView, mBuilder.getContentView());
+                    return contentView;
+                }
+            }
+            return null;
+        }
+
+        @Override
+        int getContentViewLayoutResource() {
+            return mBuilder.getContentView() != null
+                    ? R.layout.notification_template_media_custom
+                    : super.getContentViewLayoutResource();
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeBigContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom big content view required
+                return null;
+            }
+            RemoteViews innerView = mBuilder.getBigContentView() != null
+                    ? mBuilder.getBigContentView()
+                    : mBuilder.getContentView();
+            if (innerView == null) {
+                // No expandable notification
+                return null;
+            }
+            RemoteViews bigContentView = generateBigContentView();
+            buildIntoRemoteViews(bigContentView, innerView);
+            if (Build.VERSION.SDK_INT >= 21) {
+                setBackgroundColor(bigContentView);
+            }
+            return bigContentView;
+        }
+
+        @Override
+        int getBigContentViewLayoutResource(int actionCount) {
+            return actionCount <= 3
+                    ? R.layout.notification_template_big_media_narrow_custom
+                    : R.layout.notification_template_big_media_custom;
+        }
+
+        /**
+         * @hide
+         */
+        @RestrictTo(LIBRARY_GROUP)
+        @Override
+        public RemoteViews makeHeadsUpContentView(NotificationBuilderWithBuilderAccessor builder) {
+            if (Build.VERSION.SDK_INT >= 24) {
+                // No custom heads up content view required
+                return null;
+            }
+            RemoteViews innerView = mBuilder.getHeadsUpContentView() != null
+                    ? mBuilder.getHeadsUpContentView()
+                    : mBuilder.getContentView();
+            if (innerView == null) {
+                // No expandable notification
+                return null;
+            }
+            RemoteViews headsUpContentView = generateBigContentView();
+            buildIntoRemoteViews(headsUpContentView, innerView);
+            if (Build.VERSION.SDK_INT >= 21) {
+                setBackgroundColor(headsUpContentView);
+            }
+            return headsUpContentView;
+        }
+
+        private void setBackgroundColor(RemoteViews views) {
+            int color = mBuilder.getColor() != COLOR_DEFAULT
+                    ? mBuilder.getColor()
+                    : mBuilder.mContext.getResources().getColor(
+                            R.color.notification_material_background_media_default_color);
+            views.setInt(R.id.status_bar_latest_event_content, "setBackgroundColor", color);
+        }
+    }
+}
diff --git a/media-compat/java/android/support/v4/media/session/IMediaSession.aidl b/media-compat/java/android/support/v4/media/session/IMediaSession.aidl
index 2ea696b..3926ac2 100644
--- a/media-compat/java/android/support/v4/media/session/IMediaSession.aidl
+++ b/media-compat/java/android/support/v4/media/session/IMediaSession.aidl
@@ -80,6 +80,7 @@
     void rewind() = 22;
     void seekTo(long pos) = 23;
     void rate(in RatingCompat rating) = 24;
+    void rateWithExtras(in RatingCompat rating, in Bundle extras) = 50;
     void setCaptioningEnabled(boolean enabled) = 45;
     void setRepeatMode(int repeatMode) = 38;
     void setShuffleModeEnabledDeprecated(boolean shuffleMode) = 39;
diff --git a/media-compat/java/android/support/v4/media/session/MediaButtonReceiver.java b/media-compat/java/android/support/v4/media/session/MediaButtonReceiver.java
index afb72945..d411131 100644
--- a/media-compat/java/android/support/v4/media/session/MediaButtonReceiver.java
+++ b/media-compat/java/android/support/v4/media/session/MediaButtonReceiver.java
@@ -24,11 +24,11 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
+import android.os.Build;
 import android.os.RemoteException;
 import android.support.v4.media.MediaBrowserCompat;
 import android.support.v4.media.MediaBrowserServiceCompat;
 import android.support.v4.media.session.PlaybackStateCompat.MediaKeyAction;
-import android.support.v4.os.BuildCompat;
 import android.util.Log;
 import android.view.KeyEvent;
 
@@ -284,7 +284,7 @@
     }
 
     private static void startForegroundService(Context context, Intent intent) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             context.startForegroundService(intent);
         } else {
             context.startService(intent);
diff --git a/media-compat/java/android/support/v4/media/session/MediaControllerCompat.java b/media-compat/java/android/support/v4/media/session/MediaControllerCompat.java
index 2f615d8..d3c403a 100644
--- a/media-compat/java/android/support/v4/media/session/MediaControllerCompat.java
+++ b/media-compat/java/android/support/v4/media/session/MediaControllerCompat.java
@@ -46,6 +46,7 @@
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 
 /**
@@ -181,9 +182,9 @@
             case MediaSessionCompat.ACTION_FOLLOW:
             case MediaSessionCompat.ACTION_UNFOLLOW:
                 if (args == null
-                        || !args.containsKey(MediaSessionCompat.ACTION_ARGUMENT_MEDIA_ATTRIBUTE)) {
+                        || !args.containsKey(MediaSessionCompat.ARGUMENT_MEDIA_ATTRIBUTE)) {
                     throw new IllegalArgumentException("An extra field "
-                            + MediaSessionCompat.ACTION_ARGUMENT_MEDIA_ATTRIBUTE + " is required "
+                            + MediaSessionCompat.ARGUMENT_MEDIA_ATTRIBUTE + " is required "
                             + "for this action " + action + ".");
                 }
                 break;
@@ -192,6 +193,9 @@
 
     private final MediaControllerImpl mImpl;
     private final MediaSessionCompat.Token mToken;
+    // This set is used to keep references to registered callbacks to prevent them being GCed,
+    // since we only keep weak references for callbacks in this class and its inner classes.
+    private final HashSet<Callback> mRegisteredCallbacks = new HashSet<>();
 
     /**
      * Creates a media controller from a session.
@@ -241,7 +245,7 @@
     }
 
     /**
-     * Get a {@link TransportControls} instance for this session.
+     * Gets a {@link TransportControls} instance for this session.
      *
      * @return A controls instance
      */
@@ -250,7 +254,7 @@
     }
 
     /**
-     * Send the specified media button event to the session. Only media keys can
+     * Sends the specified media button event to the session. Only media keys can
      * be sent by this method, other keys will be ignored.
      *
      * @param keyEvent The media button event to dispatch.
@@ -264,7 +268,7 @@
     }
 
     /**
-     * Get the current playback state for this session.
+     * Gets the current playback state for this session.
      *
      * @return The current PlaybackState or null
      */
@@ -273,7 +277,7 @@
     }
 
     /**
-     * Get the current metadata for this session.
+     * Gets the current metadata for this session.
      *
      * @return The current MediaMetadata or null.
      */
@@ -282,7 +286,7 @@
     }
 
     /**
-     * Get the current play queue for this session if one is set. If you only
+     * Gets the current play queue for this session if one is set. If you only
      * care about the current item {@link #getMetadata()} should be used.
      *
      * @return The current play queue or null.
@@ -292,7 +296,7 @@
     }
 
     /**
-     * Add a queue item from the given {@code description} at the end of the play queue
+     * Adds a queue item from the given {@code description} at the end of the play queue
      * of this session. Not all sessions may support this. To know whether the session supports
      * this, get the session's flags with {@link #getFlags()} and check that the flag
      * {@link MediaSessionCompat#FLAG_HANDLES_QUEUE_COMMANDS} is set.
@@ -308,7 +312,7 @@
     }
 
     /**
-     * Add a queue item from the given {@code description} at the specified position
+     * Adds a queue item from the given {@code description} at the specified position
      * in the play queue of this session. Shifts the queue item currently at that position
      * (if any) and any subsequent queue items to the right (adds one to their indices).
      * Not all sessions may support this. To know whether the session supports this,
@@ -328,7 +332,7 @@
     }
 
     /**
-     * Remove the first occurrence of the specified {@link MediaSessionCompat.QueueItem}
+     * Removes the first occurrence of the specified {@link MediaSessionCompat.QueueItem}
      * with the given {@link MediaDescriptionCompat description} in the play queue of the
      * associated session. Not all sessions may support this. To know whether the session supports
      * this, get the session's flags with {@link #getFlags()} and check that the flag
@@ -345,7 +349,7 @@
     }
 
     /**
-     * Remove an queue item at the specified position in the play queue
+     * Removes an queue item at the specified position in the play queue
      * of this session. Not all sessions may support this. To know whether the session supports
      * this, get the session's flags with {@link #getFlags()} and check that the flag
      * {@link MediaSessionCompat#FLAG_HANDLES_QUEUE_COMMANDS} is set.
@@ -368,21 +372,21 @@
     }
 
     /**
-     * Get the queue title for this session.
+     * Gets the queue title for this session.
      */
     public CharSequence getQueueTitle() {
         return mImpl.getQueueTitle();
     }
 
     /**
-     * Get the extras for this session.
+     * Gets the extras for this session.
      */
     public Bundle getExtras() {
         return mImpl.getExtras();
     }
 
     /**
-     * Get the rating type supported by the session. One of:
+     * Gets the rating type supported by the session. One of:
      * <ul>
      * <li>{@link RatingCompat#RATING_NONE}</li>
      * <li>{@link RatingCompat#RATING_HEART}</li>
@@ -400,7 +404,7 @@
     }
 
     /**
-     * Return whether captioning is enabled for this session.
+     * Returns whether captioning is enabled for this session.
      *
      * @return {@code true} if captioning is enabled, {@code false} if disabled or not set.
      */
@@ -409,7 +413,7 @@
     }
 
     /**
-     * Get the repeat mode for this session.
+     * Gets the repeat mode for this session.
      *
      * @return The latest repeat mode set to the session, or
      *         {@link PlaybackStateCompat#REPEAT_MODE_NONE} if not set.
@@ -419,7 +423,7 @@
     }
 
     /**
-     * Return whether the shuffle mode is enabled for this session.
+     * Returns whether the shuffle mode is enabled for this session.
      *
      * @return {@code true} if the shuffle mode is enabled, {@code false} if disabled or not set.
      * @deprecated Use {@link #getShuffleMode} instead.
@@ -430,7 +434,7 @@
     }
 
     /**
-     * Get the shuffle mode for this session.
+     * Gets the shuffle mode for this session.
      *
      * @return The latest shuffle mode set to the session, or
      *         {@link PlaybackStateCompat#SHUFFLE_MODE_NONE} if not set.
@@ -440,7 +444,7 @@
     }
 
     /**
-     * Get the flags for this session. Flags are defined in
+     * Gets the flags for this session. Flags are defined in
      * {@link MediaSessionCompat}.
      *
      * @return The current set of flags for the session.
@@ -450,7 +454,7 @@
     }
 
     /**
-     * Get the current playback info for this session.
+     * Gets the current playback info for this session.
      *
      * @return The current playback info or null.
      */
@@ -459,7 +463,7 @@
     }
 
     /**
-     * Get an intent for launching UI associated with this session if one
+     * Gets an intent for launching UI associated with this session if one
      * exists.
      *
      * @return A {@link PendingIntent} to launch UI or null.
@@ -469,7 +473,7 @@
     }
 
     /**
-     * Get the token for the session this controller is connected to.
+     * Gets the token for the session this controller is connected to.
      *
      * @return The session's token.
      */
@@ -478,7 +482,7 @@
     }
 
     /**
-     * Set the volume of the output this session is playing on. The command will
+     * Sets the volume of the output this session is playing on. The command will
      * be ignored if it does not support
      * {@link VolumeProviderCompat#VOLUME_CONTROL_ABSOLUTE}. The flags in
      * {@link AudioManager} may be used to affect the handling.
@@ -493,7 +497,7 @@
     }
 
     /**
-     * Adjust the volume of the output this session is playing on. The direction
+     * Adjusts the volume of the output this session is playing on. The direction
      * must be one of {@link AudioManager#ADJUST_LOWER},
      * {@link AudioManager#ADJUST_RAISE}, or {@link AudioManager#ADJUST_SAME}.
      * The command will be ignored if the session does not support
@@ -534,11 +538,13 @@
         if (handler == null) {
             handler = new Handler();
         }
+        callback.setHandler(handler);
         mImpl.registerCallback(callback, handler);
+        mRegisteredCallbacks.add(callback);
     }
 
     /**
-     * Stop receiving updates on the specified callback. If an update has
+     * Stops receiving updates on the specified callback. If an update has
      * already been posted you may still receive it after calling this method.
      *
      * @param callback The callback to remove
@@ -547,7 +553,12 @@
         if (callback == null) {
             throw new IllegalArgumentException("callback must not be null");
         }
-        mImpl.unregisterCallback(callback);
+        try {
+            mRegisteredCallbacks.remove(callback);
+            mImpl.unregisterCallback(callback);
+        } finally {
+            callback.setHandler(null);
+        }
     }
 
     /**
@@ -567,7 +578,7 @@
     }
 
     /**
-     * Get the session owner's package name.
+     * Gets the session owner's package name.
      *
      * @return The package name of of the session owner.
      */
@@ -598,13 +609,11 @@
         MessageHandler mHandler;
         boolean mHasExtraCallback;
 
-        boolean mRegistered = false;
-
         public Callback() {
             if (android.os.Build.VERSION.SDK_INT >= 21) {
-                mCallbackObj = MediaControllerCompatApi21.createCallback(new StubApi21());
+                mCallbackObj = MediaControllerCompatApi21.createCallback(new StubApi21(this));
             } else {
-                mCallbackObj = new StubCompat();
+                mCallbackObj = new StubCompat(this);
             }
         }
 
@@ -665,7 +674,7 @@
         }
 
         /**
-         * Override to handle chagnes to the {@link MediaSessionCompat} extras.
+         * Override to handle changes to the {@link MediaSessionCompat} extras.
          *
          * @param extras The extras that can include other information
          *            associated with the {@link MediaSessionCompat}.
@@ -728,136 +737,221 @@
         }
 
         /**
-         * Set the handler to use for pre 21 callbacks.
+         * Set the handler to use for callbacks.
          */
-        private void setHandler(Handler handler) {
-            mHandler = new MessageHandler(handler.getLooper());
+        void setHandler(Handler handler) {
+            if (handler == null) {
+                if (mHandler != null) {
+                    mHandler.mRegistered = false;
+                    mHandler.removeCallbacksAndMessages(null);
+                    mHandler = null;
+                }
+            } else {
+                mHandler = new MessageHandler(handler.getLooper());
+                mHandler.mRegistered = true;
+            }
         }
 
-        private class StubApi21 implements MediaControllerCompatApi21.Callback {
-            StubApi21() {
+        void postToHandler(int what, Object obj, Bundle data) {
+            if (mHandler != null) {
+                Message msg = mHandler.obtainMessage(what, obj);
+                msg.setData(data);
+                msg.sendToTarget();
+            }
+        }
+
+        private static class StubApi21 implements MediaControllerCompatApi21.Callback {
+            private final WeakReference<MediaControllerCompat.Callback> mCallback;
+
+            StubApi21(MediaControllerCompat.Callback callback) {
+                mCallback = new WeakReference<>(callback);
             }
 
             @Override
             public void onSessionDestroyed() {
-                Callback.this.onSessionDestroyed();
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onSessionDestroyed();
+                }
             }
 
             @Override
             public void onSessionEvent(String event, Bundle extras) {
-                if (mHasExtraCallback && android.os.Build.VERSION.SDK_INT < 23) {
-                    // Ignore. ExtraCallback will handle this.
-                } else {
-                    Callback.this.onSessionEvent(event, extras);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    if (callback.mHasExtraCallback && android.os.Build.VERSION.SDK_INT < 23) {
+                        // Ignore. ExtraCallback will handle this.
+                    } else {
+                        callback.onSessionEvent(event, extras);
+                    }
                 }
             }
 
             @Override
             public void onPlaybackStateChanged(Object stateObj) {
-                if (mHasExtraCallback) {
-                    // Ignore. ExtraCallback will handle this.
-                } else {
-                    Callback.this.onPlaybackStateChanged(
-                            PlaybackStateCompat.fromPlaybackState(stateObj));
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    if (callback.mHasExtraCallback) {
+                        // Ignore. ExtraCallback will handle this.
+                    } else {
+                        callback.onPlaybackStateChanged(
+                                PlaybackStateCompat.fromPlaybackState(stateObj));
+                    }
                 }
             }
 
             @Override
             public void onMetadataChanged(Object metadataObj) {
-                Callback.this.onMetadataChanged(MediaMetadataCompat.fromMediaMetadata(metadataObj));
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onMetadataChanged(MediaMetadataCompat.fromMediaMetadata(metadataObj));
+                }
             }
 
             @Override
             public void onQueueChanged(List<?> queue) {
-                Callback.this.onQueueChanged(QueueItem.fromQueueItemList(queue));
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onQueueChanged(QueueItem.fromQueueItemList(queue));
+                }
             }
 
             @Override
             public void onQueueTitleChanged(CharSequence title) {
-                Callback.this.onQueueTitleChanged(title);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onQueueTitleChanged(title);
+                }
             }
 
             @Override
             public void onExtrasChanged(Bundle extras) {
-                Callback.this.onExtrasChanged(extras);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onExtrasChanged(extras);
+                }
             }
 
             @Override
             public void onAudioInfoChanged(
                     int type, int stream, int control, int max, int current) {
-                Callback.this.onAudioInfoChanged(
-                        new PlaybackInfo(type, stream, control, max, current));
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.onAudioInfoChanged(
+                            new PlaybackInfo(type, stream, control, max, current));
+                }
             }
         }
 
-        private class StubCompat extends IMediaControllerCallback.Stub {
+        private static class StubCompat extends IMediaControllerCallback.Stub {
+            private final WeakReference<MediaControllerCompat.Callback> mCallback;
 
-            StubCompat() {
+            StubCompat(MediaControllerCompat.Callback callback) {
+                mCallback = new WeakReference<>(callback);
             }
 
             @Override
             public void onEvent(String event, Bundle extras) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_EVENT, event, extras);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_EVENT, event, extras);
+                }
             }
 
             @Override
             public void onSessionDestroyed() throws RemoteException {
-                mHandler.post(MessageHandler.MSG_DESTROYED, null, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_DESTROYED, null, null);
+                }
             }
 
             @Override
             public void onPlaybackStateChanged(PlaybackStateCompat state) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_PLAYBACK_STATE, state, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_PLAYBACK_STATE, state, null);
+                }
             }
 
             @Override
             public void onMetadataChanged(MediaMetadataCompat metadata) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_METADATA, metadata, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_METADATA, metadata, null);
+                }
             }
 
             @Override
             public void onQueueChanged(List<QueueItem> queue) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_QUEUE, queue, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_QUEUE, queue, null);
+                }
             }
 
             @Override
             public void onQueueTitleChanged(CharSequence title) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_QUEUE_TITLE, title, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_QUEUE_TITLE, title, null);
+                }
             }
 
             @Override
             public void onCaptioningEnabledChanged(boolean enabled) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_CAPTIONING_ENABLED, enabled, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(
+                            MessageHandler.MSG_UPDATE_CAPTIONING_ENABLED, enabled, null);
+                }
             }
 
             @Override
             public void onRepeatModeChanged(int repeatMode) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_REPEAT_MODE, repeatMode, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_REPEAT_MODE, repeatMode, null);
+                }
             }
 
             @Override
             public void onShuffleModeChangedDeprecated(boolean enabled) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_SHUFFLE_MODE_DEPRECATED, enabled, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(
+                            MessageHandler.MSG_UPDATE_SHUFFLE_MODE_DEPRECATED, enabled, null);
+                }
             }
 
             @Override
             public void onShuffleModeChanged(int shuffleMode) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_SHUFFLE_MODE, shuffleMode, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(
+                            MessageHandler.MSG_UPDATE_SHUFFLE_MODE, shuffleMode, null);
+                }
             }
 
             @Override
             public void onExtrasChanged(Bundle extras) throws RemoteException {
-                mHandler.post(MessageHandler.MSG_UPDATE_EXTRAS, extras, null);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_EXTRAS, extras, null);
+                }
             }
 
             @Override
             public void onVolumeInfoChanged(ParcelableVolumeInfo info) throws RemoteException {
-                PlaybackInfo pi = null;
-                if (info != null) {
-                    pi = new PlaybackInfo(info.volumeType, info.audioStream, info.controlType,
-                            info.maxVolume, info.currentVolume);
+                MediaControllerCompat.Callback callback = mCallback.get();
+                if (callback != null) {
+                    PlaybackInfo pi = null;
+                    if (info != null) {
+                        pi = new PlaybackInfo(info.volumeType, info.audioStream, info.controlType,
+                                info.maxVolume, info.currentVolume);
+                    }
+                    callback.postToHandler(MessageHandler.MSG_UPDATE_VOLUME, pi, null);
                 }
-                mHandler.post(MessageHandler.MSG_UPDATE_VOLUME, pi, null);
             }
         }
 
@@ -875,7 +969,9 @@
             private static final int MSG_UPDATE_CAPTIONING_ENABLED = 11;
             private static final int MSG_UPDATE_SHUFFLE_MODE = 12;
 
-            public MessageHandler(Looper looper) {
+            boolean mRegistered = false;
+
+            MessageHandler(Looper looper) {
                 super(looper);
             }
 
@@ -923,12 +1019,6 @@
                         break;
                 }
             }
-
-            public void post(int what, Object obj, Bundle data) {
-                Message msg = obtainMessage(what, obj);
-                msg.setData(data);
-                msg.sendToTarget();
-            }
         }
     }
 
@@ -937,27 +1027,29 @@
      * to send media transport commands to the session.
      */
     public static abstract class TransportControls {
+        /**
+         * Used as an integer extra field in {@link #playFromMediaId(String, Bundle)} or
+         * {@link #prepareFromMediaId(String, Bundle)} to indicate the stream type to be used by the
+         * media player when playing or preparing the specified media id. See {@link AudioManager}
+         * for a list of stream types.
+         */
+        public static final String EXTRA_LEGACY_STREAM_TYPE =
+                "android.media.session.extra.LEGACY_STREAM_TYPE";
+
         TransportControls() {
         }
 
         /**
-         * Request that the player prepare its playback without audio focus. In other words, other
-         * session can continue to play during the preparation of this session. This method can be
-         * used to speed up the start of the playback. Once the preparation is done, the session
-         * will change its playback state to {@link PlaybackStateCompat#STATE_PAUSED}. Afterwards,
-         * {@link #play} can be called to start playback. If the preparation is not needed,
-         * {@link #play} can be directly called without this method.
+         * Request that the player prepare for playback. This can decrease the time it takes to
+         * start playback when a play command is received. Preparation is not required. You can
+         * call {@link #play} without calling this method beforehand.
          */
         public abstract void prepare();
 
         /**
-         * Request that the player prepare playback for a specific media id. In other words, other
-         * session can continue to play during the preparation of this session. This method can be
-         * used to speed up the start of the playback. Once the preparation is
-         * done, the session will change its playback state to
-         * {@link PlaybackStateCompat#STATE_PAUSED}. Afterwards, {@link #play} can be called to
-         * start playback. If the preparation is not needed, {@link #playFromMediaId} can
-         * be directly called without this method.
+         * Request that the player prepare playback for a specific media id. This can decrease the
+         * time it takes to start playback when a play command is received. Preparation is not
+         * required. You can call {@link #playFromMediaId} without calling this method beforehand.
          *
          * @param mediaId The id of the requested media.
          * @param extras Optional extras that can include extra information about the media item
@@ -966,14 +1058,10 @@
         public abstract void prepareFromMediaId(String mediaId, Bundle extras);
 
         /**
-         * Request that the player prepare playback for a specific search query.
-         * An empty or null query should be treated as a request to prepare any
-         * music. In other words, other session can continue to play during
-         * the preparation of this session. This method can be used to speed up the start of the
-         * playback. Once the preparation is done, the session will change its playback state to
-         * {@link PlaybackStateCompat#STATE_PAUSED}. Afterwards, {@link #play} can be called to
-         * start playback. If the preparation is not needed, {@link #playFromSearch} can be directly
-         * called without this method.
+         * Request that the player prepare playback for a specific search query. This can decrease
+         * the time it takes to start playback when a play command is received. An empty or null
+         * query should be treated as a request to prepare any music. Preparation is not required.
+         * You can call {@link #playFromSearch} without calling this method beforehand.
          *
          * @param query The search query.
          * @param extras Optional extras that can include extra information
@@ -982,13 +1070,9 @@
         public abstract void prepareFromSearch(String query, Bundle extras);
 
         /**
-         * Request that the player prepare playback for a specific {@link Uri}.
-         * In other words, other session can continue to play during the preparation of this
-         * session. This method can be used to speed up the start of the playback.
-         * Once the preparation is done, the session will change its playback state to
-         * {@link PlaybackStateCompat#STATE_PAUSED}. Afterwards, {@link #play} can be called to
-         * start playback. If the preparation is not needed, {@link #playFromUri} can be directly
-         * called without this method.
+         * Request that the player prepare playback for a specific {@link Uri}. This can decrease
+         * the time it takes to start playback when a play command is received. Preparation is not
+         * required. You can call {@link #playFromUri} without calling this method beforehand.
          *
          * @param uri The URI of the requested media.
          * @param extras Optional extras that can include extra information about the media item
@@ -1031,7 +1115,7 @@
         public abstract void playFromUri(Uri uri, Bundle extras);
 
         /**
-         * Play an item with a specific id in the play queue. If you specify an
+         * Plays an item with a specific id in the play queue. If you specify an
          * id that is not in the play queue, the behavior is undefined.
          */
         public abstract void skipToQueueItem(long id);
@@ -1049,52 +1133,66 @@
         public abstract void stop();
 
         /**
-         * Move to a new location in the media stream.
+         * Moves to a new location in the media stream.
          *
          * @param pos Position to move to, in milliseconds.
          */
         public abstract void seekTo(long pos);
 
         /**
-         * Start fast forwarding. If playback is already fast forwarding this
+         * Starts fast forwarding. If playback is already fast forwarding this
          * may increase the rate.
          */
         public abstract void fastForward();
 
         /**
-         * Skip to the next item.
+         * Skips to the next item.
          */
         public abstract void skipToNext();
 
         /**
-         * Start rewinding. If playback is already rewinding this may increase
+         * Starts rewinding. If playback is already rewinding this may increase
          * the rate.
          */
         public abstract void rewind();
 
         /**
-         * Skip to the previous item.
+         * Skips to the previous item.
          */
         public abstract void skipToPrevious();
 
         /**
-         * Rate the current content. This will cause the rating to be set for
-         * the current user. The Rating type must match the type returned by
-         * {@link #getRatingType()}.
+         * Rates the current content. This will cause the rating to be set for
+         * the current user. The rating type of the given {@link RatingCompat} must match the type
+         * returned by {@link #getRatingType()}.
          *
          * @param rating The rating to set for the current content
          */
         public abstract void setRating(RatingCompat rating);
 
         /**
-         * Enable/disable captioning for this session.
+         * Rates a media item. This will cause the rating to be set for
+         * the specific media item. The rating type of the given {@link RatingCompat} must match
+         * the type returned by {@link #getRatingType()}.
+         *
+         * @param rating The rating to set for the media item.
+         * @param extras Optional arguments that can include information about the media item
+         *               to be rated.
+         *
+         * @see MediaSessionCompat#ARGUMENT_MEDIA_ATTRIBUTE
+         * @see MediaSessionCompat#ARGUMENT_MEDIA_ATTRIBUTE_VALUE
+         */
+        public abstract void setRating(RatingCompat rating, Bundle extras);
+
+        /**
+         * Enables/disables captioning for this session.
          *
          * @param enabled {@code true} to enable captioning, {@code false} to disable.
          */
         public abstract void setCaptioningEnabled(boolean enabled);
 
         /**
-         * Set the repeat mode for this session.
+         * Sets the repeat mode for this session.
          *
          * @param repeatMode The repeat mode. Must be one of the followings:
          *                   {@link PlaybackStateCompat#REPEAT_MODE_NONE},
@@ -1105,7 +1203,7 @@
         public abstract void setRepeatMode(@PlaybackStateCompat.RepeatMode int repeatMode);
 
         /**
-         * Set the shuffle mode for this session.
+         * Sets the shuffle mode for this session.
          *
          * @param enabled {@code true} to enable the shuffle mode, {@code false} to disable.
          * @deprecated Use {@link #setShuffleMode} instead.
@@ -1114,7 +1212,7 @@
         public abstract void setShuffleModeEnabled(boolean enabled);
 
         /**
-         * Set the shuffle mode for this session.
+         * Sets the shuffle mode for this session.
          *
          * @param shuffleMode The shuffle mode. Must be one of the followings:
          *                    {@link PlaybackStateCompat#SHUFFLE_MODE_NONE},
@@ -1124,7 +1222,7 @@
         public abstract void setShuffleMode(@PlaybackStateCompat.ShuffleMode int shuffleMode);
 
         /**
-         * Send a custom action for the {@link MediaSessionCompat} to perform.
+         * Sends a custom action for the {@link MediaSessionCompat} to perform.
          *
          * @param customAction The action to perform.
          * @param args Optional arguments to supply to the
@@ -1134,7 +1232,7 @@
                 Bundle args);
 
         /**
-         * Send the id and args from a custom action for the
+         * Sends the id and args from a custom action for the
          * {@link MediaSessionCompat} to perform.
          *
          * @see #sendCustomAction(PlaybackStateCompat.CustomAction action,
@@ -1181,7 +1279,7 @@
         }
 
         /**
-         * Get the type of volume handling, either local or remote. One of:
+         * Gets the type of volume handling, either local or remote. One of:
          * <ul>
          * <li>{@link PlaybackInfo#PLAYBACK_TYPE_LOCAL}</li>
          * <li>{@link PlaybackInfo#PLAYBACK_TYPE_REMOTE}</li>
@@ -1194,7 +1292,7 @@
         }
 
         /**
-         * Get the stream this is currently controlling volume on. When the volume
+         * Gets the stream this is currently controlling volume on. When the volume
          * type is {@link PlaybackInfo#PLAYBACK_TYPE_REMOTE} this value does not
          * have meaning and should be ignored.
          *
@@ -1206,7 +1304,7 @@
         }
 
         /**
-         * Get the type of volume control that can be used. One of:
+         * Gets the type of volume control that can be used. One of:
          * <ul>
          * <li>{@link VolumeProviderCompat#VOLUME_CONTROL_ABSOLUTE}</li>
          * <li>{@link VolumeProviderCompat#VOLUME_CONTROL_RELATIVE}</li>
@@ -1221,7 +1319,7 @@
         }
 
         /**
-         * Get the maximum volume that may be set for this session.
+         * Gets the maximum volume that may be set for this session.
          *
          * @return The maximum allowed volume where this session is playing.
          */
@@ -1230,7 +1328,7 @@
         }
 
         /**
-         * Get the current volume for this session.
+         * Gets the current volume for this session.
          *
          * @return The current volume where this session is playing.
          */
@@ -1287,8 +1385,6 @@
             try {
                 mBinder.asBinder().linkToDeath(callback, 0);
                 mBinder.registerCallbackListener((IMediaControllerCallback) callback.mCallbackObj);
-                callback.setHandler(handler);
-                callback.mRegistered = true;
             } catch (RemoteException e) {
                 Log.e(TAG, "Dead object in registerCallback.", e);
                 callback.onSessionDestroyed();
@@ -1304,7 +1400,6 @@
                 mBinder.unregisterCallbackListener(
                         (IMediaControllerCallback) callback.mCallbackObj);
                 mBinder.asBinder().unlinkToDeath(callback, 0);
-                callback.mRegistered = false;
             } catch (RemoteException e) {
                 Log.e(TAG, "Dead object in unregisterCallback.", e);
             }
@@ -1712,6 +1807,15 @@
         }
 
         @Override
+        public void setRating(RatingCompat rating, Bundle extras) {
+            try {
+                mBinder.rateWithExtras(rating, extras);
+            } catch (RemoteException e) {
+                Log.e(TAG, "Dead object in setRating.", e);
+            }
+        }
+
+        @Override
         public void setCaptioningEnabled(boolean enabled) {
             try {
                 mBinder.setCaptioningEnabled(enabled);
@@ -1799,7 +1903,6 @@
             MediaControllerCompatApi21.registerCallback(
                     mControllerObj, callback.mCallbackObj, handler);
             if (mExtraBinder != null) {
-                callback.setHandler(handler);
                 ExtraCallback extraCallback = new ExtraCallback(callback);
                 mCallbackMap.put(callback, extraCallback);
                 callback.mHasExtraCallback = true;
@@ -1809,7 +1912,6 @@
                     Log.e(TAG, "Dead object in registerCallback.", e);
                 }
             } else {
-                callback.setHandler(handler);
                 synchronized (mPendingCallbacks) {
                     mPendingCallbacks.add(callback);
                 }
@@ -2070,21 +2172,9 @@
             }
         }
 
-        private static class ExtraCallback extends IMediaControllerCallback.Stub {
-            private Callback mCallback;
-
+        private static class ExtraCallback extends Callback.StubCompat {
             ExtraCallback(Callback callback) {
-                mCallback = callback;
-            }
-
-            @Override
-            public void onEvent(final String event, final Bundle extras) throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onSessionEvent(event, extras);
-                    }
-                });
+                super(callback);
             }
 
             @Override
@@ -2094,17 +2184,6 @@
             }
 
             @Override
-            public void onPlaybackStateChanged(final PlaybackStateCompat state)
-                    throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onPlaybackStateChanged(state);
-                    }
-                });
-            }
-
-            @Override
             public void onMetadataChanged(MediaMetadataCompat metadata) throws RemoteException {
                 // Will not be called.
                 throw new AssertionError();
@@ -2123,47 +2202,6 @@
             }
 
             @Override
-            public void onCaptioningEnabledChanged(final boolean enabled) throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onCaptioningEnabledChanged(enabled);
-                    }
-                });
-            }
-
-            @Override
-            public void onRepeatModeChanged(final int repeatMode) throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onRepeatModeChanged(repeatMode);
-                    }
-                });
-            }
-
-            @Override
-            public void onShuffleModeChangedDeprecated(final boolean enabled)
-                    throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onShuffleModeChanged(enabled);
-                    }
-                });
-            }
-
-            @Override
-            public void onShuffleModeChanged(final int shuffleMode) throws RemoteException {
-                mCallback.mHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        mCallback.onShuffleModeChanged(shuffleMode);
-                    }
-                });
-            }
-
-            @Override
             public void onExtrasChanged(Bundle extras) throws RemoteException {
                 // Will not be called.
                 throw new AssertionError();
@@ -2260,6 +2298,14 @@
         }
 
         @Override
+        public void setRating(RatingCompat rating, Bundle extras) {
+            Bundle bundle = new Bundle();
+            bundle.putParcelable(MediaSessionCompat.ACTION_ARGUMENT_RATING, rating);
+            bundle.putParcelable(MediaSessionCompat.ACTION_ARGUMENT_EXTRAS, extras);
+            sendCustomAction(MediaSessionCompat.ACTION_SET_RATING, bundle);
+        }
+
+        @Override
         public void setCaptioningEnabled(boolean enabled) {
             Bundle bundle = new Bundle();
             bundle.putBoolean(MediaSessionCompat.ACTION_ARGUMENT_CAPTIONING_ENABLED, enabled);
diff --git a/media-compat/java/android/support/v4/media/session/MediaSessionCompat.java b/media-compat/java/android/support/v4/media/session/MediaSessionCompat.java
index 888bde5..aaf0a62 100644
--- a/media-compat/java/android/support/v4/media/session/MediaSessionCompat.java
+++ b/media-compat/java/android/support/v4/media/session/MediaSessionCompat.java
@@ -115,19 +115,19 @@
     public @interface SessionFlags {}
 
     /**
-     * Set this flag on the session to indicate that it can handle media button
+     * Sets this flag on the session to indicate that it can handle media button
      * events.
      */
     public static final int FLAG_HANDLES_MEDIA_BUTTONS = 1 << 0;
 
     /**
-     * Set this flag on the session to indicate that it handles transport
+     * Sets this flag on the session to indicate that it handles transport
      * control commands through its {@link Callback}.
      */
     public static final int FLAG_HANDLES_TRANSPORT_CONTROLS = 1 << 1;
 
     /**
-     * Set this flag on the session to indicate that it handles queue
+     * Sets this flag on the session to indicate that it handles queue
      * management commands through its {@link Callback}.
      */
     public static final int FLAG_HANDLES_QUEUE_COMMANDS = 1 << 2;
@@ -149,83 +149,71 @@
 
     /**
      * Predefined custom action to follow an artist, album, or playlist. The extra bundle must have
-     * {@link #ACTION_ARGUMENT_MEDIA_ATTRIBUTE} to indicate the type of the follow action. The
+     * {@link #ARGUMENT_MEDIA_ATTRIBUTE} to indicate the type of the follow action. The
      * bundle can also have an optional string argument,
-     * {@link #ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE}, to specify the target to follow (e.g., the
+     * {@link #ARGUMENT_MEDIA_ATTRIBUTE_VALUE}, to specify the target to follow (e.g., the
      * name of the artist to follow). If this argument is omitted, the currently playing media will
      * be the target of the action. Thus, the session must perform the follow action with the
      * current metadata. If there's no specified attribute in the current metadata, the controller
      * must not omit this argument.
      *
-     * @see #ACTION_ARGUMENT_MEDIA_ATTRIBUTE
-     * @see #ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE
+     * @see #ARGUMENT_MEDIA_ATTRIBUTE
+     * @see #ARGUMENT_MEDIA_ATTRIBUTE_VALUE
      * @see Callback#onCustomAction
      */
     public static final String ACTION_FOLLOW = "android.support.v4.media.session.action.FOLLOW";
 
     /**
      * Predefined custom action to unfollow an artist, album, or playlist. The extra bundle must
-     * have {@link #ACTION_ARGUMENT_MEDIA_ATTRIBUTE} to indicate the type of the unfollow action.
+     * have {@link #ARGUMENT_MEDIA_ATTRIBUTE} to indicate the type of the unfollow action.
      * The bundle can also have an optional string argument,
-     * {@link #ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE}, to specify the target to unfollow (e.g., the
+     * {@link #ARGUMENT_MEDIA_ATTRIBUTE_VALUE}, to specify the target to unfollow (e.g., the
      * name of the artist to unfollow). If this argument is omitted, the currently playing media
      * will be the target of the action. Thus, the session must perform the unfollow action with the
      * current metadata. If there's no specified attribute in the current metadata, the controller
      * must not omit this argument.
      *
-     * @see #ACTION_ARGUMENT_MEDIA_ATTRIBUTE
-     * @see #ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE
+     * @see #ARGUMENT_MEDIA_ATTRIBUTE
+     * @see #ARGUMENT_MEDIA_ATTRIBUTE_VALUE
      * @see Callback#onCustomAction
      */
     public static final String ACTION_UNFOLLOW = "android.support.v4.media.session.action.UNFOLLOW";
 
     /**
-     * Argument for use with {@link #ACTION_FOLLOW} and {@link #ACTION_UNFOLLOW} indicating the
-     * media attribute of the follow/unfollow action. It should be one of the following:
+     * Argument to indicate the media attribute. It should be one of the following:
      * <ul>
      * <li>{@link #MEDIA_ATTRIBUTE_ARTIST}</li>
      * <li>{@link #MEDIA_ATTRIBUTE_PLAYLIST}</li>
      * <li>{@link #MEDIA_ATTRIBUTE_ALBUM}</li>
      * </ul>
-     *
-     * @see #ACTION_FOLLOW
-     * @see #ACTION_UNFOLLOW
      */
-    public static final String ACTION_ARGUMENT_MEDIA_ATTRIBUTE =
-            "android.support.v4.media.session.action.ARGUMENT_MEDIA_ATTRIBUTE";
+    public static final String ARGUMENT_MEDIA_ATTRIBUTE =
+            "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE";
 
     /**
-     * String argument for use with {@link #ACTION_FOLLOW} and {@link #ACTION_UNFOLLOW} indicating
-     * the value of the media attribute of the follow/unfollow action (e.g., the name of the artist
-     * to follow).
-     *
-     * @see #ACTION_FOLLOW
-     * @see #ACTION_UNFOLLOW
+     * String argument to indicate the value of the media attribute (e.g., the name of the artist).
      */
-    public static final String ACTION_ARGUMENT_MEDIA_ATTRIBUTE_VALUE =
-            "android.support.v4.media.session.action.ARGUMENT_MEDIA_ATTRIBUTE_VALUE";
+    public static final String ARGUMENT_MEDIA_ATTRIBUTE_VALUE =
+            "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE_VALUE";
 
     /**
-     * The media attribute of the follow action which indicates that the target of the action is an
-     * artist.
+     * The value of {@link #ARGUMENT_MEDIA_ATTRIBUTE} indicating the artist.
      *
-     * @see ACTION_ARGUMENT_MEDIA_ATTRIBUTE
+     * @see ARGUMENT_MEDIA_ATTRIBUTE
      */
     public static final int MEDIA_ATTRIBUTE_ARTIST = 0;
 
     /**
-     * The media attribute of the follow action which indicates that the target of the action is an
-     * album.
+     * The value of {@link #ARGUMENT_MEDIA_ATTRIBUTE} indicating the album.
      *
-     * @see ACTION_ARGUMENT_MEDIA_ATTRIBUTE
+     * @see ARGUMENT_MEDIA_ATTRIBUTE
      */
     public static final int MEDIA_ATTRIBUTE_ALBUM = 1;
 
     /**
-     * The media attribute of the follow action which indicates that the target of the action is a
-     * playlist.
+     * The value of {@link #ARGUMENT_MEDIA_ATTRIBUTE} indicating the playlist.
      *
-     * @see ACTION_ARGUMENT_MEDIA_ATTRIBUTE
+     * @see ARGUMENT_MEDIA_ATTRIBUTE
      */
     public static final int MEDIA_ATTRIBUTE_PLAYLIST = 2;
 
@@ -283,6 +271,12 @@
             "android.support.v4.media.session.action.SET_SHUFFLE_MODE";
 
     /**
+     * Custom action to invoke setRating() with extra fields.
+     */
+    static final String ACTION_SET_RATING =
+            "android.support.v4.media.session.action.SET_RATING";
+
+    /**
      * Argument for use with {@link #ACTION_PREPARE_FROM_MEDIA_ID} indicating media id to play.
      */
     static final String ACTION_ARGUMENT_MEDIA_ID =
@@ -302,6 +296,12 @@
             "android.support.v4.media.session.action.ARGUMENT_URI";
 
     /**
+     * Argument for use with {@link #ACTION_SET_RATING} indicating the rate to be set.
+     */
+    static final String ACTION_ARGUMENT_RATING =
+            "android.support.v4.media.session.action.ARGUMENT_RATING";
+
+    /**
      * Argument for use with various actions indicating extra bundle.
      */
     static final String ACTION_ARGUMENT_EXTRAS =
@@ -435,7 +435,7 @@
     }
 
     /**
-     * Add a callback to receive updates on for the MediaSession. This includes
+     * Adds a callback to receive updates on for the MediaSession. This includes
      * media button and volume events. The caller's thread will be used to post
      * events.
      *
@@ -446,7 +446,7 @@
     }
 
     /**
-     * Set the callback to receive updates for the MediaSession. This includes
+     * Sets the callback to receive updates for the MediaSession. This includes
      * media button and volume events. Set the callback to null to stop
      * receiving events.
      *
@@ -458,7 +458,7 @@
     }
 
     /**
-     * Set an intent for launching UI for this Session. This can be used as a
+     * Sets an intent for launching UI for this Session. This can be used as a
      * quick link to an ongoing media screen. The intent should be for an
      * activity that may be started using
      * {@link Activity#startActivity(Intent)}.
@@ -470,7 +470,7 @@
     }
 
     /**
-     * Set a pending intent for your media button receiver to allow restarting
+     * Sets a pending intent for your media button receiver to allow restarting
      * playback after the session has been stopped. If your app is started in
      * this way an {@link Intent#ACTION_MEDIA_BUTTON} intent will be sent via
      * the pending intent.
@@ -487,7 +487,7 @@
     }
 
     /**
-     * Set any flags for the session.
+     * Sets any flags for the session.
      *
      * @param flags The flags to set for this session.
      */
@@ -496,7 +496,7 @@
     }
 
     /**
-     * Set the stream this session is playing on. This will affect the system's
+     * Sets the stream this session is playing on. This will affect the system's
      * volume handling for this session. If {@link #setPlaybackToRemote} was
      * previously called it will stop receiving volume commands and the system
      * will begin sending volume changes to the appropriate stream.
@@ -510,7 +510,7 @@
     }
 
     /**
-     * Configure this session to use remote volume handling. This must be called
+     * Configures this session to use remote volume handling. This must be called
      * to receive volume button events, otherwise the system will adjust the
      * current stream volume for this session. If {@link #setPlaybackToLocal}
      * was previously called that stream will stop receiving volume changes for
@@ -532,7 +532,7 @@
     }
 
     /**
-     * Set if this session is currently active and ready to receive commands. If
+     * Sets if this session is currently active and ready to receive commands. If
      * set to false your session's controller may not be discoverable. You must
      * set the session to active before it can start receiving media button
      * events or transport commands.
@@ -552,7 +552,7 @@
     }
 
     /**
-     * Get the current active state of this session.
+     * Gets the current active state of this session.
      *
      * @return True if the session is active, false otherwise.
      */
@@ -561,7 +561,7 @@
     }
 
     /**
-     * Send a proprietary event to all MediaControllers listening to this
+     * Sends a proprietary event to all MediaControllers listening to this
      * Session. It's up to the Controller/Session owner to determine the meaning
      * of any events.
      *
@@ -585,7 +585,7 @@
     }
 
     /**
-     * Retrieve a token object that can be used by apps to create a
+     * Retrieves a token object that can be used by apps to create a
      * {@link MediaControllerCompat} for interacting with this session. The
      * owner of the session is responsible for deciding how to distribute these
      * tokens.
@@ -603,7 +603,7 @@
     }
 
     /**
-     * Get a controller for this session. This is a convenience method to avoid
+     * Gets a controller for this session. This is a convenience method to avoid
      * having to cache your own controller in process.
      *
      * @return A controller for this session.
@@ -613,7 +613,7 @@
     }
 
     /**
-     * Update the current playback state.
+     * Updates the current playback state.
      *
      * @param state The current state of playback
      */
@@ -622,7 +622,7 @@
     }
 
     /**
-     * Update the current metadata. New metadata can be created using
+     * Updates the current metadata. New metadata can be created using
      * {@link android.support.v4.media.MediaMetadataCompat.Builder}. This operation may take time
      * proportional to the size of the bitmap to replace large bitmaps with a scaled down copy.
      *
@@ -634,7 +634,7 @@
     }
 
     /**
-     * Update the list of items in the play queue. It is an ordered list and
+     * Updates the list of items in the play queue. It is an ordered list and
      * should contain the current item, and previous or upcoming items if they
      * exist. Specify null if there is no current play queue.
      * <p>
@@ -649,7 +649,7 @@
     }
 
     /**
-     * Set the title of the play queue. The UI should display this title along
+     * Sets the title of the play queue. The UI should display this title along
      * with the play queue itself. e.g. "Play Queue", "Now Playing", or an album
      * name.
      *
@@ -660,7 +660,7 @@
     }
 
     /**
-     * Set the style of rating used by this session. Apps trying to set the
+     * Sets the style of rating used by this session. Apps trying to set the
      * rating should use this style. Must be one of the following:
      * <ul>
      * <li>{@link RatingCompat#RATING_NONE}</li>
@@ -677,7 +677,7 @@
     }
 
     /**
-     * Enable/disable captioning for this session.
+     * Enables/disables captioning for this session.
      *
      * @param enabled {@code true} to enable captioning, {@code false} to disable.
      */
@@ -686,7 +686,7 @@
     }
 
     /**
-     * Set the repeat mode for this session.
+     * Sets the repeat mode for this session.
      * <p>
      * Note that if this method is not called before, {@link MediaControllerCompat#getRepeatMode}
      * will return {@link PlaybackStateCompat#REPEAT_MODE_NONE}.
@@ -702,7 +702,7 @@
     }
 
     /**
-     * Set the shuffle mode for this session.
+     * Sets the shuffle mode for this session.
      * <p>
      * Note that if this method is not called before,
      * {@link MediaControllerCompat#isShuffleModeEnabled} will return {@code false}.
@@ -716,7 +716,7 @@
     }
 
     /**
-     * Set the shuffle mode for this session.
+     * Sets the shuffle mode for this session.
      * <p>
      * Note that if this method is not called before, {@link MediaControllerCompat#getShuffleMode}
      * will return {@link PlaybackStateCompat#SHUFFLE_MODE_NONE}.
@@ -731,7 +731,7 @@
     }
 
     /**
-     * Set some extras that can be associated with the
+     * Sets some extras that can be associated with the
      * {@link MediaSessionCompat}. No assumptions should be made as to how a
      * {@link MediaControllerCompat} will handle these extras. Keys should be
      * fully qualified (e.g. com.example.MY_EXTRA) to avoid conflicts.
@@ -867,7 +867,7 @@
         final Object mCallbackObj;
         private WeakReference<MediaSessionImpl> mSessionImpl;
         private CallbackHandler mCallbackHandler = null;
-        private boolean mMediaPlayPauseKeyHandled;
+        private boolean mMediaPlayPauseKeyPending;
 
         public Callback() {
             if (android.os.Build.VERSION.SDK_INT >= 24) {
@@ -924,42 +924,45 @@
                 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
                 case KeyEvent.KEYCODE_HEADSETHOOK:
                     if (keyEvent.getRepeatCount() > 0) {
+                        // Consider long-press as a single tap.
+                        handleMediaPlayPauseKeySingleTapIfPending();
+                    } else if (mMediaPlayPauseKeyPending) {
                         mCallbackHandler.removeMessages(
                                 CallbackHandler.MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
-                        if (keyEvent.getRepeatCount() == 1) {
-                            handleMediaPlayPauseKeySingleTapIfUnhandled();
-                        }
-                    } else if (mCallbackHandler.hasMessages(
-                            CallbackHandler.MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT)) {
-                        mCallbackHandler.removeMessages(
-                                CallbackHandler.MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
+                        mMediaPlayPauseKeyPending = false;
                         PlaybackStateCompat state = impl.getPlaybackState();
                         long validActions = state == null ? 0 : state.getActions();
                         // Consider double tap as the next.
                         if ((validActions & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
                             onSkipToNext();
                         }
-                        mMediaPlayPauseKeyHandled = true;
                     } else {
-                        mMediaPlayPauseKeyHandled = false;
+                        mMediaPlayPauseKeyPending = true;
                         mCallbackHandler.sendEmptyMessageDelayed(
                                 CallbackHandler.MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT,
                                 ViewConfiguration.getDoubleTapTimeout());
                     }
                     return true;
+                default:
+                    // If another key is pressed within double tap timeout, consider the pending
+                    // pending play/pause as a single tap to handle media keys in order.
+                    handleMediaPlayPauseKeySingleTapIfPending();
+                    break;
             }
             return false;
         }
 
-        private void handleMediaPlayPauseKeySingleTapIfUnhandled() {
-            if (mMediaPlayPauseKeyHandled) {
+        private void handleMediaPlayPauseKeySingleTapIfPending() {
+            if (!mMediaPlayPauseKeyPending) {
                 return;
             }
+            mMediaPlayPauseKeyPending = false;
+            mCallbackHandler.removeMessages(
+                    CallbackHandler.MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
             MediaSessionImpl impl = mSessionImpl.get();
             if (impl == null) {
                 return;
             }
-            mMediaPlayPauseKeyHandled = true;
             PlaybackStateCompat state = impl.getPlaybackState();
             long validActions = state == null ? 0 : state.getActions();
             boolean isPlaying = state != null
@@ -976,21 +979,16 @@
         }
 
         /**
-         * Override to handle requests to prepare playback. During the preparation, a session
-         * should not hold audio focus in order to allow other session play seamlessly.
-         * The state of playback should be updated to {@link PlaybackStateCompat#STATE_PAUSED}
-         * after the preparation is done.
+         * Override to handle requests to prepare playback. Override {@link #onPlay} to handle
+         * requests for starting playback.
          */
         public void onPrepare() {
         }
 
         /**
          * Override to handle requests to prepare for playing a specific mediaId that was provided
-         * by your app. During the preparation, a session should not hold audio focus in order to
-         * allow other session play seamlessly. The state of playback should be updated to
-         * {@link PlaybackStateCompat#STATE_PAUSED} after the preparation is done. The playback
-         * of the prepared content should start in the implementation of {@link #onPlay}. Override
-         * {@link #onPlayFromMediaId} to handle requests for starting playback without preparation.
+         * by your app. Override {@link #onPlayFromMediaId} to handle requests for starting
+         * playback.
          */
         public void onPrepareFromMediaId(String mediaId, Bundle extras) {
         }
@@ -998,24 +996,17 @@
         /**
          * Override to handle requests to prepare playback from a search query. An
          * empty query indicates that the app may prepare any music. The
-         * implementation should attempt to make a smart choice about what to
-         * play. During the preparation, a session should not hold audio focus in order to allow
-         * other session play seamlessly. The state of playback should be updated to
-         * {@link PlaybackStateCompat#STATE_PAUSED} after the preparation is done.
-         * The playback of the prepared content should start in the implementation of
-         * {@link #onPlay}. Override {@link #onPlayFromSearch} to handle requests for
-         * starting playback without preparation.
+         * implementation should attempt to make a smart choice about what to play.
+         * Override {@link #onPlayFromSearch} to handle requests
+         * for starting playback.
          */
         public void onPrepareFromSearch(String query, Bundle extras) {
         }
 
         /**
          * Override to handle requests to prepare a specific media item represented by a URI.
-         * During the preparation, a session should not hold audio focus in order to allow other
-         * session play seamlessly. The state of playback should be updated to
-         * {@link PlaybackStateCompat#STATE_PAUSED} after the preparation is done. The playback of
-         * the prepared content should start in the implementation of {@link #onPlay}. Override
-         * {@link #onPlayFromUri} to handle requests for starting playback without preparation.
+         * Override {@link #onPlayFromUri} to handle requests
+         * for starting playback.
          */
         public void onPrepareFromUri(Uri uri, Bundle extras) {
         }
@@ -1102,12 +1093,21 @@
         /**
          * Override to handle the item being rated.
          *
-         * @param rating
+         * @param rating The rating being set.
          */
         public void onSetRating(RatingCompat rating) {
         }
 
         /**
+         * Override to handle the item being rated.
+         *
+         * @param rating The rating being set.
+         * @param extras The extras can include information about the media item being rated.
+         */
+        public void onSetRating(RatingCompat rating, Bundle extras) {
+        }
+
+        /**
          * Override to handle requests to enable/disable captioning.
          *
          * @param enabled {@code true} to enable captioning, {@code false} to disable.
@@ -1230,7 +1230,7 @@
             @Override
             public void handleMessage(Message msg) {
                 if (msg.what == MSG_MEDIA_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT) {
-                    handleMediaPlayPauseKeySingleTapIfUnhandled();
+                    handleMediaPlayPauseKeySingleTapIfPending();
                 }
             }
         }
@@ -1356,6 +1356,11 @@
             }
 
             @Override
+            public void onSetRating(Object ratingObj, Bundle extras) {
+                Callback.this.onSetRating(RatingCompat.fromRating(ratingObj), extras);
+            }
+
+            @Override
             public void onCustomAction(String action, Bundle extras) {
                 if (action.equals(ACTION_PLAY_FROM_URI)) {
                     Uri uri = extras.getParcelable(ACTION_ARGUMENT_URI);
@@ -1387,6 +1392,11 @@
                 } else if (action.equals(ACTION_SET_SHUFFLE_MODE)) {
                     int shuffleMode = extras.getInt(ACTION_ARGUMENT_SHUFFLE_MODE);
                     Callback.this.onSetShuffleMode(shuffleMode);
+                } else if (action.equals(ACTION_SET_RATING)) {
+                    extras.setClassLoader(RatingCompat.class.getClassLoader());
+                    RatingCompat rating = extras.getParcelable(ACTION_ARGUMENT_RATING);
+                    Bundle bundle = extras.getBundle(ACTION_ARGUMENT_EXTRAS);
+                    Callback.this.onSetRating(rating, bundle);
                 } else {
                     Callback.this.onCustomAction(action, extras);
                 }
@@ -1585,7 +1595,7 @@
         private Object mItem;
 
         /**
-         * Create a new {@link MediaSessionCompat.QueueItem}.
+         * Creates a new {@link MediaSessionCompat.QueueItem}.
          *
          * @param description The {@link MediaDescriptionCompat} for this item.
          * @param id An identifier for this item. It must be unique within the
@@ -1613,14 +1623,14 @@
         }
 
         /**
-         * Get the description for this item.
+         * Gets the description for this item.
          */
         public MediaDescriptionCompat getDescription() {
             return mDescription;
         }
 
         /**
-         * Get the queue id for this item.
+         * Gets the queue id for this item.
          */
         public long getQueueId() {
             return mId;
@@ -1638,7 +1648,7 @@
         }
 
         /**
-         * Get the underlying
+         * Gets the underlying
          * {@link android.media.session.MediaSession.QueueItem}.
          * <p>
          * On builds before {@link android.os.Build.VERSION_CODES#LOLLIPOP} null
@@ -2670,6 +2680,11 @@
             }
 
             @Override
+            public void rateWithExtras(RatingCompat rating, Bundle extras) throws RemoteException {
+                postToHandler(MessageHandler.MSG_RATE_EXTRA, rating, extras);
+            }
+
+            @Override
             public void setCaptioningEnabled(boolean enabled) throws RemoteException {
                 postToHandler(MessageHandler.MSG_SET_CAPTIONING_ENABLED, enabled);
             }
@@ -2817,6 +2832,7 @@
             private static final int MSG_REWIND = 17;
             private static final int MSG_SEEK_TO = 18;
             private static final int MSG_RATE = 19;
+            private static final int MSG_RATE_EXTRA = 31;
             private static final int MSG_CUSTOM_ACTION = 20;
             private static final int MSG_MEDIA_BUTTON = 21;
             private static final int MSG_SET_VOLUME = 22;
@@ -2926,6 +2942,9 @@
                     case MSG_RATE:
                         cb.onSetRating((RatingCompat) msg.obj);
                         break;
+                    case MSG_RATE_EXTRA:
+                        cb.onSetRating((RatingCompat) msg.obj, msg.getData());
+                        break;
                     case MSG_CUSTOM_ACTION:
                         cb.onCustomAction((String) msg.obj, msg.getData());
                         break;
@@ -3159,11 +3178,13 @@
                         metadata.getLong(MediaMetadataCompat.METADATA_KEY_YEAR));
             }
             if (metadata.containsKey(MediaMetadataCompat.METADATA_KEY_RATING)) {
-                editor.putObject(MediaMetadataEditor.RATING_KEY_BY_OTHERS,
+                // Do not remove casting here. Without this, a crash will happen in API 19.
+                ((MediaMetadataEditor) editor).putObject(MediaMetadataEditor.RATING_KEY_BY_OTHERS,
                         metadata.getParcelable(MediaMetadataCompat.METADATA_KEY_RATING));
             }
             if (metadata.containsKey(MediaMetadataCompat.METADATA_KEY_USER_RATING)) {
-                editor.putObject(MediaMetadataEditor.RATING_KEY_BY_USER,
+                // Do not remove casting here. Without this, a crash will happen in API 19.
+                ((MediaMetadataEditor) editor).putObject(MediaMetadataEditor.RATING_KEY_BY_USER,
                         metadata.getParcelable(MediaMetadataCompat.METADATA_KEY_USER_RATING));
             }
             return editor;
@@ -3586,6 +3607,12 @@
             }
 
             @Override
+            public void rateWithExtras(RatingCompat rating, Bundle extras) throws RemoteException {
+                // Will not be called.
+                throw new AssertionError();
+            }
+
+            @Override
             public void setCaptioningEnabled(boolean enabled) throws RemoteException {
                 // Will not be called.
                 throw new AssertionError();
diff --git a/media-compat/lint-baseline.xml b/media-compat/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/media-compat/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/media-compat/res-public/values/public_styles.xml b/media-compat/res-public/values/public_styles.xml
new file mode 100644
index 0000000..9113f6e
--- /dev/null
+++ b/media-compat/res-public/values/public_styles.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Definitions of styles to be exposed as public -->
+<resources>
+    <public type="style" name="TextAppearance.Compat.Notification.Media"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Title.Media"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Info.Media"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Time.Media"/>
+    <public type="style" name="TextAppearance.Compat.Notification.Line2.Media"/>
+</resources>
diff --git a/media-compat/res/layout/notification_media_action.xml b/media-compat/res/layout/notification_media_action.xml
new file mode 100644
index 0000000..f71acdd
--- /dev/null
+++ b/media-compat/res/layout/notification_media_action.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
+    style="?android:attr/borderlessButtonStyle"
+    android:id="@+id/action0"
+    android:layout_width="48dp"
+    android:layout_height="match_parent"
+    android:layout_marginLeft="2dp"
+    android:layout_marginRight="2dp"
+    android:layout_weight="1"
+    android:gravity="center"/>
\ No newline at end of file
diff --git a/media-compat/res/layout/notification_media_cancel_action.xml b/media-compat/res/layout/notification_media_cancel_action.xml
new file mode 100644
index 0000000..b0b50b4
--- /dev/null
+++ b/media-compat/res/layout/notification_media_cancel_action.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    style="?android:attr/borderlessButtonStyle"
+    android:id="@+id/cancel_action"
+    android:layout_width="48dp"
+    android:layout_height="match_parent"
+    android:layout_marginLeft="2dp"
+    android:layout_marginRight="2dp"
+    android:layout_weight="1"
+    android:src="@android:drawable/ic_menu_close_clear_cancel"
+    android:gravity="center"
+    android:visibility="gone"/>
\ No newline at end of file
diff --git a/media-compat/res/layout/notification_template_big_media.xml b/media-compat/res/layout/notification_template_big_media.xml
new file mode 100644
index 0000000..8dd93dc
--- /dev/null
+++ b/media-compat/res/layout/notification_template_big_media.xml
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="128dp"
+    >
+    <include layout="@layout/notification_template_icon_group"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+    />
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="48dp"
+        android:layout_marginLeft="2dp"
+        android:layout_marginRight="2dp"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true" />
+    <include layout="@layout/notification_template_lines_media"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_gravity="fill_vertical"
+        android:layout_marginLeft="@dimen/notification_large_icon_width"
+        android:layout_marginStart="@dimen/notification_large_icon_width"
+        android:layout_toLeftOf="@id/cancel_action"
+        android:layout_toStartOf="@id/cancel_action"/>
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="match_parent"
+        android:layout_height="48dp"
+        android:layout_alignParentBottom="true"
+        android:layout_marginLeft="12dp"
+        android:layout_marginRight="12dp"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <ImageView
+        android:layout_width="match_parent"
+        android:layout_height="1dp"
+        android:layout_above="@id/media_actions"
+        android:id="@+id/action_divider"
+        android:background="?android:attr/dividerHorizontal" />
+</RelativeLayout>
diff --git a/media-compat/res/layout/notification_template_big_media_custom.xml b/media-compat/res/layout/notification_template_big_media_custom.xml
new file mode 100644
index 0000000..cccda1d
--- /dev/null
+++ b/media-compat/res/layout/notification_template_big_media_custom.xml
@@ -0,0 +1,107 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="128dp"
+    >
+    <include layout="@layout/notification_template_icon_group"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+    />
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="48dp"
+        android:layout_marginLeft="2dp"
+        android:layout_marginRight="2dp"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true"/>
+    <LinearLayout
+        android:id="@+id/notification_main_column_container"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="@dimen/notification_large_icon_height"
+        android:layout_marginStart="@dimen/notification_large_icon_height"
+        android:minHeight="@dimen/notification_large_icon_height"
+        android:paddingTop="@dimen/notification_main_column_padding_top"
+        android:orientation="horizontal"
+        android:layout_toLeftOf="@id/cancel_action"
+        android:layout_toStartOf="@id/cancel_action">
+        <FrameLayout
+            android:id="@+id/notification_main_column"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:layout_marginLeft="@dimen/notification_content_margin_start"
+            android:layout_marginStart="@dimen/notification_content_margin_start"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:layout_marginBottom="8dp"
+        />
+        <FrameLayout
+            android:id="@+id/right_side"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:paddingTop="@dimen/notification_right_side_padding_top">
+            <DateTimeView android:id="@+id/time"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <Chronometer android:id="@+id/chronometer"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <TextView android:id="@+id/info"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Info.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginTop="20dp"
+                android:layout_gravity="end|bottom"
+                android:singleLine="true"
+            />
+        </FrameLayout>
+    </LinearLayout>
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="match_parent"
+        android:layout_height="48dp"
+        android:layout_alignParentBottom="true"
+        android:layout_marginLeft="12dp"
+        android:layout_marginRight="12dp"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <ImageView
+        android:layout_width="match_parent"
+        android:layout_height="1dp"
+        android:layout_above="@id/media_actions"
+        android:id="@+id/action_divider"
+        android:background="?android:attr/dividerHorizontal" />
+</RelativeLayout>
diff --git a/media-compat/res/layout/notification_template_big_media_narrow.xml b/media-compat/res/layout/notification_template_big_media_narrow.xml
new file mode 100644
index 0000000..ca8e289
--- /dev/null
+++ b/media-compat/res/layout/notification_template_big_media_narrow.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Layout to be used with only max 3 actions. It has a much larger picture at the left side-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="128dp"
+    >
+    <ImageView android:id="@+id/icon"
+        android:layout_width="128dp"
+        android:layout_height="128dp"
+        android:scaleType="centerCrop"
+        />
+
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="48dp"
+        android:layout_marginLeft="2dp"
+        android:layout_marginRight="2dp"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true"/>
+
+    <include layout="@layout/notification_template_lines_media"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="128dp"
+        android:layout_marginStart="128dp"
+        android:layout_toLeftOf="@id/cancel_action"
+        android:layout_toStartOf="@id/cancel_action"/>
+
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="match_parent"
+        android:layout_height="48dp"
+        android:layout_toRightOf="@id/icon"
+        android:layout_toEndOf="@id/icon"
+        android:layout_alignParentBottom="true"
+        android:layout_marginLeft="12dp"
+        android:layout_marginRight="12dp"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <ImageView
+        android:layout_width="match_parent"
+        android:layout_height="1dp"
+        android:layout_toRightOf="@id/icon"
+        android:layout_toEndOf="@id/icon"
+        android:layout_above="@id/media_actions"
+        android:id="@+id/action_divider"
+        android:background="?android:attr/dividerHorizontal" />
+</RelativeLayout>
diff --git a/media-compat/res/layout/notification_template_big_media_narrow_custom.xml b/media-compat/res/layout/notification_template_big_media_narrow_custom.xml
new file mode 100644
index 0000000..db78467
--- /dev/null
+++ b/media-compat/res/layout/notification_template_big_media_narrow_custom.xml
@@ -0,0 +1,115 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Layout to be used with only max 3 actions. It has a much larger picture at the left side-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="128dp"
+    >
+    <ImageView android:id="@+id/icon"
+        android:layout_width="128dp"
+        android:layout_height="128dp"
+        android:scaleType="centerCrop"
+        />
+
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="48dp"
+        android:layout_marginLeft="2dp"
+        android:layout_marginRight="2dp"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true"/>
+
+    <LinearLayout
+        android:id="@+id/notification_main_column_container"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="128dp"
+        android:layout_marginStart="128dp"
+        android:minHeight="@dimen/notification_large_icon_height"
+        android:paddingTop="@dimen/notification_main_column_padding_top"
+        android:orientation="horizontal"
+        android:layout_toLeftOf="@id/cancel_action"
+        android:layout_toStartOf="@id/cancel_action">
+        <FrameLayout
+            android:id="@+id/notification_main_column"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:layout_marginLeft="@dimen/notification_media_narrow_margin"
+            android:layout_marginStart="@dimen/notification_media_narrow_margin"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:layout_marginBottom="8dp"/>
+        <FrameLayout
+            android:id="@+id/right_side"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:paddingTop="@dimen/notification_right_side_padding_top">
+            <DateTimeView android:id="@+id/time"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <Chronometer android:id="@+id/chronometer"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <TextView android:id="@+id/info"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Info.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginTop="20dp"
+                android:layout_gravity="end|bottom"
+                android:singleLine="true"
+            />
+        </FrameLayout>
+    </LinearLayout>
+
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="match_parent"
+        android:layout_height="48dp"
+        android:layout_toRightOf="@id/icon"
+        android:layout_toEndOf="@id/icon"
+        android:layout_alignParentBottom="true"
+        android:layout_marginLeft="12dp"
+        android:layout_marginRight="12dp"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <ImageView
+        android:layout_width="match_parent"
+        android:layout_height="1dp"
+        android:layout_toRightOf="@id/icon"
+        android:layout_toEndOf="@id/icon"
+        android:layout_above="@id/media_actions"
+        android:id="@+id/action_divider"
+        android:background="?android:attr/dividerHorizontal" />
+</RelativeLayout>
diff --git a/media-compat/res/layout/notification_template_lines_media.xml b/media-compat/res/layout/notification_template_lines_media.xml
new file mode 100644
index 0000000..385a01b
--- /dev/null
+++ b/media-compat/res/layout/notification_template_lines_media.xml
@@ -0,0 +1,112 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:paddingRight="8dp"
+    android:paddingEnd="8dp"
+    android:paddingTop="2dp"
+    android:paddingBottom="2dp"
+    >
+    <LinearLayout
+        android:id="@+id/line1"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:paddingTop="6dp"
+        android:layout_marginLeft="@dimen/notification_content_margin_start"
+        android:layout_marginStart="@dimen/notification_content_margin_start"
+        android:orientation="horizontal"
+        >
+        <TextView android:id="@+id/title"
+            android:textAppearance="@style/TextAppearance.Compat.Notification.Title.Media"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:singleLine="true"
+            android:ellipsize="marquee"
+            android:fadingEdge="horizontal"
+            android:layout_weight="1"
+            />
+        <DateTimeView android:id="@+id/time"
+            android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:singleLine="true"
+            android:layout_gravity="center"
+            android:layout_weight="0"
+            android:visibility="gone"
+            android:paddingLeft="8dp"
+            android:paddingStart="8dp"
+        />
+        <Chronometer android:id="@+id/chronometer"
+            android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:singleLine="true"
+            android:layout_gravity="center"
+            android:layout_weight="0"
+            android:visibility="gone"
+            android:paddingLeft="8dp"
+            android:paddingStart="8dp"
+        />
+    </LinearLayout>
+    <TextView android:id="@+id/text2"
+        android:textAppearance="@style/TextAppearance.Compat.Notification.Line2.Media"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="-2dp"
+        android:layout_marginBottom="-2dp"
+        android:layout_marginLeft="@dimen/notification_content_margin_start"
+        android:layout_marginStart="@dimen/notification_content_margin_start"
+        android:singleLine="true"
+        android:fadingEdge="horizontal"
+        android:ellipsize="marquee"
+        android:visibility="gone"
+        />
+    <LinearLayout
+        android:id="@+id/line3"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:gravity="center_vertical"
+        android:layout_marginLeft="@dimen/notification_content_margin_start"
+        android:layout_marginStart="@dimen/notification_content_margin_start"
+        >
+        <TextView android:id="@+id/text"
+            android:textAppearance="@style/TextAppearance.Compat.Notification.Media"
+            android:layout_width="0dp"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:layout_gravity="center"
+            android:singleLine="true"
+            android:ellipsize="marquee"
+            android:fadingEdge="horizontal"
+            />
+        <TextView android:id="@+id/info"
+            android:textAppearance="@style/TextAppearance.Compat.Notification.Info.Media"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center"
+            android:layout_weight="0"
+            android:singleLine="true"
+            android:gravity="center"
+            android:paddingLeft="8dp"
+            android:paddingStart="8dp"
+            />
+    </LinearLayout>
+</LinearLayout>
\ No newline at end of file
diff --git a/media-compat/res/layout/notification_template_media.xml b/media-compat/res/layout/notification_template_media.xml
new file mode 100644
index 0000000..f57070a
--- /dev/null
+++ b/media-compat/res/layout/notification_template_media.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="64dp"
+    android:orientation="horizontal"
+    >
+    <include layout="@layout/notification_template_icon_group"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+    />
+    <include layout="@layout/notification_template_lines_media"
+        android:layout_width="0dp"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"/>
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:layout_gravity="center_vertical|end"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="match_parent"
+        android:layout_marginRight="6dp"
+        android:layout_marginEnd="6dp"/>
+    <ImageView android:id="@+id/end_padder"
+        android:layout_width="6dp"
+        android:layout_height="match_parent"
+        />
+</LinearLayout>
diff --git a/media-compat/res/layout/notification_template_media_custom.xml b/media-compat/res/layout/notification_template_media_custom.xml
new file mode 100644
index 0000000..36a479c
--- /dev/null
+++ b/media-compat/res/layout/notification_template_media_custom.xml
@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/status_bar_latest_event_content"
+    android:layout_width="match_parent"
+    android:layout_height="64dp"
+    android:orientation="horizontal"
+    >
+    <include layout="@layout/notification_template_icon_group"
+        android:layout_width="@dimen/notification_large_icon_width"
+        android:layout_height="@dimen/notification_large_icon_height"
+    />
+    <LinearLayout
+        android:id="@+id/notification_main_column_container"
+        android:layout_width="0dp"
+        android:layout_weight="1"
+        android:layout_height="wrap_content"
+        android:paddingTop="@dimen/notification_main_column_padding_top"
+        android:minHeight="@dimen/notification_large_icon_height"
+        android:orientation="horizontal"
+        android:layout_toLeftOf="@id/cancel_action"
+        android:layout_toStartOf="@id/cancel_action">
+        <FrameLayout
+            android:id="@+id/notification_main_column"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:layout_marginLeft="@dimen/notification_content_margin_start"
+            android:layout_marginStart="@dimen/notification_content_margin_start"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:layout_marginBottom="8dp"/>
+        <FrameLayout
+            android:id="@+id/right_side"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="8dp"
+            android:layout_marginEnd="8dp"
+            android:paddingTop="@dimen/notification_right_side_padding_top">
+            <DateTimeView android:id="@+id/time"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <Chronometer android:id="@+id/chronometer"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Time.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:singleLine="true"
+                android:layout_gravity="end|top"
+                android:visibility="gone"
+            />
+            <TextView android:id="@+id/info"
+                android:textAppearance="@style/TextAppearance.Compat.Notification.Info.Media"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginTop="20dp"
+                android:layout_gravity="end|bottom"
+                android:singleLine="true"
+            />
+        </FrameLayout>
+    </LinearLayout>
+    <LinearLayout
+        android:id="@+id/media_actions"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:layout_gravity="center_vertical|end"
+        android:orientation="horizontal"
+        android:layoutDirection="ltr"
+        >
+        <!-- media buttons will be added here -->
+    </LinearLayout>
+    <include layout="@layout/notification_media_cancel_action"
+        android:layout_width="48dp"
+        android:layout_height="match_parent"
+        android:layout_marginRight="6dp"
+        android:layout_marginEnd="6dp"/>
+    <ImageView android:id="@+id/end_padder"
+        android:layout_width="6dp"
+        android:layout_height="match_parent"
+        />
+</LinearLayout>
diff --git a/media-compat/res/values-v21/styles.xml b/media-compat/res/values-v21/styles.xml
new file mode 100644
index 0000000..b785197
--- /dev/null
+++ b/media-compat/res/values-v21/styles.xml
@@ -0,0 +1,33 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <style name="TextAppearance.Compat.Notification.Media" >
+        <item name="android:textColor">@color/secondary_text_default_material_dark</item>
+    </style>
+
+    <style name="TextAppearance.Compat.Notification.Title.Media" >
+        <item name="android:textColor">@color/primary_text_default_material_dark</item>
+    </style>
+
+    <style name="TextAppearance.Compat.Notification.Info.Media">
+        <item name="android:textColor">@color/secondary_text_default_material_dark</item>
+    </style>
+
+    <style name="TextAppearance.Compat.Notification.Time.Media">
+        <item name="android:textColor">@color/secondary_text_default_material_dark</item>
+    </style>
+</resources>
\ No newline at end of file
diff --git a/media-compat/res/values-v24/styles.xml b/media-compat/res/values-v24/styles.xml
new file mode 100644
index 0000000..31b4224
--- /dev/null
+++ b/media-compat/res/values-v24/styles.xml
@@ -0,0 +1,26 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <!-- Use platform styles, Media is dark again -->
+    <style name="TextAppearance.Compat.Notification.Media" />
+
+    <style name="TextAppearance.Compat.Notification.Title.Media" />
+
+    <style name="TextAppearance.Compat.Notification.Info.Media" />
+
+    <style name="TextAppearance.Compat.Notification.Time.Media" />
+</resources>
\ No newline at end of file
diff --git a/media-compat/res/values/colors.xml b/media-compat/res/values/colors.xml
new file mode 100644
index 0000000..67a2521
--- /dev/null
+++ b/media-compat/res/values/colors.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<resources>
+
+    <!-- The color of the material notification background for media notifications when no custom
+     color is specified -->
+    <color name="notification_material_background_media_default_color">#ff424242</color>
+
+</resources>
\ No newline at end of file
diff --git a/media-compat/res/values/colors_material.xml b/media-compat/res/values/colors_material.xml
new file mode 100644
index 0000000..9eea922
--- /dev/null
+++ b/media-compat/res/values/colors_material.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- Colors specific to Material themes. -->
+<resources>
+
+    <!-- 100% white -->
+    <color name="primary_text_default_material_dark">#ffffffff</color>
+    <!-- 70% white -->
+    <color name="secondary_text_default_material_dark">#b3ffffff</color>
+
+</resources>
diff --git a/media-compat/res/values/config.xml b/media-compat/res/values/config.xml
new file mode 100644
index 0000000..15c4328
--- /dev/null
+++ b/media-compat/res/values/config.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<!-- These resources are around just to allow their values to be customized
+     for different hardware and product builds. -->
+<resources>
+
+    <integer name="cancel_button_image_alpha">127</integer>
+
+</resources>
diff --git a/media-compat/res/values/styles.xml b/media-compat/res/values/styles.xml
new file mode 100644
index 0000000..ce351a4
--- /dev/null
+++ b/media-compat/res/values/styles.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <style name="TextAppearance.Compat.Notification.Media" />
+
+    <style name="TextAppearance.Compat.Notification.Title.Media" />
+
+    <style name="TextAppearance.Compat.Notification.Info.Media"/>
+
+    <style name="TextAppearance.Compat.Notification.Time.Media"/>
+
+    <style name="TextAppearance.Compat.Notification.Line2.Media" parent="TextAppearance.Compat.Notification.Info.Media"/>
+</resources>
diff --git a/media-compat/tests/AndroidManifest.xml b/media-compat/tests/AndroidManifest.xml
index 60b7890..6d9a4f6 100644
--- a/media-compat/tests/AndroidManifest.xml
+++ b/media-compat/tests/AndroidManifest.xml
@@ -15,19 +15,13 @@
    limitations under the License.
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.mediacompat.test">
-
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application android:supportsRtl="true">
-        <receiver android:name="android.support.v4.media.session.MediaButtonReceiver" >
+        <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
             <intent-filter>
-                <action android:name="android.intent.action.MEDIA_BUTTON" />
+                <action android:name="android.intent.action.MEDIA_BUTTON"/>
             </intent-filter>
         </receiver>
         <service android:name="android.support.v4.media.StubMediaBrowserServiceCompat">
@@ -41,7 +35,8 @@
                 <action android:name="android.media.browse.MediaBrowserService"/>
             </intent-filter>
         </service>
-        <service android:name="android.support.v4.media.StubMediaBrowserServiceCompatWithDelayedMediaSession">
+        <service
+            android:name="android.support.v4.media.StubMediaBrowserServiceCompatWithDelayedMediaSession">
             <intent-filter>
                 <action android:name="android.media.browse.MediaBrowserService"/>
             </intent-filter>
diff --git a/media-compat/tests/src/android/support/v4/media/MediaBrowserServiceCompatTest.java b/media-compat/tests/src/android/support/v4/media/MediaBrowserServiceCompatTest.java
index 4856cfd..4ceac10 100644
--- a/media-compat/tests/src/android/support/v4/media/MediaBrowserServiceCompatTest.java
+++ b/media-compat/tests/src/android/support/v4/media/MediaBrowserServiceCompatTest.java
@@ -378,7 +378,6 @@
         assertEquals(val, browserRoot.getExtras().getString(key));
     }
 
-
     @Test
     @SmallTest
     public void testDelayedSetSessionToken() throws Exception {
@@ -583,6 +582,5 @@
                 mWaitLock.notify();
             }
         }
-    };
-
+    }
 }
diff --git a/media-compat/tests/src/android/support/v4/media/session/MediaControllerCompatTest.java b/media-compat/tests/src/android/support/v4/media/session/MediaControllerCompatTest.java
index a1a59e3..6103121 100644
--- a/media-compat/tests/src/android/support/v4/media/session/MediaControllerCompatTest.java
+++ b/media-compat/tests/src/android/support/v4/media/session/MediaControllerCompatTest.java
@@ -288,9 +288,17 @@
             assertEquals(rating.getStarRating(), mCallback.mRating.getStarRating(), DELTA);
 
             mCallback.reset();
-            final String mediaId = "test-media-id";
             final Bundle extras = new Bundle();
             extras.putString(EXTRAS_KEY, EXTRAS_VALUE);
+            controls.setRating(rating, extras);
+            mWaitLock.wait(TIME_OUT_MS);
+            assertTrue(mCallback.mOnSetRatingCalled);
+            assertEquals(rating.getRatingStyle(), mCallback.mRating.getRatingStyle());
+            assertEquals(rating.getStarRating(), mCallback.mRating.getStarRating(), DELTA);
+            assertEquals(EXTRAS_VALUE, mCallback.mExtras.getString(EXTRAS_KEY));
+
+            mCallback.reset();
+            final String mediaId = "test-media-id";
             controls.playFromMediaId(mediaId, extras);
             mWaitLock.wait(TIME_OUT_MS);
             assertTrue(mCallback.mOnPlayFromMediaIdCalled);
@@ -613,6 +621,16 @@
         }
 
         @Override
+        public void onSetRating(RatingCompat rating, Bundle extras) {
+            synchronized (mWaitLock) {
+                mOnSetRatingCalled = true;
+                mRating = rating;
+                mExtras = extras;
+                mWaitLock.notify();
+            }
+        }
+
+        @Override
         public void onPlayFromMediaId(String mediaId, Bundle extras) {
             synchronized (mWaitLock) {
                 mOnPlayFromMediaIdCalled = true;
diff --git a/media-compat/tests/src/android/support/v4/media/session/MediaSessionCompatTest.java b/media-compat/tests/src/android/support/v4/media/session/MediaSessionCompatTest.java
index 536b49f..b44a085 100644
--- a/media-compat/tests/src/android/support/v4/media/session/MediaSessionCompatTest.java
+++ b/media-compat/tests/src/android/support/v4/media/session/MediaSessionCompatTest.java
@@ -18,6 +18,7 @@
 
 import static android.support.test.InstrumentationRegistry.getContext;
 import static android.support.test.InstrumentationRegistry.getInstrumentation;
+import static android.support.v4.media.MediaMetadataCompat.METADATA_KEY_RATING;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -217,8 +218,12 @@
         controller.registerCallback(mCallback, mHandler);
         synchronized (mWaitLock) {
             mCallback.resetLocked();
-            MediaMetadataCompat metadata =
-                    new MediaMetadataCompat.Builder().putString(TEST_KEY, TEST_VALUE).build();
+            RatingCompat rating = RatingCompat.newHeartRating(true);
+            MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
+                    .putString(TEST_KEY, TEST_VALUE)
+                    .putRating(METADATA_KEY_RATING, rating)
+                    .build();
+            mSession.setActive(true);
             mSession.setMetadata(metadata);
             mWaitLock.wait(TIME_OUT_MS);
             assertTrue(mCallback.mOnMetadataChangedCalled);
@@ -230,6 +235,11 @@
             metadataOut = controller.getMetadata();
             assertNotNull(metadataOut);
             assertEquals(TEST_VALUE, metadataOut.getString(TEST_KEY));
+
+            assertNotNull(metadataOut.getRating(METADATA_KEY_RATING));
+            RatingCompat ratingOut = metadataOut.getRating(METADATA_KEY_RATING);
+            assertEquals(rating.getRatingStyle(), ratingOut.getRatingStyle());
+            assertEquals(rating.getPercentRating(), ratingOut.getPercentRating(), 0.0f);
         }
     }
 
@@ -590,18 +600,8 @@
         PendingIntent pi = PendingIntent.getBroadcast(getContext(), 0, mediaButtonIntent, 0);
         mSession.setMediaButtonReceiver(pi);
 
-        long supportedActions = PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
-                | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_STOP
-                | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
-                | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
-                | PlaybackStateCompat.ACTION_FAST_FORWARD | PlaybackStateCompat.ACTION_REWIND;
-
         // Set state to STATE_PLAYING to get higher priority.
-        PlaybackStateCompat defaultState = new PlaybackStateCompat.Builder()
-                .setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PLAYING, 0L, 0.0f)
-                .build();
-        mSession.setPlaybackState(defaultState);
+        setPlaybackState(PlaybackStateCompat.STATE_PLAYING);
 
         sessionCallback.reset(1);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY);
@@ -641,24 +641,21 @@
         // Test PLAY_PAUSE button twice.
         // First, send PLAY_PAUSE button event while in STATE_PAUSED.
         sessionCallback.reset(1);
-        mSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PAUSED, 0L, 0.0f).build());
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
         assertTrue(sessionCallback.await(TIME_OUT_MS));
         assertEquals(1, sessionCallback.mOnPlayCalledCount);
 
         // Next, send PLAY_PAUSE button event while in STATE_PLAYING.
         sessionCallback.reset(1);
-        mSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PLAYING, 0L, 0.0f).build());
+        setPlaybackState(PlaybackStateCompat.STATE_PLAYING);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
         assertTrue(sessionCallback.await(TIME_OUT_MS));
         assertTrue(sessionCallback.mOnPauseCalled);
 
         // Double tap of PLAY_PAUSE is the next track.
         sessionCallback.reset(2);
-        mSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PAUSED, 0L, 0.0f).build());
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
         assertFalse(sessionCallback.await(WAIT_TIME_MS));
@@ -669,8 +666,7 @@
         // Test PLAY_PAUSE button long-press.
         // It should be the same as the single short-press.
         sessionCallback.reset(1);
-        mSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PAUSED, 0L, 0.0f).build());
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, true);
         assertTrue(sessionCallback.await(TIME_OUT_MS));
         assertEquals(1, sessionCallback.mOnPlayCalledCount);
@@ -690,16 +686,53 @@
         // Initial long-press of the PLAY_PAUSE is considered as the single short-press already,
         // so it shouldn't be used as the first tap of the double tap.
         sessionCallback.reset(2);
-        mSession.setPlaybackState(new PlaybackStateCompat.Builder().setActions(supportedActions)
-                .setState(PlaybackStateCompat.STATE_PAUSED, 0L, 0.0f).build());
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, true);
         sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
         assertTrue(sessionCallback.await(TIME_OUT_MS));
         // onMediaButtonEvent() calls either onPlay() or onPause() depending on the playback state,
         // so onPlay() should be called twice while onPause() isn't called.
-        assertEquals(2, sessionCallback.mOnPlayCalledCount);
-        assertFalse(sessionCallback.mOnPauseCalled);
+        assertEquals(1, sessionCallback.mOnPlayCalledCount);
+        assertTrue(sessionCallback.mOnPauseCalled);
         assertFalse(sessionCallback.mOnSkipToNextCalled);
+
+        // If another media key is pressed while the double tap of PLAY_PAUSE,
+        // PLAY_PAUSE should be handles as normal.
+        sessionCallback.reset(3);
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
+        sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
+        sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_STOP);
+        sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
+        assertTrue(sessionCallback.await(TIME_OUT_MS));
+        assertFalse(sessionCallback.mOnSkipToNextCalled);
+        assertTrue(sessionCallback.mOnStopCalled);
+        assertEquals(2, sessionCallback.mOnPlayCalledCount);
+
+        // Test if media keys are handled in order.
+        sessionCallback.reset(2);
+        setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
+        sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
+        sendMediaKeyInputToController(KeyEvent.KEYCODE_MEDIA_STOP);
+        assertTrue(sessionCallback.await(TIME_OUT_MS));
+        assertEquals(1, sessionCallback.mOnPlayCalledCount);
+        assertTrue(sessionCallback.mOnStopCalled);
+        synchronized (mWaitLock) {
+            assertEquals(PlaybackStateCompat.STATE_STOPPED,
+                    mSession.getController().getPlaybackState().getState());
+        }
+    }
+
+    private void setPlaybackState(int state) {
+        final long allActions = PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
+                | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_STOP
+                | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
+                | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
+                | PlaybackStateCompat.ACTION_FAST_FORWARD | PlaybackStateCompat.ACTION_REWIND;
+        PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder().setActions(allActions)
+                .setState(state, 0L, 0.0f).build();
+        synchronized (mWaitLock) {
+            mSession.setPlaybackState(playbackState);
+        }
     }
 
     @Test
@@ -985,18 +1018,21 @@
         @Override
         public void onPlay() {
             mOnPlayCalledCount++;
+            setPlaybackState(PlaybackStateCompat.STATE_PLAYING);
             mLatch.countDown();
         }
 
         @Override
         public void onPause() {
             mOnPauseCalled = true;
+            setPlaybackState(PlaybackStateCompat.STATE_PAUSED);
             mLatch.countDown();
         }
 
         @Override
         public void onStop() {
             mOnStopCalled = true;
+            setPlaybackState(PlaybackStateCompat.STATE_STOPPED);
             mLatch.countDown();
         }
 
diff --git a/paging/common/build.gradle b/paging/common/build.gradle
new file mode 100644
index 0000000..4b0dad1
--- /dev/null
+++ b/paging/common/build.gradle
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+apply plugin: 'java'
+apply plugin: 'maven'
+
+sourceCompatibility = 1.7
+// disable paging for now.
+project.ext.noDocs = true
+uploadArchives.enabled = false
+dependencies {
+    compile libs.support.annotations
+    compile project(":arch:common")
+
+    testCompile libs.junit
+    testCompile libs.mockito_core
+    compile 'com.android.support:support-annotations:25.3.1'
+    compile project(path: ':arch:common')
+    compile 'junit:junit:4.12'
+}
+
+archivesBaseName = "common"
+
+createAndroidCheckstyle(project)
diff --git a/paging/common/src/main/java/android/arch/util/paging/CountedDataSource.java b/paging/common/src/main/java/android/arch/util/paging/CountedDataSource.java
new file mode 100644
index 0000000..dd7d41c
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/CountedDataSource.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.WorkerThread;
+
+import java.util.List;
+
+/**
+ * Incremental data loader for paging content when the total number of items is known.
+ * <p>
+ * All loading methods in CountedDataSource should only be called on a background thread.
+ * loadAfter and loadBefore specifically may be called in parallel with each other, if loading in
+ * both directions is required (often for prefetching).
+ * <p>
+ * Items returned from a CountedDataSource must be treated as immutable in all properties used by
+ * {@link #loadAfter(int, Object, int)} and {@link #loadBefore(int, Object, int)}. For example, if
+ * loadAfter(...User user...) is called, with <code>user.id</code> being used to load users after
+ * that user's ID, the <code>id</code> field in User must remain immutable.
+ * <p>
+ * If the loadAfter and loadBefore methods only require indices to function, CountedDataSource does
+ * not require items returned to be immutable in any way.
+ *
+ * @param <Type> Type of the items this CountedDataSource will produce.
+ */
+public abstract class CountedDataSource<Type> extends DataSourceBase {
+    /**
+     * @return The number of items in the DataSource.
+     */
+    @WorkerThread
+    public abstract int loadCount();
+
+    /**
+     * Load initial data, starting after the passed position.
+     *
+     * @param position Position just before data to be loaded. -1 is passed to request data
+     *                 from beginning of data source.
+     * @param pageSize Suggested number of items to load.
+     * @return List of initial items, representing data starting at position + 1. Null if the
+     *         DataSource is no longer valid, and should not be queried again.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadAfterInitial(int position, int pageSize);
+
+    /**
+     * Load data after the given position / item.
+     * <p>
+     * It's valid to return a different list size than the page size, if it's easier for this data
+     * source. It is generally safer to increase number loaded than reduce.
+     *
+     * @param currentEndIndex Load items after this index, starting with currentEndIndex + 1.
+     * @param currentEndItem Load items after this item, can be used for precise querying based on
+     *                       item contents.
+     * @param pageSize Suggested number of items to load.
+     * @return List of items, starting at position currentEndIndex + 1. Null if the data source is
+     *         no longer valid, and should not be queried again.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadAfter(int currentEndIndex,
+            @NonNull Type currentEndItem, int pageSize);
+
+    /**
+     * Load data before the given position / item.
+     * <p>
+     * It's valid to return a different list size than the page size, if it's easier for this data
+     * source. It is generally safer to increase number loaded than reduce.
+     *
+     * @param currentBeginIndex Load items before this index, starting with currentBeginIndex - 1.
+     * @param currentBeginItem Load items after this item, can be used for precise querying based on
+     *                         item contents.
+     * @param pageSize Suggested number of items to load.
+     * @return List of items, in descending order, starting at position currentBeginIndex - 1.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadBefore(int currentBeginIndex,
+            @NonNull Type currentBeginItem, int pageSize);
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/DataSource.java b/paging/common/src/main/java/android/arch/util/paging/DataSource.java
new file mode 100644
index 0000000..e6af7e7
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/DataSource.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.WorkerThread;
+
+import java.util.List;
+
+
+/**
+ * Incremental data loader for list paging.
+ *
+ * @param <Key> Type of the key used to load initial data.
+ * @param <Type> Type of the items this CountedDataSource will produce.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class DataSource<Key, Type> extends DataSourceBase {
+
+    /**
+     * Get key from item.
+     *
+     * @param item The item.
+     * @return The Key.
+     */
+    public abstract Key getKey(@NonNull Type item);
+
+    /**
+     * Load initial data, starting after the passed key.
+     *
+     * @param key Key just before the data to be loaded.
+     * @param pageSize Suggested number of items to load.
+     * @return List of initial items, representing data starting at key + 1. Null if the
+     *         DataSource is no longer valid, and should not be queried again.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadAfterInitial(@Nullable Key key, int pageSize);
+
+    /**
+     * Load data, starting after the passed item.
+     *
+     * @param currentEndItem Load items after this item, can be used for precise querying based on
+     *                       item contents.
+     * @param pageSize Suggested number of items to load.
+     * @return List of initial items, representing data starting at key + 1. Null if the
+     *         DataSource is no longer valid, and should not be queried again.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadAfter(@NonNull Type currentEndItem, int pageSize);
+
+    /**
+     * Load data, before the passed item.
+     *
+     * @param currentBeginItem Load items after this item, can be used for precise querying based on
+     *                         item contents.
+     * @param pageSize Suggested number of items to load.
+     * @return List of initial items, representing data starting at key + 1. Null if the
+     *         DataSource is no longer valid, and should not be queried again.
+     */
+    @WorkerThread
+    @Nullable
+    public abstract List<Type> loadBefore(@NonNull Type currentBeginItem, int pageSize);
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/DataSourceBase.java b/paging/common/src/main/java/android/arch/util/paging/DataSourceBase.java
new file mode 100644
index 0000000..50d245d
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/DataSourceBase.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.AnyThread;
+
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Data Source base class, with common invalidation functionality.
+ */
+class DataSourceBase {
+    public interface InvalidatedCallback {
+        /*
+         * Called when the data backing the list has become invalid. This callback is typically used
+         * to signal that a new data source is needed, if the data source remains in use.
+         * <p>
+         * This callback will be invoked on the thread that calls {@link #invalidate()}. It is valid
+         * for the data source to invalidate itself during its load methods, or for an outside
+         * source to invalidate it.
+         */
+        @AnyThread
+        void onInvalidated();
+    }
+
+    private AtomicBoolean mInvalid = new AtomicBoolean(false);
+
+    private CopyOnWriteArrayList<InvalidatedCallback> mOnInvalidatedCallbacks =
+            new CopyOnWriteArrayList<>();
+    /**
+     * Add a callback to invoke when the DataSource is first invalidated.
+     * <p>
+     * Once invalidated, a data source will not become valid again.
+     * <p>
+     * A data source will only invoke its callbacks once - the first time {@link #invalidate()}
+     * is called, on that thread.
+     *
+     * @param onInvalidatedCallback The callback, will be invoked on thread that
+     *                              {@link #invalidate()} is called on.
+     */
+    @AnyThread
+    public void addInvalidatedCallback(InvalidatedCallback onInvalidatedCallback) {
+        mOnInvalidatedCallbacks.add(onInvalidatedCallback);
+    }
+
+    /**
+     * Remove a previously added invalidate callback.
+     *
+     * @param onInvalidatedCallback The previously added callback.
+     */
+    @AnyThread
+    public void removeInvalidatedCallback(InvalidatedCallback onInvalidatedCallback) {
+        mOnInvalidatedCallbacks.remove(onInvalidatedCallback);
+    }
+
+    /**
+     * Signal the data source to stop loading, and notify its callback.
+     * <p>
+     * If invalidate has already been called, this method does nothing.
+     */
+    @AnyThread
+    public void invalidate() {
+        if (mInvalid.compareAndSet(false, true)) {
+            for (InvalidatedCallback callback : mOnInvalidatedCallbacks) {
+                callback.onInvalidated();
+            }
+        }
+    }
+
+    /**
+     * @return True if the data source is invalid, and can no longer return data.
+     */
+    public boolean isInvalid() {
+        return mInvalid.get();
+    }
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/LazyList.java b/paging/common/src/main/java/android/arch/util/paging/LazyList.java
new file mode 100644
index 0000000..706df63
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/LazyList.java
@@ -0,0 +1,315 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.arch.core.internal.SafeIterableMap;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.WorkerThread;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executor;
+
+/**
+ * Lazy-loading list, which defaults each entry to be null and pages content in on-demand,
+ * with prefetching.
+ *
+ * When a list item is read as null, content is paged in from the CountedDataSource asynchronously.
+ *
+ * This class is NOT thread safe. All accesses to get()/access() and mutations should be made on the
+ * thread defined by the mainThreadExecutor.
+ *
+ * @param <Type> Data type held by this list.
+ */
+public class LazyList<Type> extends PagerBase<Type> {
+    private int mMissedMinIndex = Integer.MAX_VALUE;
+    private int mMissedMaxIndex = -1;
+
+    private int mStartPos; // position is inclusive
+    private final int mSize;
+
+    // last position accessed via get()
+    private volatile int mLastAccessed;
+
+    private SafeIterableMap<ChangeCallback,
+            ChangeCallbackWrapper> mCallbacks = new SafeIterableMap<>();
+
+    private CountedDataSource<Type> mCountedDataSource;
+
+    @WorkerThread
+    public LazyList(@NonNull CountedDataSource<Type> countedDataSource,
+            @NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            @NonNull ListConfig config) {
+        super(mainThreadExecutor, backgroundThreadExecutor, config);
+        mCountedDataSource = countedDataSource;
+        mSize = mCountedDataSource.loadCount();
+    }
+
+    // ---- List ----
+
+    @Override
+    @Nullable
+    public Type get(int index) {
+        if (index < 0 || index >= mSize) {
+            throw new IndexOutOfBoundsException(index + " is out of bounds. Size:" + mSize);
+        }
+
+        mLastAccessed = index;
+
+        final boolean initialLoadComplete = mItems != null;
+
+        // note: intentionally avoid triggering prefetching, so that prefetches aren't outstanding
+        // when LazyList is passed to consumers
+
+        // prefetch
+        int minTarget = Math.max(0, index - mConfig.mPrefetchDistance);
+        int maxTarget = Math.min(mSize, index + mConfig.mPrefetchDistance);
+        if (minTarget < mMissedMinIndex) {
+            mMissedMinIndex = minTarget;
+            if (initialLoadComplete) {
+                loadBeforeIfNeeded();
+            }
+        }
+        if (maxTarget > mMissedMaxIndex) {
+            mMissedMaxIndex = maxTarget;
+            if (initialLoadComplete) {
+                loadAfterIfNeeded();
+            }
+        }
+
+        if (initialLoadComplete) {
+            return access(index);
+        } else {
+            triggerInitialLoad(getInitialLoadPositionFor(index));
+            return null;
+        }
+    }
+
+    @Override
+    public int size() {
+        return mSize;
+    }
+
+    @Override
+    @Nullable
+    public Type access(int index) {
+        if (index < 0 || index >= mSize) {
+            throw new IndexOutOfBoundsException(index + " is out of bounds. Size:" + mSize);
+        }
+        if (mItems == null || index < mStartPos || index >= mStartPos + mItems.size()) {
+            return null;
+        } else {
+            return mItems.get(index - mStartPos);
+        }
+    }
+
+    // ---- Initial data ----
+
+    private int getInitialLoadPositionFor(int index) {
+        return Math.max(-1, index - mConfig.mPageSize / 2);
+    }
+
+    /**
+     * @return Suggested initial load position for a new LazyList to load the initial state at.
+     */
+    public int getInitialLoadPosition() {
+        return getInitialLoadPositionFor(mLastAccessed);
+    }
+
+    @MainThread
+    private void triggerInitialLoad(final int loadAfterPos) {
+        if (mInitialized) {
+            return;
+        }
+        mInitialized = true;
+        mBackgroundThreadExecutor.execute(new Runnable() {
+            @Override
+            public void run() {
+                if (mInvalid.get()) {
+                    return;
+                }
+                // find a good start point to center the index
+                final List<Type> load = mCountedDataSource.loadAfterInitial(
+                        loadAfterPos, mConfig.mPageSize);
+
+                if (load != null) {
+                    mMainThreadExecutor.execute(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (mInvalid.get()) {
+                                return;
+                            }
+                            setInitialDataAndDispatch(loadAfterPos, load);
+                        }
+                    });
+                } else {
+                    freeze();
+                }
+            }
+        });
+    }
+
+    /**
+     *
+     * @param loadAfterPos Position to pass to {@link CountedDataSource#loadAfterInitial(int, int)}
+     *                     for warmup.
+     * @return True on success.
+     */
+    public boolean internalInit(int loadAfterPos)  {
+        List<Type> load = mCountedDataSource.loadAfterInitial(loadAfterPos, mConfig.mPageSize);
+        if (load != null) {
+            setInitialDataAndDispatch(loadAfterPos, load);
+            mInitialized = true;
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    private void setInitialDataAndDispatch(int loadAfterPos, List<Type> items) {
+        mStartPos = loadAfterPos + 1;
+        setInitialData(items);
+        dispatchChange();
+    }
+
+    // ---- Callback ----
+
+    /**
+     * Adds a change callback, to observe when new content is loaded into the list. The callback is
+     * invoked once nulls in the list are loaded from the data source.
+     *
+     * @param callback The callback, invoked on the main thread.
+     *
+     * @see #removeCallback(ChangeCallback)
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void addCallback(ChangeCallback callback) {
+        int start = mStartPos;
+        int end = mStartPos + (mItems == null ? 0 : mItems.size());
+        ChangeCallbackWrapper wrapper = new ChangeCallbackWrapper(callback, start, end);
+        // do not notify the latest data so the observer can distinguish whether the data has
+        // really changed or not.
+        mCallbacks.putIfAbsent(callback, wrapper);
+    }
+
+    /**
+     * Removes a previously added change callback.
+     *
+     * @param callback The callback, invoked on the main thread.
+     *
+     * @see #addCallback(ChangeCallback)
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void removeCallback(ChangeCallback callback) {
+        mCallbacks.remove(callback);
+    }
+
+    private void dispatchChange() {
+        int start = mStartPos;
+        int end = mStartPos + mItems.size();
+        for (Map.Entry<ChangeCallback, ChangeCallbackWrapper> mCallback : mCallbacks) {
+            mCallback.getValue().dispatchLoaded(start, end);
+        }
+    }
+
+    /**
+     * Callback that signals when new content is loaded in the list.
+     */
+    public abstract static class ChangeCallback {
+        /**
+         * Called when new content is loaded into the LazyList.
+         *
+         * @param start Start index of the newly loaded items.
+         * @param count Number of newly loaded items.
+         */
+        public abstract void onLoaded(int start, int count);
+    }
+
+    private static class ChangeCallbackWrapper {
+        private final ChangeCallback mChangeCallback;
+        private int mKnownStart;
+        private int mKnownEnd;
+
+        ChangeCallbackWrapper(@NonNull ChangeCallback changeCallback,
+                int knownStart, int knownEnd) {
+            mChangeCallback = changeCallback;
+            mKnownStart = knownStart;
+            mKnownEnd = knownEnd;
+        }
+
+        void dispatchLoaded(int currentStart, int currentEnd) {
+            if (currentEnd > mKnownEnd) {
+                mChangeCallback.onLoaded(mKnownEnd, currentEnd - mKnownEnd);
+                mKnownEnd = currentEnd;
+            }
+            if (currentStart < mKnownStart) {
+                mChangeCallback.onLoaded(currentStart, mKnownStart - currentStart);
+                mKnownStart = currentStart;
+            }
+        }
+    }
+
+
+    // ---- PagerBase implementation ----
+
+    @Override
+    void onItemsPrepended(int count) {
+        mStartPos -= count;
+        dispatchChange();
+    }
+
+    @Override
+    void onItemsAppended(int count) {
+        dispatchChange();
+    }
+
+    @Override
+    void loadBeforeIfNeeded() {
+        if (mMissedMinIndex >= mStartPos) {
+            // done loading
+            mMissedMinIndex = Integer.MAX_VALUE;
+        } else {
+            // not done, resume loading
+            loadBefore(mStartPos);
+        }
+    }
+
+    @Override
+    void loadAfterIfNeeded() {
+        if (mMissedMaxIndex <= mStartPos + mItems.size() - 1) {
+            // done loading
+            mMissedMaxIndex = 0;
+        } else {
+            // not done, resume loading
+            loadAfter(mStartPos + mItems.size() - 1);
+        }
+    }
+
+    @Nullable
+    @Override
+    List<Type> loadBeforeImpl(int position, Type item) {
+        return mCountedDataSource.loadBefore(position, item, mConfig.mPageSize);
+    }
+
+    @Nullable
+    @Override
+    List<Type> loadAfterImpl(int position, Type item) {
+        return mCountedDataSource.loadAfter(position, item, mConfig.mPageSize);
+    }
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/ListConfig.java b/paging/common/src/main/java/android/arch/util/paging/ListConfig.java
new file mode 100644
index 0000000..8c3777c
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/ListConfig.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+/**
+ * Configuration object for list paging. Used to inform how and when a {@link LazyList} loads
+ * content from a {@link CountedDataSource}.
+ */
+public class ListConfig {
+    final int mPageSize;
+    final int mPrefetchDistance;
+
+    ListConfig(int pageSize, int prefetchDistance) {
+        mPageSize = pageSize;
+        mPrefetchDistance = prefetchDistance;
+    }
+
+    /**
+     * Creates a {@link Builder} that can be used to construct a {@link ListConfig}.
+     *
+     * @return a new {@link Builder}.
+     */
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    /**
+     * Builder class for {@link ListConfig}.
+     * <p>
+     * You must at minimum specify a {@link Builder#pageSize(int)}.
+     */
+    public static class Builder {
+        private int mPageSize = -1;
+        private int mPrefetchDistance = -1;
+
+        /**
+         * Defines the number of items loaded at once from the DataSource.
+         * <p>
+         * Should be several times the number of visible items onscreen.
+         */
+        public Builder pageSize(int pageSize) {
+            this.mPageSize = pageSize;
+            return this;
+        }
+
+        /**
+         * Defines how far from the edge of loaded content an access must be to trigger further
+         * loading. Defaults to page size.
+         * <p>
+         * A value of 0 indicates that no list items will be loaded before they are first requested.
+         * <p>
+         * Should be several times the number of visible items onscreen.
+         */
+        public Builder prefetchDistance(int prefetchDistance) {
+            this.mPrefetchDistance = prefetchDistance;
+            return this;
+        }
+
+        /**
+         * Creates a {@link ListConfig} with the given parameters.
+         *
+         * @return A new ListConfig.
+         */
+        public ListConfig create() {
+            if (mPageSize < 1) {
+                throw new IllegalArgumentException("Page size must be a positive number");
+            }
+            if (mPrefetchDistance < 0) {
+                mPrefetchDistance = mPageSize;
+            }
+            return new ListConfig(mPageSize, mPrefetchDistance);
+        }
+    }
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/PagedList.java b/paging/common/src/main/java/android/arch/util/paging/PagedList.java
new file mode 100644
index 0000000..283b062
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/PagedList.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.arch.core.internal.SafeIterableMap;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.WorkerThread;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executor;
+
+/**
+ * Lazy loading list that starts at size 0, and expands its size by loading pages
+ * asynchronously from a DataSource.
+ *
+ * @param <Type> Data type held by this list.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class PagedList<Type> extends PagerBase<Type> {
+    private static final int INVALID_DATA_POSITION = -1;
+
+    // Distance from front of list that should be prefetched.
+    private int mMinTarget = 0;
+
+    // Distance from tail of list that should be prefetched.
+    private int mMaxTarget = 0;
+
+    /**
+     * Stores the delta between the anchor and the most recently accessed item.
+     *
+     * The most recently accessed item's index can be referenced
+     * by adding this value to {@link #mAnchor}.
+     */
+    private volatile int mInterestedKeyOffset = -1;
+
+    // anchor position used to calculate deltas based on what revision observers last saw
+    private int mAnchor = 0;
+
+    private DataSource<Object, Type> mDataSource;
+
+    private SafeIterableMap<ChangeCallback,
+                ChangeCallbackWrapper> mCallbacks = new SafeIterableMap<>();
+
+    @WorkerThread
+    public <Key> PagedList(@NonNull DataSource<Key, Type> dataSource,
+            @NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            @NonNull ListConfig config) {
+        super(mainThreadExecutor, backgroundThreadExecutor, config);
+        if (config.mPrefetchDistance <= 0) {
+            // TODO: catch this in PagedListAdapterHelper too
+            throw new IllegalArgumentException("PagedList requires a positive prefetch distance"
+                    + " to be able to trigger page loading.");
+        }
+
+        mDataSource = (DataSource<Object, Type>) dataSource;
+    }
+
+    // ---- List ----
+
+    @Override
+    @NonNull
+    public Type get(int index) {
+        if (index < 0 || index >= size()) {
+            throw new IllegalArgumentException();
+        }
+        final int prefetchDistance = mConfig.mPrefetchDistance;
+        int minTarget = prefetchDistance - index;
+        if (minTarget > mMinTarget) {
+            mMinTarget = minTarget;
+            loadBeforeIfNeeded();
+        }
+        int maxTarget = index + prefetchDistance - size();
+        if (maxTarget > mMaxTarget) {
+            mMaxTarget = maxTarget;
+            loadAfterIfNeeded();
+        }
+
+        mInterestedKeyOffset = index - mAnchor;
+
+        return mItems.get(index);
+    }
+
+    @Override
+    @NonNull
+    public Type access(int index) {
+        if (index < 0 || index >= size()) {
+            throw new IllegalArgumentException();
+        }
+        return mItems.get(index);
+    }
+
+    @Override
+    public int size() {
+        return mItems == null ? 0 : mItems.size();
+    }
+
+
+    // ---- Initial data ----
+
+    /**
+     * Post a background task to execute loadAfter(null), and initialize the PagedList
+     * with its result.
+     */
+    @MainThread
+    public <Key> void triggerInitialLoad(final Key initialLoadKey) {
+        if (mInitialized) {
+            return;
+        }
+        mInitialized = true;
+        mBackgroundThreadExecutor.execute(new Runnable() {
+            @Override
+            public void run() {
+                if (mInvalid.get()) {
+                    return;
+                }
+
+                final List<Type> initialData =
+                        mDataSource.loadAfterInitial(initialLoadKey, mConfig.mPageSize);
+                if (initialData != null) {
+                    mMainThreadExecutor.execute(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (mInvalid.get()) {
+                                return;
+                            }
+                            setInitialDataAndDispatch(initialData);
+                        }
+                    });
+                } else {
+                    freeze();
+                }
+            }
+        });
+    }
+
+    /**
+     * Initialize the PagedList from the most-recently-accessed position information from the 'old'
+     * PagedList.
+     *
+     * This may be called on a background thread, and will only access immutable-once-invalid state
+     * in the old list, plus the volatile mInterestedKeyOffset field.
+     */
+    @WorkerThread
+    public boolean initializeFrom(PagedList<Type> old) {
+        // Note: even though old may be actively used on the foreground thread, we carefully only
+        // access parts that are immutable once old is invalid:
+        // mAnchor, and mItems (since no further prepends/appends can occur)
+
+        int targetIndex = (old.mAnchor + old.mInterestedKeyOffset);
+        int loadAfterIndex = Math.max(0, targetIndex - mConfig.mPageSize / 2) - 1;
+
+        Object loadAfterKey = null;
+        if (loadAfterIndex >= 0) {
+            Type loadAfterItem = old.mItems.get(loadAfterIndex);
+            loadAfterKey = mDataSource.getKey(loadAfterItem);
+        }
+
+        List<Type> initialData =
+                mDataSource.loadAfterInitial(loadAfterKey, mConfig.mPageSize);
+        if (initialData != null) {
+            setInitialDataAndDispatch(initialData);
+            mInitialized = true;
+            return true;
+        } else {
+            freeze();
+            return false;
+        }
+    }
+
+    // ---- Callback ----
+
+    private void setInitialDataAndDispatch(List<Type> items) {
+        // NOTE: while it's possible to prefetch given initial data, but we defer first prefetch
+        // until a consumer triggers it, so that the list is immutable until get() is called.
+
+        setInitialData(items);
+        dispatchChange();
+    }
+
+    /**
+     * Adds a change callback, to observe when new content is loaded into the list. The callback is
+     * invoked when the list has newly loaded content prepended, or appended.
+     *
+     * @param callback The callback, invoked on the main thread.
+     *
+     * @see #removeCallback(ChangeCallback)
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void addCallback(ChangeCallback callback) {
+        ChangeCallbackWrapper wrapper = new ChangeCallbackWrapper(callback, mAnchor, size());
+        // do not notify the latest data so the observer can distinguish whether the data has
+        // really changed or not.
+        mCallbacks.putIfAbsent(callback, wrapper);
+    }
+
+    /**
+     * Removes a previously added change callback.
+     *
+     * @param callback The callback, invoked on the main thread.
+     *
+     * @see #addCallback(ChangeCallback)
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void removeCallback(ChangeCallback callback) {
+        mCallbacks.remove(callback);
+    }
+
+    private void dispatchChange() {
+        int anchor = mAnchor;
+        int size = mItems.size();
+        for (Map.Entry<ChangeCallback, ChangeCallbackWrapper> mCallback : mCallbacks) {
+            mCallback.getValue().dispatchLoaded(anchor, size);
+        }
+    }
+
+    /**
+     * Callback that signals when new content is loaded in the list.
+     */
+    public abstract static class ChangeCallback {
+        /**
+         * Called when new content is inserted into the PagedList.
+         *
+         * @param start Index where the items have been inserted.
+         * @param count Number of newly inserted items.
+         */
+        public abstract void onInserted(int start, int count);
+    }
+
+    static class ChangeCallbackWrapper {
+        final ChangeCallback mChangeCallback;
+        private int mKnownAnchor;
+        private int mKnownSize;
+
+        ChangeCallbackWrapper(@NonNull ChangeCallback changeCallback,
+                int knownAnchor, int knownSize) {
+            mChangeCallback = changeCallback;
+            mKnownAnchor = knownAnchor;
+            mKnownSize = knownSize;
+        }
+
+        void dispatchLoaded(int currentAnchor, int currentSize) {
+            if (currentAnchor > mKnownAnchor) {
+                int itemsAddedToFront = currentAnchor - mKnownAnchor;
+                mChangeCallback.onInserted(0, itemsAddedToFront);
+                mKnownSize += itemsAddedToFront;
+                mKnownAnchor = currentAnchor;
+            }
+            if (mKnownSize < currentSize) {
+                int itemsAddedToBack = currentSize - mKnownSize;
+                mChangeCallback.onInserted(mKnownSize, itemsAddedToBack);
+                mKnownSize += itemsAddedToBack;
+            }
+        }
+    }
+
+
+    // ---- PagerBase implementation ----
+
+    @Override
+    void onItemsPrepended(int count) {
+        if (mMinTarget > 0) {
+            mMinTarget -= count;
+        }
+        mAnchor += count;
+        dispatchChange();
+    }
+
+    @Override
+    void onItemsAppended(int count) {
+        if (mMaxTarget > 0) {
+            mMaxTarget -= count;
+        }
+        dispatchChange();
+    }
+
+    @Override
+    void loadBeforeIfNeeded() {
+        if (mMinTarget > 0) {
+            loadBefore(INVALID_DATA_POSITION);
+        }
+    }
+
+    @Override
+    void loadAfterIfNeeded() {
+        if (mMaxTarget > 0) {
+            loadAfter(INVALID_DATA_POSITION);
+        }
+    }
+
+    @Nullable
+    @Override
+    List<Type> loadBeforeImpl(int position, Type item) {
+        return mDataSource.loadBefore(item, mConfig.mPageSize);
+    }
+
+    @Nullable
+    @Override
+    List<Type> loadAfterImpl(int position, Type item) {
+        return mDataSource.loadAfter(item, mConfig.mPageSize);
+    }
+}
diff --git a/paging/common/src/main/java/android/arch/util/paging/PagerBase.java b/paging/common/src/main/java/android/arch/util/paging/PagerBase.java
new file mode 100644
index 0000000..d53446d
--- /dev/null
+++ b/paging/common/src/main/java/android/arch/util/paging/PagerBase.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.WorkerThread;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * @param <Type> Data type held by this list.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class PagerBase<Type> {
+    List<Type> mItems;
+
+    private boolean mLoadBefore = false;
+    private boolean mLoadAfter = false;
+
+    /**
+     * Gets an item from the specified index, and loads content appropriately as a side effect.
+     * Must be between 0 and {@link #size()}.
+     *
+     * @param index Index of item to return.
+     * @return Item requested.
+     */
+    public abstract Type get(int index);
+
+    /**
+     * Gets an item from the specified index, but without side effects. Must be between 0 and
+     * {@link #size()}.
+     *
+     * @param index Index of item to return.
+     * @return Item requested.
+     */
+    public abstract Type access(int index);
+
+    /**
+     * @return Size of list.
+     */
+    public abstract int size();
+
+    boolean mInitialized;
+
+    @NonNull
+    final Executor mMainThreadExecutor;
+    @NonNull
+    final Executor mBackgroundThreadExecutor;
+
+    @Nullable
+    abstract List<Type> loadBeforeImpl(int position, Type item);
+
+    @Nullable
+    abstract List<Type> loadAfterImpl(int position, Type item);
+
+    // trigger loadBefore if positions loaded after/before aren't good enough
+    abstract void loadBeforeIfNeeded();
+
+    abstract void loadAfterIfNeeded();
+
+    // used to communicated to list provider to issue a new version
+    abstract void onItemsPrepended(int count);
+
+    abstract void onItemsAppended(int count);
+
+    AtomicBoolean mInvalid = new AtomicBoolean(false);
+    final ListConfig mConfig;
+
+    @WorkerThread
+    PagerBase(@NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            ListConfig configuration) {
+        mConfig = configuration;
+        mMainThreadExecutor = mainThreadExecutor;
+        mBackgroundThreadExecutor = backgroundThreadExecutor;
+    }
+
+    void freeze() {
+        mInvalid.set(true);
+    }
+
+    void setInitialData(List<Type> items) {
+        mItems = new ArrayList<>(items);
+        if (mItems.size() == 0) {
+            // No data loaded, so display no data, and don't try to load more.
+            mLoadBefore = mLoadAfter = true;
+        }
+        loadAfterIfNeeded();
+        loadBeforeIfNeeded();
+    }
+
+    @MainThread
+    protected void loadBefore(final int position) {
+        if (mLoadBefore) {
+            return;
+        }
+        mLoadBefore = true;
+
+        final Type item = mItems.get(0);
+        mBackgroundThreadExecutor.execute(new Runnable() {
+            @Override
+            public void run() {
+
+                if (mInvalid.get()) {
+                    return;
+                }
+
+                final List<Type> data = loadBeforeImpl(position, item);
+                if (data != null) {
+                    mMainThreadExecutor.execute(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (mInvalid.get()) {
+                                return;
+                            }
+                            prepend(data);
+                        }
+                    });
+                } else {
+                    freeze();
+                }
+            }
+        });
+    }
+
+    @MainThread
+    protected void loadAfter(final int position) {
+        if (mLoadAfter) {
+            return;
+        }
+        mLoadAfter = true;
+
+        final Type item = mItems.get(mItems.size() - 1);
+        mBackgroundThreadExecutor.execute(new Runnable() {
+            @Override
+            public void run() {
+                if (mInvalid.get()) {
+                    return;
+                }
+
+                final List<Type> data = loadAfterImpl(position, item);
+                if (data != null) {
+                    mMainThreadExecutor.execute(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (mInvalid.get()) {
+                                return;
+                            }
+                            append(data);
+                        }
+                    });
+                } else {
+                    freeze();
+                }
+            }
+        });
+    }
+
+    @MainThread
+    private void prepend(List<Type> before) {
+        final int count = before.size();
+        if (count == 0) {
+            // Nothing returned from source, stop loading in this direction
+            return;
+        }
+
+        Collections.reverse(before);
+        mItems.addAll(0, before);
+        onItemsPrepended(count);
+
+        mLoadBefore = false;
+        loadBeforeIfNeeded();
+    }
+
+    @MainThread
+    private void append(List<Type> after) {
+        final int count = after.size();
+        if (count == 0) {
+            // Nothing returned from source, stop loading in this direction
+            return;
+        }
+
+        mItems.addAll(after);
+        onItemsAppended(count);
+
+        mLoadAfter = false;
+        loadAfterIfNeeded();
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/LazyListTest.java b/paging/common/src/test/java/android/arch/util/paging/LazyListTest.java
new file mode 100644
index 0000000..7bede2e
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/LazyListTest.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mockito;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
+@RunWith(JUnit4.class)
+public class LazyListTest {
+    private TestExecutor mMainThread = new TestExecutor();
+    private TestExecutor mBackgroundThread = new TestExecutor();
+    private TestCountedDataSource mDataSource;
+
+    private LazyList.ChangeCallback mChangeCallback = Mockito.mock(LazyList.ChangeCallback.class);
+
+    private LazyList<User> createLazyList(int pageSize, int prefetchCount) {
+        LazyList<User> lazyList = new LazyList<>(mDataSource, mMainThread, mBackgroundThread,
+                 new ListConfig(pageSize, prefetchCount));
+        lazyList.addCallback(mChangeCallback);
+        return lazyList;
+    }
+
+    @Before
+    public void setup() {
+        mDataSource = new TestCountedDataSource();
+    }
+
+    @Test
+    public void initial() {
+        LazyList<User> lazyList = createLazyList(20, 5);
+        assertNull(lazyList.get(0));
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 20);
+
+        lazyList = createLazyList(10, 5);
+        assertNull(lazyList.get(0));
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 10);
+    }
+
+    @Test
+    public void initialReturnsEmpty() {
+        mDataSource.setCount(200);
+        LazyList<User> lazyList = createLazyList(20, 5);
+        assertEquals(200, lazyList.size());
+
+
+        // trigger initial load that returns nothing
+        mDataSource.setCount(0);
+        lazyList.get(0);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 0);
+
+        // now further accesses don't trigger loads
+        mDataSource.setCount(200);
+        lazyList.get(100);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 0);
+    }
+
+    @Test
+    public void initialPrefetch() {
+        LazyList<User> lazyList = createLazyList(20, 20);
+        assertNull(lazyList.get(9));
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 40);
+    }
+
+    @Test
+    public void initialPrefetchMultiple() {
+        LazyList<User> lazyList = createLazyList(20, 90);
+        lazyList.get(0);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 100);
+    }
+
+    @Test
+    public void incrementalLoading() {
+        LazyList<User> lazyList = createLazyList(20, 20);
+        lazyList.get(0);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 40);
+
+        lazyList.get(39);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 60);
+
+        lazyList.get(41);
+        drain();
+        TestCountedDataSource.verifyRange(lazyList, 0, 80);
+    }
+
+    private static <T> List<T> reverse(List<T> input) {
+        ArrayList<T> result = new ArrayList<>(input);
+        Collections.reverse(result);
+        return result;
+    }
+
+    private void drain() {
+        boolean executed;
+        do {
+            executed = mBackgroundThread.executeAll();
+            executed |= mMainThread.executeAll();
+        } while (executed);
+
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/PagedListTest.java b/paging/common/src/test/java/android/arch/util/paging/PagedListTest.java
new file mode 100644
index 0000000..8cd4665
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/PagedListTest.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import static junit.framework.TestCase.fail;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mockito;
+
+@RunWith(JUnit4.class)
+public class PagedListTest {
+    private TestExecutor mMainThread = new TestExecutor();
+    private TestExecutor mBackgroundThread = new TestExecutor();
+    private TestDataSource mDataSource = new TestDataSource();
+
+    private PagedList.ChangeCallback mChangeCallback = Mockito.mock(PagedList.ChangeCallback.class);
+
+    @Test
+    public void callbackSimple() {
+        PagedList.ChangeCallback callback = Mockito.mock(PagedList.ChangeCallback.class);
+        PagedList.ChangeCallbackWrapper wrapper =
+                new PagedList.ChangeCallbackWrapper(callback, 0, 0);
+
+        wrapper.dispatchLoaded(0, 10);
+        verify(callback).onInserted(0, 10);
+        verifyNoMoreInteractions(callback);
+
+        wrapper.dispatchLoaded(0, 10);
+        verifyNoMoreInteractions(callback);
+
+        wrapper.dispatchLoaded(0, 20);
+        verify(callback).onInserted(10, 10);
+        verifyNoMoreInteractions(callback);
+    }
+
+    @Test
+    public void callbackComplex() {
+        PagedList.ChangeCallback callback = Mockito.mock(PagedList.ChangeCallback.class);
+        PagedList.ChangeCallbackWrapper wrapper =
+                new PagedList.ChangeCallbackWrapper(callback, 0, 0);
+
+        wrapper.dispatchLoaded(0, 8);
+        verify(callback).onInserted(0, 8);
+        verifyNoMoreInteractions(callback);
+
+        wrapper.dispatchLoaded(10, 18);
+        verify(callback).onInserted(0, 10);
+        verifyNoMoreInteractions(callback);
+
+        wrapper.dispatchLoaded(10, 22);
+        verify(callback).onInserted(18, 4);
+        verifyNoMoreInteractions(callback);
+
+        // Note: prepend before append is impl detail
+        wrapper.dispatchLoaded(12, 25);
+        verify(callback).onInserted(0, 2);
+        verify(callback).onInserted(24, 1);
+        verifyNoMoreInteractions(callback);
+    }
+
+    private PagedList<User> createPagedList(int pageSize, int prefetchDistance) {
+        PagedList<User> pagedList = new PagedList<>(
+                mDataSource, mMainThread, mBackgroundThread,
+                new ListConfig(pageSize, prefetchDistance));
+        pagedList.addCallback(mChangeCallback);
+        return pagedList;
+    }
+
+    private PagedList<User> createPagedListInitializedFrom(PagedList<User> old) {
+        PagedList<User> pagedList = new PagedList<>(
+                mDataSource, mMainThread, mBackgroundThread,
+                old.mConfig);
+        if (!pagedList.initializeFrom(old)) {
+            fail();
+        }
+        return pagedList;
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void requirePrefetch() {
+        createPagedList(20, 0);
+    }
+
+    @Test
+    public void initial() {
+        PagedList<User> pagedList = createPagedList(20, 5);
+        pagedList.triggerInitialLoad(null);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 20);
+
+        pagedList = createPagedList(10, 5);
+        pagedList.triggerInitialLoad(null);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 10);
+    }
+
+    @Test
+    public void initialPrefetch() {
+        PagedList<User> pagedList = createPagedList(20, 20);
+        pagedList.triggerInitialLoad(null);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 20);
+
+        // Note: pagedList doesn't prefetch after initial load until first get call
+        pagedList.get(10);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 40);
+    }
+
+    @Test
+    public void initialPrefetchMultiple() {
+        PagedList<User> pagedList = createPagedList(20, 90);
+        pagedList.triggerInitialLoad(null);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 20);
+
+        // Note: pagedList doesn't prefetch after initial load until first get call
+        pagedList.get(0);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 100);
+    }
+
+    @Test
+    public void incrementalLoading() {
+        PagedList<User> pagedList = createPagedList(20, 20);
+        pagedList.triggerInitialLoad(null);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 20);
+
+        pagedList.get(5);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 40);
+
+        pagedList.get(39);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 60);
+
+        pagedList.get(41);
+        drain();
+        TestDataSource.verifyRange(pagedList, 0, 80);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void get_tooEarly() {
+        PagedList<User> pagedList = createPagedList(20, 20);
+        pagedList.triggerInitialLoad(null);
+        assertEquals(0, pagedList.size());
+        pagedList.get(0); // task hasn't run, zero size currently
+    }
+
+    @Test
+    public void initializeFrom() {
+        PagedList<User> pagedList = createPagedList(20, 20);
+        pagedList.triggerInitialLoad(null);
+        drain();
+    }
+
+    private void drain() {
+        boolean executed;
+        do {
+            executed = mBackgroundThread.executeAll();
+            executed |= mMainThread.executeAll();
+        } while (executed);
+
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/TestCountedDataSource.java b/paging/common/src/test/java/android/arch/util/paging/TestCountedDataSource.java
new file mode 100644
index 0000000..04ad89a
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/TestCountedDataSource.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class TestCountedDataSource extends CountedDataSource<User> {
+    private static final ArrayList<User> sUsers = TestDataSource.sUsers;
+
+    private int mCount = sUsers.size();
+
+    static void verifyRange(LazyList<User> list, int start, int end) {
+        assertEquals("size should be same", end - start, list.mItems.size());
+        for (int i = 0; i < list.mItems.size(); i++) {
+            // NOTE: avoid getter, to avoid signaling
+            assertSame(sUsers.get(start + i), list.mItems.get(i));
+        }
+    }
+
+    public void setCount(int count) {
+        assertTrue(count <= sUsers.size());
+        mCount = count;
+    }
+
+    @Override
+    public int loadCount() {
+        return mCount;
+    }
+
+    private List<User> getClampedRange(int start, int end) {
+        start = Math.max(0, start);
+        end = Math.min(loadCount(), end);
+        return sUsers.subList(start, end);
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadAfterInitial(int position, int pageSize) {
+        return getClampedRange(position + 1, position + 1 + pageSize);
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadAfter(int currentEndIndex, @NonNull User currentEndItem, int pageSize) {
+        return getClampedRange(currentEndIndex + 1, currentEndIndex + 1 + pageSize);
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadBefore(int currentBeginIndex, @NonNull User currentBeginItem,
+            int pageSize) {
+        return getClampedRange(currentBeginIndex - 1 - pageSize, currentBeginIndex);
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/TestDataSource.java b/paging/common/src/test/java/android/arch/util/paging/TestDataSource.java
new file mode 100644
index 0000000..11fd2eb
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/TestDataSource.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class TestDataSource extends DataSource<String, User> {
+    static final ArrayList<User> sUsers = new ArrayList<>();
+    static {
+        for (int i = 0; i < 300; i++) {
+            sUsers.add(new User(String.format("%03d", i), "Usernr " + i));
+        }
+    }
+
+    static void verifyRange(PagedList<User> list, int start, int end) {
+        assertEquals(end - start, list.size());
+        for (int i = 0; i < list.size(); i++) {
+            // NOTE: avoid getter, to avoid signaling
+            assertSame(sUsers.get(start + i), list.mItems.get(i));
+        }
+    }
+
+    @Override
+    public String getKey(@NonNull User item) {
+        return item.name;
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadAfterInitial(@Nullable String itemName, int pageSize) {
+        if (itemName == null) {
+            itemName = "";
+        }
+        ArrayList<User> users = new ArrayList<>();
+        int index;
+        for (index = 0; index < sUsers.size(); index++) {
+            if (itemName.compareTo(sUsers.get(index).name) < 0) {
+                break;
+            }
+        }
+        for (int i = 0; i < pageSize && index + i < sUsers.size(); i++) {
+            users.add(sUsers.get(index + i));
+        }
+        return users;
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadAfter(@NonNull User currentEndItem, int pageSize) {
+        return loadAfterInitial(currentEndItem.name, pageSize);
+    }
+
+    @Nullable
+    @Override
+    public List<User> loadBefore(@NonNull User currentBeginItem, int pageSize) {
+        ArrayList<User> users = new ArrayList<>();
+        int index;
+        for (index = sUsers.size() - 1; index >= 0; index--) {
+            if (currentBeginItem.name.compareTo(sUsers.get(index).name) > 0) {
+                break;
+            }
+        }
+        for (int i = 0; i < pageSize && index - i >= 0; i++) {
+            users.add(sUsers.get(index - i));
+        }
+        return users;
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/TestExecutor.java b/paging/common/src/test/java/android/arch/util/paging/TestExecutor.java
new file mode 100644
index 0000000..6a3f188
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/TestExecutor.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.NonNull;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.Executor;
+
+public class TestExecutor implements Executor {
+    private Queue<Runnable> mTasks = new LinkedList<>();
+
+    @Override
+    public void execute(@NonNull Runnable command) {
+        mTasks.add(command);
+    }
+
+    boolean executeAll() {
+        boolean consumed = !mTasks.isEmpty();
+        Runnable task;
+        while ((task = mTasks.poll()) != null) {
+            task.run();
+        }
+        return consumed;
+    }
+}
diff --git a/paging/common/src/test/java/android/arch/util/paging/User.java b/paging/common/src/test/java/android/arch/util/paging/User.java
new file mode 100644
index 0000000..f486955
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/util/paging/User.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+public class User {
+    public final String name;
+    public final String info;
+
+    public User(String name, String info) {
+        this.name = name;
+        this.info = info;
+    }
+
+    @Override
+    public String toString() {
+        return name;
+    }
+}
diff --git a/paging/integration-tests/testapp/.gitignore b/paging/integration-tests/testapp/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/paging/integration-tests/testapp/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/paging/integration-tests/testapp/build.gradle b/paging/integration-tests/testapp/build.gradle
new file mode 100644
index 0000000..5356dd4
--- /dev/null
+++ b/paging/integration-tests/testapp/build.gradle
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+apply plugin: 'com.android.application'
+
+project.ext.noDocs = true
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+    }
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile project(':arch:runtime')
+    compile project(':arch:common')
+    compile project(':paging:common')
+    compile project(':lifecycle:extensions')
+    compile project(':lifecycle:runtime')
+    compile project(':lifecycle:common')
+    compile project(':paging:runtime')
+    compile 'com.android.support:multidex:1.0.1'
+
+    compile libs.support.recyclerview
+    compile libs.support.app_compat
+}
+
+createAndroidCheckstyle(project)
+tasks['check'].dependsOn(tasks['connectedCheck'])
+
+uploadArchives.enabled = false
diff --git a/paging/integration-tests/testapp/proguard-rules.pro b/paging/integration-tests/testapp/proguard-rules.pro
new file mode 100644
index 0000000..b7210d1
--- /dev/null
+++ b/paging/integration-tests/testapp/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/yboyar/android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
diff --git a/paging/integration-tests/testapp/src/main/AndroidManifest.xml b/paging/integration-tests/testapp/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..fc86e8d
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.paging.integration.testapp">
+    <application
+        android:allowBackup="true"
+        android:supportsRtl="true">
+        <activity
+            android:name=".lazylist.LazyListRecyclerViewActivity"
+            android:label="LazyList"
+            android:theme="@style/Theme.AppCompat">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity
+            android:name=".pagedlist.PagedListRecyclerViewActivity"
+            android:label="PagedList"
+            android:theme="@style/Theme.AppCompat">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+  </manifest>
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/Item.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/Item.java
new file mode 100644
index 0000000..0a7b0f0
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/Item.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp;
+
+import android.arch.util.paging.DiffCallback;
+import android.support.annotation.NonNull;
+
+/**
+ * Sample item.
+ */
+public class Item {
+    public final int id;
+    public final String text;
+    public final int bgColor;
+
+    public Item(int id, String text, int bgColor) {
+        this.id = id;
+        this.text = text;
+        this.bgColor = bgColor;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Item item = (Item) o;
+        return this.id == item.id
+                && this.bgColor == item.bgColor
+                && this.text.equals(item.text);
+    }
+
+    public static final DiffCallback<Item> DIFF_CALLBACK = new DiffCallback<Item>() {
+        @Override
+        public boolean areContentsTheSame(@NonNull Item oldItem, @NonNull Item newItem) {
+            return oldItem.equals(newItem);
+        }
+
+        @Override
+        public boolean areItemsTheSame(@NonNull Item oldItem, @NonNull Item newItem) {
+            return oldItem.id == newItem.id;
+        }
+    };
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemCountedDataSource.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemCountedDataSource.java
new file mode 100644
index 0000000..89dd844
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemCountedDataSource.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp;
+
+import android.arch.util.paging.CountedDataSource;
+import android.graphics.Color;
+import android.support.annotation.ColorInt;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Sample data source with artificial data.
+ */
+public class ItemCountedDataSource extends CountedDataSource<Item> {
+    @ColorInt
+    private static final int[] COLORS = new int[] {
+            Color.RED,
+            Color.BLUE,
+            Color.BLACK,
+    };
+
+    private static int sGenerationId;
+    private final int mGenerationId = sGenerationId++;
+
+    @Override
+    public int loadCount() {
+        return 10000;
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadAfterInitial(int position, int pageSize) {
+        return createItems(position + 1, pageSize, 1);
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadAfter(int currentEndIndex, @NonNull Item currentEndItem, int pageSize) {
+        return createItems(currentEndIndex + 1, pageSize, 1);
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadBefore(int currentBeginIndex, @NonNull Item currentBeginItem,
+            int pageSize) {
+        return createItems(currentBeginIndex - 1, pageSize, -1);
+    }
+
+    @Nullable
+    private List<Item> createItems(int start, int count, int direction) {
+        if (isInvalid()) {
+            // abort!
+            return null;
+        }
+
+        List<Item> items = new ArrayList<>();
+        int end = Math.max(-1, Math.min(loadCount(), start + direction * count));
+        int bgColor = COLORS[mGenerationId % COLORS.length];
+
+        try {
+            Thread.sleep(300);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        for (int i = start; i != end; i += direction) {
+            items.add(new Item(i, "item " + i, bgColor));
+        }
+
+        if (isInvalid()) {
+            // abort!
+            return null;
+        }
+        return items;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java
new file mode 100644
index 0000000..cbfc247
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp;
+
+import android.arch.util.paging.DataSource;
+import android.graphics.Color;
+import android.support.annotation.ColorInt;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Sample data source with artificial data.
+ */
+public class ItemDataSource extends DataSource<Integer, Item> {
+    private static final int COUNT = 10000;
+
+    @ColorInt
+    private static final int[] COLORS = new int[] {
+            Color.RED,
+            Color.BLUE,
+            Color.BLACK,
+    };
+
+
+    private static int sGenerationId;
+    private final int mGenerationId = sGenerationId++;
+
+    @Override
+    public Integer getKey(@NonNull Item item) {
+        return item.id;
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadAfterInitial(@Nullable Integer position, int pageSize) {
+        if (position == null) {
+            position = -1;
+        }
+        return createItems(position + 1, pageSize, 1);
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadAfter(@NonNull Item currentEndItem, int pageSize) {
+        return createItems(currentEndItem.id + 1, pageSize, 1);
+    }
+
+    @Nullable
+    @Override
+    public List<Item> loadBefore(@NonNull Item currentBeginItem, int pageSize) {
+        return createItems(currentBeginItem.id - 1, pageSize, -1);
+    }
+
+    private List<Item> createItems(int start, int count, int direction) {
+        if (isInvalid()) {
+            // abort!
+            return null;
+        }
+
+        List<Item> items = new ArrayList<>();
+        int end = Math.max(-1, Math.min(COUNT, start + direction * count));
+        int bgColor = COLORS[mGenerationId % COLORS.length];
+
+        try {
+            Thread.sleep(300);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        for (int i = start; i != end; i += direction) {
+            items.add(new Item(i, "item " + i, bgColor));
+        }
+
+        if (isInvalid()) {
+            // abort!
+            return null;
+        }
+        return items;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemAdapter.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemAdapter.java
new file mode 100644
index 0000000..f24b717
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemAdapter.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.lazylist;
+
+import android.arch.paging.integration.testapp.Item;
+import android.arch.util.paging.LazyList;
+import android.arch.util.paging.LazyListAdapterHelper;
+import android.graphics.Color;
+import android.support.v7.widget.RecyclerView;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+/**
+ * Sample LazyList adapter, which uses a LazyListAdapterHelper.
+ */
+public class LazyListItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+
+    private final LazyListAdapterHelper<Item> mHelper;
+
+    LazyListItemAdapter() {
+        mHelper = LazyListAdapterHelper.<Item>builder()
+                .adapter(this)
+                .diffCallback(Item.DIFF_CALLBACK)
+                .create();
+    }
+
+    void setLazyList(LazyList<Item> list) {
+        mHelper.setLazyList(list);
+    }
+
+    @Override
+    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+        return new RecyclerView.ViewHolder(new TextView(parent.getContext())) {
+        };
+    }
+
+    @Override
+    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
+        Item item = mHelper.get(position);
+        ((TextView) (holder.itemView)).setText(item == null ? "loading" : item.text);
+        holder.itemView.setBackgroundColor(item == null ? Color.TRANSPARENT : item.bgColor);
+        holder.itemView.setMinimumHeight(400);
+    }
+
+    @Override
+    public int getItemCount() {
+        return mHelper.getItemCount();
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemViewModel.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemViewModel.java
new file mode 100644
index 0000000..3d0b3b4
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListItemViewModel.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.lazylist;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.ViewModel;
+import android.arch.paging.integration.testapp.Item;
+import android.arch.paging.integration.testapp.ItemCountedDataSource;
+import android.arch.util.paging.CountedDataSource;
+import android.arch.util.paging.LazyList;
+import android.arch.util.paging.ListConfig;
+import android.arch.util.paging.LiveLazyListProvider;
+
+/**
+ * Sample ViewModel backed by an artificial data source
+ */
+public class LazyListItemViewModel extends ViewModel {
+    private final LiveData<LazyList<Item>> mLiveLazyList;
+    private ItemCountedDataSource mDataSource;
+
+    public LazyListItemViewModel() {
+        mLiveLazyList = new LiveLazyListProvider<Item>() {
+            @Override
+            protected CountedDataSource<Item> createDataSource() {
+                mDataSource = new ItemCountedDataSource();
+                return mDataSource;
+            }
+        }.create(ListConfig.builder().pageSize(20).prefetchDistance(40).create());
+    }
+
+    void invalidateList() {
+        if (mDataSource != null) {
+            mDataSource.invalidate();
+        }
+    }
+
+    LiveData<LazyList<Item>> getLazyList() {
+        return mLiveLazyList;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListRecyclerViewActivity.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListRecyclerViewActivity.java
new file mode 100644
index 0000000..3e499d3
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/lazylist/LazyListRecyclerViewActivity.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.lazylist;
+
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LifecycleRegistryOwner;
+import android.arch.lifecycle.Observer;
+import android.arch.lifecycle.ViewModelProviders;
+import android.arch.paging.integration.testapp.Item;
+import android.arch.paging.integration.testapp.R;
+import android.arch.util.paging.LazyList;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v7.app.AppCompatActivity;
+import android.support.v7.widget.RecyclerView;
+import android.view.View;
+import android.widget.Button;
+
+/**
+ * Sample LazyList activity.
+ */
+public class LazyListRecyclerViewActivity extends AppCompatActivity
+        implements LifecycleRegistryOwner {
+
+    @Override
+    protected void onCreate(final Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final LazyListItemViewModel viewModel = ViewModelProviders.of(this)
+                .get(LazyListItemViewModel.class);
+        setContentView(R.layout.activity_recycler_view);
+
+        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
+        final LazyListItemAdapter adapter = new LazyListItemAdapter();
+
+
+        // TODO: helper initialization, with owner, recyclerview, LiveData<LazyList<Item>>
+        viewModel.getLazyList().observe(this, new Observer<LazyList<Item>>() {
+            @Override
+            public void onChanged(@Nullable LazyList<Item> itemLazyList) {
+                adapter.setLazyList(itemLazyList);
+                if (recyclerView.getAdapter() == null) {
+                    recyclerView.setAdapter(adapter);
+                }
+            }
+        });
+        final Button button = (Button) findViewById(R.id.button);
+        button.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                viewModel.invalidateList();
+            }
+        });
+    }
+
+    private LifecycleRegistry  mLifecycleRegistry = new LifecycleRegistry(this);
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemAdapter.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemAdapter.java
new file mode 100644
index 0000000..3f41267
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemAdapter.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.pagedlist;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.paging.integration.testapp.Item;
+import android.arch.util.paging.PagedList;
+import android.arch.util.paging.PagedListAdapterHelper;
+import android.arch.util.paging.PagerBaseAdapterHelper;
+import android.support.v7.widget.RecyclerView;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+/**
+ * Sample PagedList adapter, which uses a PagedListAdapterHelper.
+ */
+public class PagedListItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+    private final PagedListAdapterHelper<Item> mHelper;
+
+    PagedListItemAdapter() {
+        mHelper = new PagedListAdapterHelper<>(
+                AppToolkitTaskExecutor.getMainThreadExecutor(),
+                AppToolkitTaskExecutor.getIOThreadExecutor(),
+                new PagerBaseAdapterHelper.AdapterCallback(this),
+                Item.DIFF_CALLBACK);
+    }
+
+    void setPagedList(PagedList<Item> list) {
+        mHelper.setPagedList(list);
+    }
+
+    @Override
+    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+        RecyclerView.ViewHolder holder = new RecyclerView.ViewHolder(
+                new TextView(parent.getContext())) {};
+        holder.itemView.setMinimumHeight(400);
+        return holder;
+    }
+
+    @Override
+    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
+        Item item = mHelper.get(position);
+        ((TextView) (holder.itemView)).setText(item.text);
+        holder.itemView.setBackgroundColor(item.bgColor);
+    }
+
+    @Override
+    public int getItemCount() {
+        return mHelper.getItemCount();
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemViewModel.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemViewModel.java
new file mode 100644
index 0000000..e8fe13f
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListItemViewModel.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.pagedlist;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.ViewModel;
+import android.arch.paging.integration.testapp.Item;
+import android.arch.paging.integration.testapp.ItemDataSource;
+import android.arch.util.paging.DataSource;
+import android.arch.util.paging.ListConfig;
+import android.arch.util.paging.LivePagedListProvider;
+import android.arch.util.paging.PagedList;
+
+/**
+ * Sample ViewModel backed by an artificial data source
+ */
+public class PagedListItemViewModel extends ViewModel {
+    private final LiveData<PagedList<Item>> mLivePagedList;
+    private ItemDataSource mDataSource;
+
+    public PagedListItemViewModel() {
+        mLivePagedList = new LivePagedListProvider<Integer, Item>() {
+            @Override
+            protected DataSource<Integer, Item> createDataSource() {
+                mDataSource = new ItemDataSource();
+                return mDataSource;
+            }
+        }.create(ListConfig.builder().pageSize(20).prefetchDistance(40).create());
+    }
+
+    void invalidateList() {
+        if (mDataSource != null) {
+            mDataSource.invalidate();
+        }
+    }
+
+    LiveData<PagedList<Item>> getPagedList() {
+        return mLivePagedList;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListRecyclerViewActivity.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListRecyclerViewActivity.java
new file mode 100644
index 0000000..28e70f5
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/pagedlist/PagedListRecyclerViewActivity.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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 android.arch.paging.integration.testapp.pagedlist;
+
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LifecycleRegistryOwner;
+import android.arch.lifecycle.Observer;
+import android.arch.lifecycle.ViewModelProviders;
+import android.arch.paging.integration.testapp.Item;
+import android.arch.paging.integration.testapp.R;
+import android.arch.util.paging.PagedList;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v7.app.AppCompatActivity;
+import android.support.v7.widget.RecyclerView;
+import android.view.View;
+import android.widget.Button;
+
+/**
+ * Sample PagedList activity.
+ */
+public class PagedListRecyclerViewActivity extends AppCompatActivity
+        implements LifecycleRegistryOwner {
+
+    @Override
+    protected void onCreate(final Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final PagedListItemViewModel viewModel = ViewModelProviders.of(this)
+                .get(PagedListItemViewModel.class);
+        setContentView(R.layout.activity_recycler_view);
+
+        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
+        final PagedListItemAdapter adapter = new PagedListItemAdapter();
+
+        // TODO: Create and use PagedListAdapterHelper.builder
+        viewModel.getPagedList().observe(this, new Observer<PagedList<Item>>() {
+            @Override
+            public void onChanged(@Nullable PagedList<Item> itemPagedList) {
+                adapter.setPagedList(itemPagedList);
+                if (recyclerView.getAdapter() == null && itemPagedList != null) {
+                    itemPagedList.triggerInitialLoad(null); // TODO: Persist
+                    recyclerView.setAdapter(adapter);
+                }
+            }
+        });
+        final Button button = (Button) findViewById(R.id.button);
+        button.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                viewModel.invalidateList();
+            }
+        });
+    }
+
+    private LifecycleRegistry  mLifecycleRegistry = new LifecycleRegistry(this);
+
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+}
diff --git a/paging/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml b/paging/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
new file mode 100644
index 0000000..73a3e89
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/activity_recycler_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context=".lazylist.LazyListRecyclerViewActivity">
+    <android.support.v7.widget.RecyclerView
+        android:id="@+id/recyclerview"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        app:layoutManager="LinearLayoutManager"
+        android:clipToPadding="false"
+        android:paddingBottom="@dimen/activity_vertical_margin"
+        android:paddingLeft="@dimen/activity_horizontal_margin"
+        android:paddingRight="@dimen/activity_horizontal_margin"
+        android:paddingTop="@dimen/activity_vertical_margin"
+    />
+    <Button
+        android:id="@+id/button"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentRight="true"
+        android:text="Update"/>
+</RelativeLayout>
diff --git a/paging/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml b/paging/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml
new file mode 100644
index 0000000..edff918
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml
@@ -0,0 +1,23 @@
+
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>
diff --git a/paging/integration-tests/testapp/src/main/res/values/dimens.xml b/paging/integration-tests/testapp/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..3358489
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/res/values/dimens.xml
@@ -0,0 +1,21 @@
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>
diff --git a/paging/integration-tests/testapp/src/main/res/values/strings.xml b/paging/integration-tests/testapp/src/main/res/values/strings.xml
new file mode 100644
index 0000000..bed7093
--- /dev/null
+++ b/paging/integration-tests/testapp/src/main/res/values/strings.xml
@@ -0,0 +1,18 @@
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+</resources>
diff --git a/paging/runtime/build.gradle b/paging/runtime/build.gradle
new file mode 100644
index 0000000..ba3a764
--- /dev/null
+++ b/paging/runtime/build.gradle
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+// disable paging for now.
+project.ext.noDocs = true
+uploadArchives.enabled = false
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+
+    buildTypes.all {
+        consumerProguardFiles 'proguard-rules.pro'
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile project(":arch:runtime")
+    compile project(":paging:common")
+    compile project(":lifecycle:runtime")
+    compile project(':lifecycle:extensions')
+
+    compile libs.support.recyclerview
+    testCompile libs.junit
+    androidTestCompile libs.mockito_core
+    androidTestCompile libs.dexmaker_mockito
+    testCompile libs.support.annotations
+
+    androidTestCompile libs.junit
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+
+}
+
+archivesBaseName = "runtime"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/paging/runtime/proguard-rules.pro b/paging/runtime/proguard-rules.pro
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/paging/runtime/proguard-rules.pro
@@ -0,0 +1 @@
+
diff --git a/paging/runtime/src/androidTest/java/android/arch/util/paging/LazyListAdapterHelperTest.java b/paging/runtime/src/androidTest/java/android/arch/util/paging/LazyListAdapterHelperTest.java
new file mode 100644
index 0000000..a8b9572
--- /dev/null
+++ b/paging/runtime/src/androidTest/java/android/arch/util/paging/LazyListAdapterHelperTest.java
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
+import android.support.annotation.NonNull;
+import android.support.test.filters.SmallTest;
+import android.support.v7.util.ListUpdateCallback;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mockito;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.Executor;
+
+@SmallTest
+@RunWith(JUnit4.class)
+public class LazyListAdapterHelperTest {
+    public class TestExecutor implements Executor {
+        private Queue<Runnable> mTasks = new LinkedList<>();
+        @Override
+        public void execute(@NonNull Runnable command) {
+            mTasks.add(command);
+        }
+
+        boolean executeAll() {
+            boolean consumed = !mTasks.isEmpty();
+            Runnable task;
+            while ((task = mTasks.poll()) != null) {
+                task.run();
+            }
+            return consumed;
+        }
+    }
+
+    private TestExecutor mMainThread = new TestExecutor();
+    private TestExecutor mBackgroundThread = new TestExecutor();
+    private CountedDataSource<Item> mDataSource = new CountedDataSource<Item>() {
+        @Override
+        public int loadCount() {
+            return mItemData.size();
+        }
+
+        private List<Item> getClampedRange(int start, int end) {
+            start = Math.max(0, start);
+            end = Math.min(loadCount(), end);
+            return mItemData.subList(start, end);
+        }
+
+        @Override
+        public List<Item> loadAfterInitial(int position, int pageSize) {
+            return getClampedRange(position + 1, position + pageSize + 1);
+        }
+
+        @Override
+        public List<Item> loadAfter(int currentEndIndex, @NonNull Item currentEndItem,
+                int pageSize) {
+            return getClampedRange(currentEndIndex + 1, currentEndIndex + 1 + pageSize);
+        }
+
+        @Override
+        public List<Item> loadBefore(int currentBeginIndex, @NonNull Item currentBeginItem,
+                int pageSize) {
+            return getClampedRange(currentBeginIndex - 1 - pageSize, currentBeginIndex);
+        }
+    };
+
+    private static class Item {
+        int mId = 0;
+        int mGeneration = 0;
+
+        static final DiffCallback<Item> DIFF_CALLBACK = new DiffCallback<Item>() {
+            @Override
+            public boolean areContentsTheSame(@NonNull Item oldItem,
+                    @NonNull Item newItem) {
+                return oldItem.mId == newItem.mId;
+            }
+
+            @Override
+            public boolean areItemsTheSame(@NonNull Item oldItem,
+                    @NonNull Item newItem) {
+                return oldItem.equals(newItem);
+            }
+        };
+    }
+
+    private List<Item> mItemData = new ArrayList<>();
+
+    @Before
+    public void setup() {
+        for (int i = 0; i < 100; i++) {
+            Item item = new Item();
+            item.mId = i;
+            item.mGeneration = 0;
+            mItemData.add(item);
+        }
+    }
+
+    private LazyList<Item> createLazyList() {
+        return new LazyList<>(mDataSource, mMainThread, mBackgroundThread,
+                ListConfig.builder().pageSize(10).prefetchDistance(10).create());
+    }
+
+    private LazyListAdapterHelper<Item> createHelper(ListUpdateCallback callback) {
+        return LazyListAdapterHelper.<Item>builder()
+                .mainThreadExecutor(mMainThread)
+                .backgroundThreadExecutor(mBackgroundThread)
+                .updateCallback(callback)
+                .diffCallback(Item.DIFF_CALLBACK).create();
+    }
+
+    @Test
+    public void create() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        createHelper(callback);
+        verifyZeroInteractions(callback);
+    }
+
+    @Test
+    public void setEmpty() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        LazyListAdapterHelper<Item> helper = createHelper(callback);
+        verifyZeroInteractions(callback);
+
+        LazyList<Item> list = createLazyList();
+        helper.setLazyList(list);
+        drain();
+        verify(callback).onInserted(0, 100);
+        verifyNoMoreInteractions(callback);
+    }
+
+    @Test
+    public void setEmptyAndLoad() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        LazyListAdapterHelper<Item> helper = createHelper(callback);
+        verifyZeroInteractions(callback);
+
+        LazyList<Item> list = createLazyList();
+        helper.setLazyList(list);
+        drain();
+        verify(callback).onInserted(0, 100);
+        verifyNoMoreInteractions(callback);
+
+        helper.get(0);
+        verifyNoMoreInteractions(callback);
+        drain();
+        verify(callback).onChanged(0, 10, null);
+        verify(callback).onChanged(10, 10, null);
+        verifyNoMoreInteractions(callback);
+    }
+
+    @Test
+    public void setEmptyAndClear() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        LazyListAdapterHelper<Item> helper = createHelper(callback);
+        verifyZeroInteractions(callback);
+
+        LazyList<Item> list = createLazyList();
+        helper.setLazyList(list);
+        drain();
+        verify(callback).onInserted(0, 100);
+        verifyNoMoreInteractions(callback);
+
+        helper.setLazyList(null);
+        verify(callback).onRemoved(0, 100);
+        drain();
+        verifyNoMoreInteractions(callback);
+    }
+
+    @Test
+    public void setNonEmpty() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        LazyListAdapterHelper<Item> helper = createHelper(callback);
+
+        LazyList<Item> list = createLazyList();
+        list.get(0);
+        drain();
+
+        verifyZeroInteractions(callback);
+
+        // setting doesn't trigger callbacks
+        helper.setLazyList(list);
+        drain();
+        verify(callback).onInserted(0, 100);
+        verifyNoMoreInteractions(callback);
+
+        // helper has correct data, but will trigger loads on access
+        assertNotNull(helper.get(19));
+        assertNull(helper.get(20));
+        verifyNoMoreInteractions(callback);
+        drain();
+        verify(callback).onChanged(20, 10, null);
+        verify(callback).onChanged(30, 10, null);
+        verifyNoMoreInteractions(callback);
+    }
+
+    @Test
+    public void simpleDiffCalc() {
+        ListUpdateCallback callback = Mockito.mock(ListUpdateCallback.class);
+        LazyListAdapterHelper<Item> helper = createHelper(callback);
+        verifyZeroInteractions(callback);
+
+        LazyList<Item> list = createLazyList();
+        helper.setLazyList(list);
+        drain();
+        verify(callback).onInserted(0, 100);
+        verifyNoMoreInteractions(callback);
+
+        list = createLazyList();
+        list.get(0); // TODO: also test more interesting number
+        drain();
+        verifyNoMoreInteractions(callback);
+
+        helper.setLazyList(list);
+        verifyNoMoreInteractions(callback);
+        drain();
+
+        // NOTE: these aren't ideal, but they're what we currently produce.
+        // Should ideally be onChanged(0, 20)
+        verify(callback).onRemoved(80, 20);
+        verify(callback).onInserted(0, 20);
+        verifyNoMoreInteractions(callback);
+    }
+
+
+    private void drain() {
+        boolean executed;
+        do {
+            executed = mBackgroundThread.executeAll();
+            executed |= mMainThread.executeAll();
+        } while (executed);
+
+    }
+}
diff --git a/paging/runtime/src/main/AndroidManifest.xml b/paging/runtime/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..95247e5
--- /dev/null
+++ b/paging/runtime/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.util.paging.runtime">
+</manifest>
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/DiffCallback.java b/paging/runtime/src/main/java/android/arch/util/paging/DiffCallback.java
new file mode 100644
index 0000000..de66424
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/DiffCallback.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.NonNull;
+
+/**
+ * Interface that informs {@link LazyListAdapterHelper} how to compute list updates when using
+ * {@link android.support.v7.util.DiffUtil} on a background thread.
+ * <p>
+ * The AdapterHelper will pass items from different lists to this callback in order to implement
+ * the {@link android.support.v7.util.DiffUtil.Callback} it uses to compute differences between
+ * lists.
+ *
+ * @param <Value> Type of items to compare.
+ */
+public abstract class DiffCallback<Value> {
+
+    /**
+     * Called to decide whether two objects represent the same item.
+     *
+     * @param oldItem The item in the old list.
+     * @param newItem The item in the new list.
+     * @return True if the two items represent the same object or false if they are different.
+     */
+    public abstract boolean areItemsTheSame(@NonNull Value oldItem, @NonNull Value newItem);
+
+    /**
+     * Called to decide whether two items have the same data. This information is used to detect if
+     * the contents of an item have changed.
+     *
+     * @param oldItem The item in the old list.
+     * @param newItem The item in the new list.
+     * @return True if the contents of the items are the same or false if they are different.
+     */
+    public abstract boolean areContentsTheSame(@NonNull Value oldItem, @NonNull Value newItem);
+}
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/LazyListAdapterHelper.java b/paging/runtime/src/main/java/android/arch/util/paging/LazyListAdapterHelper.java
new file mode 100644
index 0000000..64931e9
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/LazyListAdapterHelper.java
@@ -0,0 +1,367 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.Observer;
+import android.arch.lifecycle.OnLifecycleEvent;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.v7.util.ListUpdateCallback;
+import android.support.v7.widget.RecyclerView;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Helper object for mapping a {@link LazyList} into a
+ * {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter} - both the internal
+ * paging of the list as more data is loaded, and updates in the form of new LazyLists.
+ * <p>
+ * The LazyListAdapterHelper can take a {@link LiveData} of LazyList and present the data simply for
+ * an adapter. It listens to LazyList loading callbacks, and uses DiffUtil on a background thread to
+ * compute updates as new LazyLists are received.
+ * <p>
+ * It provides a simple list-like API with {@link #get(int)} and {@link #getItemCount()} for an
+ * adapter to acquire and present data objects.
+ * <p>
+ * A complete usage pattern with Room would look like this:
+ * <pre>
+ * {@literal @}Dao
+ * interface UserDao {
+ *     {@literal @}Query("SELECT * FROM user ORDER BY lastName ASC")
+ *     LiveLazyListProvider&lt;User> usersByLastName();
+ * }
+ *
+ * class MyViewModel extends ViewModel {
+ *     public final LiveData&lt;LazyList&lt;User>> usersList;
+ *     public MyViewModel(UserDao userDao) {
+ *         usersList = userDao.usersByLastName().create(
+ *                        ListConfig.builder()
+ *                                  .pageSize(50)
+ *                                  .prefetchDistance(50)
+ *                                  .create());
+ *     }
+ * }
+ *
+ * class MyActivity extends Activity implements LifecycleRegistryOwner {
+ *     {@literal @}Override
+ *     public void onCreate(Bundle savedState) {
+ *         super.onCreate(savedState);
+ *         MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
+ *         RecyclerView recyclerView = findViewById(R.id.user_list);
+ *         UserAdapter&lt;User> adapter = new UserAdapter(
+ *                  LazyListAdapterHelper.&lt;User>builder()
+ *                                       .lifecycle(this)
+ *                                       .diffCallback(User.DIFF_CALLBACK)
+ *                                       .source(viewModel.usersList));
+ *         recyclerView.setAdapter(adapter);
+ *     }
+ * }
+ *
+ * class UserAdapter extends RecyclerView.Adapter&lt;UserViewHolder> {
+ *     private final LazyListAdapterHelper&lt;User> helper;
+ *     public UserAdapter(LazyListAdapterHelper.Builder&lt;User> builder) {
+ *         helper = builder.adapter(this).create();
+ *     }
+ *     {@literal @}Override
+ *     public int getItemCount() {
+ *         return mHelper.getItemCount();
+ *     }
+ *     {@literal @}Override
+ *     public void onBindViewHolder(UserViewHolder holder, int position) {
+ *         User user = mHelper.get(position);
+ *         if (user == null) {
+ *             // AdapterHelper will automatically call invalidate on this row when the actual
+ *             // object is loaded from the database
+ *             holder.clear();
+ *         } else {
+ *             holder.bindTo(user);
+ *         }
+ *     }
+ * }
+ * </pre>
+ *
+ * @param <Value> Type of the LazyLists this helper will receive.
+ */
+public class LazyListAdapterHelper<Value> extends PagerBaseAdapterHelper<Value> {
+    /**
+     * set to false if the helper is observing a LiveData.
+     */
+    private final boolean mCanSetList;
+    private LazyList.ChangeCallback mChangeCallback = new LazyList.ChangeCallback() {
+        @Override
+        public void onLoaded(int start, int count) {
+            mListUpdateCallback.onChanged(start, count, null);
+        }
+    };
+
+    private LazyListAdapterHelper(
+            @NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            @NonNull ListUpdateCallback listUpdateCallback,
+            @NonNull DiffCallback<Value> diffCallback, boolean canSetList) {
+        super(mainThreadExecutor, backgroundThreadExecutor, listUpdateCallback, diffCallback);
+        mCanSetList = canSetList;
+    }
+
+    /**
+     * Returns the item at the given index.
+     * <p>
+     * Might be null if the item is not loaded yet.
+     *
+     * @param index The position of the item
+     * @return The item at the given index or {@code null} if it is not loaded into memory yet.
+     */
+    @Override
+    @Nullable
+    public Value get(int index) {
+        return super.get(index);
+    }
+
+    /**
+     * Sets the lazy list for this adapter helper. If you are manually observing the
+     * {@link LazyList} for changes, you should call this method with the new
+     * {@link LazyList} when the previous one is invalidated.
+     * <p>
+     * Adapter helper will calculate the diff between this list and the previous one on a background
+     * thread then replace the data with this one, while unsubscribing from the previous list and
+     * subscribing to the new one.
+     * <p>
+     * If you have already provided a {@link LiveData} source via {@link Builder#source(LiveData)},
+     * calling this method will throw an {@link IllegalStateException}.
+     *
+     * @param newList The new LazyList to observe.
+     */
+    @MainThread
+    public void setLazyList(@Nullable LazyList<Value> newList) {
+        if (mCanSetList) {
+            setPagerBase(newList);
+        } else {
+            throw new IllegalStateException("When an AdapterHelper is observing a LiveData, you"
+                    + " cannot set the list on it because it will be overridden by the LiveData"
+                    + " source");
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @MainThread
+    void internalSetLazyList(@Nullable LazyList<Value> newList) {
+        setPagerBase(newList);
+    }
+
+    @Override
+    void addCallback(PagerBase<Value> list) {
+        ((LazyList<Value>) list).addCallback(mChangeCallback);
+    }
+
+    @Override
+    void removeCallback(PagerBase<Value> list) {
+        ((LazyList<Value>) list).removeCallback(mChangeCallback);
+    }
+
+    /**
+     * Creates a {@link Builder} that can be used to construct a {@link LazyListAdapterHelper}.
+     *
+     * @param <Value> The type parameter for the {@link LazyListAdapterHelper}.
+     * @return a new {@link Builder}.
+     */
+    public static <Value> Builder<Value> builder() {
+        return new Builder<>();
+    }
+
+
+    /**
+     * Builder class for {@link LazyListAdapterHelper}.
+     * <p>
+     * You must at least provide an {@link DiffCallback} and also one of the
+     * {@link Builder#adapter(RecyclerView.Adapter)} or
+     * {@link Builder#updateCallback(ListUpdateCallback)}.
+     *
+     * @param <Value> Data type held by the adapter helper.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public static class Builder<Value> {
+        private DiffCallback<Value> mDiffCallback;
+        private ListUpdateCallback mUpdateCallback;
+        private LifecycleOwner mLifecycle;
+        private LiveData<LazyList<Value>> mLiveData;
+        private Executor mMainThreadExecutor;
+        private Executor mBackgroundThreadExecutor;
+
+        /**
+         * Sets the {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter}
+         * instance that will receive the update events.
+         * <p>
+         * If you have a more complex case where your adapter has additional items from different
+         * data sources, you can use the {@link #updateCallback(ListUpdateCallback)} to manually
+         * dispatch changes to your adapter.
+         *
+         * @param adapter The adapter to receive change/move/insert/remove updates when the data
+         *                provided by the helper changes.
+         */
+        public Builder<Value> adapter(RecyclerView.Adapter adapter) {
+            return updateCallback(new PagerBaseAdapterHelper.AdapterCallback(adapter));
+        }
+
+        /**
+         * Sets the ListUpdateCallback that will receive updates as the data maintained by the
+         * helper is updated.
+         * <p>
+         * In simple cases, you can instead pass your Adapter to
+         * {@link #adapter(RecyclerView.Adapter)} to receive updates in the form of e.g.
+         * {@link android.support.v7.widget.RecyclerView.Adapter#notifyItemRangeChanged(int, int)}
+         * or
+         * {@link android.support.v7.widget.RecyclerView.Adapter#notifyItemRangeInserted(int, int)}
+         * on your adapter.
+         *
+         * @param callback The callback to receive change/move/insert/remove updates when the data
+         *                 provided by the helper changes.
+         */
+        public Builder<Value> updateCallback(ListUpdateCallback callback) {
+            mUpdateCallback = callback;
+            return this;
+        }
+
+        /**
+         * The {@link DiffCallback} to be used while diffing an old list with the updated one.
+         * Must be provided.
+         *
+         * @param diffCallback The {@link DiffCallback} instance to compare items in the list.
+         * @return this
+         */
+        public Builder<Value> diffCallback(DiffCallback<Value> diffCallback) {
+            mDiffCallback = diffCallback;
+            return this;
+        }
+
+        /**
+         * Assigns a lifecycle to the {@link LazyListAdapterHelper} so that it can cancel the
+         * observers automatically when the lifecycle is destroyed. This is especially useful if
+         * the actual {@link LazyList} is owned by a
+         * {@link android.arch.lifecycle.ViewModel ViewModel} or any other class that outlives
+         * the {@link android.app.Activity Activity} or the
+         * {@link android.support.v4.app.Fragment Fragment}.
+         * <p>
+         * Optional. If you don't provide this and the {@link LazyList} outlives the
+         * {@link android.support.v7.widget.RecyclerView.Adapter Adapter}, you should call
+         * {@link LazyListAdapterHelper#setLazyList(LazyList)} with {@code null} when the UI
+         * element is destroyed.
+         *
+         * @param lifecycleOwner The {@link LifecycleOwner} where the adapter lives.
+         * @return this
+         */
+        public Builder<Value> lifecycle(LifecycleOwner lifecycleOwner) {
+            mLifecycle = lifecycleOwner;
+            return this;
+        }
+
+        /**
+         * If provided, the created {@link LazyListAdapterHelper} will observe the given
+         * {@code source} automatically. If you provide a {@code source}, you must also provide a
+         * {@link LifecycleOwner} via the {@link #lifecycle(LifecycleOwner)} method.
+         *
+         * @param source The LiveData source that should be observed.
+         * @return this
+         */
+        public Builder<Value> source(LiveData<LazyList<Value>> source) {
+            mLiveData = source;
+            return this;
+        }
+
+        /**
+         * If provided, {@link LazyListAdapterHelper} will use the given executor to execute adapter
+         * update notifications on the main thread.
+         * <p>
+         * If not provided, it will default to the UI thread.
+         *
+         * @param executor The executor which can run tasks in the UI thread.
+         * @return this
+         */
+        public Builder<Value> mainThreadExecutor(Executor executor) {
+            mMainThreadExecutor = executor;
+            return this;
+        }
+
+        /**
+         * If provided, {@link LazyListAdapterHelper} will use the given executor to calculate the
+         * diff between an old and a new list.
+         * <p>
+         * If not provided, defaults to the IO thread pool from Architecture Components.
+         *
+         * @param executor The background executor to run list diffing.
+         * @return this
+         */
+        public Builder<Value> backgroundThreadExecutor(Executor executor) {
+            mBackgroundThreadExecutor = executor;
+            return this;
+        }
+
+        /**
+         * Creates a {@link LazyListAdapterHelper} with the given parameters.
+         *
+         * @return A new LazyListAdapterHelper.
+         */
+        public LazyListAdapterHelper<Value> create() {
+            if (mDiffCallback == null) {
+                throw new IllegalArgumentException("Must provide a diffCallback");
+            }
+            if (mUpdateCallback == null) {
+                throw new IllegalArgumentException(
+                        "must provide either an adapter or update callback");
+            }
+            if (mBackgroundThreadExecutor == null) {
+                mBackgroundThreadExecutor = AppToolkitTaskExecutor.getIOThreadExecutor();
+            }
+            if (mMainThreadExecutor == null) {
+                mMainThreadExecutor = AppToolkitTaskExecutor.getMainThreadExecutor();
+            }
+            final LazyListAdapterHelper<Value> result =
+                    new LazyListAdapterHelper<>(
+                            mMainThreadExecutor,
+                            mBackgroundThreadExecutor,
+                            mUpdateCallback, mDiffCallback,
+                            mLiveData == null);
+
+            if (mLifecycle != null) {
+                mLifecycle.getLifecycle().addObserver(new LifecycleObserver() {
+                    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
+                    public void clear() {
+                        result.internalSetLazyList(null);
+                    }
+                });
+            }
+            if (mLiveData != null) {
+                if (mLifecycle == null) {
+                    throw new IllegalArgumentException(
+                            "If you provide a LiveData to be observed, you must also provide a"
+                                    + " Livecycle via the lifecycle() method.");
+                }
+                mLiveData.observe(mLifecycle, new Observer<LazyList<Value>>() {
+                    @Override
+                    public void onChanged(@Nullable LazyList<Value> valueLazyList) {
+                        result.internalSetLazyList(valueLazyList);
+                    }
+                });
+            }
+            return result;
+        }
+    }
+}
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/LiveLazyListProvider.java b/paging/runtime/src/main/java/android/arch/util/paging/LiveLazyListProvider.java
new file mode 100644
index 0000000..f39ce85
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/LiveLazyListProvider.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.ComputableLiveData;
+import android.arch.lifecycle.LiveData;
+import android.support.annotation.Nullable;
+import android.support.annotation.WorkerThread;
+
+/**
+ * This class wraps to {@link android.arch.util.paging.CountedDataSource CountedDataSource} and can
+ * provide a {@link android.arch.lifecycle.LiveData LiveData} of
+ * {@link android.arch.util.paging.LazyList LazyList}.
+ *
+ * @param <T> Data type produced by the CountedDataSource, and held by the LazyLists.
+ *
+ * @see LazyListAdapterHelper
+ */
+public abstract class LiveLazyListProvider<T> {
+
+    /**
+     * Construct a new data source to be wrapped in a new LazyList, which will be returned through
+     * the LiveData.
+     *
+     * @return The data source.
+     */
+    @SuppressWarnings("WeakerAccess")
+    @WorkerThread
+    protected abstract CountedDataSource<T> createDataSource();
+
+    /**
+     * Creates a LiveData of LazyLists, given the ListConfig.
+     * <p>
+     * This LiveData can be passed to a {@link LazyListAdapterHelper} to be displayed with a
+     * {@link android.support.v7.widget.RecyclerView}.
+     *
+     * @param configuration ListConfig to use with created LazyLists. This specifies how the lists
+     *                      will load data.
+     *
+     * @return The LiveData of LazyLists.
+     */
+    public LiveData<LazyList<T>> create(final ListConfig configuration) {
+        return new ComputableLiveData<LazyList<T>>() {
+            @Nullable
+            private LazyList<T> mList;
+            @Nullable
+            private CountedDataSource<T> mDataSource;
+
+            private final DataSourceBase.InvalidatedCallback mCallback =
+                    new DataSourceBase.InvalidatedCallback() {
+                @Override
+                public void onInvalidated() {
+                    invalidate();
+                }
+            };
+
+            @Override
+            protected LazyList<T> compute() {
+                int loadAfterPos = mList == null ? -2 : mList.getInitialLoadPosition();
+
+                boolean done = true;
+                do {
+                    if (mDataSource != null) {
+                        mDataSource.removeInvalidatedCallback(mCallback);
+                    }
+
+                    mDataSource = createDataSource();
+                    mDataSource.addInvalidatedCallback(mCallback);
+                    mList = new LazyList<>(mDataSource,
+                            AppToolkitTaskExecutor.getMainThreadExecutor(),
+                            AppToolkitTaskExecutor.getIOThreadExecutor(),
+                            configuration);
+                    if (loadAfterPos >= -1) {
+                        done = mList.internalInit(loadAfterPos);
+                    }
+                } while (!done);
+                return mList;
+            }
+        }.getLiveData();
+    }
+}
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/LivePagedListProvider.java b/paging/runtime/src/main/java/android/arch/util/paging/LivePagedListProvider.java
new file mode 100644
index 0000000..177e639
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/LivePagedListProvider.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.ComputableLiveData;
+import android.arch.lifecycle.LiveData;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.WorkerThread;
+
+/**
+ * @param <K> Key type of the DataSource, used to initialize PagedLists.
+ * @param <T> Data type produced by the DataSource, and held by the PagedLists.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class LivePagedListProvider<K, T> {
+
+    /**
+     * Construct a new data source to be wrapped in a new PagedList, which will be returned through
+     * the LiveData.
+     *
+     * @return The data source.
+     */
+    @SuppressWarnings("WeakerAccess")
+    @WorkerThread
+    protected abstract DataSource<K, T> createDataSource();
+
+    /**
+     * Creates a LiveData of PagedLists, given the ListConfig.
+     * <p>
+     * This LiveData can be passed to a {@link PagedListAdapterHelper} to be displayed with a
+     * {@link android.support.v7.widget.RecyclerView}.
+     *
+     * @param configuration ListConfig to use with created PagedLists. This specifies how the lists
+     *                      will load data.
+     *
+     * @return The LiveData of LazyLists.
+     */
+    public LiveData<PagedList<T>> create(final ListConfig configuration) {
+        return new ComputableLiveData<PagedList<T>>() {
+            @Nullable
+            private PagedList<T> mList;
+            @Nullable
+            private DataSource<K, T> mDataSource;
+
+            private final DataSourceBase.InvalidatedCallback mCallback =
+                    new DataSourceBase.InvalidatedCallback() {
+                @Override
+                public void onInvalidated() {
+                    invalidate();
+                }
+            };
+
+            @Override
+            protected PagedList<T> compute() {
+                PagedList<T> old = mList;
+
+                boolean done = true;
+                do {
+                    if (mDataSource != null) {
+                        mDataSource.removeInvalidatedCallback(mCallback);
+                    }
+
+                    mDataSource = createDataSource();
+                    mDataSource.addInvalidatedCallback(mCallback);
+                    mList = new PagedList<>(mDataSource,
+                            AppToolkitTaskExecutor.getMainThreadExecutor(),
+                            AppToolkitTaskExecutor.getIOThreadExecutor(),
+                            configuration);
+                    if (old != null) {
+                        done = mList.initializeFrom(old);
+                    }
+                } while (!done);
+                return mList;
+            }
+        }.getLiveData();
+    }
+}
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/PagedListAdapterHelper.java b/paging/runtime/src/main/java/android/arch/util/paging/PagedListAdapterHelper.java
new file mode 100644
index 0000000..0f29cbb
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/PagedListAdapterHelper.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.v7.util.ListUpdateCallback;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Helper object for mapping a {@link PagedList} into a
+ * {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter} - both the paging in
+ * of new content as more data is loaded, and updates in the form of new PagedLists.
+ *
+ * @param <Value> Type of the PagedLists this helper will receive.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class PagedListAdapterHelper<Value> extends PagerBaseAdapterHelper<Value> {
+    private PagedList.ChangeCallback mChangeCallback = new PagedList.ChangeCallback() {
+        @Override
+        public void onInserted(int start, int count) {
+            mListUpdateCallback.onInserted(start, count);
+        }
+    };
+
+    public PagedListAdapterHelper(
+            @NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            @NonNull ListUpdateCallback listUpdateCallback,
+            @NonNull DiffCallback<Value> diffCallback) {
+        super(mainThreadExecutor, backgroundThreadExecutor, listUpdateCallback, diffCallback);
+    }
+
+    @Override
+    @NonNull
+    public Value get(int index) {
+        return super.get(index);
+    }
+
+    /**
+     * Sets the paged list for this adapter helper. If you are manually observing the
+     * {@link PagedList} for changes, you should call this method with the new
+     * {@link PagedList} when the previous one is invalidated.
+     * <p>
+     * Adapter helper will calculate the diff between this list and the previous one on a background
+     * thread then replace the data with this one, while unsubscribing from the previous list and
+     * subscribing to the new one.
+     *
+     * @param newList The new PagedList to observe.
+     */
+    @MainThread
+    public void setPagedList(@Nullable PagedList<Value> newList) {
+        setPagerBase(newList);
+    }
+
+    @Override
+    void addCallback(PagerBase<Value> list) {
+        ((PagedList<Value>) list).addCallback(mChangeCallback);
+    }
+
+    @Override
+    void removeCallback(PagerBase<Value> list) {
+        ((PagedList<Value>) list).removeCallback(mChangeCallback);
+    }
+}
diff --git a/paging/runtime/src/main/java/android/arch/util/paging/PagerBaseAdapterHelper.java b/paging/runtime/src/main/java/android/arch/util/paging/PagerBaseAdapterHelper.java
new file mode 100644
index 0000000..659298f
--- /dev/null
+++ b/paging/runtime/src/main/java/android/arch/util/paging/PagerBaseAdapterHelper.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.WorkerThread;
+import android.support.v7.util.DiffUtil;
+import android.support.v7.util.ListUpdateCallback;
+import android.support.v7.widget.RecyclerView;
+
+import java.util.concurrent.Executor;
+
+/**
+ * @param <Value> Type of the PagerBases this helper will receive.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class PagerBaseAdapterHelper<Value> {
+    final ListUpdateCallback mListUpdateCallback;
+    private final DiffCallback<Value> mDiffCallback;
+    private final Executor mMainThreadExecutor;
+    private final Executor mBackgroundThreadExecutor;
+
+    /**
+     * Default ListUpdateCallback that dispatches directly to an adapter. Can be replaced by a
+     * custom ListUpdateCallback if e.g. your adapter has a header in it, and so has an offset
+     * between list positions and adapter positions.
+     */
+    public static class AdapterCallback implements ListUpdateCallback {
+        private final RecyclerView.Adapter mAdapter;
+
+        public AdapterCallback(RecyclerView.Adapter adapter) {
+            mAdapter = adapter;
+        }
+
+        @Override
+        public void onInserted(int position, int count) {
+            mAdapter.notifyItemRangeInserted(position, count);
+        }
+
+        @Override
+        public void onRemoved(int position, int count) {
+            mAdapter.notifyItemRangeRemoved(position, count);
+        }
+
+        @Override
+        public void onMoved(int fromPosition, int toPosition) {
+            mAdapter.notifyItemMoved(fromPosition, toPosition);
+        }
+
+        @Override
+        public void onChanged(int position, int count, Object payload) {
+            mAdapter.notifyItemRangeChanged(position, count, payload);
+        }
+    }
+
+    PagerBaseAdapterHelper(
+            @NonNull Executor mainThreadExecutor, @NonNull Executor backgroundThreadExecutor,
+            @NonNull ListUpdateCallback listUpdateCallback,
+            @NonNull DiffCallback<Value> diffCallback) {
+        mMainThreadExecutor = mainThreadExecutor;
+        mBackgroundThreadExecutor = backgroundThreadExecutor;
+        mListUpdateCallback = listUpdateCallback;
+        mDiffCallback = diffCallback;
+    }
+
+    private PagerBase<Value> mList;
+    private PagerBase<Value> mProcessingList;
+    private PagerBase<Value> mQueuedList;
+    private DiffUtil.DiffResult mDiffResult;
+
+    /**
+     * Get the current list item at the given index. Index must be less than value of
+     * {@link #getItemCount()}.
+     */
+    public Value get(int index) {
+        return mList.get(index);
+    }
+
+    /**
+     * Returns the number of items in the list. This count includes all items (even the ones that
+     * are not yet loaded into memory).
+     *
+     * @return The number of items in the list.
+     */
+    public int getItemCount() {
+        return mList == null ? 0 : mList.size();
+    }
+
+    @NonNull
+    private DiffUtil.DiffResult computeDiff(
+            final PagerBase<Value> oldList, final PagerBase<Value> newList) {
+        return DiffUtil.calculateDiff(new DiffUtil.Callback() {
+            @Nullable
+            @Override
+            public Object getChangePayload(int oldItemPosition, int newItemPosition) {
+                return null;
+            }
+
+            @Override
+            public int getOldListSize() {
+                return oldList.size();
+            }
+
+            @Override
+            public int getNewListSize() {
+                return newList.size();
+            }
+
+            @Override
+            public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
+                Value oldItem = oldList.access(oldItemPosition);
+                Value newItem = newList.access(newItemPosition);
+                if (oldItem == newItem) {
+                    return true;
+                }
+                if (oldItem == null || newItem == null) {
+                    return false;
+                }
+                return mDiffCallback.areItemsTheSame(oldItem, newItem);
+            }
+
+            @Override
+            public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
+                Value oldItem = oldList.access(oldItemPosition);
+                Value newItem = newList.access(newItemPosition);
+                if (oldItem == newItem) {
+                    return true;
+                }
+                if (oldItem == null || newItem == null) {
+                    return false;
+                }
+
+                return mDiffCallback.areContentsTheSame(oldItem, newItem);
+            }
+        }, false);
+    }
+
+    private void applyDiff(DiffUtil.DiffResult diffResult) {
+        diffResult.dispatchUpdatesTo(mListUpdateCallback);
+    }
+
+    private Runnable mBackgroundDiffRunnable = new Runnable() {
+        @WorkerThread
+        @Override
+        public void run() {
+            mDiffResult = computeDiff(mList, mProcessingList);
+            mMainThreadExecutor.execute(mApplyDiffRunnable);
+        }
+    };
+
+    private Runnable mApplyDiffRunnable = new Runnable() {
+        @MainThread
+        @Override
+        public void run() {
+            if (mQueuedList == null) {
+                // null list queued, trigger immediately
+                removeCallback(mList);
+                mListUpdateCallback.onRemoved(0, mList.size());
+                mList = null;
+                mProcessingList = null;
+                mDiffResult = null;
+                return;
+            }
+
+            // apply processing list, dispatching updates
+            removeCallback(mList);
+            mList = mProcessingList;
+            addCallback(mList);
+
+            applyDiff(mDiffResult);
+            mDiffResult = null;
+
+            if (mQueuedList == mProcessingList) {
+                // no further work
+                mProcessingList = null;
+                mQueuedList = null;
+            } else {
+                // enqueue diff for most recent PagerBase
+                mProcessingList = mQueuedList;
+                mBackgroundThreadExecutor.execute(mBackgroundDiffRunnable);
+            }
+        }
+    };
+
+    @MainThread
+    void setPagerBase(@Nullable PagerBase<Value> newList) {
+        if (mList == null) {
+            // first list
+            mList = newList;
+            if (mList != null) {
+                addCallback(mList);
+                mListUpdateCallback.onInserted(0, mList.size());
+            }
+        } else if (mProcessingList == null) {
+            if (newList == null) {
+                // swap in immediately
+                removeCallback(mList);
+                mListUpdateCallback.onRemoved(0, mList.size());
+                mList = null;
+            } else {
+                // not working on a list, enqueue runnable
+                mProcessingList = newList;
+                mQueuedList = newList;
+                mBackgroundThreadExecutor.execute(mBackgroundDiffRunnable);
+            }
+        } else {
+            // already working on new list, enqueue work. Note that this includes a null list,
+            // which is greedily applied in mApplyDiffRunnable. For simplicity, we don't attempt to
+            mQueuedList = newList;
+        }
+
+    }
+
+    abstract void addCallback(PagerBase<Value> list);
+    abstract void removeCallback(PagerBase<Value> list);
+
+    @Override
+    public String toString() {
+        return mList + ", " + mProcessingList + ", " + mQueuedList;
+    }
+}
diff --git a/percent/build.gradle b/percent/build.gradle
index 90c2962..bd129d7 100644
--- a/percent/build.gradle
+++ b/percent/build.gradle
@@ -2,11 +2,12 @@
 archivesBaseName = 'percent'
 
 dependencies {
-    compile project(':support-compat')
-    androidTestCompile (libs.test_runner) {
+    api project(':support-compat')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/percent/lint-baseline.xml b/percent/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/percent/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/percent/tests/AndroidManifest.xml b/percent/tests/AndroidManifest.xml
index 9e15e6d..969b7a8 100644
--- a/percent/tests/AndroidManifest.xml
+++ b/percent/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.percent.test">
-    <uses-sdk
-        android:minSdkVersion="14"
-        android:targetSdkVersion="23"
-        tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-              android.support.test.espresso, android.support.test.espresso.idling" />
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application android:supportsRtl="true">
         <activity android:name="android.support.percent.TestFrameActivity"/>
diff --git a/recommendation/build.gradle b/recommendation/build.gradle
index 9becae9..86743d3 100644
--- a/recommendation/build.gradle
+++ b/recommendation/build.gradle
@@ -2,7 +2,7 @@
 archivesBaseName = 'recommendation'
 
 dependencies {
-    compile project(':support-v4')
+    api project(':support-v4')
 }
 
 android {
diff --git a/recommendation/lint-baseline.xml b/recommendation/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/recommendation/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/room/.gitignore b/room/.gitignore
new file mode 100644
index 0000000..be4e6f1
--- /dev/null
+++ b/room/.gitignore
@@ -0,0 +1,4 @@
+local.properties
+maven-repo/
+build/
+*.DS_Store
diff --git a/room/common/build.gradle b/room/common/build.gradle
new file mode 100644
index 0000000..5b0d53d
--- /dev/null
+++ b/room/common/build.gradle
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+apply plugin: 'java'
+apply plugin: 'maven'
+
+sourceCompatibility = 1.7
+
+dependencies {
+    compile libs.support.annotations
+    testCompile libs.junit
+    testCompile libs.mockito_core
+}
+
+archivesBaseName = "common"
+
+createAndroidCheckstyle(project)
diff --git a/room/common/src/main/java/android/arch/persistence/room/ColumnInfo.java b/room/common/src/main/java/android/arch/persistence/room/ColumnInfo.java
new file mode 100644
index 0000000..84f5844
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/ColumnInfo.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.support.annotation.IntDef;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Allows specific customization about the column associated with this field.
+ * <p>
+ * For example, you can specify a column name for the field or change the column's type affinity.
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.CLASS)
+public @interface ColumnInfo {
+    /**
+     * Name of the column in the database. Defaults to the field name if not set.
+     * @return Name of the column in the database.
+     */
+    String name() default INHERIT_FIELD_NAME;
+
+    /**
+     * The type affinity for the column, which will be used when constructing the database.
+     * <p>
+     * If it is not specified, Room resolves it based on the field's type and available
+     * TypeConverters.
+     * <p>
+     * See <a href="https://www.sqlite.org/datatype3.html">SQLite types documentation</a> for
+     * details.
+     *
+     * @return The type affinity of the column.
+     */
+    @SuppressWarnings("unused") @SQLiteTypeAffinity int typeAffinity() default UNDEFINED;
+
+    /**
+     * Convenience method to index the field.
+     * <p>
+     * If you would like to create a composite index instead, see: {@link Index}.
+     *
+     * @return True if this field should be indexed, false otherwise. Defaults to false.
+     */
+    boolean index() default false;
+
+    /**
+     * Constant to let Room inherit the field name as the column name. If used, Room will use the
+     * field name as the column name.
+     */
+    String INHERIT_FIELD_NAME = "[field-name]";
+
+    /**
+     * Undefined type affinity. Will be resolved based on the type.
+     */
+    int UNDEFINED = 1;
+    /**
+     * Column affinity constant for strings.
+     */
+    int TEXT = 2;
+    /**
+     * Column affinity constant for integers or booleans.
+     */
+    int INTEGER = 3;
+    /**
+     * Column affinity constant for floats or doubles.
+     */
+    int REAL = 4;
+    /**
+     * Column affinity constant for binary data.
+     */
+    int BLOB = 5;
+
+    /**
+     * The SQLite column type constants that can be used in {@link #typeAffinity()}
+     */
+    @IntDef({UNDEFINED, TEXT, INTEGER, REAL, BLOB})
+    @interface SQLiteTypeAffinity {
+    }
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Dao.java b/room/common/src/main/java/android/arch/persistence/room/Dao.java
new file mode 100644
index 0000000..ea205e6
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Dao.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks the class as a Data Access Object.
+ * <p>
+ * Data Access Objects are the main classes where you define your database interactions. They can
+ * include a variety of query methods.
+ * <p>
+ * The class marked with {@code @Dao} should either be an interface or an abstract class. At compile
+ * time, Room will generate an implementation of this class when it is referenced by a
+ * {@link Database}.
+ * <p>
+ * An abstract {@code @Dao} class can optionally have a constructor that takes a {@link Database}
+ * as its only parameter.
+ * <p>
+ * It is recommended to have multiple {@code Dao} classes in your codebase depending on the tables
+ * they touch.
+ *
+ * @see Query
+ * @see Delete
+ * @see Insert
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.CLASS)
+public @interface Dao {
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Database.java b/room/common/src/main/java/android/arch/persistence/room/Database.java
new file mode 100644
index 0000000..f12d1b9
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Database.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a class as a RoomDatabase.
+ * <p>
+ * The class should be an abstract class and extend
+ * {@link android.arch.persistence.room.RoomDatabase RoomDatabase}.
+ * <p>
+ * You can receive an implementation of the class via
+ * {@link android.arch.persistence.room.Room#databaseBuilder Room.databaseBuilder} or
+ * {@link android.arch.persistence.room.Room#inMemoryDatabaseBuilder Room.inMemoryDatabaseBuilder}.
+ * <p>
+ * <pre>
+ * // User and Book are classes annotated with {@literal @}Entity.
+ * {@literal @}Database(version = 1, entities = {User.class, Book.class})
+ * abstract class AppDatabase extends RoomDatabase() {
+ *     // BookDao is a class annotated with {@literal @}Dao.
+ *     abstract public BookDao bookDao();
+ *     // UserDao is a class annotated with {@literal @}Dao.
+ *     abstract public UserDao userDao();
+ *     // UserBookDao is a class annotated with {@literal @}Dao.
+ *     abstract public UserBookDao userBookDao();
+ * }
+ * </pre>
+ * The example above defines a class that has 2 tables and 3 DAO classes that are used to access it.
+ * There is no limit on the number of {@link Entity} or {@link Dao} classes but they must be unique
+ * within the Database.
+ * <p>
+ * Instead of running queries on the database directly, you are highly recommended to create
+ * {@link Dao} classes. Using Dao classes will allow you to abstract the database communication in
+ * a more logical layer which will be much easier to mock in tests (compared to running direct
+ * sql queries). It also automatically does the conversion from {@code Cursor} to your application
+ * classes so you don't need to deal with lower level database APIs for most of your data access.
+ * <p>
+ * Room also verifies all of your queries in {@link Dao} classes while the application is being
+ * compiled so that if there is a problem in one of the queries, you will be notified instantly.
+ * @see Dao
+ * @see Entity
+ * @see android.arch.persistence.room.RoomDatabase RoomDatabase
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.CLASS)
+public @interface Database {
+    /**
+     * The list of entities included in the database. Each entity turns into a table in the
+     * database.
+     *
+     * @return The list of entities in the database.
+     */
+    Class[] entities();
+
+    /**
+     * The database version.
+     *
+     * @return The database version.
+     */
+    int version();
+
+    /**
+     * You can set annotation processor argument ({@code room.schemaLocation})
+     * to tell Room to export the schema into a folder. Even though it is not mandatory, it is a
+     * good practice to have version history in your codebase and you should commit that file into
+     * your version control system (but don't ship it with your app!).
+     * <p>
+     * When {@code room.schemaLocation} is set, Room will check this variable and if it is set to
+     * {@code true}, its schema will be exported into the given folder.
+     * <p>
+     * {@code exportSchema} is {@code true} by default but you can disable it for databases when
+     * you don't want to keep history of versions (like an in-memory only database).
+     *
+     * @return Whether the schema should be exported to the given folder when the
+     * {@code room.schemaLocation} argument is set. Defaults to {@code true}.
+     */
+    boolean exportSchema() default true;
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Delete.java b/room/common/src/main/java/android/arch/persistence/room/Delete.java
new file mode 100644
index 0000000..678b743
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Delete.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a method in a {@link Dao} annotated class as a delete method.
+ * <p>
+ * The implementation of the method will delete its parameters from the database.
+ * <p>
+ * All of the parameters of the Delete method must either be classes annotated with {@link Entity}
+ * or collections/array of it.
+ * <p>
+ * Example:
+ * <pre>
+ * {@literal @}Dao
+ * public interface MyDao {
+ *     {@literal @}Delete
+ *     public void deleteUsers(User... users);
+ *     {@literal @}Delete
+ *     public void deleteAll(User user1, User user2);
+ *     {@literal @}Delete
+ *     public void deleteWithFriends(User user, List&lt;User&gt; friends);
+ * }
+ * </pre>
+ *
+ * @see Insert
+ * @see Query
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.CLASS)
+public @interface Delete {
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Embedded.java b/room/common/src/main/java/android/arch/persistence/room/Embedded.java
new file mode 100644
index 0000000..781f026
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Embedded.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Can be used as an annotation on a field of an {@link Entity} or {@code Pojo} to signal that
+ * nested fields (i.e. fields of the annotated field's class) can be referenced directly in the SQL
+ * queries.
+ * <p>
+ * If the container is an {@link Entity}, these sub fields will be columns in the {@link Entity}'s
+ * database table.
+ * <p>
+ * For example, if you have 2 classes:
+ * <pre>
+ *   public class Coordinates {
+ *       double latitude;
+ *       double longitude;
+ *   }
+ *   public class Address {
+ *       String street;
+ *       {@literal @}Embedded
+ *       Coordinates coordinates;
+ *   }
+ * </pre>
+ * Room will consider {@code latitude} and {@code longitude} as if they are fields of the
+ * {@code Address} class when mapping an SQLite row to {@code Address}.
+ * <p>
+ * So if you have a query that returns {@code street, latitude, longitude}, Room will properly
+ * construct an {@code Address} class.
+ * <p>
+ * If the {@code Address} class is annotated with {@link Entity}, its database table will have 3
+ * columns: {@code street, latitude, longitude}
+ * <p>
+ * If there is a name conflict with the fields of the sub object and the owner object, you can
+ * specify a {@link #prefix()} for the items of the sub object. Note that prefix is always applied
+ * to sub fields even if they have a {@link ColumnInfo} with a specific {@code name}.
+ * <p>
+ * If sub fields of an embedded field has {@link PrimaryKey} annotation, they <b>will not</b> be
+ * considered as primary keys in the owner {@link Entity}.
+ * <p>
+ * When an embedded field is read, if all fields of the embedded field (and its sub fields) are
+ * {@code null} in the {@link android.database.Cursor Cursor}, it is set to {@code null}. Otherwise,
+ * it is constructed.
+ * <p>
+ * Note that even if you have {@link TypeConverter}s that convert a {@code null} column into a
+ * {@code non-null} value, if all columns of the embedded field in the
+ * {@link android.database.Cursor Cursor} are null, the {@link TypeConverter} will never be called
+ * and the embedded field will not be constructed.
+ * <p>
+ * You can override this behavior by annotating the embedded field with
+ * {@link android.support.annotation.NonNull}.
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.CLASS)
+public @interface Embedded {
+    /**
+     * Specifies a prefix to prepend the column names of the fields in the embedded fields.
+     * <p>
+     * For the example above, if we've written:
+     * <pre>
+     *   {@literal @}Embedded(prefix = "foo_")
+     *   Coordinates coordinates;
+     * </pre>
+     * The column names for {@code latitude} and {@code longitude} will be {@code foo_latitude} and
+     * {@code foo_longitude} respectively.
+     * <p>
+     * By default, prefix is the empty string.
+     *
+     * @return The prefix to be used for the fields of the embedded item.
+     */
+    String prefix() default  "";
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Entity.java b/room/common/src/main/java/android/arch/persistence/room/Entity.java
new file mode 100644
index 0000000..f54f0f8
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Entity.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a class as an entity. This class will have a mapping SQLite table in the database.
+ * <p>
+ * Each entity must have at least 1 field annotated with {@link PrimaryKey}.
+ * You can also use {@link #primaryKeys()} attribute to define the primary key.
+ * <p>
+ * Each entity must either have a no-arg constructor or a constructor whose parameters match
+ * fields (based on type and name). Constructor does not have to receive all fields as parameters
+ * but if a field is not passed into the constructor, it should either be public or have a public
+ * setter. If a matching constructor is available, Room will always use it. If you don't want it
+ * to use a constructor, you can annotate it with {@link Ignore}.
+ * <p>
+ * When a class is marked as an Entity, all of its fields are persisted. If you would like to
+ * exclude some of its fields, you can mark them with {@link Ignore}.
+ * <p>
+ * Example:
+ * <pre>
+ * {@literal @}Entity
+ * public class User {
+ *   {@literal @}PrimaryKey
+ *   private final int uid;
+ *   private String name;
+ *   {@literal @}ColumnInfo(name = "last_name")
+ *   private String lastName;
+ *
+ *   public User(int uid) {
+ *       this.uid = uid;
+ *   }
+ *   public String getLastName() {
+ *       return lastName;
+ *   }
+ *   public void setLastName(String lastName) {
+ *       this.lastName = lastName;
+ *   }
+ * }
+ * </pre>
+ *
+ * @see Dao
+ * @see Database
+ * @see PrimaryKey
+ * @see ColumnInfo
+ * @see Index
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.CLASS)
+public @interface Entity {
+    /**
+     * The table name in the SQLite database. If not set, defaults to the class name.
+     *
+     * @return The SQLite tableName of the Entity.
+     */
+    String tableName() default "";
+
+    /**
+     * List of indices on the table.
+     *
+     * @return The list of indices on the table.
+     */
+    Index[] indices() default {};
+
+    /**
+     * If set to {@code true}, any Index defined in parent classes of this class will be carried
+     * over to the current {@code Entity}. Note that if you set this to {@code true}, even if the
+     * {@code Entity} has a parent which sets this value to {@code false}, the {@code Entity} will
+     * still inherit indices from it and its parents.
+     * <p>
+     * When the {@code Entity} inherits an index from the parent, it is <b>always</b> renamed with
+     * the default naming schema since SQLite <b>does not</b> allow using the same index name in
+     * multiple tables. See {@link Index} for the details of the default name.
+     * <p>
+     * By default, indices defined in parent classes are dropped to avoid unexpected indices.
+     * When this happens, you will receive a {@link RoomWarnings#INDEX_FROM_PARENT_FIELD_IS_DROPPED}
+     * or {@link RoomWarnings#INDEX_FROM_PARENT_IS_DROPPED} warning during compilation.
+     *
+     * @return True if indices from parent classes should be automatically inherited by this Entity,
+     *         false otherwise. Defaults to false.
+     */
+    boolean inheritSuperIndices() default false;
+
+    /**
+     * The list of Primary Key column names.
+     * <p>
+     * If you would like to define an auto generated primary key, you can use {@link PrimaryKey}
+     * annotation on the field with {@link PrimaryKey#autoGenerate()} set to {@code true}.
+     *
+     * @return The primary key of this Entity. Can be empty if the class has a field annotated
+     * with {@link PrimaryKey}.
+     */
+    String[] primaryKeys() default {};
+
+    /**
+     * List of {@link ForeignKey} constraints on this entity.
+     *
+     * @return The list of {@link ForeignKey} constraints on this entity.
+     */
+    ForeignKey[] foreignKeys() default {};
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/ForeignKey.java b/room/common/src/main/java/android/arch/persistence/room/ForeignKey.java
new file mode 100644
index 0000000..4ba0fb3
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/ForeignKey.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.support.annotation.IntDef;
+
+/**
+ * Declares a foreign key on another {@link Entity}.
+ * <p>
+ * Foreign keys allows you to specify constraints across Entities such that SQLite will ensure that
+ * the relationship is valid when you modify the database.
+ * <p>
+ * When a foreign key constraint is specified, SQLite requires the referenced columns to be part of
+ * a unique index in the parent table or the primary key of that table. You must create a unique
+ * index in the parent entity that covers the referenced columns (Room will verify this at compile
+ * time and print an error if it is missing).
+ * <p>
+ * It is also recommended to create an index on the child table to avoid full table scans when the
+ * parent table is modified. If a suitable index on the child table is missing, Room will print
+ * {@link RoomWarnings#MISSING_INDEX_ON_FOREIGN_KEY_CHILD} warning.
+ * <p>
+ * A foreign key constraint can be deferred until the transaction is complete. This is useful if
+ * you are doing bulk inserts into the database in a single transaction. By default, foreign key
+ * constraints are immediate but you can change this value by setting {@link #deferred()} to
+ * {@code true}. You can also use
+ * <a href="https://sqlite.org/pragma.html#pragma_defer_foreign_keys">defer_foreign_keys</a> PRAGMA
+ * to defer them depending on your transaction.
+ * <p>
+ * Please refer to the SQLite <a href="https://sqlite.org/foreignkeys.html>foreign keys</a>
+ * documentation for details.
+ */
+public @interface ForeignKey {
+    /**
+     * The parent Entity to reference. It must be a class annotated with {@link Entity} and
+     * referenced in the same database.
+     *
+     * @return The parent Entity.
+     */
+    Class entity();
+
+    /**
+     * The list of column names in the parent {@link Entity}.
+     * <p>
+     * Number of columns must match the number of columns specified in {@link #childColumns()}.
+     *
+     * @return The list of column names in the parent Entity.
+     * @see #childColumns()
+     */
+    String[] parentColumns();
+
+    /**
+     * The list of column names in the current {@link Entity}.
+     * <p>
+     * Number of columns must match the number of columns specified in {@link #parentColumns()}.
+     *
+     * @return The list of column names in the current Entity.
+     */
+    String[] childColumns();
+
+    /**
+     * Action to take when the parent {@link Entity} is deleted from the database.
+     * <p>
+     * By default, {@link #NO_ACTION} is used.
+     *
+     * @return The action to take when the referenced entity is deleted from the database.
+     */
+    @Action int onDelete() default NO_ACTION;
+
+    /**
+     * Action to take when the parent {@link Entity} is updated in the database.
+     * <p>
+     * By default, {@link #NO_ACTION} is used.
+     *
+     * @return The action to take when the referenced entity is updated in the database.
+     */
+    @Action int onUpdate() default NO_ACTION;
+
+    /**
+     * * A foreign key constraint can be deferred until the transaction is complete. This is useful
+     * if you are doing bulk inserts into the database in a single transaction. By default, foreign
+     * key constraints are immediate but you can change it by setting this field to {@code true}.
+     * You can also use
+     * <a href="https://sqlite.org/pragma.html#pragma_defer_foreign_keys">defer_foreign_keys</a>
+     * PRAGMA to defer them depending on your transaction.
+     *
+     * @return Whether the foreign key constraint should be deferred until the transaction is
+     * complete. Defaults to {@code false}.
+     */
+    boolean deferred() default false;
+
+    /**
+     * Possible value for {@link #onDelete()} or {@link #onUpdate()}.
+     * <p>
+     * When a parent key is modified or deleted from the database, no special action is taken.
+     * This means that SQLite will not make any effort to fix the constraint failure, instead,
+     * reject the change.
+     */
+    int NO_ACTION = 1;
+
+    /**
+     * Possible value for {@link #onDelete()} or {@link #onUpdate()}.
+     * <p>
+     * The RESTRICT action means that the application is prohibited from deleting
+     * (for {@link #onDelete()}) or modifying (for {@link #onUpdate()}) a parent key when there
+     * exists one or more child keys mapped to it. The difference between the effect of a RESTRICT
+     * action and normal foreign key constraint enforcement is that the RESTRICT action processing
+     * happens as soon as the field is updated - not at the end of the current statement as it would
+     * with an immediate constraint, or at the end of the current transaction as it would with a
+     * {@link #deferred()} constraint.
+     * <p>
+     * Even if the foreign key constraint it is attached to is {@link #deferred()}, configuring a
+     * RESTRICT action causes SQLite to return an error immediately if a parent key with dependent
+     * child keys is deleted or modified.
+     */
+    int RESTRICT = 2;
+
+    /**
+     * Possible value for {@link #onDelete()} or {@link #onUpdate()}.
+     * <p>
+     * If the configured action is "SET NULL", then when a parent key is deleted
+     * (for {@link #onDelete()}) or modified (for {@link #onUpdate()}), the child key columns of all
+     * rows in the child table that mapped to the parent key are set to contain {@code NULL} values.
+     */
+    int SET_NULL = 3;
+
+    /**
+     * Possible value for {@link #onDelete()} or {@link #onUpdate()}.
+     * <p>
+     * The "SET DEFAULT" actions are similar to {@link #SET_NULL}, except that each of the child key
+     * columns is set to contain the columns default value instead of {@code NULL}.
+     */
+    int SET_DEFAULT = 4;
+
+    /**
+     * Possible value for {@link #onDelete()} or {@link #onUpdate()}.
+     * <p>
+     * A "CASCADE" action propagates the delete or update operation on the parent key to each
+     * dependent child key. For {@link #onDelete()} action, this means that each row in the child
+     * entity that was associated with the deleted parent row is also deleted. For an
+     * {@link #onUpdate()} action, it means that the values stored in each dependent child key are
+     * modified to match the new parent key values.
+     */
+    int CASCADE = 5;
+
+    /**
+     * Constants definition for values that can be used in {@link #onDelete()} and
+     * {@link #onUpdate()}.
+     */
+    @IntDef({NO_ACTION, RESTRICT, SET_NULL, SET_DEFAULT, CASCADE})
+    @interface Action {
+    }
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Ignore.java b/room/common/src/main/java/android/arch/persistence/room/Ignore.java
new file mode 100644
index 0000000..6effc33
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Ignore.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Ignores the marked element from Room's processing logic.
+ * <p>
+ * This annotation can be used in multiple places where Room processor runs. For instance, you can
+ * add it to a field of an {@link Entity} and Room will not persist that field.
+ */
+@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR})
+@Retention(RetentionPolicy.CLASS)
+public @interface Ignore {
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Index.java b/room/common/src/main/java/android/arch/persistence/room/Index.java
new file mode 100644
index 0000000..b814efd
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Index.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Declares an index on an Entity.
+ * see: <a href="https://sqlite.org/lang_createindex.html">SQLite Index Documentation</a>
+ * <p>
+ * Adding an index usually speeds up your select queries but will slow down other queries like
+ * insert or update. You should be careful when adding indices to ensure that this additional cost
+ * is worth the gain.
+ * <p>
+ * There are 2 ways to define an index in an {@link Entity}. You can either set
+ * {@link ColumnInfo#index()} property to index individual fields or define composite indices via
+ * {@link Entity#indices()}.
+ * <p>
+ * If an indexed field is embedded into another Entity via {@link Embedded}, it is <b>NOT</b>
+ * added as an index to the containing {@link Entity}. If you want to keep it indexed, you must
+ * re-declare it in the containing {@link Entity}.
+ * <p>
+ * Similarly, if an {@link Entity} extends another class, indices from the super classes are
+ * <b>NOT</b> inherited. You must re-declare them in the child {@link Entity} or set
+ * {@link Entity#inheritSuperIndices()} to {@code true}.
+ * */
+@Target({})
+@Retention(RetentionPolicy.CLASS)
+public @interface Index {
+    /**
+     * List of column names in the Index.
+     * <p>
+     * The order of columns is important as it defines when SQLite can use a particular index.
+     * See <a href="https://www.sqlite.org/optoverview.html">SQLite documentation</a> for details on
+     * index usage in the query optimizer.
+     *
+     * @return The list of column names in the Index.
+     */
+    String[] value();
+
+    /**
+     * Name of the index. If not set, Room will set it to the list of columns joined by '_' and
+     * prefixed by "index_${tableName}". So if you have a table with name "Foo" and with an index
+     * of {"bar", "baz"}, generated index name will be  "index_Foo_bar_baz". If you need to specify
+     * the index in a query, you should never rely on this name, instead, specify a name for your
+     * index.
+     *
+     * @return The name of the index.
+     */
+    String name() default "";
+
+    /**
+     * If set to true, this will be a unique index and any duplicates will be rejected.
+     *
+     * @return True if index is unique. False by default.
+     */
+    boolean unique() default false;
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Insert.java b/room/common/src/main/java/android/arch/persistence/room/Insert.java
new file mode 100644
index 0000000..802dd96
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Insert.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a method in a {@link Dao} annotated class as an insert method.
+ * <p>
+ * The implementation of the method will insert its parameters into the database.
+ * <p>
+ * All of the parameters of the Insert method must either be classes annotated with {@link Entity}
+ * or collections/array of it.
+ * <p>
+ * Example:
+ * <pre>
+ * {@literal @}Dao
+ * public interface MyDao {
+ *     {@literal @}Insert(onConflict = OnConflictStrategy.REPLACE)
+ *     public void insertUsers(User... users);
+ *     {@literal @}Insert
+ *     public void insertBoth(User user1, User user2);
+ *     {@literal @}Insert
+ *     public void insertWithFriends(User user, List&lt;User&gt; friends);
+ * }
+ * </pre>
+ *
+ * @see Update
+ * @see Delete
+ */
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.CLASS)
+public @interface Insert {
+    /**
+     * What to do if a conflict happens.
+     * @see <a href="https://sqlite.org/lang_conflict.html">SQLite conflict documentation</a>
+     *
+     * @return How to handle conflicts. Defaults to {@link OnConflictStrategy#ABORT}.
+     */
+    @OnConflictStrategy
+    int onConflict() default OnConflictStrategy.ABORT;
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/OnConflictStrategy.java b/room/common/src/main/java/android/arch/persistence/room/OnConflictStrategy.java
new file mode 100644
index 0000000..5217b61
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/OnConflictStrategy.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import static java.lang.annotation.RetentionPolicy.SOURCE;
+
+import android.support.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Set of conflict handling strategies for various {@link Dao} methods.
+ * <p>
+ * Check <a href="https://sqlite.org/lang_conflict.html">SQLite conflict documentation</a> for
+ * details.
+ */
+@Retention(SOURCE)
+@IntDef({OnConflictStrategy.REPLACE, OnConflictStrategy.ROLLBACK, OnConflictStrategy.ABORT,
+        OnConflictStrategy.FAIL, OnConflictStrategy.IGNORE})
+public @interface OnConflictStrategy {
+    /**
+     * OnConflict strategy constant to replace the old data and continue the transaction.
+     */
+    int REPLACE = 1;
+    /**
+     * OnConflict strategy constant to rollback the transaction.
+     */
+    int ROLLBACK = 2;
+    /**
+     * OnConflict strategy constant to abort the transaction.
+     */
+    int ABORT = 3;
+    /**
+     * OnConflict strategy constant to fail the transaction.
+     */
+    int FAIL = 4;
+    /**
+     * OnConflict strategy constant to ignore the conflict.
+     */
+    int IGNORE = 5;
+
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/PrimaryKey.java b/room/common/src/main/java/android/arch/persistence/room/PrimaryKey.java
new file mode 100644
index 0000000..9a8062ca
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/PrimaryKey.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a field in an {@link Entity} as the primary key.
+ * <p>
+ * If you would like to define a composite primary key, you should use {@link Entity#primaryKeys()}
+ * method.
+ * <p>
+ * Each {@link Entity} must declare a primary key unless one of its super classes declares a
+ * primary key. If both an {@link Entity} and its super class defines a {@code PrimaryKey}, the
+ * child's {@code PrimaryKey} definition will override the parent's {@code PrimaryKey}.
+ * <p>
+ * If {@code PrimaryKey} annotation is used on a {@link Embedded}d field, all columns inherited
+ * from that embedded field becomes the composite primary key (including its grand children
+ * fields).
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.CLASS)
+public @interface PrimaryKey {
+    /**
+     * Set to true to let SQLite generate the unique id.
+     * <p>
+     * When set to {@code true}, the SQLite type affinity for the field should be {@code INTEGER}.
+     * <p>
+     * If the field type is {@code long} or {@code int} (or its TypeConverter converts it to a
+     * {@code long} or {@code int}), {@link Insert} methods treat {@code 0} as not-set while
+     * inserting the item.
+     * <p>
+     * If the field's type is {@link Integer} or {@link Long} (or its TypeConverter converts it to
+     * an {@link Integer} or a {@link Long}), {@link Insert} methods treat {@code null} as
+     * not-set while inserting the item.
+     *
+     * @return Whether the primary key should be auto-generated by SQLite or not. Defaults
+     * to false.
+     */
+    boolean autoGenerate() default false;
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Query.java b/room/common/src/main/java/android/arch/persistence/room/Query.java
new file mode 100644
index 0000000..bd838e8
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Query.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a method in a {@link Dao} annotated class as a query method.
+ * <p>
+ * The value of the annotation includes the query that will be run when this method is called. This
+ * query is <b>verified at compile time</b> by Room to ensure that it compiles fine against the
+ * database.
+ * <p>
+ * The arguments of the method will be bound to the bind arguments in the SQL statement. See
+ * <href="https://www.sqlite.org/c3ref/bind_blob.html">SQLite's binding documentation</> for
+ * details of bind arguments in SQLite.
+ * <p>
+ * Room only supports named bind parameter {@code :name} to avoid any confusion between the
+ * method parameters and the query bind parameters.
+ * <p>
+ * Room will automatically bind the parameters of the method into the bind arguments. This is done
+ * by matching the name of the parameters to the name of the bind arguments.
+ * <pre>
+ *     {@literal @}Query("SELECT * FROM user WHERE user_name LIKE :name AND last_name LIKE :last")
+ *     public abstract List&lt;User&gt; findUsersByNameAndLastName(String name, String last);
+ * </pre>
+ * <p>
+ * As an extension over SQLite bind arguments, Room supports binding a list of parameters to the
+ * query. At runtime, Room will build the correct query to have matching number of bind arguments
+ * depending on the number of items in the method parameter.
+ * <pre>
+ *     {@literal @}Query("SELECT * FROM user WHERE uid IN(:userIds)")
+ *     public abstract List<User> findByIds(int[] userIds);
+ * </pre>
+ * For the example above, if the {@code userIds} is an array of 3 elements, Room will run the
+ * query as: {@code SELECT * FROM user WHERE uid IN(?, ?, ?)} and bind each item in the
+ * {@code userIds} array into the statement.
+ * <p>
+ * There are 3 types of queries supported in {@code Query} methods: SELECT, UPDATE and DELETE.
+ * <p>
+ * For SELECT queries, Room will infer the result contents from the method's return type and
+ * generate the code that will automatically convert the query result into the method's return
+ * type. For single result queries, the return type can be any java object. For queries that return
+ * multiple values, you can use {@link java.util.List} or {@code Array}. In addition to these, any
+ * query may return {@link android.database.Cursor Cursor} or any query result can be wrapped in
+ * a {@link android.arch.lifecycle.LiveData LiveData}.
+ * <p>
+ * <b>RxJava2</b> If you are using RxJava2, you can also return {@code Flowable<T>} or
+ * {@code Publisher<T>} from query methods. Since Reactive Streams does not allow {@code null}, if
+ * the query returns a nullable type, it will not dispatch anything if the value is {@code null}
+ * (like fetching an {@link Entity} row that does not exist).
+ * You can return {@code Flowable<T[]>} or {@code Flowable<List<T>>} to workaround this limitation.
+ * <p>
+ * Both {@code Flowable<T>} and {@code Publisher<T>} will observe the database for changes and
+ * re-dispatch if data changes. If you want to query the database without observing changes, you can
+ * use {@code Maybe<T>} or {@code Single<T>}. If a {@code Single<T>} query returns {@code null},
+ * Room will throw
+ * {@link android.arch.persistence.room.EmptyResultSetException EmptyResultSetException}.
+ * <p>
+ * UPDATE or DELETE queries can return {@code void} or {@code int}. If it is an {@code int},
+ * the value is the number of rows affected by this query.
+ * <p>
+ * You can return arbitrary POJOs from your query methods as long as the fields of the POJO match
+ * the column names in the query result.
+ * For example, if you have class:
+ * <pre>
+ * class UserName {
+ *     public String name;
+ *     {@literal @}ColumnInfo(name = "last_name")
+ *     public String lastName;
+ * }
+ * </pre>
+ * You can write a query like this:
+ * <pre>
+ *     {@literal @}Query("SELECT last_name, name FROM user WHERE uid = :userId LIMIT 1")
+ *     public abstract UserName findOneUserName(int userId);
+ * </pre>
+ * And Room will create the correct implementation to convert the query result into a
+ * {@code UserName} object. If there is a mismatch between the query result and the fields of the
+ * POJO, as long as there is at least 1 field match, Room prints a
+ * {@link RoomWarnings#CURSOR_MISMATCH} warning and sets as many fields as it can.
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.CLASS)
+public @interface Query {
+    /**
+     * The SQLite query to be run.
+     * @return The query to be run.
+     */
+    String value();
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Relation.java b/room/common/src/main/java/android/arch/persistence/room/Relation.java
new file mode 100644
index 0000000..0d2f152
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Relation.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * A convenience annotation which can be used in a Pojo to automatically fetch relation entities.
+ * When the Pojo is returned from a query, all of its relations are also fetched by Room.
+ *
+ * <pre>
+ * {@literal @}Entity
+ * public class Pet {
+ *     int userId;
+ *     String name;
+ *     // other fields
+ * }
+ * public class UserNameAndAllPets {
+ *   public int id;
+ *   public String name;
+ *   {@literal @}Relation(parentColumn = "id", entityColumn = "userId")
+ *   public List&lt;Pet&gt; pets;
+ * }
+ *
+ * {@literal @}Dao
+ * public interface UserPetDao {
+ *     {@literal @}Query("SELECT id, name from User WHERE age &gte; ?")
+ *     public List&lt;UserNameAndAllPets&gt; loadUserAndPets(int minAge);
+ * }
+ * </pre>
+ * <p>
+ * The type of the field annotated with {@code Relation} must be a {@link java.util.List} or
+ * {@link java.util.Set}. By default, the {@link Entity} type is inferred from the return type.
+ * If you would like to return a different object, you can specify the {@link #entity()} property
+ * in the annotation.
+ * <pre>
+ * public class User {
+ *     int id;
+ *     // other fields
+ * }
+ * public class PetNameAndId {
+ *     int id;
+ *     String name;
+ * }
+ * public class UserAllPets {
+ *   {@literal @}Embedded
+ *   public User user;
+ *   {@literal @}Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
+ *   public List<PetNameAndId> pets;
+ * }
+ * {@literal @}Dao
+ * public interface UserPetDao {
+ *     {@literal @}Query("SELECT * from User WHERE age &gte; ?")
+ *     public List&lt;UserAllPets&gt; loadUserAndPets(int minAge);
+ * }
+ * </pre>
+ * <p>
+ * In the example above, {@code PetNameAndId} is a regular but all of fields are fetched
+ * from the {@code entity} defined in the {@code @Relation} annotation (<i>Pet</i>).
+ * {@code PetNameAndId} could also define its own relations all of which would also be fetched
+ * automatically.
+ * <p>
+ * If you would like to specify which columns are fetched from the child {@link Entity}, you can
+ * use {@link #projection()} property in the {@code Relation} annotation.
+ * <pre>
+ * public class UserAndAllPets {
+ *   {@literal @}Embedded
+ *   public User user;
+ *   {@literal @}Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class,
+ *           projection = {"name"})
+ *   public List<String> petNames;
+ * }
+ * </pre>
+ * <p>
+ * Note that {@code @Relation} annotation can be used only in Pojo classes, an {@link Entity} class
+ * cannot have relations. This is a design decision to avoid common pitfalls in {@link Entity}
+ * setups. You can read more about it in the main Room documentation. When loading data, you can
+ * simply work around this limitation by creating Pojo classes that extend the {@link Entity}.
+ *
+ * Note that the {@code @Relation} annotated field cannot be a constructor parameter, it must be
+ * public or have a public setter.
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.CLASS)
+public @interface Relation {
+    /**
+     * The entity to fetch the item from. You don't need to set this if the entity matches the
+     * type argument in the return type.
+     *
+     * @return The entity to fetch from. By default, inherited from the return type.
+     */
+    Class entity() default Object.class;
+
+    /**
+     * Reference field in the parent Pojo.
+     * <p>
+     * If you would like to access to a sub item of a {@link Embedded}d field, you can use
+     * the {@code .} notation.
+     * <p>
+     * For instance, if you have a {@link Embedded}d field named {@code user} with a sub field
+     * {@code id}, you can reference it via {@code user.id}.
+     * <p>
+     * This value will be matched against the value defined in {@link #entityColumn()}.
+     *
+     * @return The field reference in the parent object.
+     */
+    String parentColumn();
+
+    /**
+     * The field path to match in the {@link #entity()}. This value will be matched against the
+     * value defined in {@link #parentColumn()}.
+     */
+    String entityColumn();
+
+    /**
+     * If sub fields should be fetched from the entity, you can specify them using this field.
+     * <p>
+     * By default, inferred from the the return type.
+     *
+     * @return The list of columns to be selected from the {@link #entity()}.
+     */
+    String[] projection() default {};
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/RoomMasterTable.java b/room/common/src/main/java/android/arch/persistence/room/RoomMasterTable.java
new file mode 100644
index 0000000..621845d
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/RoomMasterTable.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.support.annotation.RestrictTo;
+
+/**
+ * Schema information about Room's master table.
+ *
+ * @hide
+ */
+@SuppressWarnings("WeakerAccess")
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class RoomMasterTable {
+    /**
+     * The master table where room keeps its metadata information.
+     */
+    public static final String TABLE_NAME = "room_master_table";
+    // must match the runtime property Room#MASTER_TABLE_NAME
+    public static final String NAME = "room_master_table";
+    private static final String COLUMN_ID = "id";
+    private static final String COLUMN_IDENTITY_HASH = "identity_hash";
+    public static final String DEFAULT_ID = "42";
+
+    public static final String CREATE_QUERY = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
+            + COLUMN_ID + " INTEGER PRIMARY KEY,"
+            + COLUMN_IDENTITY_HASH + " TEXT)";
+
+    public static final String READ_QUERY = "SELECT " + COLUMN_IDENTITY_HASH
+            + " FROM " + TABLE_NAME + " WHERE "
+            + COLUMN_ID + " = " + DEFAULT_ID + " LIMIT 1";
+
+    /**
+     * We don't escape here since we know what we are passing.
+     */
+    public static String createInsertQuery(String hash) {
+        return "INSERT OR REPLACE INTO " + TABLE_NAME + " ("
+                + COLUMN_ID + "," + COLUMN_IDENTITY_HASH + ")"
+                + " VALUES(" + DEFAULT_ID + ", \"" + hash + "\")";
+    }
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/RoomWarnings.java b/room/common/src/main/java/android/arch/persistence/room/RoomWarnings.java
new file mode 100644
index 0000000..91f32e4
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/RoomWarnings.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+/**
+ * The list of warnings that are produced by Room.
+ * <p>
+ * You can use these values inside a {@link SuppressWarnings} annotation to disable the warnings.
+ */
+@SuppressWarnings({"unused", "WeakerAccess"})
+public class RoomWarnings {
+    /**
+     * The warning dispatched by Room when the return value of a {@link Query} method does not
+     * exactly match the fields in the query result.
+     */
+    // if you change this, don't forget to change android.arch.persistence.room.vo.Warning
+    public static final String CURSOR_MISMATCH = "ROOM_CURSOR_MISMATCH";
+
+    /**
+     * Reported when Room cannot verify database queries during compilation due to lack of
+     * tmp dir access in JVM.
+     */
+    public static final String MISSING_JAVA_TMP_DIR = "ROOM_MISSING_JAVA_TMP_DIR";
+
+    /**
+     * Reported when Room cannot verify database queries during compilation. This usually happens
+     * when it cannot find the SQLite JDBC driver on the host machine.
+     * <p>
+     * Room can function without query verification but its functionality will be limited.
+     */
+    public static final String CANNOT_CREATE_VERIFICATION_DATABASE =
+            "ROOM_CANNOT_CREATE_VERIFICATION_DATABASE";
+
+    /**
+     * Reported when an {@link Entity} field that is annotated with {@link Embedded} has a
+     * sub field which is annotated with {@link PrimaryKey} but the {@link PrimaryKey} is dropped
+     * while composing it into the parent object.
+     */
+    public static final String PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED =
+            "ROOM_EMBEDDED_PRIMARY_KEY_IS_DROPPED";
+
+    /**
+     * Reported when an {@link Entity} field that is annotated with {@link Embedded} has a
+     * sub field which has a {@link ColumnInfo} annotation with {@code index = true}.
+     * <p>
+     * You can re-define the index in the containing {@link Entity}.
+     */
+    public static final String INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED =
+            "ROOM_EMBEDDED_INDEX_IS_DROPPED";
+
+    /**
+     * Reported when an {@link Entity} that has a {@link Embedded}d field whose type is another
+     * {@link Entity} and that {@link Entity} has some indices defined.
+     * These indices will NOT be created in the containing {@link Entity}. If you want to preserve
+     * them, you can re-define them in the containing {@link Entity}.
+     */
+    public static final String INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED =
+            "ROOM_EMBEDDED_ENTITY_INDEX_IS_DROPPED";
+
+    /**
+     * Reported when an {@link Entity}'s parent declares an {@link Index}. Room does not
+     * automatically inherit these indices to avoid hidden costs or unexpected constraints.
+     * <p>
+     * If you want your child class to have the indices of the parent, you must re-declare
+     * them in the child class. Alternatively, you can set {@link Entity#inheritSuperIndices()}
+     * to {@code true}.
+     */
+    public static final String INDEX_FROM_PARENT_IS_DROPPED =
+            "ROOM_PARENT_INDEX_IS_DROPPED";
+
+    /**
+     * Reported when an {@link Entity} inherits a field from its super class and the field has a
+     * {@link ColumnInfo} annotation with {@code index = true}.
+     * <p>
+     * These indices are dropped for the {@link Entity} and you would need to re-declare them if
+     * you want to keep them. Alternatively, you can set {@link Entity#inheritSuperIndices()}
+     * to {@code true}.
+     */
+    public static final String INDEX_FROM_PARENT_FIELD_IS_DROPPED =
+            "ROOM_PARENT_FIELD_INDEX_IS_DROPPED";
+
+    /**
+     * Reported when a {@link Relation} {@link Entity}'s SQLite column type does not match the type
+     * in the parent. Room will still do the matching using {@code String} representations.
+     */
+    public static final String RELATION_TYPE_MISMATCH = "ROOM_RELATION_TYPE_MISMATCH";
+
+    /**
+     * Reported when a `room.schemaLocation` argument is not provided into the annotation processor.
+     * You can either set {@link Database#exportSchema()} to {@code false} or provide
+     * `room.schemaLocation` to the annotation processor. You are strongly adviced to provide it
+     * and also commit them into your version control system.
+     */
+    public static final String MISSING_SCHEMA_LOCATION = "ROOM_MISSING_SCHEMA_LOCATION";
+
+    /**
+     * When there is a foreign key from Entity A to Entity B, it is a good idea to index the
+     * reference columns in B, otherwise, each modification on Entity A will trigger a full table
+     * scan on Entity B.
+     * <p>
+     * If Room cannot find a proper index in the child entity (Entity B in this case), Room will
+     * print this warning.
+     */
+    public static final String MISSING_INDEX_ON_FOREIGN_KEY_CHILD =
+            "ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX";
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/SkipQueryVerification.java b/room/common/src/main/java/android/arch/persistence/room/SkipQueryVerification.java
new file mode 100644
index 0000000..dc2ded3
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/SkipQueryVerification.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Skips database verification for the annotated element.
+ * <p>
+ * If it is a class annotated with {@link Database}, none of the queries for the database will
+ * be verified at compile time.
+ * <p>
+ * If it is a class annotated with {@link Dao}, none of the queries in the Dao class will
+ * be verified at compile time.
+ * <p>
+ * If it is a method in a Dao class, just the method's sql verification will be skipped.
+ * <p>
+ * You should use this as the last resort if Room cannot properly understand your query and you are
+ * 100% sure it works. Removing validation may limit the functionality of Room since it won't be
+ * able to understand the query response.
+ */
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.CLASS)
+public @interface SkipQueryVerification {
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/TypeConverter.java b/room/common/src/main/java/android/arch/persistence/room/TypeConverter.java
new file mode 100644
index 0000000..bea68c8
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/TypeConverter.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a method as a type converter. A class can have as many @Converter methods as it needs.
+ * <p>
+ * Each converter method should receive 1 parameter and have non-void return type.
+ *
+ * <pre>
+ * // example converter for java.util.Date
+ * public static class Converters {
+ *    {@literal @}TypeConverter
+ *    public Date fromTimestamp(Long value) {
+ *        return value == null ? null : new Date(value);
+ *    }
+ *
+ *    {@literal @}TypeConverter
+ *    public Long dateToTimestamp(Date date) {
+ *        if (date == null) {
+ *            return null;
+ *        } else {
+ *            return date.getTime();
+ *        }
+ *    }
+ *}
+ * </pre>
+ * @see TypeConverters
+ */
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.CLASS)
+public @interface TypeConverter {
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/TypeConverters.java b/room/common/src/main/java/android/arch/persistence/room/TypeConverters.java
new file mode 100644
index 0000000..7f7e6ab
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/TypeConverters.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Specifies additional type converters that Room can use. The TypeConverter is added to the scope
+ * of the element so if you put it on a class / interface, all methods / fields in that class will
+ * be able to use the converters.
+ * <ul>
+ * <li>If you put it on a {@link Database}, all Daos and Entities in that database will be able to
+ * use it.
+ * <li>If you put it on a {@link Dao}, all methods in the Dao will be able to use it.
+ * <li>If you put it on an {@link Entity}, all fields of the Entity will be able to use it.
+ * <li>If you put it on a POJO, all fields of the POJO will be able to use it.
+ * <li>If you put it on an {@link Entity} field, only that field will be able to use it.
+ * <li>If you put it on a {@link Dao} method, all parameters of the method will be able to use it.
+ * <li>If you put it on a {@link Dao} method parameter, just that field will be able to use it.
+ * </ul>
+ * @see TypeConverter
+ */
+@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.FIELD})
+@Retention(RetentionPolicy.CLASS)
+public @interface TypeConverters {
+    /**
+     * The list of type converter classes. If converter methods are not static, Room will create
+     * an instance of these classes.
+     *
+     * @return The list of classes that contains the converter methods.
+     */
+    Class<?>[] value();
+}
diff --git a/room/common/src/main/java/android/arch/persistence/room/Update.java b/room/common/src/main/java/android/arch/persistence/room/Update.java
new file mode 100644
index 0000000..670a085
--- /dev/null
+++ b/room/common/src/main/java/android/arch/persistence/room/Update.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+/**
+ * Marks a method in a {@link Dao} annotated class as an update method.
+ * <p>
+ * The implementation of the method will update its parameters in the database if they already
+ * exists (checked by primary keys). If they don't already exists, this option will not change the
+ * database.
+ * <p>
+ * All of the parameters of the Update method must either be classes annotated with {@link Entity}
+ * or collections/array of it.
+ *
+ * @see Insert
+ * @see Delete
+ */
+public @interface Update {
+    /**
+     * What to do if a conflict happens.
+     * @see <a href="https://sqlite.org/lang_conflict.html">SQLite conflict documentation</a>
+     *
+     * @return How to handle conflicts. Defaults to {@link OnConflictStrategy#ABORT}.
+     */
+    @OnConflictStrategy
+    int onConflict() default OnConflictStrategy.ABORT;
+}
diff --git a/room/compiler/SQLite.g4 b/room/compiler/SQLite.g4
new file mode 100644
index 0000000..8eb895d
--- /dev/null
+++ b/room/compiler/SQLite.g4
@@ -0,0 +1,911 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014 by Bart Kiers
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Project      : sqlite-parser; an ANTLR4 grammar for SQLite
+ *                https://github.com/bkiers/sqlite-parser
+ * Developed by : Bart Kiers, bart@big-o.nl
+ */
+grammar SQLite;
+
+parse
+ : ( sql_stmt_list | error )* EOF
+ ;
+
+error
+ : UNEXPECTED_CHAR 
+   { 
+     throw new RuntimeException("UNEXPECTED_CHAR=" + $UNEXPECTED_CHAR.text); 
+   }
+ ;
+
+sql_stmt_list
+ : ';'* sql_stmt ( ';'+ sql_stmt )* ';'*
+ ;
+
+sql_stmt
+ : ( K_EXPLAIN ( K_QUERY K_PLAN )? )? ( alter_table_stmt
+                                      | analyze_stmt
+                                      | attach_stmt
+                                      | begin_stmt
+                                      | commit_stmt
+                                      | compound_select_stmt
+                                      | create_index_stmt
+                                      | create_table_stmt
+                                      | create_trigger_stmt
+                                      | create_view_stmt
+                                      | create_virtual_table_stmt
+                                      | delete_stmt
+                                      | delete_stmt_limited
+                                      | detach_stmt
+                                      | drop_index_stmt
+                                      | drop_table_stmt
+                                      | drop_trigger_stmt
+                                      | drop_view_stmt
+                                      | factored_select_stmt
+                                      | insert_stmt
+                                      | pragma_stmt
+                                      | reindex_stmt
+                                      | release_stmt
+                                      | rollback_stmt
+                                      | savepoint_stmt
+                                      | simple_select_stmt
+                                      | select_stmt
+                                      | update_stmt
+                                      | update_stmt_limited
+                                      | vacuum_stmt )
+ ;
+
+alter_table_stmt
+ : K_ALTER K_TABLE ( database_name '.' )? table_name
+   ( K_RENAME K_TO new_table_name
+   | K_ADD K_COLUMN? column_def
+   )
+ ;
+
+analyze_stmt
+ : K_ANALYZE ( database_name | table_or_index_name | database_name '.' table_or_index_name )?
+ ;
+
+attach_stmt
+ : K_ATTACH K_DATABASE? expr K_AS database_name
+ ;
+
+begin_stmt
+ : K_BEGIN ( K_DEFERRED | K_IMMEDIATE | K_EXCLUSIVE )? ( K_TRANSACTION transaction_name? )?
+ ;
+
+commit_stmt
+ : ( K_COMMIT | K_END ) ( K_TRANSACTION transaction_name? )?
+ ;
+
+compound_select_stmt
+ : with_clause?
+   select_core ( ( K_UNION K_ALL? | K_INTERSECT | K_EXCEPT ) select_core )+
+   ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+   ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )?
+ ;
+
+create_index_stmt
+ : K_CREATE K_UNIQUE? K_INDEX ( K_IF K_NOT K_EXISTS )?
+   ( database_name '.' )? index_name K_ON table_name '(' indexed_column ( ',' indexed_column )* ')'
+   ( K_WHERE expr )?
+ ;
+
+create_table_stmt
+ : K_CREATE ( K_TEMP | K_TEMPORARY )? K_TABLE ( K_IF K_NOT K_EXISTS )?
+   ( database_name '.' )? table_name
+   ( '(' column_def ( ',' column_def )*? ( ',' table_constraint )* ')' ( K_WITHOUT IDENTIFIER )?
+   | K_AS select_stmt
+   )
+ ;
+
+create_trigger_stmt
+ : K_CREATE ( K_TEMP | K_TEMPORARY )? K_TRIGGER ( K_IF K_NOT K_EXISTS )?
+   ( database_name '.' )? trigger_name ( K_BEFORE  | K_AFTER | K_INSTEAD K_OF )?
+   ( K_DELETE | K_INSERT | K_UPDATE ( K_OF column_name ( ',' column_name )* )? ) K_ON ( database_name '.' )? table_name
+   ( K_FOR K_EACH K_ROW )? ( K_WHEN expr )?
+   K_BEGIN ( ( update_stmt | insert_stmt | delete_stmt | select_stmt ) ';' )+ K_END
+ ;
+
+create_view_stmt
+ : K_CREATE ( K_TEMP | K_TEMPORARY )? K_VIEW ( K_IF K_NOT K_EXISTS )?
+   ( database_name '.' )? view_name K_AS select_stmt
+ ;
+
+create_virtual_table_stmt
+ : K_CREATE K_VIRTUAL K_TABLE ( K_IF K_NOT K_EXISTS )?
+   ( database_name '.' )? table_name
+   K_USING module_name ( '(' module_argument ( ',' module_argument )* ')' )?
+ ;
+
+delete_stmt
+ : with_clause? K_DELETE K_FROM qualified_table_name
+   ( K_WHERE expr )?
+ ;
+
+delete_stmt_limited
+ : with_clause? K_DELETE K_FROM qualified_table_name
+   ( K_WHERE expr )?
+   ( ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+     K_LIMIT expr ( ( K_OFFSET | ',' ) expr )?
+   )?
+ ;
+
+detach_stmt
+ : K_DETACH K_DATABASE? database_name
+ ;
+
+drop_index_stmt
+ : K_DROP K_INDEX ( K_IF K_EXISTS )? ( database_name '.' )? index_name
+ ;
+
+drop_table_stmt
+ : K_DROP K_TABLE ( K_IF K_EXISTS )? ( database_name '.' )? table_name
+ ;
+
+drop_trigger_stmt
+ : K_DROP K_TRIGGER ( K_IF K_EXISTS )? ( database_name '.' )? trigger_name
+ ;
+
+drop_view_stmt
+ : K_DROP K_VIEW ( K_IF K_EXISTS )? ( database_name '.' )? view_name
+ ;
+
+factored_select_stmt
+ : with_clause?
+   select_core ( compound_operator select_core )*
+   ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+   ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )?
+ ;
+
+insert_stmt
+ : with_clause? ( K_INSERT
+                | K_REPLACE
+                | K_INSERT K_OR K_REPLACE
+                | K_INSERT K_OR K_ROLLBACK
+                | K_INSERT K_OR K_ABORT
+                | K_INSERT K_OR K_FAIL
+                | K_INSERT K_OR K_IGNORE ) K_INTO
+   ( database_name '.' )? table_name ( '(' column_name ( ',' column_name )* ')' )?
+   ( K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )*
+   | select_stmt
+   | K_DEFAULT K_VALUES
+   )
+ ;
+
+pragma_stmt
+ : K_PRAGMA ( database_name '.' )? pragma_name ( '=' pragma_value
+                                               | '(' pragma_value ')' )?
+ ;
+
+reindex_stmt
+ : K_REINDEX ( collation_name
+             | ( database_name '.' )? ( table_name | index_name )
+             )?
+ ;
+
+release_stmt
+ : K_RELEASE K_SAVEPOINT? savepoint_name
+ ;
+
+rollback_stmt
+ : K_ROLLBACK ( K_TRANSACTION transaction_name? )? ( K_TO K_SAVEPOINT? savepoint_name )?
+ ;
+
+savepoint_stmt
+ : K_SAVEPOINT savepoint_name
+ ;
+
+simple_select_stmt
+ : with_clause?
+   select_core ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+   ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )?
+ ;
+
+select_stmt
+ : with_clause?
+   select_or_values ( compound_operator select_or_values )*
+   ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+   ( K_LIMIT expr ( ( K_OFFSET | ',' ) expr )? )?
+ ;
+
+select_or_values
+ : K_SELECT ( K_DISTINCT | K_ALL )? result_column ( ',' result_column )*
+   ( K_FROM ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) )?
+   ( K_WHERE expr )?
+   ( K_GROUP K_BY expr ( ',' expr )* ( K_HAVING expr )? )?
+ | K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )*
+ ;
+
+update_stmt
+ : with_clause? K_UPDATE ( K_OR K_ROLLBACK
+                         | K_OR K_ABORT
+                         | K_OR K_REPLACE
+                         | K_OR K_FAIL
+                         | K_OR K_IGNORE )? qualified_table_name
+   K_SET column_name '=' expr ( ',' column_name '=' expr )* ( K_WHERE expr )?
+ ;
+
+update_stmt_limited
+ : with_clause? K_UPDATE ( K_OR K_ROLLBACK
+                         | K_OR K_ABORT
+                         | K_OR K_REPLACE
+                         | K_OR K_FAIL
+                         | K_OR K_IGNORE )? qualified_table_name
+   K_SET column_name '=' expr ( ',' column_name '=' expr )* ( K_WHERE expr )?
+   ( ( K_ORDER K_BY ordering_term ( ',' ordering_term )* )?
+     K_LIMIT expr ( ( K_OFFSET | ',' ) expr )?
+   )?
+ ;
+
+vacuum_stmt
+ : K_VACUUM
+ ;
+
+column_def
+ : column_name type_name? column_constraint*
+ ;
+
+type_name
+ : name+? ( '(' signed_number ')'
+         | '(' signed_number ',' signed_number ')' )?
+ ;
+
+column_constraint
+ : ( K_CONSTRAINT name )?
+   ( K_PRIMARY K_KEY ( K_ASC | K_DESC )? conflict_clause K_AUTOINCREMENT?
+   | K_NOT? K_NULL conflict_clause
+   | K_UNIQUE conflict_clause
+   | K_CHECK '(' expr ')'
+   | K_DEFAULT (signed_number | literal_value | '(' expr ')')
+   | K_COLLATE collation_name
+   | foreign_key_clause
+   )
+ ;
+
+conflict_clause
+ : ( K_ON K_CONFLICT ( K_ROLLBACK
+                     | K_ABORT
+                     | K_FAIL
+                     | K_IGNORE
+                     | K_REPLACE
+                     )
+   )?
+ ;
+
+/*
+    SQLite understands the following binary operators, in order from highest to
+    lowest precedence:
+
+    ||
+    *    /    %
+    +    -
+    <<   >>   &    |
+    <    <=   >    >=
+    =    ==   !=   <>   IS   IS NOT   IN   LIKE   GLOB   MATCH   REGEXP
+    AND
+    OR
+*/
+expr
+ : literal_value
+ | BIND_PARAMETER
+ | ( ( database_name '.' )? table_name '.' )? column_name
+ | unary_operator expr
+ | expr '||' expr
+ | expr ( '*' | '/' | '%' ) expr
+ | expr ( '+' | '-' ) expr
+ | expr ( '<<' | '>>' | '&' | '|' ) expr
+ | expr ( '<' | '<=' | '>' | '>=' ) expr
+ | expr ( '=' | '==' | '!=' | '<>' ) expr
+ | expr K_AND expr
+ | expr K_OR expr
+ | function_name '(' ( K_DISTINCT? expr ( ',' expr )* | '*' )? ')'
+ | '(' expr ')'
+ | K_CAST '(' expr K_AS type_name ')'
+ | expr K_COLLATE collation_name
+ | expr K_NOT? ( K_LIKE | K_GLOB | K_REGEXP | K_MATCH ) expr ( K_ESCAPE expr )?
+ | expr ( K_ISNULL | K_NOTNULL | K_NOT K_NULL )
+ | expr K_IS K_NOT? expr
+ | expr K_NOT? K_BETWEEN expr K_AND expr
+ | expr K_NOT? K_IN ( '(' ( select_stmt
+                          | expr ( ',' expr )*
+                          )?
+                      ')'
+                    | ( database_name '.' )? table_name )
+ | ( ( K_NOT )? K_EXISTS )? '(' select_stmt ')'
+ | K_CASE expr? ( K_WHEN expr K_THEN expr )+ ( K_ELSE expr )? K_END
+ | raise_function
+ ;
+
+foreign_key_clause
+ : K_REFERENCES foreign_table ( '(' column_name ( ',' column_name )* ')' )?
+   ( ( K_ON ( K_DELETE | K_UPDATE ) ( K_SET K_NULL
+                                    | K_SET K_DEFAULT
+                                    | K_CASCADE
+                                    | K_RESTRICT
+                                    | K_NO K_ACTION )
+     | K_MATCH name
+     )
+   )*
+   ( K_NOT? K_DEFERRABLE ( K_INITIALLY K_DEFERRED | K_INITIALLY K_IMMEDIATE )? )?
+ ;
+
+raise_function
+ : K_RAISE '(' ( K_IGNORE
+               | ( K_ROLLBACK | K_ABORT | K_FAIL ) ',' error_message )
+           ')'
+ ;
+
+indexed_column
+ : column_name ( K_COLLATE collation_name )? ( K_ASC | K_DESC )?
+ ;
+
+table_constraint
+ : ( K_CONSTRAINT name )?
+   ( ( K_PRIMARY K_KEY | K_UNIQUE ) '(' indexed_column ( ',' indexed_column )* ')' conflict_clause
+   | K_CHECK '(' expr ')'
+   | K_FOREIGN K_KEY '(' column_name ( ',' column_name )* ')' foreign_key_clause
+   )
+ ;
+
+with_clause
+ : K_WITH K_RECURSIVE? common_table_expression ( ',' common_table_expression )*
+ ;
+
+qualified_table_name
+ : ( database_name '.' )? table_name ( K_INDEXED K_BY index_name
+                                     | K_NOT K_INDEXED )?
+ ;
+
+ordering_term
+ : expr ( K_COLLATE collation_name )? ( K_ASC | K_DESC )?
+ ;
+
+pragma_value
+ : signed_number
+ | name
+ | STRING_LITERAL
+ ;
+
+common_table_expression
+ : table_name ( '(' column_name ( ',' column_name )* ')' )? K_AS '(' select_stmt ')'
+ ;
+
+result_column
+ : '*'
+ | table_name '.' '*'
+ | expr ( K_AS? column_alias )?
+ ;
+
+table_or_subquery
+ : ( schema_name '.' )? table_name ( K_AS? table_alias )?
+   ( K_INDEXED K_BY index_name
+   | K_NOT K_INDEXED )?
+ | ( schema_name '.' )? table_function_name '(' ( expr ( ',' expr )* )? ')' ( K_AS? table_alias )?
+ | '(' ( table_or_subquery ( ',' table_or_subquery )*
+       | join_clause )
+   ')'
+ | '(' select_stmt ')' ( K_AS? table_alias )?
+ ;
+
+join_clause
+ : table_or_subquery ( join_operator table_or_subquery join_constraint )*
+ ;
+
+join_operator
+ : ','
+ | K_NATURAL? ( K_LEFT K_OUTER? | K_INNER | K_CROSS )? K_JOIN
+ ;
+
+join_constraint
+ : ( K_ON expr
+   | K_USING '(' column_name ( ',' column_name )* ')' )?
+ ;
+
+select_core
+ : K_SELECT ( K_DISTINCT | K_ALL )? result_column ( ',' result_column )*
+   ( K_FROM ( table_or_subquery ( ',' table_or_subquery )* | join_clause ) )?
+   ( K_WHERE expr )?
+   ( K_GROUP K_BY expr ( ',' expr )* ( K_HAVING expr )? )?
+ | K_VALUES '(' expr ( ',' expr )* ')' ( ',' '(' expr ( ',' expr )* ')' )*
+ ;
+
+compound_operator
+ : K_UNION
+ | K_UNION K_ALL
+ | K_INTERSECT
+ | K_EXCEPT
+ ;
+
+signed_number
+ : ( '+' | '-' )? NUMERIC_LITERAL
+ ;
+
+literal_value
+ : NUMERIC_LITERAL
+ | STRING_LITERAL
+ | BLOB_LITERAL
+ | K_NULL
+ | K_CURRENT_TIME
+ | K_CURRENT_DATE
+ | K_CURRENT_TIMESTAMP
+ ;
+
+unary_operator
+ : '-'
+ | '+'
+ | '~'
+ | K_NOT
+ ;
+
+error_message
+ : STRING_LITERAL
+ ;
+
+module_argument // TODO check what exactly is permitted here
+ : expr
+ | column_def
+ ;
+
+column_alias
+ : IDENTIFIER
+ | STRING_LITERAL
+ ;
+
+keyword
+ : K_ABORT
+ | K_ACTION
+ | K_ADD
+ | K_AFTER
+ | K_ALL
+ | K_ALTER
+ | K_ANALYZE
+ | K_AND
+ | K_AS
+ | K_ASC
+ | K_ATTACH
+ | K_AUTOINCREMENT
+ | K_BEFORE
+ | K_BEGIN
+ | K_BETWEEN
+ | K_BY
+ | K_CASCADE
+ | K_CASE
+ | K_CAST
+ | K_CHECK
+ | K_COLLATE
+ | K_COLUMN
+ | K_COMMIT
+ | K_CONFLICT
+ | K_CONSTRAINT
+ | K_CREATE
+ | K_CROSS
+ | K_CURRENT_DATE
+ | K_CURRENT_TIME
+ | K_CURRENT_TIMESTAMP
+ | K_DATABASE
+ | K_DEFAULT
+ | K_DEFERRABLE
+ | K_DEFERRED
+ | K_DELETE
+ | K_DESC
+ | K_DETACH
+ | K_DISTINCT
+ | K_DROP
+ | K_EACH
+ | K_ELSE
+ | K_END
+ | K_ESCAPE
+ | K_EXCEPT
+ | K_EXCLUSIVE
+ | K_EXISTS
+ | K_EXPLAIN
+ | K_FAIL
+ | K_FOR
+ | K_FOREIGN
+ | K_FROM
+ | K_FULL
+ | K_GLOB
+ | K_GROUP
+ | K_HAVING
+ | K_IF
+ | K_IGNORE
+ | K_IMMEDIATE
+ | K_IN
+ | K_INDEX
+ | K_INDEXED
+ | K_INITIALLY
+ | K_INNER
+ | K_INSERT
+ | K_INSTEAD
+ | K_INTERSECT
+ | K_INTO
+ | K_IS
+ | K_ISNULL
+ | K_JOIN
+ | K_KEY
+ | K_LEFT
+ | K_LIKE
+ | K_LIMIT
+ | K_MATCH
+ | K_NATURAL
+ | K_NO
+ | K_NOT
+ | K_NOTNULL
+ | K_NULL
+ | K_OF
+ | K_OFFSET
+ | K_ON
+ | K_OR
+ | K_ORDER
+ | K_OUTER
+ | K_PLAN
+ | K_PRAGMA
+ | K_PRIMARY
+ | K_QUERY
+ | K_RAISE
+ | K_RECURSIVE
+ | K_REFERENCES
+ | K_REGEXP
+ | K_REINDEX
+ | K_RELEASE
+ | K_RENAME
+ | K_REPLACE
+ | K_RESTRICT
+ | K_RIGHT
+ | K_ROLLBACK
+ | K_ROW
+ | K_SAVEPOINT
+ | K_SELECT
+ | K_SET
+ | K_TABLE
+ | K_TEMP
+ | K_TEMPORARY
+ | K_THEN
+ | K_TO
+ | K_TRANSACTION
+ | K_TRIGGER
+ | K_UNION
+ | K_UNIQUE
+ | K_UPDATE
+ | K_USING
+ | K_VACUUM
+ | K_VALUES
+ | K_VIEW
+ | K_VIRTUAL
+ | K_WHEN
+ | K_WHERE
+ | K_WITH
+ | K_WITHOUT
+ ;
+
+// TODO check all names below
+
+name
+ : any_name
+ ;
+
+function_name
+ : any_name
+ ;
+
+database_name
+ : any_name
+ ;
+
+schema_name
+ : any_name
+ ;
+
+table_function_name
+ : any_name
+ ;
+
+table_name
+ : any_name
+ ;
+
+table_or_index_name
+ : any_name
+ ;
+
+new_table_name
+ : any_name
+ ;
+
+column_name
+ : any_name
+ ;
+
+collation_name
+ : any_name
+ ;
+
+foreign_table
+ : any_name
+ ;
+
+index_name
+ : any_name
+ ;
+
+trigger_name
+ : any_name
+ ;
+
+view_name
+ : any_name
+ ;
+
+module_name
+ : any_name
+ ;
+
+pragma_name
+ : any_name
+ ;
+
+savepoint_name
+ : any_name
+ ;
+
+table_alias
+ : IDENTIFIER
+ | STRING_LITERAL
+ | '(' table_alias ')'
+ ;
+
+transaction_name
+ : any_name
+ ;
+
+any_name
+ : IDENTIFIER
+ | keyword
+ | STRING_LITERAL
+ | '(' any_name ')'
+ ;
+
+SCOL : ';';
+DOT : '.';
+OPEN_PAR : '(';
+CLOSE_PAR : ')';
+COMMA : ',';
+ASSIGN : '=';
+STAR : '*';
+PLUS : '+';
+MINUS : '-';
+TILDE : '~';
+PIPE2 : '||';
+DIV : '/';
+MOD : '%';
+LT2 : '<<';
+GT2 : '>>';
+AMP : '&';
+PIPE : '|';
+LT : '<';
+LT_EQ : '<=';
+GT : '>';
+GT_EQ : '>=';
+EQ : '==';
+NOT_EQ1 : '!=';
+NOT_EQ2 : '<>';
+
+// http://www.sqlite.org/lang_keywords.html
+K_ABORT : A B O R T;
+K_ACTION : A C T I O N;
+K_ADD : A D D;
+K_AFTER : A F T E R;
+K_ALL : A L L;
+K_ALTER : A L T E R;
+K_ANALYZE : A N A L Y Z E;
+K_AND : A N D;
+K_AS : A S;
+K_ASC : A S C;
+K_ATTACH : A T T A C H;
+K_AUTOINCREMENT : A U T O I N C R E M E N T;
+K_BEFORE : B E F O R E;
+K_BEGIN : B E G I N;
+K_BETWEEN : B E T W E E N;
+K_BY : B Y;
+K_CASCADE : C A S C A D E;
+K_CASE : C A S E;
+K_CAST : C A S T;
+K_CHECK : C H E C K;
+K_COLLATE : C O L L A T E;
+K_COLUMN : C O L U M N;
+K_COMMIT : C O M M I T;
+K_CONFLICT : C O N F L I C T;
+K_CONSTRAINT : C O N S T R A I N T;
+K_CREATE : C R E A T E;
+K_CROSS : C R O S S;
+K_CURRENT_DATE : C U R R E N T '_' D A T E;
+K_CURRENT_TIME : C U R R E N T '_' T I M E;
+K_CURRENT_TIMESTAMP : C U R R E N T '_' T I M E S T A M P;
+K_DATABASE : D A T A B A S E;
+K_DEFAULT : D E F A U L T;
+K_DEFERRABLE : D E F E R R A B L E;
+K_DEFERRED : D E F E R R E D;
+K_DELETE : D E L E T E;
+K_DESC : D E S C;
+K_DETACH : D E T A C H;
+K_DISTINCT : D I S T I N C T;
+K_DROP : D R O P;
+K_EACH : E A C H;
+K_ELSE : E L S E;
+K_END : E N D;
+K_ESCAPE : E S C A P E;
+K_EXCEPT : E X C E P T;
+K_EXCLUSIVE : E X C L U S I V E;
+K_EXISTS : E X I S T S;
+K_EXPLAIN : E X P L A I N;
+K_FAIL : F A I L;
+K_FOR : F O R;
+K_FOREIGN : F O R E I G N;
+K_FROM : F R O M;
+K_FULL : F U L L;
+K_GLOB : G L O B;
+K_GROUP : G R O U P;
+K_HAVING : H A V I N G;
+K_IF : I F;
+K_IGNORE : I G N O R E;
+K_IMMEDIATE : I M M E D I A T E;
+K_IN : I N;
+K_INDEX : I N D E X;
+K_INDEXED : I N D E X E D;
+K_INITIALLY : I N I T I A L L Y;
+K_INNER : I N N E R;
+K_INSERT : I N S E R T;
+K_INSTEAD : I N S T E A D;
+K_INTERSECT : I N T E R S E C T;
+K_INTO : I N T O;
+K_IS : I S;
+K_ISNULL : I S N U L L;
+K_JOIN : J O I N;
+K_KEY : K E Y;
+K_LEFT : L E F T;
+K_LIKE : L I K E;
+K_LIMIT : L I M I T;
+K_MATCH : M A T C H;
+K_NATURAL : N A T U R A L;
+K_NO : N O;
+K_NOT : N O T;
+K_NOTNULL : N O T N U L L;
+K_NULL : N U L L;
+K_OF : O F;
+K_OFFSET : O F F S E T;
+K_ON : O N;
+K_OR : O R;
+K_ORDER : O R D E R;
+K_OUTER : O U T E R;
+K_PLAN : P L A N;
+K_PRAGMA : P R A G M A;
+K_PRIMARY : P R I M A R Y;
+K_QUERY : Q U E R Y;
+K_RAISE : R A I S E;
+K_RECURSIVE : R E C U R S I V E;
+K_REFERENCES : R E F E R E N C E S;
+K_REGEXP : R E G E X P;
+K_REINDEX : R E I N D E X;
+K_RELEASE : R E L E A S E;
+K_RENAME : R E N A M E;
+K_REPLACE : R E P L A C E;
+K_RESTRICT : R E S T R I C T;
+K_RIGHT : R I G H T;
+K_ROLLBACK : R O L L B A C K;
+K_ROW : R O W;
+K_SAVEPOINT : S A V E P O I N T;
+K_SELECT : S E L E C T;
+K_SET : S E T;
+K_TABLE : T A B L E;
+K_TEMP : T E M P;
+K_TEMPORARY : T E M P O R A R Y;
+K_THEN : T H E N;
+K_TO : T O;
+K_TRANSACTION : T R A N S A C T I O N;
+K_TRIGGER : T R I G G E R;
+K_UNION : U N I O N;
+K_UNIQUE : U N I Q U E;
+K_UPDATE : U P D A T E;
+K_USING : U S I N G;
+K_VACUUM : V A C U U M;
+K_VALUES : V A L U E S;
+K_VIEW : V I E W;
+K_VIRTUAL : V I R T U A L;
+K_WHEN : W H E N;
+K_WHERE : W H E R E;
+K_WITH : W I T H;
+K_WITHOUT : W I T H O U T;
+
+IDENTIFIER
+ : '"' (~'"' | '""')* '"'
+ | '`' (~'`' | '``')* '`'
+ | '[' ~']'* ']'
+ | [a-zA-Z_] [a-zA-Z_0-9]* // TODO check: needs more chars in set
+ ;
+
+NUMERIC_LITERAL
+ : DIGIT+ ( '.' DIGIT* )? ( E [-+]? DIGIT+ )?
+ | '.' DIGIT+ ( E [-+]? DIGIT+ )?
+ ;
+
+BIND_PARAMETER
+ : '?' DIGIT*
+ | [:@$] IDENTIFIER
+ ;
+
+STRING_LITERAL
+ : '\'' ( ~'\'' | '\'\'' )* '\''
+ ;
+
+BLOB_LITERAL
+ : X STRING_LITERAL
+ ;
+
+SINGLE_LINE_COMMENT
+ : '--' ~[\r\n]* -> channel(HIDDEN)
+ ;
+
+MULTILINE_COMMENT
+ : '/*' .*? ( '*/' | EOF ) -> channel(HIDDEN)
+ ;
+
+SPACES
+ : [ \u000B\t\r\n] -> channel(HIDDEN)
+ ;
+
+UNEXPECTED_CHAR
+ : .
+ ;
+
+fragment DIGIT : [0-9];
+
+fragment A : [aA];
+fragment B : [bB];
+fragment C : [cC];
+fragment D : [dD];
+fragment E : [eE];
+fragment F : [fF];
+fragment G : [gG];
+fragment H : [hH];
+fragment I : [iI];
+fragment J : [jJ];
+fragment K : [kK];
+fragment L : [lL];
+fragment M : [mM];
+fragment N : [nN];
+fragment O : [oO];
+fragment P : [pP];
+fragment Q : [qQ];
+fragment R : [rR];
+fragment S : [sS];
+fragment T : [tT];
+fragment U : [uU];
+fragment V : [vV];
+fragment W : [wW];
+fragment X : [xX];
+fragment Y : [yY];
+fragment Z : [zZ];
\ No newline at end of file
diff --git a/room/compiler/build.gradle b/room/compiler/build.gradle
new file mode 100644
index 0000000..0802a06
--- /dev/null
+++ b/room/compiler/build.gradle
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+apply plugin: 'kotlin'
+apply plugin: 'maven'
+
+def antlrOut = "$buildDir/generated/antlr/grammar-gen/"
+sourceSets {
+    main.java.srcDirs += 'src/main/grammar-gen'
+    test.java.srcDirs += 'src/tests/kotlin'
+    main.java.srcDirs += antlrOut
+}
+project.ext.noDocs = true
+
+// Temporary hack to stop AS to adding two guavas into test's classpath
+configurations.all {
+    resolutionStrategy {
+        force libs.guava
+    }
+}
+
+dependencies {
+    // taken from ButterKnife
+    def logger = new com.android.build.gradle.internal.LoggerWrapper(project.logger)
+    def sdkHandler = new com.android.build.gradle.internal.SdkHandler(project, logger)
+    compile project(":room:common")
+    compile project(":room:migration")
+    compile libs.kotlin.stdlib
+    compile libs.auto_common
+    compile libs.javapoet
+    compile libs.antlr
+    compile libs.xerial
+    compile libs.apache.commons.codec
+    testCompile libs.google_compile_testing
+    testCompile project(":paging:common")
+    testCompile libs.junit
+    testCompile libs.ij_annotations
+    testCompile libs.mockito_core
+    testCompile fileTree(dir: "${sdkHandler.sdkFolder}/platforms/android-$tools.current_sdk/",
+            include : "android.jar")
+    testCompile fileTree(dir: "${new File(project(":room:runtime").buildDir, "libJar")}",
+            include : "*.jar")
+    testCompile fileTree(dir: "${new File(project(":room:db").buildDir, "libJar")}",
+            include : "*.jar")
+    testCompile files(org.gradle.internal.jvm.Jvm.current().getToolsJar())
+}
+
+archivesBaseName = "compiler"
+
+def generateAntlrTask = task('generateAntlrGrammar', type: JavaExec) {
+    def outFolder = file(antlrOut)
+    outputs.dir(outFolder)
+    inputs.dir("$projectDir/SQLite.g4")
+    classpath configurations.runtime
+    main "org.antlr.v4.Tool"
+    args "SQLite.g4", "-visitor", "-o", new File(outFolder, "android/arch/persistence/room/parser").path,
+            "-package", "android.arch.persistence.room.parser"
+}
+
+tasks.findByName("compileKotlin").dependsOn(generateAntlrTask)
+tasks.findByName("compileKotlin").dependsOn(":room:runtime:jarDebug")
+tasks.findByName("compileKotlin").dependsOn(":room:db:jarDebug")
+
+createKotlinCheckstyle(project)
+
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/RoomProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/RoomProcessor.kt
new file mode 100644
index 0000000..78849eb
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/RoomProcessor.kt
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room
+
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.DatabaseProcessor
+import android.arch.persistence.room.processor.ProcessorErrors
+import android.arch.persistence.room.vo.DaoMethod
+import android.arch.persistence.room.vo.Warning
+import android.arch.persistence.room.writer.DaoWriter
+import android.arch.persistence.room.writer.DatabaseWriter
+import com.google.auto.common.BasicAnnotationProcessor
+import com.google.auto.common.MoreElements
+import com.google.common.collect.SetMultimap
+import java.io.File
+import javax.annotation.processing.SupportedSourceVersion
+import javax.lang.model.SourceVersion
+import javax.lang.model.element.Element
+
+/**
+ * The annotation processor for Room.
+ */
+@SupportedSourceVersion(SourceVersion.RELEASE_7)
+class RoomProcessor : BasicAnnotationProcessor() {
+    override fun initSteps(): MutableIterable<ProcessingStep>? {
+        val context = Context(processingEnv)
+        return arrayListOf(DatabaseProcessingStep(context))
+    }
+
+    override fun getSupportedOptions(): MutableSet<String> {
+        return Context.ARG_OPTIONS.toMutableSet()
+    }
+
+    class DatabaseProcessingStep(context: Context) : ContextBoundProcessingStep(context) {
+        override fun process(elementsByAnnotation: SetMultimap<Class<out Annotation>, Element>)
+                : MutableSet<Element> {
+            // TODO multi step support
+            val databases = elementsByAnnotation[Database::class.java]
+                    ?.map {
+                        DatabaseProcessor(context, MoreElements.asType(it)).process()
+                    }
+            val allDaoMethods = databases?.flatMap { it.daoMethods }
+            allDaoMethods?.let {
+                prepareDaosForWriting(databases!!, it)
+                it.forEach {
+                    DaoWriter(it.dao, context.processingEnv).write(context.processingEnv)
+                }
+            }
+
+            databases?.forEach { db ->
+                DatabaseWriter(db).write(context.processingEnv)
+                if (db.exportSchema) {
+                    val schemaOutFolder = context.schemaOutFolder
+                    if (schemaOutFolder == null) {
+                        context.logger.w(Warning.MISSING_SCHEMA_LOCATION, db.element,
+                                ProcessorErrors.MISSING_SCHEMA_EXPORT_DIRECTORY)
+                    } else {
+                        if (!schemaOutFolder.exists()) {
+                            schemaOutFolder.mkdirs()
+                        }
+                        val qName = db.element.qualifiedName.toString()
+                        val dbSchemaFolder = File(schemaOutFolder, qName)
+                        if (!dbSchemaFolder.exists()) {
+                            dbSchemaFolder.mkdirs()
+                        }
+                        db.exportSchema(File(dbSchemaFolder, "${db.version}.json"))
+                    }
+                }
+            }
+            context.databaseVerifier?.let {
+                it.closeConnection()
+            }
+            return mutableSetOf()
+        }
+        override fun annotations(): MutableSet<out Class<out Annotation>> {
+            return mutableSetOf(Database::class.java, Dao::class.java, Entity::class.java)
+        }
+
+        /**
+         * Traverses all dao methods and assigns them suffix if they are used in multiple databases.
+         */
+        private fun prepareDaosForWriting(
+                databases: List<android.arch.persistence.room.vo.Database>,
+                daoMethods: List<DaoMethod>) {
+            daoMethods.groupBy { it.dao.typeName }
+                    // if used only in 1 database, nothing to do.
+                    .filter { entry -> entry.value.size > 1 }
+                    .forEach { entry ->
+                        entry.value.groupBy { daoMethod ->
+                            // first suffix guess: Database's simple name
+                            val db = databases.first { db -> db.daoMethods.contains(daoMethod) }
+                            db.typeName.simpleName()
+                        }.forEach { entry ->
+                            val dbName = entry.key
+                            val methods = entry.value
+                            if (methods.size == 1) {
+                                //good, db names do not clash, use db name as suffix
+                                methods.first().dao.setSuffix(dbName)
+                            } else {
+                                // ok looks like a dao is used in 2 different databases both of
+                                // which have the same name. enumerate.
+                                methods.forEachIndexed { index, method ->
+                                    method.dao.setSuffix("${dbName}_$index")
+                                }
+                            }
+                        }
+                    }
+        }
+    }
+
+    abstract class ContextBoundProcessingStep(val context: Context) : ProcessingStep
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/element_ext.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/element_ext.kt
new file mode 100644
index 0000000..09b6221
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/element_ext.kt
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+
+package android.arch.persistence.room.ext
+
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.element.AnnotationValue
+import javax.lang.model.element.Element
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.TypeElement
+import javax.lang.model.element.VariableElement
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+import javax.lang.model.util.SimpleAnnotationValueVisitor6
+import kotlin.reflect.KClass
+
+fun Element.hasAnyOf(vararg modifiers: Modifier): Boolean {
+    return this.modifiers.any { modifiers.contains(it) }
+}
+
+fun Element.hasAnnotation(klass: KClass<out Annotation>): Boolean {
+    return MoreElements.isAnnotationPresent(this, klass.java)
+}
+
+fun Element.isNonNull() =
+        asType().kind.isPrimitive
+                || hasAnnotation(android.support.annotation.NonNull::class)
+                || hasAnnotation(org.jetbrains.annotations.NotNull::class)
+
+/**
+ * Checks if it has all of the annotations
+ */
+fun Element.hasAllOf(vararg klasses: KClass<out Annotation>): Boolean {
+    return !klasses.any { !hasAnnotation(it) }
+}
+
+/**
+ * gets all members including super privates. does not handle duplicate field names!!!
+ */
+// TODO handle conflicts with super: b/35568142
+fun TypeElement.getAllFieldsIncludingPrivateSupers(processingEnvironment: ProcessingEnvironment):
+        Set<VariableElement> {
+    val myMembers = processingEnvironment.elementUtils.getAllMembers(this)
+            .filter { it.kind == ElementKind.FIELD }
+            .filter { it is VariableElement }
+            .map { it as VariableElement }
+            .toSet()
+    if (superclass.kind != TypeKind.NONE) {
+        return myMembers + MoreTypes.asTypeElement(superclass)
+                .getAllFieldsIncludingPrivateSupers(processingEnvironment)
+    } else {
+        return myMembers
+    }
+}
+
+// code below taken from dagger2
+// compiler/src/main/java/dagger/internal/codegen/ConfigurationAnnotations.java
+private val TO_LIST_OF_TYPES = object
+    : SimpleAnnotationValueVisitor6<List<TypeMirror>, Void?>() {
+    override fun visitArray(values: MutableList<out AnnotationValue>?, p: Void?)
+            : List<TypeMirror> {
+        return values?.map {
+            val tmp = TO_TYPE.visit(it)
+            tmp
+        }?.filterNotNull() ?: emptyList()
+    }
+
+
+    override fun defaultAction(o: Any?, p: Void?): List<TypeMirror>? {
+        return emptyList()
+    }
+}
+
+private val TO_TYPE = object : SimpleAnnotationValueVisitor6<TypeMirror, Void>() {
+
+    override fun visitType(t: TypeMirror, p: Void?): TypeMirror {
+        return t
+    }
+
+    override fun defaultAction(o: Any?, p: Void?): TypeMirror {
+        throw TypeNotPresentException(o!!.toString(), null)
+    }
+}
+
+fun AnnotationValue.toListOfClassTypes(): List<TypeMirror> {
+    return TO_LIST_OF_TYPES.visit(this)
+}
+
+fun AnnotationValue.toType(): TypeMirror {
+    return TO_TYPE.visit(this)
+}
+
+fun AnnotationValue.toClassType(): TypeMirror? {
+    return TO_TYPE.visit(this)
+}
+
+fun TypeMirror.isCollection(): Boolean {
+    return MoreTypes.isType(this)
+            && (MoreTypes.isTypeOf(java.util.List::class.java, this)
+            || MoreTypes.isTypeOf(java.util.Set::class.java, this))
+}
+
+fun Element.getAnnotationValue(annotation: Class<out Annotation>, fieldName: String): Any? {
+    return MoreElements.getAnnotationMirror(this, annotation)
+            .orNull()?.let {
+        AnnotationMirrors.getAnnotationValue(it, fieldName)?.value
+    }
+}
+
+private val ANNOTATION_VALUE_TO_INT_VISITOR = object : SimpleAnnotationValueVisitor6<Int?, Void>() {
+    override fun visitInt(i: Int, p: Void?): Int? {
+        return i
+    }
+}
+
+private val ANNOTATION_VALUE_TO_BOOLEAN_VISITOR = object
+    : SimpleAnnotationValueVisitor6<Boolean?, Void>() {
+    override fun visitBoolean(b: Boolean, p: Void?): Boolean? {
+        return b
+    }
+}
+
+private val ANNOTATION_VALUE_TO_STRING_VISITOR = object
+    : SimpleAnnotationValueVisitor6<String?, Void>() {
+    override fun visitString(s: String?, p: Void?): String? {
+        return s
+    }
+}
+
+private val ANNOTATION_VALUE_STRING_ARR_VISITOR = object
+    : SimpleAnnotationValueVisitor6<List<String>, Void>() {
+    override fun visitArray(vals: MutableList<out AnnotationValue>?, p: Void?): List<String> {
+        return vals?.map {
+            ANNOTATION_VALUE_TO_STRING_VISITOR.visit(it)
+        }?.filterNotNull() ?: emptyList()
+    }
+}
+
+fun AnnotationValue.getAsInt(def: Int? = null): Int? {
+    return ANNOTATION_VALUE_TO_INT_VISITOR.visit(this) ?: def
+}
+
+fun AnnotationValue.getAsString(def: String? = null): String? {
+    return ANNOTATION_VALUE_TO_STRING_VISITOR.visit(this) ?: def
+}
+
+fun AnnotationValue.getAsBoolean(def: Boolean): Boolean {
+    return ANNOTATION_VALUE_TO_BOOLEAN_VISITOR.visit(this) ?: def
+}
+
+fun AnnotationValue.getAsStringList(): List<String> {
+    return ANNOTATION_VALUE_STRING_ARR_VISITOR.visit(this)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/javapoet_ext.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/javapoet_ext.kt
new file mode 100644
index 0000000..fa2f342
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/javapoet_ext.kt
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.ext
+
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.TypeMirror
+import kotlin.reflect.KClass
+
+val L = "\$L"
+val T = "\$T"
+val N = "\$N"
+val S = "\$S"
+
+fun KClass<*>.typeName() = ClassName.get(this.java)
+fun KClass<*>.arrayTypeName() = ArrayTypeName.of(typeName())
+fun TypeMirror.typeName() = TypeName.get(this)
+
+object SupportDbTypeNames {
+    val DB: ClassName = ClassName.get("android.arch.persistence.db", "SupportSQLiteDatabase")
+    val SQLITE_STMT : ClassName =
+            ClassName.get("android.arch.persistence.db", "SupportSQLiteStatement")
+    val SQLITE_OPEN_HELPER : ClassName =
+            ClassName.get("android.arch.persistence.db", "SupportSQLiteOpenHelper")
+    val SQLITE_OPEN_HELPER_CALLBACK : ClassName =
+            ClassName.get("android.arch.persistence.db", "SupportSQLiteOpenHelper.Callback")
+    val SQLITE_OPEN_HELPER_FACTORY : ClassName =
+            ClassName.get("android.arch.persistence.db", "SupportSQLiteOpenHelper.Factory")
+    val SQLITE_OPEN_HELPER_CONFIG : ClassName =
+            ClassName.get("android.arch.persistence.db", "SupportSQLiteOpenHelper.Configuration")
+    val SQLITE_OPEN_HELPER_CONFIG_BUILDER : ClassName =
+            ClassName.get("android.arch.persistence.db",
+                    "SupportSQLiteOpenHelper.Configuration.Builder")
+}
+
+object RoomTypeNames {
+    val STRING_UTIL: ClassName = ClassName.get("android.arch.persistence.room.util", "StringUtil")
+    val CURSOR_CONVERTER : ClassName =
+            ClassName.get("android.arch.persistence.room", "CursorConverter")
+    val ROOM : ClassName = ClassName.get("android.arch.persistence.room", "Room")
+    val ROOM_DB : ClassName = ClassName.get("android.arch.persistence.room", "RoomDatabase")
+    val ROOM_DB_CONFIG : ClassName = ClassName.get("android.arch.persistence.room",
+            "DatabaseConfiguration")
+    val INSERTION_ADAPTER : ClassName =
+            ClassName.get("android.arch.persistence.room", "EntityInsertionAdapter")
+    val DELETE_OR_UPDATE_ADAPTER : ClassName =
+            ClassName.get("android.arch.persistence.room", "EntityDeletionOrUpdateAdapter")
+    val SHARED_SQLITE_STMT : ClassName =
+            ClassName.get("android.arch.persistence.room", "SharedSQLiteStatement")
+    val INVALIDATION_TRACKER : ClassName =
+            ClassName.get("android.arch.persistence.room", "InvalidationTracker")
+    val INVALIDATION_OBSERVER : ClassName =
+            ClassName.get("android.arch.persistence.room.InvalidationTracker", "Observer")
+    val ROOM_SQL_QUERY : ClassName =
+            ClassName.get("android.arch.persistence.room", "RoomSQLiteQuery")
+    val OPEN_HELPER : ClassName =
+            ClassName.get("android.arch.persistence.room", "RoomOpenHelper")
+    val OPEN_HELPER_DELEGATE: ClassName =
+            ClassName.get("android.arch.persistence.room", "RoomOpenHelper.Delegate")
+    val TABLE_INFO : ClassName =
+            ClassName.get("android.arch.persistence.room.util", "TableInfo")
+    val TABLE_INFO_COLUMN : ClassName =
+            ClassName.get("android.arch.persistence.room.util", "TableInfo.Column")
+    val TABLE_INFO_FOREIGN_KEY : ClassName =
+            ClassName.get("android.arch.persistence.room.util", "TableInfo.ForeignKey")
+    val LIMIT_OFFSET_DATA_SOURCE : ClassName =
+            ClassName.get("android.arch.persistence.room.paging", "LimitOffsetDataSource")
+}
+
+object ArchTypeNames {
+    val APP_EXECUTOR : ClassName =
+            ClassName.get("android.arch.core.executor", "AppToolkitTaskExecutor")
+}
+
+object PagingTypeNames {
+    val COUNTED_DATA_SOURCE : ClassName =
+            ClassName.get("android.arch.util.paging", "CountedDataSource")
+    val LIVE_LAZY_LIST_PROVIDER: ClassName =
+            ClassName.get("android.arch.util.paging", "LiveLazyListProvider")
+
+}
+
+object LifecyclesTypeNames {
+    val LIVE_DATA: ClassName = ClassName.get("android.arch.lifecycle", "LiveData")
+    val COMPUTABLE_LIVE_DATA : ClassName = ClassName.get("android.arch.lifecycle",
+            "ComputableLiveData")
+}
+
+object AndroidTypeNames {
+    val CURSOR : ClassName = ClassName.get("android.database", "Cursor")
+    val ARRAY_MAP : ClassName = ClassName.get("android.support.v4.util", "ArrayMap")
+}
+
+object CommonTypeNames {
+    val LIST = ClassName.get("java.util", "List")
+    val SET = ClassName.get("java.util", "Set")
+    val STRING = ClassName.get("java.lang", "String")
+    val INTEGER = ClassName.get("java.lang", "Integer")
+}
+
+object RxJava2TypeNames {
+    val FLOWABLE = ClassName.get("io.reactivex", "Flowable")
+    val MAYBE = ClassName.get("io.reactivex", "Maybe")
+    val SINGLE = ClassName.get("io.reactivex", "Single")
+}
+
+object ReactiveStreamsTypeNames {
+    val PUBLISHER = ClassName.get("org.reactivestreams", "Publisher")
+}
+
+object RoomRxJava2TypeNames {
+    val RX_ROOM = ClassName.get("android.arch.persistence.room", "RxRoom")
+    val RX_EMPTY_RESULT_SET_EXCEPTION = ClassName.get("android.arch.persistence.room",
+            "EmptyResultSetException")
+}
+
+fun TypeName.defaultValue() : String {
+    return if (!isPrimitive) {
+        "null"
+    } else if (this == TypeName.BOOLEAN) {
+        "false"
+    } else {
+        "0"
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/string_ext.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/string_ext.kt
new file mode 100644
index 0000000..9b07e27
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/string_ext.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+private fun String.toCamelCase() : String {
+    val split = this.split("_")
+    if (split.isEmpty()) return ""
+    if (split.size == 1) return split[0].capitalize()
+    return split.joinToCamelCase()
+}
+
+private fun String.toCamelCaseAsVar() : String {
+    val split = this.split("_")
+    if (split.isEmpty()) return ""
+    if (split.size == 1) return split[0]
+    return split.joinToCamelCaseAsVar()
+}
+
+private fun List<String>.joinToCamelCase(): String = when(size) {
+    0 -> throw IllegalArgumentException("invalid section size, cannot be zero")
+    1 -> this[0].toCamelCase()
+    else -> this.map {it.toCamelCase()}.joinToString("")
+}
+
+private fun List<String>.joinToCamelCaseAsVar(): String = when(size) {
+    0 -> throw IllegalArgumentException("invalid section size, cannot be zero")
+    1 -> this[0].toCamelCaseAsVar()
+    else -> get(0).toCamelCaseAsVar() + drop(1).joinToCamelCase()
+}
+
+private val javaCharRegex = "[^a-zA-Z0-9]".toRegex()
+fun String.stripNonJava(): String {
+    return this.split(javaCharRegex)
+            .map(String::trim)
+            .joinToCamelCaseAsVar()
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/type_mirror_ext.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/type_mirror_ext.kt
new file mode 100644
index 0000000..97cd051
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/ext/type_mirror_ext.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+import javax.lang.model.type.TypeKind.BOOLEAN
+import javax.lang.model.type.TypeKind.BYTE
+import javax.lang.model.type.TypeKind.CHAR
+import javax.lang.model.type.TypeKind.DOUBLE
+import javax.lang.model.type.TypeKind.FLOAT
+import javax.lang.model.type.TypeKind.INT
+import javax.lang.model.type.TypeKind.LONG
+import javax.lang.model.type.TypeKind.SHORT
+import javax.lang.model.type.TypeMirror
+
+fun TypeMirror.defaultValue() : String {
+    return when(this.kind) {
+        BOOLEAN -> "false"
+        BYTE, SHORT, INT, LONG, CHAR, FLOAT, DOUBLE -> "0"
+        else -> "null"
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/log/RLog.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/log/RLog.kt
new file mode 100644
index 0000000..10614ce
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/log/RLog.kt
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+@file:Suppress("unused")
+
+package android.arch.persistence.room.log
+
+import android.arch.persistence.room.vo.Warning
+import java.util.UnknownFormatConversionException
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.element.Element
+import javax.tools.Diagnostic
+import javax.tools.Diagnostic.Kind.ERROR
+import javax.tools.Diagnostic.Kind.NOTE
+import javax.tools.Diagnostic.Kind.WARNING
+
+class RLog(val messager : Messager, val suppressedWarnings : Set<Warning>,
+           val defaultElement : Element?) {
+    private fun String.safeFormat(vararg args: Any): String {
+        try {
+            return format(args)
+        } catch (ex: UnknownFormatConversionException) {
+            // the input string might be from random source in which case we rather print the
+            // msg as is instead of crashing while reporting an error.
+            return this
+        }
+    }
+
+    fun d(element: Element, msg: String, vararg args: Any) {
+        messager.printMessage(NOTE, msg.safeFormat(args), element)
+    }
+
+    fun d(msg: String, vararg args: Any) {
+        messager.printMessage(NOTE, msg.safeFormat(args))
+    }
+
+    fun e(element: Element, msg: String, vararg args: Any) {
+        messager.printMessage(ERROR, msg.safeFormat(args), element)
+    }
+
+    fun e(msg: String, vararg args: Any) {
+        messager.printMessage(ERROR, msg.safeFormat(args), defaultElement)
+    }
+
+    fun w(warning: Warning, element: Element? = null, msg: String, vararg args: Any) {
+        if (suppressedWarnings.contains(warning)) {
+            return
+        }
+        messager.printMessage(WARNING, msg.safeFormat(args),
+                element ?: defaultElement)
+    }
+
+    fun w(warning: Warning, msg: String, vararg args: Any) {
+        if (suppressedWarnings.contains(warning)) {
+            return
+        }
+        messager.printMessage(WARNING, msg.safeFormat(args), defaultElement)
+    }
+
+    interface Messager {
+        fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element? = null)
+    }
+
+    class ProcessingEnvMessager(val processingEnv: ProcessingEnvironment) : Messager {
+        override fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element?) {
+            processingEnv.messager.printMessage(kind, msg, element)
+        }
+    }
+
+    class CollectingMessager : Messager {
+        private val messages = mutableMapOf<Diagnostic.Kind, MutableList<Pair<String, Element?>>> ()
+        override fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element?) {
+            messages.getOrPut(kind, {
+                arrayListOf<Pair<String, Element?>>()
+            }).add(Pair(msg, element))
+        }
+
+        fun hasErrors() = messages.containsKey(Diagnostic.Kind.ERROR)
+
+        fun writeTo(env : ProcessingEnvironment) {
+            messages.forEach { pair ->
+                val kind = pair.key
+                pair.value.forEach {
+                    env.messager.printMessage(kind, it.first, it.second)
+                }
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParsedQuery.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParsedQuery.kt
new file mode 100644
index 0000000..85d578d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParsedQuery.kt
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.parser
+
+import android.arch.persistence.room.parser.SectionType.BIND_VAR
+import android.arch.persistence.room.parser.SectionType.NEWLINE
+import android.arch.persistence.room.parser.SectionType.TEXT
+import android.arch.persistence.room.verifier.QueryResultInfo
+import org.antlr.v4.runtime.tree.TerminalNode
+
+enum class SectionType {
+    BIND_VAR,
+    TEXT,
+    NEWLINE
+}
+
+data class Section(val text: String, val type: SectionType) {
+    companion object {
+        fun text(text: String) = Section(text, SectionType.TEXT)
+        fun newline() = Section("", SectionType.NEWLINE)
+        fun bindVar(text: String) = Section(text, SectionType.BIND_VAR)
+    }
+}
+
+data class Table(val name: String, val alias: String)
+
+data class ParsedQuery(val original: String, val type: QueryType,
+                       val inputs: List<TerminalNode>,
+                       // pairs of table name and alias,
+                       val tables: Set<Table>,
+                       val syntaxErrors: List<String>) {
+    companion object {
+        val STARTS_WITH_NUMBER = "^\\?[0-9]".toRegex()
+        val MISSING = ParsedQuery("missing query", QueryType.UNKNOWN, emptyList(), emptySet(),
+                emptyList())
+    }
+
+    /**
+     * Optional data that might be assigned when the query is parsed inside an annotation processor.
+     * User may turn this off or it might be disabled for any reason so generated code should
+     * always handle not having it.
+     */
+    var resultInfo: QueryResultInfo? = null
+
+    val sections by lazy {
+        val lines = original.lines()
+        val inputsByLine = inputs.groupBy { it.symbol.line }
+        val sections = arrayListOf<Section>()
+        lines.forEachIndexed { index, line ->
+            var charInLine = 0
+            inputsByLine[index + 1]?.forEach { bindVar ->
+                if (charInLine < bindVar.symbol.charPositionInLine) {
+                    sections.add(Section.text(line.substring(charInLine,
+                            bindVar.symbol.charPositionInLine)))
+                }
+                sections.add(Section.bindVar(bindVar.text))
+                charInLine = bindVar.symbol.charPositionInLine + bindVar.symbol.text.length
+            }
+            if (charInLine < line.length) {
+                sections.add(Section.text(line.substring(charInLine)))
+            }
+            if (index + 1 < lines.size) {
+                sections.add(Section.newline())
+            }
+        }
+        sections
+    }
+
+    val bindSections by lazy { sections.filter { it.type == BIND_VAR } }
+
+    private fun unnamedVariableErrors(): List<String> {
+        val anonymousBindError = if (inputs.any { it.text == "?" }) {
+            arrayListOf(ParserErrors.ANONYMOUS_BIND_ARGUMENT)
+        } else {
+            emptyList<String>()
+        }
+        return anonymousBindError + inputs.filter {
+            it.text.matches(STARTS_WITH_NUMBER)
+        }.map {
+            ParserErrors.cannotUseVariableIndices(it.text, it.symbol.charPositionInLine)
+        }
+    }
+
+    private fun unknownQueryTypeErrors(): List<String> {
+        return if (QueryType.SUPPORTED.contains(type)) {
+            emptyList()
+        } else {
+            listOf(ParserErrors.invalidQueryType(type))
+        }
+    }
+
+    val errors by lazy {
+        if (syntaxErrors.isNotEmpty()) {
+            // if there is a syntax error, don't report others since they might be misleading.
+            syntaxErrors
+        } else {
+            unnamedVariableErrors() + unknownQueryTypeErrors()
+        }
+    }
+
+    val queryWithReplacedBindParams by lazy {
+        sections.joinToString("") {
+            when (it.type) {
+                TEXT -> it.text
+                BIND_VAR -> "?"
+                NEWLINE -> "\n"
+                else -> throw IllegalArgumentException("??")
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParserErrors.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParserErrors.kt
new file mode 100644
index 0000000..e3b4f40
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/ParserErrors.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.parser
+
+object ParserErrors {
+    val ANONYMOUS_BIND_ARGUMENT = "Room does not support ? as bind parameters. You must use" +
+            " named bind arguments (e..g :argName)"
+
+    val NOT_ONE_QUERY = "Must have exactly 1 query in @Query value"
+
+    fun invalidQueryType(type: QueryType): String {
+        return "$type query type is not supported yet. You can use:" +
+                QueryType.SUPPORTED.joinToString(", ") { it.name }
+    }
+
+    fun cannotUseVariableIndices(name: String, position: Int) = "Cannot use variable indices." +
+            " Use named parameters instead (e.g. WHERE name LIKE :nameArg and lastName LIKE " +
+            ":lastName). Problem: $name at $position"
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/SqlParser.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/SqlParser.kt
new file mode 100644
index 0000000..7bdd397
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/parser/SqlParser.kt
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.parser
+
+import android.arch.persistence.room.ColumnInfo
+import org.antlr.v4.runtime.ANTLRInputStream
+import org.antlr.v4.runtime.BaseErrorListener
+import org.antlr.v4.runtime.CommonTokenStream
+import org.antlr.v4.runtime.RecognitionException
+import org.antlr.v4.runtime.Recognizer
+import org.antlr.v4.runtime.tree.ParseTree
+import org.antlr.v4.runtime.tree.TerminalNode
+import java.util.ArrayList
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+class QueryVisitor(val original: String, val syntaxErrors: ArrayList<String>,
+                   statement: ParseTree) : SQLiteBaseVisitor<Void?>() {
+    val bindingExpressions = arrayListOf<TerminalNode>()
+    // table name alias mappings
+    val tableNames = mutableSetOf<Table>()
+    val queryType: QueryType
+
+    init {
+        queryType = (0..statement.childCount - 1).map {
+            findQueryType(statement.getChild(it))
+        }.filterNot { it == QueryType.UNKNOWN }.firstOrNull() ?: QueryType.UNKNOWN
+
+        statement.accept(this)
+    }
+
+    private fun findQueryType(statement: ParseTree): QueryType {
+        return when (statement) {
+            is SQLiteParser.Factored_select_stmtContext,
+            is SQLiteParser.Compound_select_stmtContext,
+            is SQLiteParser.Select_stmtContext,
+            is SQLiteParser.Simple_select_stmtContext ->
+                QueryType.SELECT
+
+            is SQLiteParser.Delete_stmt_limitedContext,
+            is SQLiteParser.Delete_stmtContext ->
+                QueryType.DELETE
+
+            is SQLiteParser.Insert_stmtContext ->
+                QueryType.INSERT
+            is SQLiteParser.Update_stmtContext,
+            is SQLiteParser.Update_stmt_limitedContext ->
+                QueryType.UPDATE
+            is TerminalNode -> when (statement.text) {
+                "EXPLAIN" -> QueryType.EXPLAIN
+                else -> QueryType.UNKNOWN
+            }
+            else -> QueryType.UNKNOWN
+        }
+    }
+
+    override fun visitExpr(ctx: SQLiteParser.ExprContext): Void? {
+        val bindParameter = ctx.BIND_PARAMETER()
+        if (bindParameter != null) {
+            bindingExpressions.add(bindParameter)
+        }
+        return super.visitExpr(ctx)
+    }
+
+    fun createParsedQuery(): ParsedQuery {
+        return ParsedQuery(original,
+                queryType,
+                bindingExpressions.sortedBy { it.sourceInterval.a },
+                tableNames,
+                syntaxErrors)
+    }
+
+    override fun visitTable_or_subquery(ctx: SQLiteParser.Table_or_subqueryContext): Void? {
+        val tableName = ctx.table_name()?.text
+        if (tableName != null) {
+            val tableAlias = ctx.table_alias()?.text
+            tableNames.add(Table(unescapeIdentifier(tableName),
+                    unescapeIdentifier(tableAlias ?: tableName)))
+        }
+        return super.visitTable_or_subquery(ctx)
+    }
+
+    private fun unescapeIdentifier(text : String) : String {
+        val trimmed = text.trim()
+        if (trimmed.startsWith("`") && trimmed.endsWith('`')) {
+            return unescapeIdentifier(trimmed.substring(1, trimmed.length - 1))
+        }
+        if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
+            return unescapeIdentifier(trimmed.substring(1, trimmed.length - 1))
+        }
+        return trimmed
+    }
+}
+
+class SqlParser {
+    companion object {
+        fun parse(input: String): ParsedQuery {
+            val inputStream = ANTLRInputStream(input)
+            val lexer = SQLiteLexer(inputStream)
+            val tokenStream = CommonTokenStream(lexer)
+            val parser = SQLiteParser(tokenStream)
+            val syntaxErrors = arrayListOf<String>()
+            parser.addErrorListener(object : BaseErrorListener() {
+                override fun syntaxError(recognizer: Recognizer<*, *>, offendingSymbol: Any,
+                                         line: Int, charPositionInLine: Int, msg: String,
+                                         e: RecognitionException?) {
+                    syntaxErrors.add(msg)
+                }
+            })
+            try {
+                val parsed = parser.parse()
+                val statementList = parsed.sql_stmt_list()
+                if (statementList.isEmpty()) {
+                    syntaxErrors.add(ParserErrors.NOT_ONE_QUERY)
+                    return ParsedQuery(input, QueryType.UNKNOWN, emptyList(), emptySet(),
+                            listOf(ParserErrors.NOT_ONE_QUERY))
+                }
+                val statements = statementList.first().children
+                        .filter { it is SQLiteParser.Sql_stmtContext }
+                if (statements.size != 1) {
+                    syntaxErrors.add(ParserErrors.NOT_ONE_QUERY)
+                }
+                val statement = statements.first()
+                return QueryVisitor(input, syntaxErrors, statement).createParsedQuery()
+            } catch (antlrError: RuntimeException) {
+                return ParsedQuery(input, QueryType.UNKNOWN, emptyList(), emptySet(),
+                        listOf("unknown error while parsing $input : ${antlrError.message}"))
+            }
+        }
+    }
+}
+
+enum class QueryType {
+    UNKNOWN,
+    SELECT,
+    DELETE,
+    UPDATE,
+    EXPLAIN,
+    INSERT;
+
+    companion object {
+        // IF you change this, don't forget to update @Query documentation.
+        val SUPPORTED = hashSetOf(SELECT, DELETE, UPDATE)
+    }
+}
+
+enum class SQLTypeAffinity {
+    NULL,
+    TEXT,
+    INTEGER,
+    REAL,
+    BLOB;
+    fun getTypeMirrors(env : ProcessingEnvironment) : List<TypeMirror>? {
+        val typeUtils = env.typeUtils
+        return when(this) {
+            TEXT -> listOf(env.elementUtils.getTypeElement("java.lang.String").asType())
+            INTEGER -> withBoxedTypes(env, TypeKind.INT, TypeKind.BYTE, TypeKind.CHAR,
+                    TypeKind.BOOLEAN, TypeKind.LONG, TypeKind.SHORT)
+            REAL -> withBoxedTypes(env, TypeKind.DOUBLE, TypeKind.FLOAT)
+            BLOB -> listOf(typeUtils.getArrayType(
+                    typeUtils.getPrimitiveType(TypeKind.BYTE)))
+            else -> emptyList()
+        }
+    }
+
+    private fun withBoxedTypes(env : ProcessingEnvironment, vararg primitives : TypeKind) :
+            List<TypeMirror> {
+        return primitives.flatMap {
+            val primitiveType = env.typeUtils.getPrimitiveType(it)
+            listOf(primitiveType, env.typeUtils.boxedClass(primitiveType).asType())
+        }
+    }
+
+    companion object {
+        // converts from ColumnInfo#SQLiteTypeAffinity
+        fun fromAnnotationValue(value : Int) : SQLTypeAffinity? {
+            return when(value) {
+                ColumnInfo.BLOB -> BLOB
+                ColumnInfo.INTEGER -> INTEGER
+                ColumnInfo.REAL -> REAL
+                ColumnInfo.TEXT -> TEXT
+                else -> null
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/preconditions/Checks.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/preconditions/Checks.kt
new file mode 100644
index 0000000..dad5c1c
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/preconditions/Checks.kt
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.preconditions
+
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.log.RLog
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeVariableName
+import javax.lang.model.element.Element
+import kotlin.reflect.KClass
+
+/**
+ * Similar to preconditions but element bound and just logs the error instead of throwing an
+ * exception.
+ * <p>
+ * It is important for processing to continue when some errors happen so that we can generate as
+ * much code as possible, leaving only the errors in javac output.
+ */
+class Checks(private val logger: RLog) {
+
+    fun check(predicate: Boolean, element: Element, errorMsg: String, vararg args: Any): Boolean {
+        if (!predicate) {
+            logger.e(element, errorMsg, args)
+        }
+        return predicate
+    }
+
+    fun hasAnnotation(element: Element, annotation: KClass<out Annotation>, errorMsg: String,
+                      vararg args: Any): Boolean {
+        return if (!element.hasAnnotation(annotation)) {
+            logger.e(element, errorMsg, args)
+            false
+        } else {
+            true
+        }
+    }
+
+    fun notUnbound(typeName: TypeName, element: Element, errorMsg: String,
+                   vararg args: Any): Boolean {
+        // TODO support bounds cases like <T extends Foo> T bar()
+        val failed = check(typeName !is TypeVariableName, element, errorMsg, args)
+        if (typeName is ParameterizedTypeName) {
+            val nestedFailure = typeName.typeArguments
+                    .map { notUnbound(it, element, errorMsg, args) }
+                    .any { it == true }
+            return !(failed || nestedFailure)
+        }
+        return !failed
+    }
+
+    fun notBlank(value: String?, element: Element, msg: String, vararg args: Any) : Boolean {
+        return check(value != null && value.isNotBlank(), element, msg, args)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/Context.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/Context.kt
new file mode 100644
index 0000000..4e84be3
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/Context.kt
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.log.RLog
+import android.arch.persistence.room.preconditions.Checks
+import android.arch.persistence.room.processor.cache.Cache
+import android.arch.persistence.room.solver.TypeAdapterStore
+import android.arch.persistence.room.verifier.DatabaseVerifier
+import java.io.File
+import java.util.LinkedHashSet
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.element.Element
+import javax.lang.model.type.TypeMirror
+
+class Context private constructor(val processingEnv: ProcessingEnvironment,
+                                  val logger: RLog,
+                                  private val typeConverters
+                                        : CustomConverterProcessor.ProcessResult,
+                                  private val inheritedAdapterStore: TypeAdapterStore?,
+                                  val cache: Cache) {
+    val checker: Checks = Checks(logger)
+    val COMMON_TYPES: Context.CommonTypes = Context.CommonTypes(processingEnv)
+
+    val typeAdapterStore by lazy {
+        if (inheritedAdapterStore != null) {
+            TypeAdapterStore.copy(this, inheritedAdapterStore)
+        } else {
+            TypeAdapterStore.create(this, typeConverters.converters)
+        }
+    }
+
+    // set when database and its entities are processed.
+    var databaseVerifier: DatabaseVerifier? = null
+
+    companion object {
+        val ARG_OPTIONS by lazy {
+            ProcessorOptions.values().map { it.argName }
+        }
+    }
+
+    constructor(processingEnv: ProcessingEnvironment) : this(
+            processingEnv = processingEnv,
+            logger = RLog(RLog.ProcessingEnvMessager(processingEnv), emptySet(), null),
+            typeConverters = CustomConverterProcessor.ProcessResult.EMPTY,
+            inheritedAdapterStore = null,
+            cache = Cache(null, LinkedHashSet(), emptySet())) {
+    }
+
+    class CommonTypes(val processingEnv: ProcessingEnvironment) {
+        val STRING: TypeMirror by lazy {
+            processingEnv.elementUtils.getTypeElement("java.lang.String").asType()
+        }
+    }
+
+    val schemaOutFolder by lazy {
+        val arg = processingEnv.options[ProcessorOptions.OPTION_SCHEMA_FOLDER.argName]
+        if (arg?.isNotEmpty() ?: false) {
+            File(arg)
+        } else {
+            null
+        }
+    }
+
+    fun <T> collectLogs(handler: (Context) -> T): Pair<T, RLog.CollectingMessager> {
+        val collector = RLog.CollectingMessager()
+        val subContext = Context(processingEnv = processingEnv,
+                logger = RLog(collector, logger.suppressedWarnings, logger.defaultElement),
+                typeConverters = this.typeConverters,
+                inheritedAdapterStore = typeAdapterStore,
+                cache = cache)
+        subContext.databaseVerifier = databaseVerifier
+        val result = handler(subContext)
+        return Pair(result, collector)
+    }
+
+    fun fork(element: Element): Context {
+        val suppressedWarnings = SuppressWarningProcessor.getSuppressedWarnings(element)
+        val processConvertersResult = CustomConverterProcessor.findConverters(this, element)
+        val canReUseAdapterStore = processConvertersResult.classes.isEmpty()
+        // order here is important since the sub context should give priority to new converters.
+        val subTypeConverters = if (canReUseAdapterStore) {
+            this.typeConverters
+        } else {
+            processConvertersResult + this.typeConverters
+        }
+        val subSuppressedWarnings = suppressedWarnings + logger.suppressedWarnings
+        val subCache = Cache(cache, subTypeConverters.classes, subSuppressedWarnings)
+        val subContext = Context(
+                processingEnv = processingEnv,
+                logger = RLog(logger.messager, subSuppressedWarnings, element),
+                typeConverters = subTypeConverters,
+                inheritedAdapterStore = if (canReUseAdapterStore) typeAdapterStore else null,
+                cache = subCache)
+        subContext.databaseVerifier = databaseVerifier
+        return subContext
+    }
+
+    enum class ProcessorOptions(val argName: String) {
+        OPTION_SCHEMA_FOLDER("room.schemaLocation")
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/CustomConverterProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/CustomConverterProcessor.kt
new file mode 100644
index 0000000..1ed245d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/CustomConverterProcessor.kt
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.TypeConverter
+import android.arch.persistence.room.TypeConverters
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.ext.hasAnyOf
+import android.arch.persistence.room.ext.toListOfClassTypes
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_BAD_RETURN_TYPE
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_EMPTY_CLASS
+import android.arch.persistence.room.processor.ProcessorErrors
+        .TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_MUST_BE_PUBLIC
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_MUST_RECEIVE_1_PARAM
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_UNBOUND_GENERIC
+import android.arch.persistence.room.solver.types.CustomTypeConverterWrapper
+import android.arch.persistence.room.vo.CustomTypeConverter
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import java.util.LinkedHashSet
+import javax.lang.model.element.Element
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+import javax.lang.model.util.ElementFilter
+
+/**
+ * Processes classes that are referenced in TypeConverters annotations.
+ */
+class CustomConverterProcessor(val context: Context, val element: TypeElement) {
+    companion object {
+        private val INVALID_RETURN_TYPES = setOf(TypeKind.ERROR, TypeKind.VOID, TypeKind.NONE)
+        fun findConverters(context: Context, element: Element): ProcessResult {
+            val annotation = MoreElements.getAnnotationMirror(element,
+                    TypeConverters::class.java).orNull()
+            return annotation?.let {
+                val classes = AnnotationMirrors.getAnnotationValue(annotation, "value")
+                        ?.toListOfClassTypes()
+                        ?.filter {
+                            MoreTypes.isType(it)
+                        }?.mapTo(LinkedHashSet(), {it}) ?: LinkedHashSet<TypeMirror>()
+                val converters = classes
+                        .flatMap {
+                            CustomConverterProcessor(context, MoreTypes.asTypeElement(it))
+                                    .process()
+                        }
+                converters.let {
+                    reportDuplicates(context, converters)
+                }
+                ProcessResult(classes, converters.map(::CustomTypeConverterWrapper))
+            } ?: ProcessResult.EMPTY
+        }
+
+        fun reportDuplicates(context: Context, converters : List<CustomTypeConverter>) {
+            val groupedByFrom = converters.groupBy { it.from.typeName() }
+            groupedByFrom.forEach {
+                it.value.groupBy { it.to.typeName() }.forEach {
+                    if (it.value.size > 1) {
+                        it.value.forEach { converter ->
+                            context.logger.e(converter.method, ProcessorErrors
+                                    .duplicateTypeConverters(it.value.minus(converter)))
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    fun process(): List<CustomTypeConverter> {
+        // using element utils instead of MoreElements to include statics.
+        val methods = ElementFilter
+                .methodsIn(context.processingEnv.elementUtils.getAllMembers(element))
+        val declaredType = MoreTypes.asDeclared(element.asType())
+        val converterMethods = methods.filter {
+            it.hasAnnotation(TypeConverter::class)
+        }
+        context.checker.check(converterMethods.isNotEmpty(), element, TYPE_CONVERTER_EMPTY_CLASS)
+        val allStatic = converterMethods.all { it.modifiers.contains(Modifier.STATIC) }
+        val constructors = ElementFilter.constructorsIn(
+                context.processingEnv.elementUtils.getAllMembers(element))
+        context.checker.check(allStatic || constructors.isEmpty() || constructors.any {
+            it.parameters.isEmpty()
+        }, element, TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR)
+        return converterMethods.map {
+            processMethod(declaredType, it)
+        }.filterNotNull()
+    }
+
+    private fun processMethod(container: DeclaredType, methodElement: ExecutableElement)
+            : CustomTypeConverter? {
+        val asMember = context.processingEnv.typeUtils.asMemberOf(container, methodElement)
+        val executableType = MoreTypes.asExecutable(asMember)
+        val returnType = executableType.returnType
+        val invalidReturnType = INVALID_RETURN_TYPES.contains(returnType.kind)
+        context.checker.check(methodElement.hasAnyOf(Modifier.PUBLIC), methodElement,
+                TYPE_CONVERTER_MUST_BE_PUBLIC)
+        if (invalidReturnType) {
+            context.logger.e(methodElement, TYPE_CONVERTER_BAD_RETURN_TYPE)
+            return null
+        }
+        val returnTypeName = returnType.typeName()
+        context.checker.notUnbound(returnTypeName, methodElement,
+                TYPE_CONVERTER_UNBOUND_GENERIC)
+        val params = methodElement.parameters
+        if (params.size != 1) {
+            context.logger.e(methodElement, TYPE_CONVERTER_MUST_RECEIVE_1_PARAM)
+            return null
+        }
+        val param = params.map {
+            MoreTypes.asMemberOf(context.processingEnv.typeUtils, container, it)
+        }.first()
+        context.checker.notUnbound(param.typeName(), params[0], TYPE_CONVERTER_UNBOUND_GENERIC)
+        return CustomTypeConverter(container, methodElement, param, returnType)
+    }
+
+    /**
+     * Order of classes is important hence they are a LinkedHashSet not a set.
+     */
+    open class ProcessResult(val classes: LinkedHashSet<TypeMirror>,
+                             val converters: List<CustomTypeConverterWrapper>) {
+        object EMPTY : ProcessResult(LinkedHashSet(), emptyList())
+        operator fun plus(other : ProcessResult) : ProcessResult {
+            val newClasses = LinkedHashSet<TypeMirror>()
+            newClasses.addAll(classes)
+            newClasses.addAll(other.classes)
+            return ProcessResult(newClasses, converters + other.converters)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DaoProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DaoProcessor.kt
new file mode 100644
index 0000000..0c0ff49
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DaoProcessor.kt
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Delete
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.SkipQueryVerification
+import android.arch.persistence.room.Update
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.ext.hasAnyOf
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.verifier.DatabaseVerifier
+import android.arch.persistence.room.vo.Dao
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier.ABSTRACT
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+
+class DaoProcessor(baseContext : Context, val element: TypeElement, val dbType: DeclaredType,
+                   val dbVerifier : DatabaseVerifier?) {
+    val context = baseContext.fork(element)
+
+    companion object {
+        val PROCESSED_ANNOTATIONS = listOf(Insert::class, Delete::class, Query::class,
+                Update::class)
+    }
+
+    fun process() : Dao {
+        context.checker.hasAnnotation(element, android.arch.persistence.room.Dao::class,
+                ProcessorErrors.DAO_MUST_BE_ANNOTATED_WITH_DAO)
+        context.checker.check(element.hasAnyOf(ABSTRACT) || element.kind == ElementKind.INTERFACE,
+                element, ProcessorErrors.DAO_MUST_BE_AN_ABSTRACT_CLASS_OR_AN_INTERFACE)
+
+        val declaredType = MoreTypes.asDeclared(element.asType())
+        val allMembers = context.processingEnv.elementUtils.getAllMembers(element)
+        val methods = allMembers
+            .filter {
+                it.hasAnyOf(ABSTRACT) && it.kind == ElementKind.METHOD
+            }.map {
+                MoreElements.asExecutable(it)
+            }.groupBy { method ->
+                context.checker.check(
+                        PROCESSED_ANNOTATIONS.count { method.hasAnnotation(it) } == 1, method,
+                        ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_DAO_METHOD_ANNOTATION
+                )
+                if (method.hasAnnotation(Query::class)) {
+                    Query::class
+                } else if (method.hasAnnotation(Insert::class)) {
+                    Insert::class
+                } else if (method.hasAnnotation(Delete::class)) {
+                    Delete::class
+                } else if (method.hasAnnotation(Update::class)) {
+                    Update::class
+                } else {
+                    Any::class
+                }
+            }
+        val processorVerifier = if (element.hasAnnotation(SkipQueryVerification::class)) {
+            null
+        } else {
+            dbVerifier
+        }
+
+        val queryMethods = methods[Query::class]?.map {
+            QueryMethodProcessor(
+                    baseContext = context,
+                    containing = declaredType,
+                    executableElement = it,
+                    dbVerifier = processorVerifier).process()
+        } ?: emptyList()
+
+        val insertionMethods = methods[Insert::class]?.map {
+            InsertionMethodProcessor(
+                    baseContext = context,
+                    containing = declaredType,
+                    executableElement = it).process()
+        } ?: emptyList()
+
+        val deletionMethods = methods[Delete::class]?.map {
+            DeletionMethodProcessor(
+                    baseContext = context,
+                    containing = declaredType,
+                    executableElement = it).process()
+        } ?: emptyList()
+
+        val updateMethods = methods[Update::class]?.map {
+            UpdateMethodProcessor(
+                    baseContext = context,
+                    containing = declaredType,
+                    executableElement = it).process()
+        } ?: emptyList()
+
+        val constructors = allMembers
+                .filter { it.kind == ElementKind.CONSTRUCTOR }
+                .map { MoreElements.asExecutable(it) }
+        val typeUtils = context.processingEnv.typeUtils
+        val goodConstructor = constructors
+                .filter {
+                    it.parameters.size == 1
+                            && typeUtils.isAssignable(dbType, it.parameters[0].asType())
+                }
+                .firstOrNull()
+        val constructorParamType = if (goodConstructor != null) {
+            goodConstructor.parameters[0].asType().typeName()
+        } else {
+            validateEmptyConstructor(constructors)
+            null
+        }
+
+        context.checker.check(methods[Any::class] == null, element,
+                ProcessorErrors.ABSTRACT_METHOD_IN_DAO_MISSING_ANY_ANNOTATION)
+
+        val type = TypeName.get(declaredType)
+        context.checker.notUnbound(type, element,
+                ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_DAO_CLASSES)
+
+        return Dao(element = element,
+                type = declaredType,
+                queryMethods = queryMethods,
+                insertionMethods = insertionMethods,
+                deletionMethods = deletionMethods,
+                updateMethods = updateMethods,
+                constructorParamType = constructorParamType)
+    }
+
+    private fun validateEmptyConstructor(constructors: List<ExecutableElement>) {
+        if (constructors.isNotEmpty() && constructors.all { it.parameters.isNotEmpty() }) {
+            context.logger.e(element, ProcessorErrors.daoMustHaveMatchingConstructor(
+                    element.toString(), dbType.toString()))
+        }
+    }
+
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DatabaseProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DatabaseProcessor.kt
new file mode 100644
index 0000000..9ebf6df
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DatabaseProcessor.kt
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.SkipQueryVerification
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.getAsBoolean
+import android.arch.persistence.room.ext.getAsInt
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.ext.hasAnyOf
+import android.arch.persistence.room.ext.toListOfClassTypes
+import android.arch.persistence.room.verifier.DatabaseVerifier
+import android.arch.persistence.room.vo.Dao
+import android.arch.persistence.room.vo.DaoMethod
+import android.arch.persistence.room.vo.Database
+import android.arch.persistence.room.vo.Entity
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.AnnotationMirror
+import javax.lang.model.element.Element
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.TypeMirror
+
+
+class DatabaseProcessor(baseContext: Context, val element: TypeElement) {
+    val context = baseContext.fork(element)
+
+    val baseClassElement: TypeMirror by lazy {
+        context.processingEnv.elementUtils.getTypeElement(
+                RoomTypeNames.ROOM_DB.packageName() + "." + RoomTypeNames.ROOM_DB.simpleName())
+                .asType()
+    }
+
+    fun process(): Database {
+        val dbAnnotation = MoreElements
+                .getAnnotationMirror(element, android.arch.persistence.room.Database::class.java)
+                .orNull()
+        val entities = processEntities(dbAnnotation, element)
+        validateUniqueTableNames(element, entities)
+        validateForeignKeys(element, entities)
+
+        val extendsRoomDb = context.processingEnv.typeUtils.isAssignable(
+                MoreElements.asType(element).asType(), baseClassElement)
+        context.checker.check(extendsRoomDb, element, ProcessorErrors.DB_MUST_EXTEND_ROOM_DB)
+
+        val allMembers = context.processingEnv.elementUtils.getAllMembers(element)
+
+        val dbVerifier = if (element.hasAnnotation(SkipQueryVerification::class)) {
+            null
+        } else {
+            DatabaseVerifier.create(context, element, entities)
+        }
+        context.databaseVerifier = dbVerifier
+
+        val declaredType = MoreTypes.asDeclared(element.asType())
+        val daoMethods = allMembers.filter {
+            it.hasAnyOf(Modifier.ABSTRACT) && it.kind == ElementKind.METHOD
+        }.filterNot {
+            // remove methods that belong to room
+            val containing = it.enclosingElement
+            MoreElements.isType(containing) &&
+                    TypeName.get(containing.asType()) == RoomTypeNames.ROOM_DB
+        }.map {
+            val executable = MoreElements.asExecutable(it)
+            // TODO when we add support for non Dao return types (e.g. database), this code needs
+            // to change
+            val daoType = MoreTypes.asTypeElement(executable.returnType)
+            val dao = DaoProcessor(context, daoType, declaredType, dbVerifier).process()
+            DaoMethod(executable, executable.simpleName.toString(), dao)
+        }
+        validateUniqueDaoClasses(element, daoMethods, entities)
+        validateUniqueIndices(element, entities)
+        val version = AnnotationMirrors.getAnnotationValue(dbAnnotation, "version")
+                .getAsInt(1)!!.toInt()
+        val exportSchema = AnnotationMirrors.getAnnotationValue(dbAnnotation, "exportSchema")
+                .getAsBoolean(true)
+
+        val hasForeignKeys = entities.any { it.foreignKeys.isNotEmpty() }
+
+        val database = Database(
+                version = version,
+                element = element,
+                type = MoreElements.asType(element).asType(),
+                entities = entities,
+                daoMethods = daoMethods,
+                exportSchema = exportSchema,
+                enableForeignKeys = hasForeignKeys)
+        return database
+    }
+
+    private fun validateForeignKeys(element: TypeElement, entities: List<Entity>) {
+        val byTableName = entities.associateBy { it.tableName }
+        entities.forEach { entity ->
+            entity.foreignKeys.forEach foreignKeyLoop@ { foreignKey ->
+                val parent = byTableName[foreignKey.parentTable]
+                if (parent == null) {
+                    context.logger.e(element, ProcessorErrors
+                            .foreignKeyMissingParentEntityInDatabase(foreignKey.parentTable,
+                                    entity.element.qualifiedName.toString()))
+                    return@foreignKeyLoop
+                }
+                val parentFields = foreignKey.parentColumns.map { columnName ->
+                    val parentField = parent.fields.find {
+                        it.columnName == columnName
+                    }
+                    if (parentField == null) {
+                        context.logger.e(entity.element,
+                                ProcessorErrors.foreignKeyParentColumnDoesNotExist(
+                                        parentEntity = parent.element.qualifiedName.toString(),
+                                        missingColumn = columnName,
+                                        allColumns = parent.fields.map { it.columnName }))
+                    }
+                    parentField
+                }.filterNotNull()
+                if (parentFields.size != foreignKey.parentColumns.size) {
+                    return@foreignKeyLoop
+                }
+                // ensure that it is indexed in the parent
+                if (!parent.isUnique(foreignKey.parentColumns)) {
+                    context.logger.e(parent.element, ProcessorErrors
+                            .foreignKeyMissingIndexInParent(
+                                    parentEntity = parent.element.qualifiedName.toString(),
+                                    childEntity = entity.element.qualifiedName.toString(),
+                                    parentColumns = foreignKey.parentColumns,
+                                    childColumns = foreignKey.childFields
+                                            .map { it.columnName }))
+                    return@foreignKeyLoop
+                }
+            }
+        }
+    }
+
+    private fun validateUniqueIndices(element: TypeElement, entities: List<Entity>) {
+        entities
+                .flatMap { entity ->
+                    // associate each index with its entity
+                    entity.indices.map { Pair(it.name, entity) }
+                }
+                .groupBy { it.first } // group by index name
+                .filter { it.value.size > 1 } // get the ones with duplicate names
+                .forEach {
+                    // do not report duplicates from the same entity
+                    if (it.value.distinctBy { it.second.typeName }.size > 1) {
+                        context.logger.e(element,
+                                ProcessorErrors.duplicateIndexInDatabase(it.key,
+                                        it.value.map { "${it.second.typeName} > ${it.first}" }))
+                    }
+                }
+    }
+
+    private fun validateUniqueDaoClasses(dbElement: TypeElement, daoMethods: List<DaoMethod>,
+                                         entities : List<Entity>) {
+        val entityTypeNames = entities.map { it.typeName }.toSet()
+        daoMethods.groupBy { it.dao.typeName }
+                .forEach {
+                    if (it.value.size > 1) {
+                        val error = ProcessorErrors.duplicateDao(it.key, it.value.map { it.name })
+                        it.value.forEach { daoMethod ->
+                            context.logger.e(daoMethod.element,
+                                    ProcessorErrors.DAO_METHOD_CONFLICTS_WITH_OTHERS)
+                        }
+                        // also report the full error for the database
+                        context.logger.e(dbElement, error)
+                    }
+                }
+        val check = fun(element : Element, dao : Dao,
+                        typeName : TypeName?) {
+            typeName?.let {
+                if (!entityTypeNames.contains(typeName)) {
+                    context.logger.e(element,
+                            ProcessorErrors.shortcutEntityIsNotInDatabase(
+                                    database = dbElement.qualifiedName.toString(),
+                                    dao = dao.typeName.toString(),
+                                    entity = typeName.toString()
+                            ))
+                }
+            }
+        }
+        daoMethods.forEach { daoMethod ->
+            daoMethod.dao.shortcutMethods.forEach { method ->
+                method.entities.forEach {
+                    check(method.element, daoMethod.dao, it.value.typeName)
+                }
+            }
+            daoMethod.dao.insertionMethods.forEach { method ->
+                method.entities.forEach {
+                    check(method.element, daoMethod.dao, it.value.typeName)
+                }
+            }
+        }
+    }
+
+    private fun validateUniqueTableNames(dbElement: TypeElement, entities: List<Entity>) {
+        entities
+                .groupBy {
+                    it.tableName.toLowerCase()
+                }.filter {
+            it.value.size > 1
+        }.forEach { byTableName ->
+            val error = ProcessorErrors.duplicateTableNames(byTableName.key,
+                    byTableName.value.map { it.typeName.toString() })
+            // report it for each of them and the database to make it easier
+            // for the developer
+            byTableName.value.forEach { entity ->
+                context.logger.e(entity.element, error)
+            }
+            context.logger.e(dbElement, error)
+        }
+    }
+
+    private fun processEntities(dbAnnotation: AnnotationMirror?, element: TypeElement):
+            List<Entity> {
+        if (!context.checker.check(dbAnnotation != null, element,
+                ProcessorErrors.DATABASE_MUST_BE_ANNOTATED_WITH_DATABASE)) {
+            return listOf()
+        }
+
+        val entityList = AnnotationMirrors.getAnnotationValue(dbAnnotation, "entities")
+        val listOfTypes = entityList.toListOfClassTypes()
+        context.checker.check(listOfTypes.isNotEmpty(), element,
+                ProcessorErrors.DATABASE_ANNOTATION_MUST_HAVE_LIST_OF_ENTITIES)
+        return listOfTypes.map {
+            EntityProcessor(context, MoreTypes.asTypeElement(it)).process()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessor.kt
new file mode 100644
index 0000000..4812306
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessor.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Delete
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.vo.DeletionMethod
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+
+class DeletionMethodProcessor(baseContext: Context,
+                              val containing: DeclaredType,
+                              val executableElement: ExecutableElement) {
+    val context = baseContext.fork(executableElement)
+
+    fun process(): DeletionMethod {
+        val delegate = ShortcutMethodProcessor(context, containing, executableElement)
+        delegate.extractAnnotation(Delete::class, ProcessorErrors.MISSING_DELETE_ANNOTATION)
+
+        val returnTypeName = delegate.extractReturnType().typeName()
+        context.checker.check(
+                returnTypeName == TypeName.VOID || returnTypeName == TypeName.INT,
+                executableElement,
+                ProcessorErrors.DELETION_METHODS_MUST_RETURN_VOID_OR_INT
+        )
+
+        val (entities, params) = delegate.extractParams(
+                missingParamError = ProcessorErrors
+                        .DELETION_MISSING_PARAMS
+        )
+
+        return DeletionMethod(
+                element = delegate.executableElement,
+                name = delegate.executableElement.simpleName.toString(),
+                entities = entities,
+                returnCount = returnTypeName == TypeName.INT,
+                parameters = params
+        )
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/EntityProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/EntityProcessor.kt
new file mode 100644
index 0000000..4f4a7f4
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/EntityProcessor.kt
@@ -0,0 +1,543 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.ext.getAsBoolean
+import android.arch.persistence.room.ext.getAsInt
+import android.arch.persistence.room.ext.getAsString
+import android.arch.persistence.room.ext.getAsStringList
+import android.arch.persistence.room.ext.toType
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.ProcessorErrors.INDEX_COLUMNS_CANNOT_BE_EMPTY
+import android.arch.persistence.room.processor.ProcessorErrors.RELATION_IN_ENTITY
+import android.arch.persistence.room.processor.cache.Cache
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.ForeignKey
+import android.arch.persistence.room.vo.ForeignKeyAction
+import android.arch.persistence.room.vo.Index
+import android.arch.persistence.room.vo.Pojo
+import android.arch.persistence.room.vo.PrimaryKey
+import android.arch.persistence.room.vo.Warning
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.AnnotationMirrors.getAnnotationValue
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import javax.lang.model.element.AnnotationMirror
+import javax.lang.model.element.AnnotationValue
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+import javax.lang.model.util.SimpleAnnotationValueVisitor6
+
+class EntityProcessor(baseContext: Context, val element: TypeElement) {
+    val context = baseContext.fork(element)
+
+    fun process(): Entity {
+        return context.cache.entities.get(Cache.EntityKey(element), {
+            doProcess()
+        })
+    }
+    private fun doProcess() : Entity {
+        context.checker.hasAnnotation(element, android.arch.persistence.room.Entity::class,
+                ProcessorErrors.ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY)
+        val pojo = PojoProcessor(
+                baseContext = context,
+                element = element,
+                bindingScope = FieldProcessor.BindingScope.TWO_WAY,
+                parent = null).process()
+        context.checker.check(pojo.relations.isEmpty(), element, RELATION_IN_ENTITY)
+        val annotation = MoreElements.getAnnotationMirror(element,
+                android.arch.persistence.room.Entity::class.java).orNull()
+        val tableName: String
+        val entityIndices: List<IndexInput>
+        val foreignKeyInputs: List<ForeignKeyInput>
+        val inheritSuperIndices: Boolean
+        if (annotation != null) {
+            tableName = extractTableName(element, annotation)
+            entityIndices = extractIndices(annotation, tableName)
+            inheritSuperIndices = AnnotationMirrors
+                    .getAnnotationValue(annotation, "inheritSuperIndices").getAsBoolean(false)
+            foreignKeyInputs = extractForeignKeys(annotation)
+        } else {
+            tableName = element.simpleName.toString()
+            foreignKeyInputs = emptyList()
+            entityIndices = emptyList()
+            inheritSuperIndices = false
+        }
+        context.checker.notBlank(tableName, element,
+                ProcessorErrors.ENTITY_TABLE_NAME_CANNOT_BE_EMPTY)
+
+        val fieldIndices = pojo.fields
+                .filter { it.indexed }
+                .map {
+                    if (it.parent != null) {
+                        it.indexed = false
+                        context.logger.w(Warning.INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED, it.element,
+                                ProcessorErrors.droppedEmbeddedFieldIndex(
+                                        it.getPath(), element.qualifiedName.toString()))
+                        null
+                    } else if (it.element.enclosingElement != element && !inheritSuperIndices) {
+                        it.indexed = false
+                        context.logger.w(Warning.INDEX_FROM_PARENT_FIELD_IS_DROPPED,
+                                ProcessorErrors.droppedSuperClassFieldIndex(
+                                        it.columnName, element.toString(),
+                                        it.element.enclosingElement.toString()
+                                ))
+                        null
+                    } else {
+                        IndexInput(
+                                name = createIndexName(listOf(it.columnName), tableName),
+                                unique = false,
+                                columnNames = listOf(it.columnName)
+                        )
+                    }
+                }.filterNotNull()
+        val superIndices = loadSuperIndices(element.superclass, tableName, inheritSuperIndices)
+        val indexInputs = entityIndices + fieldIndices + superIndices
+        val indices = validateAndCreateIndices(indexInputs, pojo)
+
+        val primaryKey = findPrimaryKey(pojo.fields, pojo.embeddedFields)
+        val affinity = primaryKey.fields.firstOrNull()?.affinity ?: SQLTypeAffinity.TEXT
+        context.checker.check(
+                !primaryKey.autoGenerateId || affinity == SQLTypeAffinity.INTEGER,
+                primaryKey.fields.firstOrNull()?.element ?: element,
+                ProcessorErrors.AUTO_INCREMENTED_PRIMARY_KEY_IS_NOT_INT
+        )
+
+        val entityForeignKeys = validateAndCreateForeignKeyReferences(foreignKeyInputs, pojo)
+        checkIndicesForForeignKeys(entityForeignKeys, primaryKey, indices)
+
+        val entity = Entity(element = element,
+                tableName = tableName,
+                type = pojo.type,
+                fields = pojo.fields,
+                embeddedFields = pojo.embeddedFields,
+                indices = indices,
+                primaryKey = primaryKey,
+                foreignKeys = entityForeignKeys,
+                constructor = pojo.constructor)
+
+        return entity
+    }
+
+    private fun checkIndicesForForeignKeys(entityForeignKeys: List<ForeignKey>,
+                                           primaryKey: PrimaryKey,
+                                           indices: List<Index>) {
+        fun covers(columnNames: List<String>, fields : List<Field>) : Boolean =
+            fields.size >= columnNames.size && columnNames.withIndex().all {
+                fields[it.index].columnName == it.value
+            }
+
+        entityForeignKeys.forEach { fKey ->
+            val columnNames = fKey.childFields.map { it.columnName }
+            val exists = covers(columnNames, primaryKey.fields) || indices.any { index ->
+                covers(columnNames, index.fields)
+            }
+            if (!exists) {
+                if (columnNames.size == 1) {
+                    context.logger.w(Warning.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, element,
+                            ProcessorErrors.foreignKeyMissingIndexInChildColumn(columnNames[0]))
+                } else {
+                    context.logger.w(Warning.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, element,
+                            ProcessorErrors.foreignKeyMissingIndexInChildColumns(columnNames))
+                }
+            }
+        }
+    }
+
+    /**
+     * Does a validation on foreign keys except the parent table's columns.
+     */
+    private fun validateAndCreateForeignKeyReferences(foreignKeyInputs: List<ForeignKeyInput>,
+                                                      pojo: Pojo): List<ForeignKey> {
+        return foreignKeyInputs.map {
+            if (it.onUpdate == null) {
+                context.logger.e(element, ProcessorErrors.INVALID_FOREIGN_KEY_ACTION)
+                return@map null
+            }
+            if (it.onDelete == null) {
+                context.logger.e(element, ProcessorErrors.INVALID_FOREIGN_KEY_ACTION)
+                return@map null
+            }
+            if (it.childColumns.isEmpty()) {
+                context.logger.e(element, ProcessorErrors.FOREIGN_KEY_EMPTY_CHILD_COLUMN_LIST)
+                return@map null
+            }
+            if (it.parentColumns.isEmpty()) {
+                context.logger.e(element, ProcessorErrors.FOREIGN_KEY_EMPTY_PARENT_COLUMN_LIST)
+                return@map null
+            }
+            if (it.childColumns.size != it.parentColumns.size) {
+                context.logger.e(element, ProcessorErrors.foreignKeyColumnNumberMismatch(
+                        it.childColumns, it.parentColumns
+                ))
+                return@map null
+            }
+            val parentElement = try {
+                MoreTypes.asElement(it.parent) as TypeElement
+            } catch (noClass: IllegalArgumentException) {
+                context.logger.e(element, ProcessorErrors.FOREIGN_KEY_CANNOT_FIND_PARENT)
+                return@map null
+            }
+            val parentAnnotation = MoreElements.getAnnotationMirror(parentElement,
+                    android.arch.persistence.room.Entity::class.java).orNull()
+            if (parentAnnotation == null) {
+                context.logger.e(element,
+                        ProcessorErrors.foreignKeyNotAnEntity(parentElement.toString()))
+                return@map null
+            }
+            val tableName = extractTableName(parentElement, parentAnnotation)
+            val fields = it.childColumns.map { columnName ->
+                val field = pojo.fields.find { it.columnName == columnName }
+                if (field == null) {
+                    context.logger.e(pojo.element,
+                            ProcessorErrors.foreignKeyChildColumnDoesNotExist(columnName,
+                                    pojo.fields.map { it.columnName }))
+                }
+                field
+            }.filterNotNull()
+            if (fields.size != it.childColumns.size) {
+                return@map null
+            }
+            ForeignKey(
+                    parentTable = tableName,
+                    childFields = fields,
+                    parentColumns = it.parentColumns,
+                    onDelete = it.onDelete,
+                    onUpdate = it.onUpdate,
+                    deferred = it.deferred
+            )
+        }.filterNotNull()
+    }
+
+    private fun findPrimaryKey(fields: List<Field>, embeddedFields: List<EmbeddedField>)
+            : PrimaryKey {
+        val candidates = collectPrimaryKeysFromEntityAnnotations(element, fields) +
+                collectPrimaryKeysFromPrimaryKeyAnnotations(fields) +
+                collectPrimaryKeysFromEmbeddedFields(embeddedFields)
+
+        context.checker.check(candidates.isNotEmpty(), element, ProcessorErrors.MISSING_PRIMARY_KEY)
+        if (candidates.size == 1) {
+            // easy :)
+            return candidates.first()
+        }
+
+        return choosePrimaryKey(candidates, element)
+    }
+
+    /**
+     * Check fields for @PrimaryKey.
+     */
+    private fun collectPrimaryKeysFromPrimaryKeyAnnotations(fields: List<Field>): List<PrimaryKey> {
+        return fields.map { field ->
+            MoreElements.getAnnotationMirror(field.element,
+                    android.arch.persistence.room.PrimaryKey::class.java).orNull()?.let {
+                if (field.parent != null) {
+                    // the field in the entity that contains this error.
+                    val grandParentField = field.parent.mRootParent.field.element
+                    // bound for entity.
+                    context.fork(grandParentField).logger.w(
+                            Warning.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,
+                            grandParentField,
+                            ProcessorErrors.embeddedPrimaryKeyIsDropped(
+                                    element.qualifiedName.toString(), field.name))
+                    null
+                } else {
+                    PrimaryKey(declaredIn = field.element.enclosingElement,
+                            fields = listOf(field),
+                            autoGenerateId = AnnotationMirrors
+                                    .getAnnotationValue(it, "autoGenerate")
+                                    .getAsBoolean(false))
+                }
+            }
+        }.filterNotNull()
+    }
+
+    /**
+     * Check classes for @Entity(primaryKeys = ?).
+     */
+    private fun collectPrimaryKeysFromEntityAnnotations(typeElement: TypeElement,
+                                                        availableFields: List<Field>)
+            : List<PrimaryKey> {
+        val myPkeys = MoreElements.getAnnotationMirror(typeElement,
+                android.arch.persistence.room.Entity::class.java).orNull()?.let {
+            val primaryKeyColumns = AnnotationMirrors.getAnnotationValue(it, "primaryKeys")
+                    .getAsStringList()
+            if (primaryKeyColumns.isEmpty()) {
+                emptyList<PrimaryKey>()
+            } else {
+                val fields = primaryKeyColumns.map { pKeyColumnName ->
+                    val field = availableFields.firstOrNull { it.columnName == pKeyColumnName }
+                    context.checker.check(field != null, typeElement,
+                            ProcessorErrors.primaryKeyColumnDoesNotExist(pKeyColumnName,
+                                    availableFields.map { it.columnName }))
+                    field
+                }.filterNotNull()
+                listOf(PrimaryKey(declaredIn = typeElement,
+                        fields = fields,
+                        autoGenerateId = false))
+            }
+        } ?: emptyList<PrimaryKey>()
+        // checks supers.
+        val mySuper = typeElement.superclass
+        val superPKeys = if (mySuper != null && mySuper.kind != TypeKind.NONE) {
+            // my super cannot see my fields so remove them.
+            val remainingFields = availableFields.filterNot {
+                it.element.enclosingElement == typeElement
+            }
+            collectPrimaryKeysFromEntityAnnotations(
+                    MoreTypes.asTypeElement(mySuper), remainingFields)
+        } else {
+            emptyList()
+        }
+        return superPKeys + myPkeys
+    }
+
+    private fun collectPrimaryKeysFromEmbeddedFields(embeddedFields: List<EmbeddedField>)
+            : List<PrimaryKey> {
+        return embeddedFields.map { embeddedField ->
+            MoreElements.getAnnotationMirror(embeddedField.field.element,
+                    android.arch.persistence.room.PrimaryKey::class.java).orNull()?.let {
+                val autoGenerate = AnnotationMirrors
+                        .getAnnotationValue(it, "autoGenerate").getAsBoolean(false)
+                context.checker.check(!autoGenerate || embeddedField.pojo.fields.size == 1,
+                        embeddedField.field.element,
+                        ProcessorErrors.AUTO_INCREMENT_EMBEDDED_HAS_MULTIPLE_FIELDS)
+                PrimaryKey(declaredIn = embeddedField.field.element.enclosingElement,
+                        fields = embeddedField.pojo.fields,
+                        autoGenerateId = autoGenerate)
+            }
+        }.filterNotNull()
+    }
+
+    // start from my element and check if anywhere in the list we can find the only well defined
+    // pkey, if so, use it.
+    private fun choosePrimaryKey(candidates: List<PrimaryKey>, typeElement: TypeElement)
+            : PrimaryKey {
+        // If 1 of these primary keys is declared in this class, then it is the winner. Just print
+        //    a note for the others.
+        // If 0 is declared, check the parent.
+        // If more than 1 primary key is declared in this class, it is an error.
+        val myPKeys = candidates.filter { candidate ->
+            candidate.declaredIn == typeElement
+        }
+        return if (myPKeys.size == 1) {
+            // just note, this is not worth an error or warning
+            (candidates - myPKeys).forEach {
+                context.logger.d(element,
+                        "${it.toHumanReadableString()} is" +
+                                " overridden by ${myPKeys.first().toHumanReadableString()}")
+            }
+            myPKeys.first()
+        } else if (myPKeys.isEmpty()) {
+            // i have not declared anything, delegate to super
+            val mySuper = typeElement.superclass
+            if (mySuper != null && mySuper.kind != TypeKind.NONE) {
+                return choosePrimaryKey(candidates, MoreTypes.asTypeElement(mySuper))
+            }
+            PrimaryKey.MISSING
+        } else {
+            context.logger.e(element, ProcessorErrors.multiplePrimaryKeyAnnotations(
+                    myPKeys.map(PrimaryKey::toHumanReadableString)))
+            PrimaryKey.MISSING
+        }
+    }
+
+    private fun validateAndCreateIndices(inputs: List<IndexInput>, pojo: Pojo): List<Index> {
+        // check for columns
+        val indices = inputs.map { input ->
+            context.checker.check(input.columnNames.isNotEmpty(), element,
+                    INDEX_COLUMNS_CANNOT_BE_EMPTY)
+            val fields = input.columnNames.map { columnName ->
+                val field = pojo.fields.firstOrNull {
+                    it.columnName == columnName
+                }
+                context.checker.check(field != null, element,
+                        ProcessorErrors.indexColumnDoesNotExist(
+                                columnName, pojo.fields.map { it.columnName }
+                        ))
+                field
+            }.filterNotNull()
+            if (fields.isEmpty()) {
+                null
+            } else {
+                Index(name = input.name, unique = input.unique, fields = fields)
+            }
+        }.filterNotNull()
+
+        // check for duplicate indices
+        indices
+                .groupBy { it.name }
+                .filter { it.value.size > 1 }
+                .forEach {
+                    context.logger.e(element, ProcessorErrors.duplicateIndexInEntity(it.key))
+                }
+
+        // see if any embedded field is an entity with indices, if so, report a warning
+        pojo.embeddedFields.forEach { embedded ->
+            val embeddedElement = embedded.pojo.element
+            val subEntityAnnotation = MoreElements.getAnnotationMirror(embeddedElement,
+                    android.arch.persistence.room.Entity::class.java).orNull()
+            subEntityAnnotation?.let {
+                val subIndices = extractIndices(subEntityAnnotation, "")
+                if (subIndices.isNotEmpty()) {
+                    context.logger.w(Warning.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED,
+                            embedded.field.element, ProcessorErrors.droppedEmbeddedIndex(
+                            entityName = embedded.pojo.typeName.toString(),
+                            fieldPath = embedded.field.getPath(),
+                            grandParent = element.qualifiedName.toString()))
+                }
+            }
+        }
+        return indices
+    }
+
+    // check if parent is an Entity, if so, report its annotation indices
+    private fun loadSuperIndices(typeMirror: TypeMirror?, tableName: String, inherit: Boolean)
+            : List<IndexInput> {
+        if (typeMirror == null || typeMirror.kind == TypeKind.NONE) {
+            return emptyList()
+        }
+        val parentElement = MoreTypes.asTypeElement(typeMirror)
+        val myIndices = MoreElements.getAnnotationMirror(parentElement,
+                android.arch.persistence.room.Entity::class.java).orNull()?.let { annotation ->
+            val indices = extractIndices(annotation, tableName = "super")
+            if (indices.isEmpty()) {
+                emptyList()
+            } else if (inherit) {
+                // rename them
+                indices.map {
+                    IndexInput(
+                            name = createIndexName(it.columnNames, tableName),
+                            unique = it.unique,
+                            columnNames = it.columnNames)
+                }
+            } else {
+                context.logger.w(Warning.INDEX_FROM_PARENT_IS_DROPPED,
+                        parentElement,
+                        ProcessorErrors.droppedSuperClassIndex(
+                                childEntity = element.qualifiedName.toString(),
+                                superEntity = parentElement.qualifiedName.toString()))
+                emptyList()
+            }
+        } ?: emptyList()
+        return myIndices + loadSuperIndices(parentElement.superclass, tableName, inherit)
+    }
+
+    companion object {
+        private fun extractTableName(element: TypeElement, annotation: AnnotationMirror)
+                : String {
+            val annotationValue = AnnotationMirrors
+                    .getAnnotationValue(annotation, "tableName").value.toString()
+            return if (annotationValue == "") {
+                element.simpleName.toString()
+            } else {
+                annotationValue
+            }
+        }
+
+        private fun extractIndices(annotation: AnnotationMirror, tableName: String)
+                : List<IndexInput> {
+            val arrayOfIndexAnnotations = AnnotationMirrors.getAnnotationValue(annotation,
+                    "indices")
+            return INDEX_LIST_VISITOR.visit(arrayOfIndexAnnotations, tableName)
+        }
+
+        private val INDEX_LIST_VISITOR = object
+            : SimpleAnnotationValueVisitor6<List<IndexInput>, String>() {
+            override fun visitArray(values: MutableList<out AnnotationValue>?, tableName: String)
+                    : List<IndexInput> {
+                return values?.map {
+                    INDEX_VISITOR.visit(it, tableName)
+                }?.filterNotNull() ?: emptyList<IndexInput>()
+            }
+        }
+
+        private val INDEX_VISITOR = object : SimpleAnnotationValueVisitor6<IndexInput?, String>() {
+            override fun visitAnnotation(a: AnnotationMirror?, tableName: String): IndexInput? {
+                val fieldInput = getAnnotationValue(a, "value").getAsStringList()
+                val unique = getAnnotationValue(a, "unique").getAsBoolean(false)
+                val nameValue = getAnnotationValue(a, "name")
+                        .getAsString("")
+                val name = if (nameValue == null || nameValue == "") {
+                    createIndexName(fieldInput, tableName)
+                } else {
+                    nameValue
+                }
+                return IndexInput(name, unique, fieldInput)
+            }
+        }
+
+        private fun createIndexName(columnNames: List<String>, tableName: String): String {
+            return "index_" + tableName + "_" + columnNames.joinToString("_")
+        }
+
+        private fun extractForeignKeys(annotation: AnnotationMirror): List<ForeignKeyInput> {
+            val arrayOfForeignKeyAnnotations = getAnnotationValue(annotation, "foreignKeys")
+            return FOREIGN_KEY_LIST_VISITOR.visit(arrayOfForeignKeyAnnotations)
+        }
+
+        private val FOREIGN_KEY_LIST_VISITOR = object
+            : SimpleAnnotationValueVisitor6<List<ForeignKeyInput>, Void?>() {
+            override fun visitArray(values: MutableList<out AnnotationValue>?, void: Void?)
+                    : List<ForeignKeyInput> {
+                return values?.map {
+                    FOREIGN_KEY_VISITOR.visit(it)
+                }?.filterNotNull() ?: emptyList<ForeignKeyInput>()
+            }
+        }
+
+        private val FOREIGN_KEY_VISITOR = object : SimpleAnnotationValueVisitor6<ForeignKeyInput?,
+                Void?>() {
+            override fun visitAnnotation(a: AnnotationMirror?, void: Void?): ForeignKeyInput? {
+                val entityClass = try {
+                    getAnnotationValue(a, "entity").toType()
+                } catch (notPresent: TypeNotPresentException) {
+                    return null
+                }
+                val parentColumns = getAnnotationValue(a, "parentColumns").getAsStringList()
+                val childColumns = getAnnotationValue(a, "childColumns").getAsStringList()
+                val onDeleteInput = getAnnotationValue(a, "onDelete").getAsInt()
+                val onUpdateInput = getAnnotationValue(a, "onUpdate").getAsInt()
+                val deferred = getAnnotationValue(a, "deferred").getAsBoolean(true)
+                val onDelete = ForeignKeyAction.fromAnnotationValue(onDeleteInput)
+                val onUpdate = ForeignKeyAction.fromAnnotationValue(onUpdateInput)
+                return ForeignKeyInput(
+                        parent = entityClass,
+                        parentColumns = parentColumns,
+                        childColumns = childColumns,
+                        onDelete = onDelete,
+                        onUpdate = onUpdate,
+                        deferred = deferred)
+            }
+        }
+    }
+
+    /**
+     * processed Index annotation output
+     */
+    data class IndexInput(val name: String, val unique: Boolean, val columnNames: List<String>)
+
+    /**
+     * ForeignKey, before it is processed in the context of a database.
+     */
+    data class ForeignKeyInput(val parent : TypeMirror, val parentColumns : List<String>,
+                     val childColumns : List<String>, val onDelete : ForeignKeyAction?,
+                     val onUpdate : ForeignKeyAction?, val deferred : Boolean)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/FieldProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/FieldProcessor.kt
new file mode 100644
index 0000000..2d11588
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/FieldProcessor.kt
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.ColumnInfo
+import android.arch.persistence.room.ext.getAsBoolean
+import android.arch.persistence.room.ext.getAsInt
+import android.arch.persistence.room.ext.getAsString
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.Field
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.Element
+import javax.lang.model.type.DeclaredType
+
+class FieldProcessor(baseContext: Context, val containing: DeclaredType, val element: Element,
+                     val bindingScope: BindingScope,
+                     // pass only if this is processed as a child of Embedded field
+                     val fieldParent: EmbeddedField?) {
+    val context = baseContext.fork(element)
+    fun process(): Field {
+        val member = context.processingEnv.typeUtils.asMemberOf(containing, element)
+        val type = TypeName.get(member)
+        val columnInfoAnnotation = MoreElements.getAnnotationMirror(element,
+                ColumnInfo::class.java)
+        val name = element.simpleName.toString()
+        val columnName: String
+        val affinity : SQLTypeAffinity?
+        val fieldPrefix = fieldParent?.prefix ?: ""
+        val indexed : Boolean
+        if (columnInfoAnnotation.isPresent) {
+            val nameInAnnotation = AnnotationMirrors
+                    .getAnnotationValue(columnInfoAnnotation.get(), "name")
+                    .getAsString(ColumnInfo.INHERIT_FIELD_NAME)
+            columnName = fieldPrefix + if (nameInAnnotation == ColumnInfo.INHERIT_FIELD_NAME) {
+                name
+            } else {
+                nameInAnnotation
+            }
+
+            affinity = try {
+                val userDefinedAffinity = AnnotationMirrors
+                        .getAnnotationValue(columnInfoAnnotation.get(), "typeAffinity")
+                        .getAsInt(ColumnInfo.UNDEFINED)!!
+                SQLTypeAffinity.fromAnnotationValue(userDefinedAffinity)
+            } catch (ex : NumberFormatException) {
+                null
+            }
+
+            indexed = AnnotationMirrors
+                    .getAnnotationValue(columnInfoAnnotation.get(), "index")
+                    .getAsBoolean(false)
+
+        } else {
+            columnName = fieldPrefix + name
+            affinity = null
+            indexed = false
+        }
+        context.checker.notBlank(columnName, element,
+                ProcessorErrors.COLUMN_NAME_CANNOT_BE_EMPTY)
+        context.checker.notUnbound(type, element,
+                ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS)
+
+        val field = Field(name = name,
+                type = member,
+                element = element,
+                columnName = columnName,
+                affinity = affinity,
+                parent = fieldParent,
+                indexed = indexed)
+
+        when (bindingScope) {
+            BindingScope.TWO_WAY -> {
+                val adapter = context.typeAdapterStore.findColumnTypeAdapter(field.type,
+                        field.affinity)
+                field.statementBinder = adapter
+                field.cursorValueReader = adapter
+                field.affinity = adapter?.typeAffinity ?: field.affinity
+                context.checker.check(adapter != null, field.element,
+                        ProcessorErrors.CANNOT_FIND_COLUMN_TYPE_ADAPTER)
+            }
+            BindingScope.BIND_TO_STMT -> {
+                field.statementBinder = context.typeAdapterStore
+                        .findStatementValueBinder(field.type, field.affinity)
+                context.checker.check(field.statementBinder != null, field.element,
+                        ProcessorErrors.CANNOT_FIND_STMT_BINDER)
+            }
+            BindingScope.READ_FROM_CURSOR -> {
+                field.cursorValueReader = context.typeAdapterStore
+                        .findCursorValueReader(field.type, field.affinity)
+                context.checker.check(field.cursorValueReader != null, field.element,
+                        ProcessorErrors.CANNOT_FIND_CURSOR_READER)
+            }
+        }
+        return field
+    }
+
+    /**
+     * Defines what we need to assign
+     */
+    enum class BindingScope {
+        TWO_WAY, // both bind and read.
+        BIND_TO_STMT, // just value to statement
+        READ_FROM_CURSOR // just cursor to value
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessor.kt
new file mode 100644
index 0000000..dba4a87
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessor.kt
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+
+package android.arch.persistence.room.processor
+
+import android.support.annotation.VisibleForTesting
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.OnConflictStrategy.IGNORE
+import android.arch.persistence.room.OnConflictStrategy.REPLACE
+import android.arch.persistence.room.vo.InsertionMethod
+import android.arch.persistence.room.vo.InsertionMethod.Type
+import android.arch.persistence.room.vo.ShortcutQueryParameter
+import com.google.auto.common.MoreTypes
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeKind.LONG
+import javax.lang.model.type.TypeKind.VOID
+import javax.lang.model.type.TypeMirror
+
+class InsertionMethodProcessor(baseContext: Context,
+                               val containing: DeclaredType,
+                               val executableElement: ExecutableElement) {
+    val context = baseContext.fork(executableElement)
+    fun process(): InsertionMethod {
+        val delegate = ShortcutMethodProcessor(context, containing, executableElement)
+        val annotation = delegate.extractAnnotation(Insert::class,
+                ProcessorErrors.MISSING_INSERT_ANNOTATION)
+
+        val onConflict = OnConflictProcessor.extractFrom(annotation)
+        context.checker.check(onConflict <= IGNORE && onConflict >= REPLACE,
+                executableElement, ProcessorErrors.INVALID_ON_CONFLICT_VALUE)
+
+        val returnType = delegate.extractReturnType()
+        val returnTypeName = TypeName.get(returnType)
+        context.checker.notUnbound(returnTypeName, executableElement,
+                ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_INSERTION_METHODS)
+
+        val (entities, params) = delegate.extractParams(
+                missingParamError = ProcessorErrors
+                        .INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT
+        )
+
+        // TODO we can support more types
+        var insertionType = getInsertionType(returnType)
+        context.checker.check(insertionType != null, executableElement,
+                ProcessorErrors.INVALID_INSERTION_METHOD_RETURN_TYPE)
+
+        if (insertionType != null) {
+            val acceptable = acceptableTypes(params)
+            if (insertionType !in acceptable) {
+                context.logger.e(executableElement,
+                        ProcessorErrors.insertionMethodReturnTypeMismatch(
+                                insertionType.returnTypeName,
+                                acceptable.map { it.returnTypeName }))
+                // clear it, no reason to generate code for it.
+                insertionType = null
+            }
+        }
+        return InsertionMethod(
+                element = executableElement,
+                name = executableElement.simpleName.toString(),
+                returnType = returnType,
+                entities = entities,
+                parameters = params,
+                onConflict = onConflict,
+                insertionType = insertionType
+        )
+    }
+
+    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+    private fun getInsertionType(returnType: TypeMirror): InsertionMethod.Type? {
+        // TODO we need to support more types here.
+        fun isLongPrimitiveType(typeMirror: TypeMirror) = typeMirror.kind == LONG
+
+        fun isLongBoxType(typeMirror: TypeMirror) =
+                MoreTypes.isType(typeMirror) &&
+                        MoreTypes.isTypeOf(java.lang.Long::class.java, typeMirror)
+
+        fun isLongType(typeMirror: TypeMirror) =
+                isLongPrimitiveType(typeMirror) || isLongBoxType(typeMirror)
+
+        return if (returnType.kind == VOID) {
+            Type.INSERT_VOID
+        } else if (returnType.kind == TypeKind.ARRAY) {
+            val arrayType = MoreTypes.asArray(returnType)
+            val param = arrayType.componentType
+            if (isLongPrimitiveType(param)) {
+                Type.INSERT_ID_ARRAY
+            } else if (isLongBoxType(param)) {
+                Type.INSERT_ID_ARRAY_BOX
+            } else {
+                null
+            }
+        } else if (MoreTypes.isType(returnType)
+                && MoreTypes.isTypeOf(List::class.java, returnType)) {
+            val declared = MoreTypes.asDeclared(returnType)
+            val param = declared.typeArguments.first()
+            if (isLongBoxType(param)) {
+                Type.INSERT_ID_LIST
+            } else {
+                null
+            }
+        } else if (isLongType(returnType)) {
+            Type.INSERT_SINGLE_ID
+        } else {
+            null
+        }
+    }
+
+    companion object {
+        @VisibleForTesting
+        val VOID_SET by lazy { setOf(Type.INSERT_VOID) }
+        @VisibleForTesting
+        val SINGLE_ITEM_SET by lazy { setOf(Type.INSERT_VOID, Type.INSERT_SINGLE_ID) }
+        @VisibleForTesting
+        val MULTIPLE_ITEM_SET by lazy {
+            setOf(Type.INSERT_VOID, Type.INSERT_ID_ARRAY, Type.INSERT_ID_ARRAY_BOX,
+                    Type.INSERT_ID_LIST)
+        }
+        fun acceptableTypes(params : List<ShortcutQueryParameter>) : Set<InsertionMethod.Type> {
+            if (params.isEmpty()) {
+                return VOID_SET
+            }
+            if (params.size > 1) {
+                return VOID_SET
+            }
+            if (params.first().isMultiple) {
+                return MULTIPLE_ITEM_SET
+            } else {
+                return SINGLE_ITEM_SET
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/OnConflictProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/OnConflictProcessor.kt
new file mode 100644
index 0000000..ac5ed5b
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/OnConflictProcessor.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.OnConflictStrategy
+import com.google.auto.common.AnnotationMirrors
+import javax.lang.model.element.AnnotationMirror
+
+/**
+ * Processes on conflict fields in annotations
+ */
+object OnConflictProcessor {
+    val INVALID_ON_CONFLICT = -1
+
+    @OnConflictStrategy
+    fun extractFrom(annotation: AnnotationMirror?, fieldName: String = "onConflict"): Int {
+        return if (annotation == null) {
+            INVALID_ON_CONFLICT
+        } else {
+            try {
+                val onConflictValue = AnnotationMirrors
+                        .getAnnotationValue(annotation, fieldName)
+                        .value
+                onConflictValue.toString().toInt()
+            } catch (ex: NumberFormatException) {
+                INVALID_ON_CONFLICT
+            }
+        }
+    }
+
+    fun onConflictText(@OnConflictStrategy onConflict: Int): String {
+        return when (onConflict) {
+            OnConflictStrategy.REPLACE -> "REPLACE"
+            OnConflictStrategy.ABORT -> "ABORT"
+            OnConflictStrategy.FAIL -> "FAIL"
+            OnConflictStrategy.IGNORE -> "IGNORE"
+            OnConflictStrategy.ROLLBACK -> "ROLLBACK"
+            else -> "BAD_CONFLICT_CONSTRAINT"
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/PojoProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/PojoProcessor.kt
new file mode 100644
index 0000000..baa351d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/PojoProcessor.kt
@@ -0,0 +1,519 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Relation
+import android.arch.persistence.room.ColumnInfo
+import android.arch.persistence.room.Embedded
+import android.arch.persistence.room.Ignore
+import android.arch.persistence.room.ext.getAllFieldsIncludingPrivateSupers
+import android.arch.persistence.room.ext.getAnnotationValue
+import android.arch.persistence.room.ext.getAsString
+import android.arch.persistence.room.ext.getAsStringList
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.ext.hasAnyOf
+import android.arch.persistence.room.ext.isCollection
+import android.arch.persistence.room.ext.toClassType
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_GETTER_FOR_FIELD
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_SETTER_FOR_FIELD
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_TYPE
+import android.arch.persistence.room.processor.ProcessorErrors.POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME
+import android.arch.persistence.room.processor.cache.Cache
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Constructor
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.FieldGetter
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.FieldSetter
+import android.arch.persistence.room.vo.Pojo
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import javax.lang.model.element.Element
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.Modifier.ABSTRACT
+import javax.lang.model.element.Modifier.PRIVATE
+import javax.lang.model.element.Modifier.PROTECTED
+import javax.lang.model.element.Modifier.PUBLIC
+import javax.lang.model.element.Modifier.STATIC
+import javax.lang.model.element.TypeElement
+import javax.lang.model.element.VariableElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+import javax.lang.model.util.ElementFilter
+
+/**
+ * Processes any class as if it is a Pojo.
+ */
+class PojoProcessor(baseContext: Context, val element: TypeElement,
+                    val bindingScope: FieldProcessor.BindingScope,
+                    val parent: EmbeddedField?) {
+    val context = baseContext.fork(element)
+    companion object {
+        val PROCESSED_ANNOTATIONS = listOf(ColumnInfo::class, Embedded::class,
+                    Relation::class)
+    }
+    fun process() : Pojo {
+        return context.cache.pojos.get(Cache.PojoKey(element, bindingScope, parent), {
+            doProcess()
+        })
+    }
+
+    private fun doProcess(): Pojo {
+        // TODO handle recursion: b/35980205
+        val declaredType = MoreTypes.asDeclared(element.asType())
+        // TODO handle conflicts with super: b/35568142
+        val allFields = element.getAllFieldsIncludingPrivateSupers(context.processingEnv)
+                .filter {
+                    !it.hasAnnotation(Ignore::class) && !it.hasAnyOf(Modifier.STATIC)
+                }
+                .groupBy { field ->
+                    context.checker.check(
+                            PROCESSED_ANNOTATIONS.count { field.hasAnnotation(it) } < 2, field,
+                            ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION
+                    )
+                    if (field.hasAnnotation(Embedded::class)) {
+                        Embedded::class
+                    } else if (field.hasAnnotation(Relation::class)) {
+                        Relation::class
+                    } else {
+                        null
+                    }
+                }
+        val myFields = allFields[null]
+                ?.map {
+                    FieldProcessor(
+                            baseContext = context,
+                            containing = declaredType,
+                            element = it,
+                            bindingScope = bindingScope,
+                            fieldParent = parent).process()
+                } ?: emptyList()
+
+        val embeddedFields = allFields[Embedded::class]
+                ?.map {
+                    processEmbeddedField(declaredType, it)
+                } ?: emptyList()
+        val subFields = embeddedFields.flatMap { it.pojo.fields }
+
+        val fields = myFields + subFields
+
+        val myRelationsList = allFields[Relation::class]
+                ?.map {
+                    processRelationField(fields, declaredType, it)
+                }
+                ?.filterNotNull() ?: emptyList()
+
+        val subRelations = embeddedFields.flatMap { it.pojo.relations }
+
+        val relations = myRelationsList + subRelations
+
+        fields.groupBy { it.columnName }
+                .filter { it.value.size > 1 }
+                .forEach {
+                    context.logger.e(element, ProcessorErrors.pojoDuplicateFieldNames(
+                            it.key, it.value.map(Field::getPath)
+                    ))
+                    it.value.forEach {
+                        context.logger.e(it.element, POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME)
+                    }
+                }
+        val methods = MoreElements.getLocalAndInheritedMethods(element,
+                context.processingEnv.elementUtils)
+                .filter {
+                    !it.hasAnyOf(PRIVATE, ABSTRACT, STATIC)
+                            && !it.hasAnnotation(Ignore::class)
+                }
+                .map { MoreElements.asExecutable(it) }
+
+        val getterCandidates = methods.filter {
+            it.parameters.size == 0 && it.returnType.kind != TypeKind.VOID
+        }
+
+        val setterCandidates = methods.filter {
+            it.parameters.size == 1 && it.returnType.kind == TypeKind.VOID
+        }
+        // don't try to find a constructor for binding to statement.
+        val constructor = if (bindingScope == FieldProcessor.BindingScope.BIND_TO_STMT) {
+            // we don't need to construct this POJO.
+            null
+        } else {
+            chooseConstructor(myFields, embeddedFields)
+        }
+
+        assignGetters(myFields, getterCandidates)
+        assignSetters(myFields, setterCandidates, constructor)
+
+        embeddedFields.forEach {
+            assignGetter(it.field, getterCandidates)
+            assignSetter(it.field, setterCandidates, constructor)
+        }
+
+        myRelationsList.forEach {
+            assignGetter(it.field, getterCandidates)
+            assignSetter(it.field, setterCandidates, constructor)
+        }
+
+        val pojo = Pojo(element = element,
+                type = declaredType,
+                fields = fields,
+                embeddedFields = embeddedFields,
+                relations = relations,
+                constructor = constructor)
+        return pojo
+    }
+
+    private fun chooseConstructor(myFields: List<Field>, embedded: List<EmbeddedField>)
+            : Constructor? {
+        val constructors = ElementFilter.constructorsIn(element.enclosedElements)
+                .filterNot { it.hasAnnotation(Ignore::class) || it.hasAnyOf(PRIVATE) }
+        val fieldMap = myFields.associateBy { it.name }
+        val embeddedMap = embedded.associateBy { it.field.name }
+        val typeUtils = context.processingEnv.typeUtils
+        val failedConstructors = mutableMapOf<ExecutableElement, List<Constructor.Param?>>()
+        val goodConstructors = constructors.map { constructor ->
+            val params = constructor.parameters.map param@ { param ->
+                val paramName = param.simpleName.toString()
+                val paramType = param.asType()
+
+                val matches = fun(field: Field?): Boolean {
+                    return if (field == null) {
+                        false
+                    } else if (!field.nameWithVariations.contains(paramName)) {
+                        false
+                    } else {
+                        typeUtils.isAssignable(paramType, field.type)
+                    }
+                }
+
+                val exactFieldMatch = fieldMap[paramName]
+
+                if (matches(exactFieldMatch)) {
+                    return@param Constructor.FieldParam(exactFieldMatch!!)
+                }
+                val exactEmbeddedMatch = embeddedMap[paramName]
+                if (matches(exactEmbeddedMatch?.field)) {
+                    return@param Constructor.EmbeddedParam(exactEmbeddedMatch!!)
+                }
+
+                val matchingFields = myFields.filter {
+                    matches(it)
+                }
+                val embeddedMatches = embedded.filter {
+                    matches(it.field)
+                }
+                if (matchingFields.isEmpty() && embeddedMatches.isEmpty()) {
+                    null
+                } else if (matchingFields.size + embeddedMatches.size == 1) {
+                    if (matchingFields.isNotEmpty()) {
+                        Constructor.FieldParam(matchingFields.first())
+                    } else {
+                        Constructor.EmbeddedParam(embeddedMatches.first())
+                    }
+                } else {
+                    context.logger.e(param, ProcessorErrors.ambigiousConstructor(
+                            pojo = element.qualifiedName.toString(),
+                            paramName = param.simpleName.toString(),
+                            matchingFields = matchingFields.map { it.getPath() }
+                                    + embedded.map { it.field.getPath() }
+                    ))
+                    null
+                }
+            }
+            if (params.any { it == null }) {
+                failedConstructors.put(constructor, params)
+                null
+            } else {
+                @Suppress("UNCHECKED_CAST")
+                Constructor(constructor, params as List<Constructor.Param>)
+            }
+        }.filterNotNull()
+        if (goodConstructors.isEmpty()) {
+            if (failedConstructors.isNotEmpty()) {
+                val failureMsg = failedConstructors.entries.joinToString("\n") { entry ->
+                    val paramsMatching = entry.key.parameters.withIndex().joinToString(", ") {
+                        "${it.value.simpleName} : ${entry.value[it.index]?.log()}"
+                    }
+                    "${entry.key} : [$paramsMatching]"
+                }
+                context.logger.e(element, ProcessorErrors.MISSING_POJO_CONSTRUCTOR +
+                        "\nTried the following constructors but they failed to match:\n$failureMsg")
+            }
+            context.logger.e(element, ProcessorErrors.MISSING_POJO_CONSTRUCTOR)
+            return null
+        }
+        if (goodConstructors.size > 1) {
+            goodConstructors.forEach {
+                context.logger.e(it.element, ProcessorErrors.TOO_MANY_POJO_CONSTRUCTORS)
+            }
+            return null
+        }
+        return goodConstructors.first()
+    }
+
+    private fun processEmbeddedField(declaredType: DeclaredType?, it: Element): EmbeddedField {
+        val fieldPrefix = it.getAnnotationValue(Embedded::class.java, "prefix")
+                ?.toString() ?: ""
+        val inheritedPrefix = parent?.prefix ?: ""
+        val embeddedField = Field(
+                it,
+                it.simpleName.toString(),
+                type = context.processingEnv.typeUtils.asMemberOf(declaredType, it),
+                affinity = null,
+                parent = parent)
+        val subParent = EmbeddedField(
+                field = embeddedField,
+                prefix = inheritedPrefix + fieldPrefix,
+                parent = parent)
+        val asVariable = MoreElements.asVariable(it)
+        subParent.pojo = PojoProcessor(baseContext = context.fork(it),
+                element = MoreTypes.asTypeElement(asVariable.asType()),
+                bindingScope = bindingScope,
+                parent = subParent).process()
+        return subParent
+    }
+
+    private fun processRelationField(myFields : List<Field>, container: DeclaredType?,
+                                     relationElement: VariableElement)
+            : android.arch.persistence.room.vo.Relation? {
+        val annotation = MoreElements.getAnnotationMirror(relationElement, Relation::class.java)
+                .orNull()!!
+        val parentColumnInput = AnnotationMirrors.getAnnotationValue(annotation, "parentColumn")
+                .getAsString("") ?: ""
+
+        val parentField = myFields.firstOrNull {
+            it.columnName == parentColumnInput
+        }
+        if (parentField == null) {
+            context.logger.e(relationElement,
+                    ProcessorErrors.relationCannotFindParentEntityField(
+                            entityName = element.qualifiedName.toString(),
+                            columnName = parentColumnInput,
+                            availableColumns = myFields.map { it.columnName }))
+            return null
+        }
+        // parse it as an entity.
+        val asMember = MoreTypes
+                .asMemberOf(context.processingEnv.typeUtils, container, relationElement)
+        if (asMember.kind == TypeKind.ERROR) {
+            context.logger.e(ProcessorErrors.CANNOT_FIND_TYPE, element)
+            return null
+        }
+        val declared = MoreTypes.asDeclared(asMember)
+        if (!declared.isCollection()) {
+            context.logger.e(relationElement, ProcessorErrors.RELATION_NOT_COLLECTION)
+            return null
+        }
+        val typeArg = declared.typeArguments.first()
+        if (typeArg.kind == TypeKind.ERROR) {
+            context.logger.e(MoreTypes.asTypeElement(typeArg), CANNOT_FIND_TYPE)
+            return null
+        }
+        val typeArgElement = MoreTypes.asTypeElement(typeArg)
+        val entityClassInput = AnnotationMirrors
+                .getAnnotationValue(annotation, "entity").toClassType()
+        val pojo : Pojo
+        val entity : Entity
+        if (entityClassInput == null
+                || MoreTypes.isTypeOf(Any::class.java, entityClassInput)) {
+            entity = EntityProcessor(context, typeArgElement).process()
+            pojo = entity
+        } else {
+            entity = EntityProcessor(context, MoreTypes.asTypeElement(entityClassInput)).process()
+            pojo = PojoProcessor(baseContext = context,
+                    element = typeArgElement,
+                    bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR,
+                    parent = parent).process()
+        }
+        // now find the field in the entity.
+        val entityColumnInput = AnnotationMirrors.getAnnotationValue(annotation, "entityColumn")
+                .getAsString() ?: ""
+        val entityField = entity.fields.firstOrNull {
+            it.columnName == entityColumnInput
+        }
+
+        if (entityField == null) {
+            context.logger.e(relationElement,
+                    ProcessorErrors.relationCannotFindEntityField(
+                            entityName = entity.typeName.toString(),
+                            columnName = entityColumnInput,
+                            availableColumns = entity.fields.map { it.columnName }))
+            return null
+        }
+
+        val field = Field(
+                element = relationElement,
+                name = relationElement.simpleName.toString(),
+                type = context.processingEnv.typeUtils.asMemberOf(container, relationElement),
+                affinity = null,
+                parent = parent)
+
+        val projection = AnnotationMirrors.getAnnotationValue(annotation, "projection")
+                .getAsStringList()
+        if(projection.isNotEmpty()) {
+            val missingColumns = projection.filterNot { columnName ->
+                entity.fields.any { columnName == it.columnName }
+            }
+            if (missingColumns.isNotEmpty()) {
+                context.logger.e(relationElement,
+                        ProcessorErrors.relationBadProject(entity.typeName.toString(),
+                                missingColumns, entity.fields.map { it.columnName }))
+            }
+        }
+
+        // if types don't match, row adapter prints a warning
+        return android.arch.persistence.room.vo.Relation(
+                entity = entity,
+                pojo = pojo,
+                field = field,
+                parentField = parentField,
+                entityField = entityField,
+                projection = projection
+        )
+    }
+
+    private fun assignGetters(fields: List<Field>, getterCandidates: List<ExecutableElement>) {
+        fields.forEach { field ->
+            assignGetter(field, getterCandidates)
+        }
+    }
+
+    private fun assignGetter(field: Field, getterCandidates: List<ExecutableElement>) {
+        val success = chooseAssignment(field = field,
+                candidates = getterCandidates,
+                nameVariations = field.getterNameWithVariations,
+                getType = { method ->
+                    method.returnType
+                },
+                assignFromField = {
+                    field.getter = FieldGetter(
+                            name = field.name,
+                            type = field.type,
+                            callType = CallType.FIELD)
+                },
+                assignFromMethod = { match ->
+                    field.getter = FieldGetter(
+                            name = match.simpleName.toString(),
+                            type = match.returnType,
+                            callType = CallType.METHOD)
+                },
+                reportAmbiguity = { matching ->
+                    context.logger.e(field.element,
+                            ProcessorErrors.tooManyMatchingGetters(field, matching))
+                })
+        context.checker.check(success, field.element, CANNOT_FIND_GETTER_FOR_FIELD)
+    }
+
+    private fun assignSetters(fields: List<Field>, setterCandidates: List<ExecutableElement>,
+                              constructor : Constructor?) {
+        fields.forEach { field ->
+            assignSetter(field, setterCandidates, constructor)
+        }
+    }
+
+    private fun assignSetter(field: Field, setterCandidates: List<ExecutableElement>,
+                             constructor: Constructor?) {
+        if (constructor != null && constructor.hasField(field)) {
+            field.setter = FieldSetter(field.name, field.type, CallType.CONSTRUCTOR)
+            return
+        }
+        val success = chooseAssignment(field = field,
+                candidates = setterCandidates,
+                nameVariations = field.setterNameWithVariations,
+                getType = { method ->
+                    method.parameters.first().asType()
+                },
+                assignFromField = {
+                    field.setter = FieldSetter(
+                            name = field.name,
+                            type = field.type,
+                            callType = CallType.FIELD)
+                },
+                assignFromMethod = { match ->
+                    val paramType = match.parameters.first().asType()
+                    field.setter = FieldSetter(
+                            name = match.simpleName.toString(),
+                            type = paramType,
+                            callType = CallType.METHOD)
+                },
+                reportAmbiguity = { matching ->
+                    context.logger.e(field.element,
+                            ProcessorErrors.tooManyMatchingSetter(field, matching))
+                })
+        context.checker.check(success, field.element, CANNOT_FIND_SETTER_FOR_FIELD)
+    }
+
+    /**
+     * Finds a setter/getter from available list of methods.
+     * It returns true if assignment is successful, false otherwise.
+     * At worst case, it sets to the field as if it is accessible so that the rest of the
+     * compilation can continue.
+     */
+    private fun chooseAssignment(field: Field, candidates: List<ExecutableElement>,
+                                 nameVariations: List<String>,
+                                 getType: (ExecutableElement) -> TypeMirror,
+                                 assignFromField: () -> Unit,
+                                 assignFromMethod: (ExecutableElement) -> Unit,
+                                 reportAmbiguity: (List<String>) -> Unit): Boolean {
+        if (field.element.hasAnyOf(PUBLIC)) {
+            assignFromField()
+            return true
+        }
+        val types = context.processingEnv.typeUtils
+
+        val matching = candidates
+                .filter {
+                    types.isAssignable(getType(it), field.element.asType())
+                            && (field.nameWithVariations.contains(it.simpleName.toString())
+                            || nameVariations.contains(it.simpleName.toString()))
+                }
+                .groupBy {
+                    if (it.hasAnyOf(PUBLIC)) PUBLIC else PROTECTED
+                }
+        if (matching.isEmpty()) {
+            // we always assign to avoid NPEs in the rest of the compilation.
+            assignFromField()
+            // if field is not private, assume it works (if we are on the same package).
+            // if not, compiler will tell, we didn't have any better alternative anyways.
+            return !field.element.hasAnyOf(PRIVATE)
+        }
+        val match = verifyAndChooseOneFrom(matching[PUBLIC], reportAmbiguity) ?:
+                verifyAndChooseOneFrom(matching[PROTECTED], reportAmbiguity)
+        if (match == null) {
+            assignFromField()
+            return false
+        } else {
+            assignFromMethod(match)
+            return true
+        }
+    }
+
+    private fun verifyAndChooseOneFrom(candidates: List<ExecutableElement>?,
+                                       reportAmbiguity: (List<String>) -> Unit)
+            : ExecutableElement? {
+        if (candidates == null) {
+            return null
+        }
+        if (candidates.size > 1) {
+            reportAmbiguity(candidates.map { it.simpleName.toString() })
+        }
+        return candidates.first()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ProcessorErrors.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ProcessorErrors.kt
new file mode 100644
index 0000000..fc83b30
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ProcessorErrors.kt
@@ -0,0 +1,443 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Delete
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.Update
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.vo.CustomTypeConverter
+import android.arch.persistence.room.vo.Field
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.TypeMirror
+
+object ProcessorErrors {
+    private fun String.trim(): String {
+        return this.trimIndent().replace(System.lineSeparator(), " ")
+    }
+    val MISSING_QUERY_ANNOTATION = "Query methods must be annotated with ${Query::class.java}"
+    val MISSING_INSERT_ANNOTATION = "Insertion methods must be annotated with ${Insert::class.java}"
+    val MISSING_DELETE_ANNOTATION = "Deletion methods must be annotated with ${Delete::class.java}"
+    val MISSING_UPDATE_ANNOTATION = "Update methods must be annotated with ${Update::class.java}"
+    val INVALID_ON_CONFLICT_VALUE = "On conflict value must be one of @OnConflictStrategy values."
+    val INVALID_INSERTION_METHOD_RETURN_TYPE = "Methods annotated with @Insert can return either" +
+            " void, long, Long, long[], Long[] or List<Long>."
+
+    fun insertionMethodReturnTypeMismatch(definedReturn : TypeName,
+                                          expectedReturnTypes : List<TypeName>) : String {
+        return "Method returns $definedReturn but it should return one of the following: `" +
+                expectedReturnTypes.joinToString(", ") + "`. If you want to return the list of" +
+                " row ids from the query, your insertion method can receive only 1 parameter."
+    }
+
+    val ABSTRACT_METHOD_IN_DAO_MISSING_ANY_ANNOTATION = "Abstract method in DAO must be annotated" +
+            " with ${Query::class.java} AND ${Insert::class.java}"
+    val CANNOT_USE_MORE_THAN_ONE_DAO_METHOD_ANNOTATION = "A DAO method can be annotated with only" +
+            " one of the following:" + DaoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") {
+        it.java.simpleName
+    }
+    val CANNOT_RESOLVE_RETURN_TYPE = "Cannot resolve return type for %s"
+    val CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS = "Cannot use unbound generics in query" +
+            " methods. It must be bound to a type through base Dao class."
+    val CANNOT_USE_UNBOUND_GENERICS_IN_INSERTION_METHODS = "Cannot use unbound generics in" +
+            " insertion methods. It must be bound to a type through base Dao class."
+    val CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS = "Cannot use unbound fields in entities."
+    val CANNOT_USE_UNBOUND_GENERICS_IN_DAO_CLASSES = "Cannot use unbound generics in Dao classes." +
+            " If you are trying to create a base DAO, create a normal class, extend it with type" +
+            " params then mark the subclass with @Dao."
+    val CANNOT_FIND_GETTER_FOR_FIELD = "Cannot find getter for field."
+    val CANNOT_FIND_SETTER_FOR_FIELD = "Cannot find setter for field."
+    val MISSING_PRIMARY_KEY = "An entity must have at least 1 field annotated with @PrimaryKey"
+    val AUTO_INCREMENTED_PRIMARY_KEY_IS_NOT_INT = "If a primary key is annotated with" +
+            " autoGenerate, its type must be int, Integer, long or Long."
+    val AUTO_INCREMENT_EMBEDDED_HAS_MULTIPLE_FIELDS = "When @PrimaryKey annotation is used on a" +
+            " field annotated with @Embedded, the embedded class should have only 1 field."
+
+    fun multiplePrimaryKeyAnnotations(primaryKeys: List<String>): String {
+        return """
+                You cannot have multiple primary keys defined in an Entity. If you
+                want to declare a composite primary key, you should use @Entity#primaryKeys and
+                not use @PrimaryKey. Defined Primary Keys:
+                ${primaryKeys.joinToString(", ")}""".trim()
+    }
+
+    fun primaryKeyColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
+        return "$columnName referenced in the primary key does not exists in the Entity." +
+                " Available column names:${allColumns.joinToString(", ")}"
+    }
+
+    val DAO_MUST_BE_AN_ABSTRACT_CLASS_OR_AN_INTERFACE = "Dao class must be an abstract class or" +
+            " an interface"
+    val DATABASE_MUST_BE_ANNOTATED_WITH_DATABASE = "Database must be annotated with @Database"
+    val DAO_MUST_BE_ANNOTATED_WITH_DAO = "Dao class must be annotated with @Dao"
+
+    fun daoMustHaveMatchingConstructor(daoName: String, dbName: String): String {
+        return """
+                $daoName needs to have either an empty constructor or a constructor that takes
+                $dbName as its only parameter.
+                """.trim()
+    }
+
+    val ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY = "Entity class must be annotated with @Entity"
+    val DATABASE_ANNOTATION_MUST_HAVE_LIST_OF_ENTITIES = "@Database annotation must specify list" +
+            " of entities"
+    val COLUMN_NAME_CANNOT_BE_EMPTY = "Column name cannot be blank. If you don't want to set it" +
+            ", just remove the @ColumnInfo annotation or use @ColumnInfo.INHERIT_FIELD_NAME."
+
+    val ENTITY_TABLE_NAME_CANNOT_BE_EMPTY = "Entity table name cannot be blank. If you don't want" +
+            " to set it, just remove the tableName property."
+
+    val CANNOT_BIND_QUERY_PARAMETER_INTO_STMT = "Query method parameters should either be a" +
+            " type that can be converted into a database column or a List / Array that contains" +
+            " such type. You can consider adding a Type Adapter for this."
+
+    val QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE = "Query/Insert method parameters cannot " +
+            "start with underscore (_)."
+
+    val CANNOT_FIND_QUERY_RESULT_ADAPTER = "Not sure how to convert a Cursor to this method's " +
+            "return type"
+
+    val INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT = "Method annotated with" +
+            " @Insert but does not have any parameters to insert."
+
+    val DELETION_MISSING_PARAMS = "Method annotated with" +
+            " @Delete but does not have any parameters to delete."
+
+    val UPDATE_MISSING_PARAMS = "Method annotated with" +
+            " @Update but does not have any parameters to update."
+
+    val CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER = "Type of the parameter must be a class " +
+            "annotated with @Entity or a collection/array of it."
+
+    val DB_MUST_EXTEND_ROOM_DB = "Classes annotated with @Database should extend " +
+            RoomTypeNames.ROOM_DB
+
+    val LIVE_DATA_QUERY_WITHOUT_SELECT = "LiveData return type can only be used with SELECT" +
+            " queries."
+
+    private val TOO_MANY_MATCHING_GETTERS = "Ambiguous getter for %s. All of the following " +
+            "match: %s. You can @Ignore the ones that you don't want to match."
+
+    fun tooManyMatchingGetters(field: Field, methodNames: List<String>): String {
+        return TOO_MANY_MATCHING_GETTERS.format(field, methodNames.joinToString(", "))
+    }
+
+    private val TOO_MANY_MATCHING_SETTERS = "Ambiguous setter for %s. All of the following " +
+            "match: %s. You can @Ignore the ones that you don't want to match."
+
+    fun tooManyMatchingSetter(field: Field, methodNames: List<String>): String {
+        return TOO_MANY_MATCHING_SETTERS.format(field, methodNames.joinToString(", "))
+    }
+
+    val CANNOT_FIND_COLUMN_TYPE_ADAPTER = "Cannot figure out how to save this field into" +
+            " database. You can consider adding a type converter for it."
+
+    val CANNOT_FIND_STMT_BINDER = "Cannot figure out how to bind this field into a statement."
+
+    val CANNOT_FIND_CURSOR_READER = "Cannot figure out how to read this field from a cursor."
+
+    private val MISSING_PARAMETER_FOR_BIND = "Each bind variable in the query must have a" +
+            " matching method parameter. Cannot find method parameters for %s."
+
+    fun missingParameterForBindVariable(bindVarName: List<String>): String {
+        return MISSING_PARAMETER_FOR_BIND.format(bindVarName.joinToString(", "))
+    }
+
+    private val UNUSED_QUERY_METHOD_PARAMETER = "Unused parameter%s: %s"
+    fun unusedQueryMethodParameter(unusedParams: List<String>): String {
+        return UNUSED_QUERY_METHOD_PARAMETER.format(
+                if (unusedParams.size > 1) "s" else "",
+                unusedParams.joinToString(","))
+    }
+
+    private val DUPLICATE_TABLES = "Table name \"%s\" is used by multiple entities: %s"
+    fun duplicateTableNames(tableName: String, entityNames: List<String>): String {
+        return DUPLICATE_TABLES.format(tableName, entityNames.joinToString(", "))
+    }
+
+    val DELETION_METHODS_MUST_RETURN_VOID_OR_INT = "Deletion methods must either return void or" +
+            " return int (the number of deleted rows)."
+
+    val UPDATE_METHODS_MUST_RETURN_VOID_OR_INT = "Update methods must either return void or" +
+            " return int (the number of updated rows)."
+
+    val DAO_METHOD_CONFLICTS_WITH_OTHERS = "Dao method has conflicts."
+
+    fun duplicateDao(dao: TypeName, methodNames: List<String>): String {
+        return """
+                All of these functions [${methodNames.joinToString(", ")}] return the same DAO
+                class [$dao].
+                A database can use a DAO only once so you should remove ${methodNames.size - 1} of
+                these conflicting DAO methods. If you are implementing any of these to fulfill an
+                interface, don't make it abstract, instead, implement the code that calls the
+                other one.
+                """.trim()
+    }
+
+    fun cursorPojoMismatch(pojoTypeName: TypeName,
+                           unusedColumns: List<String>, allColumns: List<String>,
+                           unusedFields: List<Field>, allFields: List<Field>): String {
+        val unusedColumnsWarning = if (unusedColumns.isNotEmpty()) {
+            """
+                The query returns some columns [${unusedColumns.joinToString(", ")}] which are not
+                use by $pojoTypeName. You can use @ColumnInfo annotation on the fields to specify
+                the mapping.
+            """.trim()
+        } else {
+            ""
+        }
+        val unusedFieldsWarning = if (unusedFields.isNotEmpty()) {
+            """
+                $pojoTypeName has some fields
+                [${unusedFields.joinToString(", ") { it.columnName }}] which are not returned by the
+                query. If they are not supposed to be read from the result, you can mark them with
+                @Ignore annotation.
+            """.trim()
+        } else {
+            ""
+        }
+        return """
+            $unusedColumnsWarning
+            $unusedFieldsWarning
+            You can suppress this warning by annotating the method with
+            @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH).
+            Columns returned by the query: ${allColumns.joinToString(", ")}.
+            Fields in $pojoTypeName: ${allFields.joinToString(", ") { it.columnName }}.
+            """.trim()
+    }
+
+    val TYPE_CONVERTER_UNBOUND_GENERIC = "Cannot use unbound generics in Type Converters."
+    val TYPE_CONVERTER_BAD_RETURN_TYPE = "Invalid return type for a type converter."
+    val TYPE_CONVERTER_MUST_RECEIVE_1_PARAM = "Type converters must receive 1 parameter."
+    val TYPE_CONVERTER_EMPTY_CLASS = "Class is referenced as a converter but it does not have any" +
+            " converter methods."
+    val TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR = "Classes that are used as TypeConverters must" +
+            " have no-argument public constructors."
+    val TYPE_CONVERTER_MUST_BE_PUBLIC = "Type converters must be public."
+
+    fun duplicateTypeConverters(converters: List<CustomTypeConverter>): String {
+        return "Multiple methods define the same conversion. Conflicts with these:" +
+                " ${converters.joinToString(", ") { it.toString() }}"
+    }
+
+    // TODO must print field paths.
+    val POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME = "Field has non-unique column name."
+
+    fun pojoDuplicateFieldNames(columnName: String, fieldPaths: List<String>): String {
+        return "Multiple fields have the same columnName: $columnName." +
+                " Field names: ${fieldPaths.joinToString(", ")}."
+    }
+
+    fun embeddedPrimaryKeyIsDropped(entityQName: String, fieldName: String): String {
+        return "Primary key constraint on $fieldName is ignored when being merged into " +
+                entityQName
+    }
+
+    val INDEX_COLUMNS_CANNOT_BE_EMPTY = "List of columns in an index cannot be empty"
+
+    fun indexColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
+        return "$columnName referenced in the index does not exists in the Entity." +
+                " Available column names:${allColumns.joinToString(", ")}"
+    }
+
+    fun duplicateIndexInEntity(indexName: String): String {
+        return "There are multiple indices with name $indexName. This happen if you've declared" +
+                " the same index multiple times or different indices have the same name. See" +
+                " @Index documentation for details."
+    }
+
+    fun duplicateIndexInDatabase(indexName: String, indexPaths: List<String>): String {
+        return "There are multiple indices with name $indexName. You should rename " +
+                "${indexPaths.size - 1} of these to avoid the conflict:" +
+                "${indexPaths.joinToString(", ")}."
+    }
+
+    fun droppedEmbeddedFieldIndex(fieldPath: String, grandParent: String): String {
+        return "The index will be dropped when being merged into $grandParent" +
+                "($fieldPath). You must re-declare it in $grandParent if you want to index this" +
+                " field in $grandParent."
+    }
+
+    fun droppedEmbeddedIndex(entityName: String, fieldPath: String, grandParent: String)
+            : String {
+        return "Indices defined in $entityName will be dropped when it is merged into" +
+                " $grandParent ($fieldPath). You can re-declare them in $grandParent."
+    }
+
+    fun droppedSuperClassIndex(childEntity: String, superEntity: String): String {
+        return "Indices defined in $superEntity will NOT be re-used in $childEntity. If you want" +
+                " to inherit them, you must re-declare them in $childEntity." +
+                " Alternatively, you can set inheritSuperIndices to true in the @Entity annotation."
+    }
+
+    fun droppedSuperClassFieldIndex(fieldName: String, childEntity: String,
+                                    superEntity: String): String {
+        return "Index defined on field `$fieldName` in $superEntity will NOT be re-used in" +
+                " $childEntity. " +
+                "If you want to inherit it, you must re-declare it in $childEntity." +
+                " Alternatively, you can set inheritSuperIndices to true in the @Entity annotation."
+    }
+
+    val RELATION_NOT_COLLECTION = "Fields annotated with @Relation must be a List or Set."
+
+    fun relationCannotFindEntityField(entityName : String, columnName: String,
+                                      availableColumns: List<String>) : String {
+        return "Cannot find the child entity column `$columnName` in $entityName." +
+                " Options: ${availableColumns.joinToString(", ")}"
+    }
+
+    fun relationCannotFindParentEntityField(entityName : String, columnName: String,
+                                            availableColumns: List<String>) : String {
+        return "Cannot find the parent entity column `$columnName` in $entityName." +
+                " Options: ${availableColumns.joinToString(", ")}"
+    }
+
+    val RELATION_IN_ENTITY = "Entities cannot have relations."
+
+    val CANNOT_FIND_TYPE = "Cannot find type."
+
+    fun relationAffinityMismatch(parentColumn: String, childColumn: String,
+                                 parentAffinity : SQLTypeAffinity?,
+                                 childAffinity : SQLTypeAffinity?) : String {
+        return """
+        The affinity of parent column ($parentColumn : $parentAffinity) does not match the type
+        affinity of the child column ($childColumn : $childAffinity).
+        """.trim()
+    }
+
+    val CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION = "A field can be annotated with only" +
+            " one of the following:" + PojoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") {
+        it.java.simpleName
+    }
+
+    fun relationBadProject(entityQName : String, missingColumnNames : List<String>,
+                           availableColumnNames : List<String>) : String {
+        return """
+        $entityQName does not have the following columns: ${missingColumnNames.joinToString(",")}.
+        Available columns are: ${availableColumnNames.joinToString(",")}
+        """.trim()
+    }
+
+    val MISSING_SCHEMA_EXPORT_DIRECTORY = "Schema export directory is not provided to the" +
+            " annotation processor so we cannot export the schema. You can either provide" +
+            " `room.schemaLocation` annotation processor argument OR set exportSchema to false."
+
+    val INVALID_FOREIGN_KEY_ACTION = "Invalid foreign key action. It must be one of the constants" +
+            " defined in ForeignKey.Action"
+
+    fun foreignKeyNotAnEntity(className : String) : String {
+        return """
+        Classes referenced in Foreign Key annotations must be @Entity classes. $className is not
+        an entity
+        """.trim()
+    }
+
+    val FOREIGN_KEY_CANNOT_FIND_PARENT = "Cannot find parent entity class."
+
+    fun foreignKeyChildColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
+        return "($columnName) referenced in the foreign key does not exists in the Entity." +
+                " Available column names:${allColumns.joinToString(", ")}"
+    }
+
+    fun foreignKeyParentColumnDoesNotExist(parentEntity : String,
+                                           missingColumn: String,
+                                           allColumns : List<String>): String {
+        return "($missingColumn) does not exist in $parentEntity. Available columns are" +
+                " ${allColumns.joinToString(",")}"
+    }
+
+    val FOREIGN_KEY_EMPTY_CHILD_COLUMN_LIST = "Must specify at least 1 column name for the child"
+
+    val FOREIGN_KEY_EMPTY_PARENT_COLUMN_LIST = "Must specify at least 1 column name for the parent"
+
+    fun foreignKeyColumnNumberMismatch(childColumns : List<String>, parentColumns : List<String>)
+            : String {
+        return """
+                Number of child columns in foreign key must match number of parent columns.
+                Child reference has ${childColumns.joinToString(",")} and parent reference has
+                ${parentColumns.joinToString(",")}
+               """.trim()
+    }
+
+    fun foreignKeyMissingParentEntityInDatabase(parentTable : String, childEntity : String)
+            : String {
+        return """
+                $parentTable table referenced in the foreign keys of $childEntity does not exist in
+                the database. Maybe you forgot to add the referenced entity in the entities list of
+                the @Database annotation?""".trim()
+    }
+
+    fun foreignKeyMissingIndexInParent(parentEntity : String, parentColumns: List<String>,
+                                       childEntity : String, childColumns: List<String>): String {
+        return """
+                $childEntity has a foreign key (${childColumns.joinToString(",")}) that references
+                $parentEntity (${parentColumns.joinToString(",")}) but $parentEntity does not have
+                a unique index on those columns nor the columns are its primary key.
+                SQLite requires having a unique constraint on referenced parent columns so you must
+                add a unique index to $parentEntity that has
+                (${parentColumns.joinToString(",")}) column(s).
+               """.trim()
+    }
+
+    fun foreignKeyMissingIndexInChildColumns(childColumns: List<String>) : String {
+        return """
+                (${childColumns.joinToString(",")}) column(s) reference a foreign key but
+                they are not part of an index. This may trigger full table scans whenever parent
+                table is modified so you are highly advised to create an index that covers these
+                columns.
+               """.trim()
+    }
+
+    fun foreignKeyMissingIndexInChildColumn(childColumn: String) : String {
+        return """
+                $childColumn column references a foreign key but it is not part of an index. This
+                may trigger full table scans whenever parent table is modified so you are highly
+                advised to create an index that covers this column.
+               """.trim()
+    }
+
+    fun shortcutEntityIsNotInDatabase(database : String, dao : String, entity : String) : String {
+        return """
+                $dao is part of $database but this entity is not in the database. Maybe you forgot
+                to add $entity to the entities section of the @Database?
+                """.trim()
+    }
+    val MISSING_ROOM_RXJAVA2_ARTIFACT = "To use RxJava2 features, you must add `rxjava2`" +
+            " artifact from Room as a dependency. android.arch.persistence.room:rxjava2:<version>"
+
+    fun ambigiousConstructor(pojo : String, paramName:String, matchingFields : List<String>)
+            : String {
+        return """
+            Ambiguous constructor. The parameter ($paramName) in $pojo matches multiple fields:
+            [${matchingFields.joinToString(",")}]. If you don't want to use this constructor,
+            you can annotate it with @Ignore. If you want Room to use this constructor, you can
+            rename the parameters to exactly match the field name to fix the ambiguity.
+            """.trim()
+    }
+
+    val MISSING_POJO_CONSTRUCTOR = """
+            Entities and Pojos must have a usable public constructor. You can have an empty
+            constructor or a constructor whose parameters match the fields (by name and type).
+            """.trim()
+
+    val TOO_MANY_POJO_CONSTRUCTORS = """
+            Room cannot pick a constructor since multiple constructors are suitable. Try to annotate
+            unwanted constructors with @Ignore.
+            """.trim()
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryMethodProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryMethodProcessor.kt
new file mode 100644
index 0000000..fc60074
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryMethodProcessor.kt
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.SkipQueryVerification
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.parser.QueryType
+import android.arch.persistence.room.parser.SqlParser
+import android.arch.persistence.room.solver.query.result.LiveDataQueryResultBinder
+import android.arch.persistence.room.verifier.DatabaseVerificaitonErrors
+import android.arch.persistence.room.verifier.DatabaseVerifier
+import android.arch.persistence.room.vo.QueryMethod
+import android.arch.persistence.room.vo.QueryParameter
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeKind
+
+class QueryMethodProcessor(baseContext: Context,
+                           val containing: DeclaredType,
+                           val executableElement: ExecutableElement,
+                           val dbVerifier: DatabaseVerifier? = null) {
+    val context = baseContext.fork(executableElement)
+
+    fun process(): QueryMethod {
+        val asMember = context.processingEnv.typeUtils.asMemberOf(containing, executableElement)
+        val executableType = MoreTypes.asExecutable(asMember)
+
+        val annotation = MoreElements.getAnnotationMirror(executableElement,
+                Query::class.java).orNull()
+        context.checker.check(annotation != null, executableElement,
+                ProcessorErrors.MISSING_QUERY_ANNOTATION)
+
+        val query = if (annotation != null) {
+            val query = SqlParser.parse(
+                    AnnotationMirrors.getAnnotationValue(annotation, "value").value.toString())
+            context.checker.check(query.errors.isEmpty(), executableElement,
+                    query.errors.joinToString("\n"))
+            if (!executableElement.hasAnnotation(SkipQueryVerification::class)) {
+                query.resultInfo = dbVerifier?.analyze(query.original)
+            }
+            if (query.resultInfo?.error != null) {
+                context.logger.e(executableElement,
+                        DatabaseVerificaitonErrors.cannotVerifyQuery(query.resultInfo!!.error!!))
+            }
+
+            context.checker.check(executableType.returnType.kind != TypeKind.ERROR,
+                    executableElement, ProcessorErrors.CANNOT_RESOLVE_RETURN_TYPE,
+                    executableElement)
+            query
+        } else {
+            ParsedQuery.MISSING
+        }
+
+        val returnTypeName = TypeName.get(executableType.returnType)
+        context.checker.notUnbound(returnTypeName, executableElement,
+                ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS)
+
+        if (query.type == QueryType.DELETE) {
+            context.checker.check(
+                    returnTypeName == TypeName.VOID || returnTypeName == TypeName.INT,
+                    executableElement,
+                    ProcessorErrors.DELETION_METHODS_MUST_RETURN_VOID_OR_INT
+            )
+        }
+        val resultBinder = context.typeAdapterStore
+                .findQueryResultBinder(executableType.returnType, query)
+        context.checker.check(resultBinder.adapter != null || query.type != QueryType.SELECT,
+                executableElement, ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER)
+        if (resultBinder is LiveDataQueryResultBinder) {
+            context.checker.check(query.type == QueryType.SELECT, executableElement,
+                    ProcessorErrors.LIVE_DATA_QUERY_WITHOUT_SELECT)
+        }
+
+        val queryMethod = QueryMethod(
+                element = executableElement,
+                query = query,
+                name = executableElement.simpleName.toString(),
+                returnType = executableType.returnType,
+                parameters = executableElement.parameters
+                        .map { QueryParameterProcessor(
+                                baseContext = context,
+                                containing = containing,
+                                element = it).process() },
+                queryResultBinder = resultBinder)
+
+        val missing = queryMethod.sectionToParamMapping
+                .filter { it.second == null }
+                .map { it.first.text }
+        if (missing.isNotEmpty()) {
+            context.logger.e(executableElement,
+                    ProcessorErrors.missingParameterForBindVariable(missing))
+        }
+
+        val unused = queryMethod.parameters.filterNot { param ->
+            queryMethod.sectionToParamMapping.any { it.second == param }
+        }.map(QueryParameter::name)
+
+        if (unused.isNotEmpty()) {
+            context.logger.e(executableElement, ProcessorErrors.unusedQueryMethodParameter(unused))
+        }
+        return queryMethod
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryParameterProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryParameterProcessor.kt
new file mode 100644
index 0000000..1fe3afe
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/QueryParameterProcessor.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.vo.QueryParameter
+import com.google.auto.common.MoreTypes
+import javax.lang.model.element.VariableElement
+import javax.lang.model.type.DeclaredType
+
+class QueryParameterProcessor(baseContext: Context,
+                              val containing: DeclaredType,
+                              val element: VariableElement) {
+    val context = baseContext.fork(element)
+    fun process(): QueryParameter {
+        val asMember = MoreTypes.asMemberOf(context.processingEnv.typeUtils, containing, element)
+        val parameterAdapter = context.typeAdapterStore.findQueryParameterAdapter(asMember)
+        context.checker.check(parameterAdapter != null, element,
+                ProcessorErrors.CANNOT_BIND_QUERY_PARAMETER_INTO_STMT)
+
+        val name = element.simpleName.toString()
+        context.checker.check(!name.startsWith("_"), element,
+                ProcessorErrors.QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE)
+        return QueryParameter(name = name,
+                type = asMember,
+                queryParamAdapter = parameterAdapter)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessor.kt
new file mode 100644
index 0000000..95d16f5
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessor.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.ShortcutQueryParameter
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import javax.lang.model.element.AnnotationMirror
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+import kotlin.reflect.KClass
+
+/**
+ * Common functionality for shortcut method processors
+ */
+class ShortcutMethodProcessor(baseContext : Context,
+                              val containing: DeclaredType,
+                              val executableElement: ExecutableElement) {
+    val context = baseContext.fork(executableElement)
+    private val asMember = context.processingEnv.typeUtils.asMemberOf(containing, executableElement)
+    private val executableType = MoreTypes.asExecutable(asMember)
+
+    fun extractAnnotation(klass : KClass<out Annotation>,
+                          errorMsg : String) : AnnotationMirror? {
+        val annotation = MoreElements.getAnnotationMirror(executableElement,
+                klass.java).orNull()
+        context.checker.check(annotation != null, executableElement, errorMsg)
+        return annotation
+    }
+
+    fun extractReturnType() : TypeMirror {
+        return executableType.returnType
+    }
+
+    fun extractParams(missingParamError: String)
+            : Pair<Map<String, Entity>, List<ShortcutQueryParameter>> {
+        val params = executableElement.parameters
+                .map { ShortcutParameterProcessor(
+                        baseContext = context,
+                        containing = containing,
+                        element = it).process() }
+        context.checker.check(params.isNotEmpty(), executableElement, missingParamError)
+        val entities = params
+                .filter { it.entityType != null }
+                .associateBy({ it.name }, {
+                    EntityProcessor(
+                            baseContext = context,
+                            element = MoreTypes.asTypeElement(it.entityType)).process()
+                })
+        return Pair(entities, params)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutParameterProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutParameterProcessor.kt
new file mode 100644
index 0000000..4f66920
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/ShortcutParameterProcessor.kt
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.vo.ShortcutQueryParameter
+import com.google.auto.common.MoreTypes
+import javax.lang.model.element.TypeElement
+import javax.lang.model.element.VariableElement
+import javax.lang.model.type.ArrayType
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+import javax.lang.model.util.ElementFilter
+
+/**
+ * Processes parameters of methods that are annotated with Insert, Delete.
+ */
+class ShortcutParameterProcessor(baseContext : Context,
+                                 val containing: DeclaredType,
+                                 val element: VariableElement) {
+    val context = baseContext.fork(element)
+    fun process(): ShortcutQueryParameter {
+        val asMember = MoreTypes.asMemberOf(context.processingEnv.typeUtils, containing, element)
+        val name = element.simpleName.toString()
+        context.checker.check(!name.startsWith("_"), element,
+                ProcessorErrors.QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE)
+
+        val (entityType, isMultiple) = extractEntityType(asMember)
+        context.checker.check(entityType != null, element,
+                ProcessorErrors.CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER)
+
+        return ShortcutQueryParameter(
+                name = name,
+                type = asMember,
+                entityType = entityType,
+                isMultiple = isMultiple
+        )
+    }
+
+    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+    fun extractEntityType(typeMirror: TypeMirror) : Pair<TypeMirror?, Boolean> {
+
+        val elementUtils = context.processingEnv.elementUtils
+        val typeUtils = context.processingEnv.typeUtils
+
+        fun verifyAndPair(entityType: TypeMirror, isMultiple : Boolean)
+                : Pair<TypeMirror?, Boolean> {
+            if (!MoreTypes.isType(entityType)) {
+                return Pair(null, isMultiple)
+            }
+            val entityElement = MoreTypes.asElement(entityType)
+            return if (entityElement.hasAnnotation(Entity::class)) {
+                Pair(entityType, isMultiple)
+            } else {
+                Pair(null, isMultiple)
+            }
+        }
+
+        fun extractEntityTypeFromIterator(iterableType: DeclaredType): TypeMirror {
+            ElementFilter.methodsIn(elementUtils
+                    .getAllMembers(typeUtils.asElement(iterableType) as TypeElement)).forEach {
+                if (it.simpleName.toString() == "iterator") {
+                    return MoreTypes.asDeclared(MoreTypes.asExecutable(
+                            typeUtils.asMemberOf(iterableType, it)).returnType)
+                            .typeArguments.first()
+                }
+            }
+            throw IllegalArgumentException("iterator() not found in Iterable $iterableType")
+        }
+
+        val iterableType = typeUtils.erasure(elementUtils
+                .getTypeElement("java.lang.Iterable").asType())
+        if (typeUtils.isAssignable(typeMirror, iterableType)) {
+            val declared = MoreTypes.asDeclared(typeMirror)
+            val entity = extractEntityTypeFromIterator(declared)
+            return verifyAndPair(entity, true)
+        }
+        if (typeMirror is ArrayType) {
+            val entity = typeMirror.componentType
+            return verifyAndPair(entity, true)
+        }
+        return verifyAndPair(typeMirror, false)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/SuppressWarningProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/SuppressWarningProcessor.kt
new file mode 100644
index 0000000..e2215d9
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/SuppressWarningProcessor.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.vo.Warning
+import com.google.auto.common.AnnotationMirrors
+import com.google.auto.common.MoreElements
+import javax.lang.model.element.AnnotationValue
+import javax.lang.model.element.Element
+import javax.lang.model.util.SimpleAnnotationValueVisitor6
+
+/**
+ * A visitor that reads SuppressWarnings annotations and keeps the ones we know about.
+ */
+object SuppressWarningProcessor {
+
+    fun getSuppressedWarnings(element: Element): Set<Warning> {
+        val annotation = MoreElements.getAnnotationMirror(element,
+                SuppressWarnings::class.java).orNull()
+        return if (annotation == null) {
+            emptySet<Warning>()
+        } else {
+            val value = AnnotationMirrors.getAnnotationValue(annotation, "value")
+            if (value == null) {
+                emptySet<Warning>()
+            } else {
+                VISITOR.visit(value)
+            }
+        }
+    }
+
+    private object VISITOR : SimpleAnnotationValueVisitor6<Set<Warning>, String>() {
+        override fun visitArray(values: List<AnnotationValue>?, elementName: String?)
+                : Set<Warning> {
+            return values?.map {
+                Warning.fromPublicKey(it.value.toString())
+            }?.filterNotNull()?.toSet() ?: emptySet()
+        }
+
+        override fun defaultAction(o: Any?, p: String?): Set<Warning> {
+            return emptySet()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessor.kt
new file mode 100644
index 0000000..452ea4a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessor.kt
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.OnConflictStrategy.IGNORE
+import android.arch.persistence.room.OnConflictStrategy.REPLACE
+import android.arch.persistence.room.Update
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.vo.UpdateMethod
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+
+class UpdateMethodProcessor(baseContext: Context,
+                              val containing: DeclaredType,
+                              val executableElement: ExecutableElement) {
+    val context = baseContext.fork(executableElement)
+
+    fun process(): UpdateMethod {
+        val delegate = ShortcutMethodProcessor(context, containing, executableElement)
+        val annotation = delegate
+                .extractAnnotation(Update::class, ProcessorErrors.MISSING_UPDATE_ANNOTATION)
+
+        val onConflict = OnConflictProcessor.extractFrom(annotation)
+        context.checker.check(onConflict <= IGNORE && onConflict >= REPLACE,
+                executableElement, ProcessorErrors.INVALID_ON_CONFLICT_VALUE)
+
+        val returnTypeName = delegate.extractReturnType().typeName()
+        context.checker.check(
+                returnTypeName == TypeName.VOID || returnTypeName == TypeName.INT,
+                executableElement,
+                ProcessorErrors.UPDATE_METHODS_MUST_RETURN_VOID_OR_INT
+        )
+
+        val (entities, params) = delegate.extractParams(
+                missingParamError = ProcessorErrors
+                        .UPDATE_MISSING_PARAMS
+        )
+
+        return UpdateMethod(
+                element = delegate.executableElement,
+                name = delegate.executableElement.simpleName.toString(),
+                entities = entities,
+                onConflictStrategy = onConflict,
+                returnCount = returnTypeName == TypeName.INT,
+                parameters = params
+        )
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/cache/Cache.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/cache/Cache.kt
new file mode 100644
index 0000000..37f6c6d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/processor/cache/Cache.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+@file:Suppress("AddVarianceModifier")
+
+package android.arch.persistence.room.processor.cache
+
+import android.arch.persistence.room.processor.FieldProcessor
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.Pojo
+import android.arch.persistence.room.vo.Warning
+import java.util.LinkedHashSet
+import javax.lang.model.element.Element
+import javax.lang.model.type.TypeMirror
+
+/**
+ * A cache key can be used to avoid re-processing elements.
+ * <p>
+ * Each context has a cache variable that uses the same backing storage as the Root Context but
+ * adds current adapters and warning suppression list to the key.
+ */
+class Cache(val parent: Cache?, val converters: LinkedHashSet<TypeMirror>,
+            val suppressedWarnings: Set<Warning>) {
+    val entities: Bucket<EntityKey, Entity> = Bucket(parent?.entities)
+    val pojos: Bucket<PojoKey, Pojo> = Bucket(parent?.pojos)
+
+    inner class Bucket<K, T>(source: Bucket<K, T>?) {
+        private val entries: MutableMap<FullKey<K>, T> = source?.entries ?: mutableMapOf()
+        fun get(key : K, calculate: () -> T): T {
+            val fullKey = FullKey(converters, suppressedWarnings, key)
+            return entries.getOrPut(fullKey, {
+                calculate()
+            })
+        }
+    }
+
+    /**
+     * Key for Entity cache
+     */
+    data class EntityKey(val element: Element)
+
+    /**
+     * Key for Pojo cache
+     */
+    data class PojoKey(val element: Element, val scope : FieldProcessor.BindingScope,
+                       val parent : EmbeddedField?)
+
+    /**
+     * Internal key representation with adapters & warnings included.
+     * <p>
+     * Converters are kept in a linked set since the order is important for the TypeAdapterStore.
+     */
+    private data class FullKey<T>(val converters: LinkedHashSet<TypeMirror>,
+                               val suppressedWarnings: Set<Warning>,
+                               val key: T)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/CodeGenScope.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/CodeGenScope.kt
new file mode 100644
index 0000000..64e4f48
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/CodeGenScope.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver
+
+import com.google.common.annotations.VisibleForTesting
+import com.squareup.javapoet.CodeBlock
+import android.arch.persistence.room.writer.ClassWriter
+/**
+ * Defines a code generation scope where we can provide temporary variables, global variables etc
+ */
+class CodeGenScope(val writer : ClassWriter) {
+    private var tmpVarIndices = mutableMapOf<String, Int>()
+    private var builder : CodeBlock.Builder? = null
+    companion object {
+        const val TMP_VAR_DEFAULT_PREFIX = "_tmp"
+        const val CLASS_PROPERTY_PREFIX = "__"
+        @VisibleForTesting
+        fun _tmpVar(index:Int) = _tmpVar(TMP_VAR_DEFAULT_PREFIX, index)
+        fun _tmpVar(prefix : String, index:Int) = "$prefix${if(index == 0) "" else "_$index"}"
+    }
+
+    fun builder() : CodeBlock.Builder {
+        if (builder == null) {
+            builder = CodeBlock.builder()
+        }
+        return builder!!
+    }
+
+    fun getTmpVar() : String {
+        return getTmpVar(TMP_VAR_DEFAULT_PREFIX)
+    }
+
+    fun getTmpVar(prefix : String) : String {
+        if (!prefix.startsWith("_")) {
+            throw IllegalArgumentException("tmp variable prefixes should start with _")
+        }
+        if (prefix.startsWith(CLASS_PROPERTY_PREFIX)) {
+            throw IllegalArgumentException("cannot use $CLASS_PROPERTY_PREFIX for tmp variables")
+        }
+        val index = tmpVarIndices.getOrElse(prefix) { 0 }
+        val result = _tmpVar(prefix, index)
+        tmpVarIndices.put(prefix, index + 1)
+        return result
+    }
+
+    fun generate() = builder().build().toString()
+
+    /**
+     * copies all variable indices but excludes generated code.
+     */
+    fun fork() : CodeGenScope {
+        val forked = CodeGenScope(writer)
+        forked.tmpVarIndices.putAll(tmpVarIndices)
+        return forked
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/QueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/QueryResultBinderProvider.kt
new file mode 100644
index 0000000..b76be3e
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/QueryResultBinderProvider.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver
+
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import javax.lang.model.type.DeclaredType
+
+interface QueryResultBinderProvider {
+    fun provide(declared : DeclaredType, query: ParsedQuery) : QueryResultBinder
+    fun matches(declared: DeclaredType) : Boolean
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/TypeAdapterStore.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/TypeAdapterStore.kt
new file mode 100644
index 0000000..eca5986
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/TypeAdapterStore.kt
@@ -0,0 +1,448 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.EntityProcessor
+import android.arch.persistence.room.processor.FieldProcessor
+import android.arch.persistence.room.processor.PojoProcessor
+import android.arch.persistence.room.solver.binderprovider.CountedDataSourceQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.CursorQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.FlowableQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.InstantQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.LiveDataQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.LiveLazyListQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.RxMaybeQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.RxSingleQueryResultBinderProvider
+import android.arch.persistence.room.solver.query.parameter.ArrayQueryParameterAdapter
+import android.arch.persistence.room.solver.query.parameter.BasicQueryParameterAdapter
+import android.arch.persistence.room.solver.query.parameter.CollectionQueryParameterAdapter
+import android.arch.persistence.room.solver.query.parameter.QueryParameterAdapter
+import android.arch.persistence.room.solver.query.result.ArrayQueryResultAdapter
+import android.arch.persistence.room.solver.query.result.EntityRowAdapter
+import android.arch.persistence.room.solver.query.result.InstantQueryResultBinder
+import android.arch.persistence.room.solver.query.result.ListQueryResultAdapter
+import android.arch.persistence.room.solver.query.result.PojoRowAdapter
+import android.arch.persistence.room.solver.query.result.QueryResultAdapter
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import android.arch.persistence.room.solver.query.result.RowAdapter
+import android.arch.persistence.room.solver.query.result.SingleColumnRowAdapter
+import android.arch.persistence.room.solver.query.result.SingleEntityQueryResultAdapter
+import android.arch.persistence.room.solver.types.BoxedBooleanToBoxedIntConverter
+import android.arch.persistence.room.solver.types.BoxedPrimitiveColumnTypeAdapter
+import android.arch.persistence.room.solver.types.ByteArrayColumnTypeAdapter
+import android.arch.persistence.room.solver.types.ColumnTypeAdapter
+import android.arch.persistence.room.solver.types.CompositeAdapter
+import android.arch.persistence.room.solver.types.CompositeTypeConverter
+import android.arch.persistence.room.solver.types.CursorValueReader
+import android.arch.persistence.room.solver.types.NoOpConverter
+import android.arch.persistence.room.solver.types.PrimitiveBooleanToIntConverter
+import android.arch.persistence.room.solver.types.PrimitiveColumnTypeAdapter
+import android.arch.persistence.room.solver.types.StatementValueBinder
+import android.arch.persistence.room.solver.types.StringColumnTypeAdapter
+import android.arch.persistence.room.solver.types.TypeConverter
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.annotations.VisibleForTesting
+import java.util.LinkedList;
+import javax.lang.model.type.ArrayType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+/**
+ * Holds all type adapters and can create on demand composite type adapters to convert a type into a
+ * database column.
+ */
+class TypeAdapterStore private constructor(val context: Context,
+                                           /**
+                                            * first type adapter has the highest priority
+                                            */
+                                           private val columnTypeAdapters: List<ColumnTypeAdapter>,
+                                           /**
+                                            * first converter has the highest priority
+                                            */
+                                           private val typeConverters: List<TypeConverter>) {
+
+
+    companion object {
+        fun copy(context: Context, store: TypeAdapterStore): TypeAdapterStore {
+            return TypeAdapterStore(context = context,
+                    columnTypeAdapters = store.columnTypeAdapters,
+                    typeConverters = store.typeConverters)
+        }
+
+        fun create(context: Context, @VisibleForTesting vararg extras: Any): TypeAdapterStore {
+            val adapters = arrayListOf<ColumnTypeAdapter>()
+            val converters = arrayListOf<TypeConverter>()
+
+            fun addAny(extra: Any?) {
+                when (extra) {
+                    is TypeConverter -> converters.add(extra)
+                    is ColumnTypeAdapter -> adapters.add(extra)
+                    is List<*> -> extra.forEach(::addAny)
+                    else -> throw IllegalArgumentException("unknown extra $extra")
+                }
+            }
+
+            extras.forEach(::addAny)
+            fun addTypeConverter(converter: TypeConverter) {
+                converters.add(converter)
+            }
+
+            fun addColumnAdapter(adapter: ColumnTypeAdapter) {
+                adapters.add(adapter)
+            }
+
+            val primitives = PrimitiveColumnTypeAdapter
+                    .createPrimitiveAdapters(context.processingEnv)
+            primitives.forEach(::addColumnAdapter)
+            BoxedPrimitiveColumnTypeAdapter
+                    .createBoxedPrimitiveAdapters(context.processingEnv, primitives)
+                    .forEach(::addColumnAdapter)
+            addColumnAdapter(StringColumnTypeAdapter(context.processingEnv))
+            addColumnAdapter(ByteArrayColumnTypeAdapter(context.processingEnv))
+            PrimitiveBooleanToIntConverter.create(context.processingEnv).forEach(::addTypeConverter)
+            BoxedBooleanToBoxedIntConverter.create(context.processingEnv)
+                    .forEach(::addTypeConverter)
+            return TypeAdapterStore(context = context, columnTypeAdapters = adapters,
+                    typeConverters = converters)
+        }
+    }
+
+    val queryResultBinderProviders = listOf(
+            CursorQueryResultBinderProvider(context),
+            LiveDataQueryResultBinderProvider(context),
+            FlowableQueryResultBinderProvider(context),
+            RxMaybeQueryResultBinderProvider(context),
+            RxSingleQueryResultBinderProvider(context),
+            CountedDataSourceQueryResultBinderProvider(context),
+            LiveLazyListQueryResultBinderProvider(context),
+            InstantQueryResultBinderProvider(context)
+    )
+
+    // type mirrors that be converted into columns w/o an extra converter
+    private val knownColumnTypeMirrors by lazy {
+        columnTypeAdapters.map { it.out }
+    }
+
+    /**
+     * Searches 1 way to bind a value into a statement.
+     */
+    fun findStatementValueBinder(input: TypeMirror, affinity: SQLTypeAffinity?)
+            : StatementValueBinder? {
+        if (input.kind == TypeKind.ERROR) {
+            return null
+        }
+        val adapter = findDirectAdapterFor(input, affinity)
+        if (adapter != null) {
+            return adapter
+        }
+        val targetTypes = targetTypeMirrorsFor(affinity)
+        val binder = findTypeConverter(input, targetTypes) ?: return null
+        return CompositeAdapter(input, getAllColumnAdapters(binder.to).first(), binder, null)
+    }
+
+    /**
+     * Returns which entities targets the given affinity.
+     */
+    private fun targetTypeMirrorsFor(affinity: SQLTypeAffinity?): List<TypeMirror> {
+        val specifiedTargets = affinity?.getTypeMirrors(context.processingEnv)
+        return if (specifiedTargets == null || specifiedTargets.isEmpty()) {
+            knownColumnTypeMirrors
+        } else {
+            specifiedTargets
+        }
+    }
+
+    /**
+     * Searches 1 way to read it from cursor
+     */
+    fun findCursorValueReader(output: TypeMirror, affinity: SQLTypeAffinity?): CursorValueReader? {
+        if (output.kind == TypeKind.ERROR) {
+            return null
+        }
+        val adapter = findColumnTypeAdapter(output, affinity)
+        if (adapter != null) {
+            // two way is better
+            return adapter
+        }
+        // we could not find a two way version, search for anything
+        val targetTypes = targetTypeMirrorsFor(affinity)
+        val converter = findTypeConverter(targetTypes, output) ?: return null
+        return CompositeAdapter(output,
+                getAllColumnAdapters(converter.from).first(), null, converter)
+    }
+
+    /**
+     * Tries to reverse the converter going through the same nodes, if possible.
+     */
+    @VisibleForTesting
+    fun reverse(converter: TypeConverter): TypeConverter? {
+        return when (converter) {
+            is NoOpConverter -> converter
+            is CompositeTypeConverter -> {
+                val r1 = reverse(converter.conv1) ?: return null
+                val r2 = reverse(converter.conv2) ?: return null
+                CompositeTypeConverter(r2, r1)
+            }
+            else -> {
+                val types = context.processingEnv.typeUtils
+                typeConverters.firstOrNull {
+                    types.isSameType(it.from, converter.to) && types
+                            .isSameType(it.to, converter.from)
+                }
+            }
+        }
+    }
+
+    /**
+     * Finds a two way converter, if you need 1 way, use findStatementValueBinder or
+     * findCursorValueReader.
+     */
+    fun findColumnTypeAdapter(out: TypeMirror, affinity: SQLTypeAffinity?)
+            : ColumnTypeAdapter? {
+        if (out.kind == TypeKind.ERROR) {
+            return null
+        }
+        val adapter = findDirectAdapterFor(out, affinity)
+        if (adapter != null) {
+            return adapter
+        }
+        val targetTypes = targetTypeMirrorsFor(affinity)
+        val intoStatement = findTypeConverter(out, targetTypes) ?: return null
+        // ok found a converter, try the reverse now
+        val fromCursor = reverse(intoStatement) ?: findTypeConverter(intoStatement.to, out)
+                ?: return null
+        return CompositeAdapter(out, getAllColumnAdapters(intoStatement.to).first(), intoStatement,
+                fromCursor)
+    }
+
+    private fun findDirectAdapterFor(out: TypeMirror, affinity: SQLTypeAffinity?)
+            : ColumnTypeAdapter? {
+        val adapter = getAllColumnAdapters(out).firstOrNull {
+            affinity == null || it.typeAffinity == affinity
+        }
+        return adapter
+    }
+
+    fun findTypeConverter(input: TypeMirror, output: TypeMirror): TypeConverter? {
+        return findTypeConverter(listOf(input), listOf(output))
+    }
+
+    fun findQueryResultBinder(typeMirror: TypeMirror, query: ParsedQuery): QueryResultBinder {
+        return if (typeMirror.kind == TypeKind.DECLARED) {
+            val declared = MoreTypes.asDeclared(typeMirror)
+            return queryResultBinderProviders.first {
+                it.matches(declared)
+            }.provide(declared, query)
+        } else {
+            InstantQueryResultBinder(findQueryResultAdapter(typeMirror, query))
+        }
+    }
+
+    fun findQueryResultAdapter(typeMirror: TypeMirror, query: ParsedQuery)
+            : QueryResultAdapter? {
+        if (typeMirror.kind == TypeKind.ERROR) {
+            return null
+        }
+        if (typeMirror.kind == TypeKind.DECLARED) {
+            val declared = MoreTypes.asDeclared(typeMirror)
+            if (declared.typeArguments.isEmpty()) {
+                val rowAdapter = findRowAdapter(typeMirror, query) ?: return null
+                return SingleEntityQueryResultAdapter(rowAdapter)
+            }
+            if (MoreTypes.isTypeOf(java.util.List::class.java, typeMirror)) {
+                val typeArg = declared.typeArguments.first()
+                val rowAdapter = findRowAdapter(typeArg, query) ?: return null
+                return ListQueryResultAdapter(rowAdapter)
+            }
+            return null
+        } else if (typeMirror is ArrayType && typeMirror.componentType.kind != TypeKind.BYTE) {
+            val rowAdapter =
+                    findRowAdapter(typeMirror.componentType, query) ?: return null
+            return ArrayQueryResultAdapter(rowAdapter)
+        } else {
+            val rowAdapter = findRowAdapter(typeMirror, query) ?: return null
+            return SingleEntityQueryResultAdapter(rowAdapter)
+        }
+    }
+
+    /**
+     * Find a converter from cursor to the given type mirror.
+     * If there is information about the query result, we try to use it to accept *any* POJO.
+     */
+    @VisibleForTesting
+    fun findRowAdapter(typeMirror: TypeMirror, query: ParsedQuery): RowAdapter? {
+        if (typeMirror.kind == TypeKind.ERROR) {
+            return null
+        }
+        if (typeMirror.kind == TypeKind.DECLARED) {
+            val declared = MoreTypes.asDeclared(typeMirror)
+            if (declared.typeArguments.isNotEmpty()) {
+                // TODO one day support this
+                return null
+            }
+            val resultInfo = query.resultInfo
+
+            val (rowAdapter, rowAdapterLogs) = if (resultInfo != null && query.errors.isEmpty()
+                    && resultInfo.error == null) {
+                // if result info is not null, first try a pojo row adapter
+                context.collectLogs { subContext ->
+                    val pojo = PojoProcessor(
+                            baseContext = subContext,
+                            element = MoreTypes.asTypeElement(typeMirror),
+                            bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR,
+                            parent = null
+                    ).process()
+                    PojoRowAdapter(
+                            context = subContext,
+                            info = resultInfo,
+                            pojo = pojo,
+                            out = typeMirror)
+                }
+            } else {
+                Pair(null, null)
+            }
+
+            if (rowAdapter == null && query.resultInfo == null) {
+                // we don't know what query returns. Check for entity.
+                val asElement = MoreTypes.asElement(typeMirror)
+                if (asElement.hasAnnotation(Entity::class)) {
+                    return EntityRowAdapter(EntityProcessor(context,
+                            MoreElements.asType(asElement)).process())
+                }
+            }
+
+            if (rowAdapter != null && !(rowAdapterLogs?.hasErrors() ?: false)) {
+                rowAdapterLogs?.writeTo(context.processingEnv)
+                return rowAdapter
+            }
+
+            if ((resultInfo?.columns?.size ?: 1) == 1) {
+                val singleColumn = findCursorValueReader(typeMirror,
+                        resultInfo?.columns?.get(0)?.type)
+                if (singleColumn != null) {
+                    return SingleColumnRowAdapter(singleColumn)
+                }
+            }
+            // if we tried, return its errors
+            if (rowAdapter != null) {
+                rowAdapterLogs?.writeTo(context.processingEnv)
+                return rowAdapter
+            }
+            return null
+        } else {
+            val singleColumn = findCursorValueReader(typeMirror, null) ?: return null
+            return SingleColumnRowAdapter(singleColumn)
+        }
+    }
+
+    fun findQueryParameterAdapter(typeMirror: TypeMirror): QueryParameterAdapter? {
+        if (MoreTypes.isType(typeMirror)
+                && (MoreTypes.isTypeOf(java.util.List::class.java, typeMirror)
+                || MoreTypes.isTypeOf(java.util.Set::class.java, typeMirror))) {
+            val declared = MoreTypes.asDeclared(typeMirror)
+            val binder = findStatementValueBinder(declared.typeArguments.first(),
+                    null) ?: return null
+            return CollectionQueryParameterAdapter(binder)
+        } else if (typeMirror is ArrayType && typeMirror.componentType.kind != TypeKind.BYTE) {
+            val component = typeMirror.componentType
+            val binder = findStatementValueBinder(component, null) ?: return null
+            return ArrayQueryParameterAdapter(binder)
+        } else {
+            val binder = findStatementValueBinder(typeMirror, null) ?: return null
+            return BasicQueryParameterAdapter(binder)
+        }
+    }
+
+    private fun findTypeConverter(input: TypeMirror, outputs: List<TypeMirror>): TypeConverter? {
+        return findTypeConverter(listOf(input), outputs)
+    }
+
+    private fun findTypeConverter(input: List<TypeMirror>, output: TypeMirror): TypeConverter? {
+        return findTypeConverter(input, listOf(output))
+    }
+
+    private fun findTypeConverter(inputs: List<TypeMirror>, outputs: List<TypeMirror>)
+            : TypeConverter? {
+        if (inputs.isEmpty()) {
+            return null
+        }
+        val types = context.processingEnv.typeUtils
+        inputs.forEach { input ->
+            if (outputs.any { output -> types.isSameType(input, output) }) {
+                return NoOpConverter(input)
+            }
+        }
+
+        val excludes = arrayListOf<TypeMirror>()
+
+        val queue = LinkedList<TypeConverter>()
+        fun exactMatch(candidates: List<TypeConverter>)
+                : TypeConverter? {
+            return candidates.firstOrNull {
+                outputs.any { output -> types.isSameType(output, it.to) }
+            }
+        }
+        inputs.forEach { input ->
+            val candidates = getAllTypeConverters(input, excludes)
+            val match = exactMatch(candidates)
+            if (match != null) {
+                return match
+            }
+            candidates.forEach {
+                excludes.add(it.to)
+                queue.add(it)
+            }
+        }
+        excludes.addAll(inputs)
+        while (queue.isNotEmpty()) {
+            val prev = queue.pop()
+            val from = prev.to
+            val candidates = getAllTypeConverters(from, excludes)
+            val match = exactMatch(candidates)
+            if (match != null) {
+                return CompositeTypeConverter(prev, match)
+            }
+            candidates.forEach {
+                excludes.add(it.to)
+                queue.add(CompositeTypeConverter(prev, it))
+            }
+        }
+        return null
+    }
+
+    private fun getAllColumnAdapters(input: TypeMirror): List<ColumnTypeAdapter> {
+        return columnTypeAdapters.filter {
+            context.processingEnv.typeUtils.isSameType(input, it.out)
+        }
+    }
+
+    private fun getAllTypeConverters(input: TypeMirror, excludes: List<TypeMirror>):
+            List<TypeConverter> {
+        val types = context.processingEnv.typeUtils
+        return typeConverters.filter { converter ->
+            types.isSameType(input, converter.from) &&
+                    !excludes.any { types.isSameType(it, converter.to) }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CountedDataSourceQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CountedDataSourceQueryResultBinderProvider.kt
new file mode 100644
index 0000000..c23e31f
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CountedDataSourceQueryResultBinderProvider.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.PagingTypeNames
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.CountedDataSourceQueryResultBinder
+import android.arch.persistence.room.solver.query.result.ListQueryResultAdapter
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.google.common.annotations.VisibleForTesting
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+
+class CountedDataSourceQueryResultBinderProvider(val context: Context) : QueryResultBinderProvider {
+    private val countedDataSourceTypeMirror: TypeMirror? by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(PagingTypeNames.COUNTED_DATA_SOURCE.toString())?.asType()
+    }
+
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        val typeArg = declared.typeArguments.first()
+        val listAdapter = context.typeAdapterStore.findRowAdapter(typeArg, query)?.let {
+            ListQueryResultAdapter(it)
+        }
+        return CountedDataSourceQueryResultBinder(listAdapter, query.tables.map { it.name })
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+            declared.typeArguments.size == 1 && isCountedDataSource(declared)
+
+    private fun isCountedDataSource(declared: DeclaredType): Boolean {
+        if (countedDataSourceTypeMirror == null) {
+            return false
+        }
+        val erasure = context.processingEnv.typeUtils.erasure(declared)
+        return context.processingEnv.typeUtils.isAssignable(countedDataSourceTypeMirror
+                , erasure)
+    }
+
+
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CursorQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CursorQueryResultBinderProvider.kt
new file mode 100644
index 0000000..e160672
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/CursorQueryResultBinderProvider.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.CursorQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.DeclaredType
+
+class CursorQueryResultBinderProvider(val context: Context) : QueryResultBinderProvider {
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        return CursorQueryResultBinder()
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+        declared.typeArguments.size == 0 && TypeName.get(declared) == AndroidTypeNames.CURSOR
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/FlowableQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/FlowableQueryResultBinderProvider.kt
new file mode 100644
index 0000000..828f5a7
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/FlowableQueryResultBinderProvider.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.RoomRxJava2TypeNames
+import android.arch.persistence.room.ext.RxJava2TypeNames
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.ProcessorErrors
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.FlowableQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.google.common.annotations.VisibleForTesting
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+
+class FlowableQueryResultBinderProvider(val context : Context) : QueryResultBinderProvider {
+    private val flowableTypeMirror: TypeMirror? by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(RxJava2TypeNames.FLOWABLE.toString())?.asType()
+    }
+
+    private val hasRxJava2Artifact by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(RoomRxJava2TypeNames.RX_ROOM.toString()) != null
+    }
+
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        val typeArg = declared.typeArguments.first()
+        return FlowableQueryResultBinder(typeArg, query.tables.map { it.name },
+                context.typeAdapterStore.findQueryResultAdapter(typeArg, query))
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+            declared.typeArguments.size == 1 && isRxJava2Publisher(declared)
+
+    private fun isRxJava2Publisher(declared: DeclaredType): Boolean {
+        if (flowableTypeMirror == null) {
+            return false
+        }
+        val erasure = context.processingEnv.typeUtils.erasure(declared)
+        val match = context.processingEnv.typeUtils.isAssignable(flowableTypeMirror, erasure)
+        if (match && !hasRxJava2Artifact) {
+            context.logger.e(ProcessorErrors.MISSING_ROOM_RXJAVA2_ARTIFACT)
+        }
+        return match
+    }
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/InstantQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/InstantQueryResultBinderProvider.kt
new file mode 100644
index 0000000..af03a88
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/InstantQueryResultBinderProvider.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.InstantQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import javax.lang.model.type.DeclaredType
+
+class InstantQueryResultBinderProvider(val context : Context) : QueryResultBinderProvider {
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        return InstantQueryResultBinder(
+                context.typeAdapterStore.findQueryResultAdapter(declared, query))
+    }
+
+    override fun matches(declared: DeclaredType): Boolean = true
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveDataQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveDataQueryResultBinderProvider.kt
new file mode 100644
index 0000000..2aee5d2
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveDataQueryResultBinderProvider.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.LifecyclesTypeNames
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.LiveDataQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.google.common.annotations.VisibleForTesting
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+
+class LiveDataQueryResultBinderProvider(val context : Context) : QueryResultBinderProvider {
+    private val liveDataTypeMirror: TypeMirror? by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(LifecyclesTypeNames.LIVE_DATA.toString())?.asType()
+    }
+
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        val liveDataTypeArg = declared.typeArguments.first()
+        return LiveDataQueryResultBinder(liveDataTypeArg, query.tables.map { it.name },
+                context.typeAdapterStore.findQueryResultAdapter(liveDataTypeArg, query))
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+            declared.typeArguments.size == 1 && isLiveData(declared)
+
+    private fun isLiveData(declared: DeclaredType): Boolean {
+        if (liveDataTypeMirror == null) {
+            return false
+        }
+        val erasure = context.processingEnv.typeUtils.erasure(declared)
+        return context.processingEnv.typeUtils.isAssignable(liveDataTypeMirror, erasure)
+    }
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveLazyListQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveLazyListQueryResultBinderProvider.kt
new file mode 100644
index 0000000..c931d69
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/LiveLazyListQueryResultBinderProvider.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.PagingTypeNames
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.CountedDataSourceQueryResultBinder
+import android.arch.persistence.room.solver.query.result.ListQueryResultAdapter
+import android.arch.persistence.room.solver.query.result.LiveLazyListQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.google.common.annotations.VisibleForTesting
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeMirror
+
+class LiveLazyListQueryResultBinderProvider(val context: Context) : QueryResultBinderProvider {
+    private val livePagedListTypeMirror: TypeMirror? by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(PagingTypeNames.LIVE_LAZY_LIST_PROVIDER.toString())?.asType()
+    }
+
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        val typeArg = declared.typeArguments.first()
+        val listAdapter = context.typeAdapterStore.findRowAdapter(typeArg, query)?.let {
+            ListQueryResultAdapter(it)
+        }
+        val countedBinder = CountedDataSourceQueryResultBinder(listAdapter,
+                query.tables.map { it.name })
+        return LiveLazyListQueryResultBinder(countedBinder)
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+            declared.typeArguments.size == 1 && isLivePagedList(declared)
+
+    private fun isLivePagedList(declared: DeclaredType): Boolean {
+        if (livePagedListTypeMirror == null) {
+            return false
+        }
+        val erasure = context.processingEnv.typeUtils.erasure(declared)
+        // we don't want to return paged list unless explicitly requested
+        return context.processingEnv.typeUtils.isAssignable(livePagedListTypeMirror, erasure)
+    }
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/RxCallableQueryResultBinderProvider.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/RxCallableQueryResultBinderProvider.kt
new file mode 100644
index 0000000..84c71eb
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/binderprovider/RxCallableQueryResultBinderProvider.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.binderprovider
+
+import android.arch.persistence.room.ext.RoomRxJava2TypeNames
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.ProcessorErrors
+import android.arch.persistence.room.solver.QueryResultBinderProvider
+import android.arch.persistence.room.solver.query.result.InstantQueryResultBinder
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import android.arch.persistence.room.solver.query.result.RxCallableQueryResultBinder
+import javax.lang.model.type.DeclaredType
+
+sealed class RxCallableQueryResultBinderProvider(val context: Context,
+                                                 val rxType: RxCallableQueryResultBinder.RxType)
+    : QueryResultBinderProvider {
+    private val hasRxJava2Artifact by lazy {
+        context.processingEnv.elementUtils
+                .getTypeElement(RoomRxJava2TypeNames.RX_ROOM.toString()) != null
+    }
+
+    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
+        val typeArg = declared.typeArguments.first()
+        val adapter = context.typeAdapterStore.findQueryResultAdapter(typeArg, query)
+        return RxCallableQueryResultBinder(rxType,
+                typeArg, InstantQueryResultBinder(adapter), adapter)
+    }
+
+    override fun matches(declared: DeclaredType): Boolean =
+            declared.typeArguments.size == 1 && matchesRxType(declared)
+
+    private fun matchesRxType(declared: DeclaredType): Boolean {
+        val erasure = context.processingEnv.typeUtils.erasure(declared)
+        val match = erasure.typeName() == rxType.className
+        if (match && !hasRxJava2Artifact) {
+            context.logger.e(ProcessorErrors.MISSING_ROOM_RXJAVA2_ARTIFACT)
+        }
+        return match
+    }
+}
+
+class RxSingleQueryResultBinderProvider(context: Context)
+    : RxCallableQueryResultBinderProvider(context, RxCallableQueryResultBinder.RxType.SINGLE)
+
+class RxMaybeQueryResultBinderProvider(context: Context)
+    : RxCallableQueryResultBinderProvider(context, RxCallableQueryResultBinder.RxType.MAYBE)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/ArrayQueryParameterAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/ArrayQueryParameterAdapter.kt
new file mode 100644
index 0000000..9cafb23
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/ArrayQueryParameterAdapter.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.parameter
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.solver.types.StatementValueBinder
+import com.squareup.javapoet.TypeName
+
+/**
+ * Binds ARRAY(T) (e.g. int[]) into String[] args of a query.
+ */
+class ArrayQueryParameterAdapter(val bindAdapter : StatementValueBinder)
+            : QueryParameterAdapter(true) {
+    override fun bindToStmt(inputVarName: String, stmtVarName: String, startIndexVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            val itrVar = scope.getTmpVar("_item")
+            beginControlFlow("for ($T $L : $L)", bindAdapter.typeMirror().typeName(), itrVar,
+                    inputVarName).apply {
+                        bindAdapter.bindToStmt(stmtVarName, startIndexVarName, itrVar, scope)
+                        addStatement("$L ++", startIndexVarName)
+            }
+            endControlFlow()
+        }
+    }
+
+    override fun getArgCount(inputVarName: String, outputVarName : String, scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("final $T $L = $L.length", TypeName.INT, outputVarName, inputVarName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/BasicQueryParameterAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/BasicQueryParameterAdapter.kt
new file mode 100644
index 0000000..11521f2
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/BasicQueryParameterAdapter.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.parameter
+
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.solver.types.StatementValueBinder
+
+/**
+ * Knows how to convert a query parameter into arguments
+ */
+class BasicQueryParameterAdapter(val bindAdapter : StatementValueBinder)
+            : QueryParameterAdapter(false) {
+    override fun bindToStmt(inputVarName: String, stmtVarName: String, startIndexVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            bindAdapter.bindToStmt(stmtVarName, startIndexVarName, inputVarName, scope)
+        }
+    }
+
+    override fun getArgCount(inputVarName: String, outputVarName : String, scope: CodeGenScope) {
+        throw UnsupportedOperationException("should not call getArgCount on basic adapters." +
+                "It is always one.")
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/CollectionQueryParameterAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/CollectionQueryParameterAdapter.kt
new file mode 100644
index 0000000..7e0b206
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/CollectionQueryParameterAdapter.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.parameter
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.solver.types.StatementValueBinder
+import com.squareup.javapoet.TypeName
+
+/**
+ * Binds Collection<T> (e.g. List<T>) into String[] query args.
+ */
+class CollectionQueryParameterAdapter(val bindAdapter : StatementValueBinder)
+            : QueryParameterAdapter(true) {
+    override fun bindToStmt(inputVarName: String, stmtVarName: String, startIndexVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            val itrVar = scope.getTmpVar("_item")
+            beginControlFlow("for ($T $L : $L)", bindAdapter.typeMirror().typeName(), itrVar,
+                    inputVarName).apply {
+                        bindAdapter.bindToStmt(stmtVarName, startIndexVarName, itrVar, scope)
+                        addStatement("$L ++", startIndexVarName)
+                    }
+            endControlFlow()
+        }
+    }
+
+    override fun getArgCount(inputVarName: String, outputVarName : String, scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("final $T $L = $L.size()", TypeName.INT, outputVarName, inputVarName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/QueryParameterAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/QueryParameterAdapter.kt
new file mode 100644
index 0000000..b93659e
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/parameter/QueryParameterAdapter.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.parameter
+
+import android.arch.persistence.room.solver.CodeGenScope
+
+/**
+ * Knows how to convert a query parameter into query arguments.
+ */
+abstract class QueryParameterAdapter(val isMultiple: Boolean) {
+    /**
+     * Must bind the value into the statement at the given index.
+     */
+    abstract fun bindToStmt(inputVarName: String, stmtVarName: String, startIndexVarName: String,
+                         scope: CodeGenScope)
+
+    /**
+     * Should declare and set the given value with the count
+     */
+    abstract fun getArgCount(inputVarName: String, outputVarName : String, scope : CodeGenScope)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ArrayQueryResultAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ArrayQueryResultAdapter.kt
new file mode 100644
index 0000000..e8330bc
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ArrayQueryResultAdapter.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.TypeName
+
+class ArrayQueryResultAdapter(rowAdapter: RowAdapter) : QueryResultAdapter(rowAdapter) {
+    val type = rowAdapter.out
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            rowAdapter?.onCursorReady(cursorVarName, scope)
+
+            val arrayType = ArrayTypeName.of(type.typeName())
+            addStatement("final $T $L = new $T[$L.getCount()]",
+                    arrayType, outVarName, type.typeName(), cursorVarName)
+            val tmpVarName = scope.getTmpVar("_item")
+            val indexVar = scope.getTmpVar("_index")
+            addStatement("$T $L = 0", TypeName.INT, indexVar)
+            beginControlFlow("while($L.moveToNext())", cursorVarName).apply {
+                addStatement("final $T $L", type.typeName(), tmpVarName)
+                rowAdapter?.convert(tmpVarName, cursorVarName, scope)
+                addStatement("$L[$L] = $L", outVarName, indexVar, tmpVarName)
+                addStatement("$L ++", indexVar)
+            }
+            endControlFlow()
+            rowAdapter?.onCursorFinished()?.invoke(scope)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/BaseObservableQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/BaseObservableQueryResultBinder.kt
new file mode 100644
index 0000000..7872c33
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/BaseObservableQueryResultBinder.kt
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.writer.DaoWriter
+import com.squareup.javapoet.MethodSpec
+import javax.lang.model.element.Modifier
+
+/**
+ * Base class for query result binders that observe the database. It includes common functionality
+ * like creating a finalizer to release the query or creating the actual adapter call code.
+ */
+abstract class BaseObservableQueryResultBinder(adapter: QueryResultAdapter?)
+    : QueryResultBinder(adapter) {
+
+    protected fun createFinalizeMethod(roomSQLiteQueryVar: String): MethodSpec {
+        return MethodSpec.methodBuilder("finalize").apply {
+            addModifiers(Modifier.PROTECTED)
+            addAnnotation(Override::class.java)
+            addStatement("$L.release()", roomSQLiteQueryVar)
+        }.build()
+    }
+
+    protected fun createRunQueryAndReturnStatements(builder: MethodSpec.Builder,
+                                                    roomSQLiteQueryVar: String,
+                                                    scope: CodeGenScope) {
+        val outVar = scope.getTmpVar("_result")
+        val cursorVar = scope.getTmpVar("_cursor")
+        builder.apply {
+            addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar,
+                    DaoWriter.dbField, roomSQLiteQueryVar)
+            beginControlFlow("try").apply {
+                val adapterScope = scope.fork()
+                adapter?.convert(outVar, cursorVar, adapterScope)
+                addCode(adapterScope.builder().build())
+                addStatement("return $L", outVar)
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$L.close()", cursorVar)
+            }
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CountedDataSourceQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CountedDataSourceQueryResultBinder.kt
new file mode 100644
index 0000000..f91a09a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CountedDataSourceQueryResultBinder.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.CommonTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+
+class CountedDataSourceQueryResultBinder(val listAdapter : ListQueryResultAdapter?,
+                                         val tableNames : List<String>)
+            : QueryResultBinder(listAdapter) {
+    val itemTypeName : TypeName = listAdapter?.rowAdapter?.out?.typeName() ?: TypeName.OBJECT
+    val typeName : ParameterizedTypeName = ParameterizedTypeName.get(
+            RoomTypeNames.LIMIT_OFFSET_DATA_SOURCE, itemTypeName)
+    override fun convertAndReturn(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        val tableNamesList = tableNames.joinToString(",") { "\"$it\"" }
+        val spec = TypeSpec.anonymousClassBuilder("$N, $L, $L",
+                dbField, roomSQLiteQueryVar, tableNamesList).apply {
+            superclass(typeName)
+            addMethod(createConvertRowsMethod(scope))
+        }.build()
+        scope.builder().apply {
+            addStatement("return $L", spec)
+        }
+    }
+
+    fun createConvertRowsMethod(scope : CodeGenScope): MethodSpec =
+            MethodSpec.methodBuilder("convertRows").apply {
+                addAnnotation(Override::class.java)
+                addModifiers(Modifier.PROTECTED)
+                returns(ParameterizedTypeName.get(CommonTypeNames.LIST, itemTypeName))
+                val cursorParam = ParameterSpec.builder(AndroidTypeNames.CURSOR, "cursor")
+                        .build()
+                addParameter(cursorParam)
+                val resultVar = scope.getTmpVar("_res")
+                val rowsScope = scope.fork()
+                listAdapter?.convert(resultVar, cursorParam.name, rowsScope)
+                addCode(rowsScope.builder().build())
+                addStatement("return $L", resultVar)
+            }.build()
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CursorQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CursorQueryResultBinder.kt
new file mode 100644
index 0000000..cd8ea74
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/CursorQueryResultBinder.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.writer.DaoWriter
+import com.squareup.javapoet.FieldSpec
+
+class CursorQueryResultBinder : QueryResultBinder(NO_OP_RESULT_ADAPTER) {
+    override fun convertAndReturn(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        scope.builder().apply {
+            addStatement("return $N.query($L)", DaoWriter.dbField, roomSQLiteQueryVar)
+        }
+    }
+    companion object {
+        private val NO_OP_RESULT_ADAPTER = object : QueryResultAdapter(null) {
+            override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/EntityRowAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/EntityRowAdapter.kt
new file mode 100644
index 0000000..c97f69e
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/EntityRowAdapter.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.writer.EntityCursorConverterWriter
+import com.squareup.javapoet.MethodSpec
+
+class EntityRowAdapter(val entity: Entity) : RowAdapter(entity.type) {
+    lateinit var methodSpec: MethodSpec
+    override fun onCursorReady(cursorVarName: String, scope: CodeGenScope) {
+        methodSpec = scope.writer.getOrCreateMethod(EntityCursorConverterWriter(entity))
+    }
+
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L = $N($L)", outVarName, methodSpec, cursorVarName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/FlowableQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/FlowableQueryResultBinder.kt
new file mode 100644
index 0000000..dbd66ce
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/FlowableQueryResultBinder.kt
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomRxJava2TypeNames
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.arrayTypeName
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.writer.DaoWriter
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Binds the result as an RxJava2 Flowable.
+ */
+class FlowableQueryResultBinder(val typeArg: TypeMirror, val queryTableNames: List<String>,
+                                adapter: QueryResultAdapter?)
+    : BaseObservableQueryResultBinder(adapter) {
+    override fun convertAndReturn(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        val callableImpl = TypeSpec.anonymousClassBuilder("").apply {
+            val typeName = typeArg.typeName()
+            superclass(ParameterizedTypeName.get(java.util.concurrent.Callable::class.typeName(),
+                    typeName))
+            addMethod(MethodSpec.methodBuilder("call").apply {
+                returns(typeName)
+                addException(Exception::class.typeName())
+                addModifiers(Modifier.PUBLIC)
+                createRunQueryAndReturnStatements(this, roomSQLiteQueryVar, scope)
+            }.build())
+            addMethod(createFinalizeMethod(roomSQLiteQueryVar))
+        }.build()
+        scope.builder().apply {
+            val tableNamesList = queryTableNames.joinToString(",") { "\"$it\"" }
+            addStatement("return $T.createFlowable($N, new $T{$L}, $L)",
+                    RoomRxJava2TypeNames.RX_ROOM, DaoWriter.dbField,
+                    String::class.arrayTypeName(), tableNamesList, callableImpl)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/InstantQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/InstantQueryResultBinder.kt
new file mode 100644
index 0000000..ff15252
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/InstantQueryResultBinder.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.writer.DaoWriter
+import com.squareup.javapoet.FieldSpec
+
+/**
+ * Instantly runs and returns the query.
+ */
+class InstantQueryResultBinder(adapter: QueryResultAdapter?) : QueryResultBinder(adapter) {
+    override fun convertAndReturn(roomSQLiteQueryVar : String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        scope.builder().apply {
+            val outVar = scope.getTmpVar("_result")
+            val cursorVar = scope.getTmpVar("_cursor")
+            addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar,
+                    DaoWriter.dbField, roomSQLiteQueryVar)
+            beginControlFlow("try").apply {
+                adapter?.convert(outVar, cursorVar, scope)
+                addStatement("return $L", outVar)
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$L.close()", cursorVar)
+                addStatement("$L.release()", roomSQLiteQueryVar)
+            }
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ListQueryResultAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ListQueryResultAdapter.kt
new file mode 100644
index 0000000..b70ec5a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/ListQueryResultAdapter.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.ParameterizedTypeName
+import java.util.ArrayList
+
+class ListQueryResultAdapter(rowAdapter: RowAdapter) : QueryResultAdapter(rowAdapter) {
+    val type = rowAdapter.out
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            rowAdapter?.onCursorReady(cursorVarName, scope)
+            val collectionType = ParameterizedTypeName
+                    .get(ClassName.get(List::class.java), type.typeName())
+            val arrayListType = ParameterizedTypeName
+                    .get(ClassName.get(ArrayList::class.java), type.typeName())
+            addStatement("final $T $L = new $T($L.getCount())",
+                    collectionType, outVarName, arrayListType, cursorVarName)
+            val tmpVarName = scope.getTmpVar("_item")
+            beginControlFlow("while($L.moveToNext())", cursorVarName).apply {
+                addStatement("final $T $L", type.typeName(), tmpVarName)
+                rowAdapter?.convert(tmpVarName, cursorVarName, scope)
+                addStatement("$L.add($L)", outVarName, tmpVarName)
+            }
+            endControlFlow()
+            rowAdapter?.onCursorFinished()?.invoke(scope)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveDataQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveDataQueryResultBinder.kt
new file mode 100644
index 0000000..4c9b0ca
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveDataQueryResultBinder.kt
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.LifecyclesTypeNames
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.RoomTypeNames.INVALIDATION_OBSERVER
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import android.support.annotation.NonNull
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Converts the query into a LiveData and returns it. No query is run until necessary.
+ */
+class LiveDataQueryResultBinder(val typeArg: TypeMirror, queryTableNames: List<String>,
+                                adapter: QueryResultAdapter?)
+    : BaseObservableQueryResultBinder(adapter) {
+    @Suppress("JoinDeclarationAndAssignment")
+    val tableNames = ((adapter?.accessedTableNames() ?: emptyList()) + queryTableNames).toSet()
+    override fun convertAndReturn(roomSQLiteQueryVar : String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        val typeName = typeArg.typeName()
+
+        val liveDataImpl = TypeSpec.anonymousClassBuilder("").apply {
+            superclass(ParameterizedTypeName.get(LifecyclesTypeNames.COMPUTABLE_LIVE_DATA,
+                    typeName))
+            val observerField = FieldSpec.builder(RoomTypeNames.INVALIDATION_OBSERVER,
+                    scope.getTmpVar("_observer"), Modifier.PRIVATE).build()
+            addField(observerField)
+            addMethod(createComputeMethod(
+                    observerField = observerField,
+                    typeName = typeName,
+                    roomSQLiteQueryVar = roomSQLiteQueryVar,
+                    dbField = dbField,
+                    scope = scope
+            ))
+            addMethod(createFinalizeMethod(roomSQLiteQueryVar))
+        }.build()
+        scope.builder().apply {
+            addStatement("return $L.getLiveData()", liveDataImpl)
+        }
+    }
+
+    private fun createComputeMethod(roomSQLiteQueryVar: String, typeName: TypeName,
+                                    observerField: FieldSpec, dbField: FieldSpec,
+                                    scope: CodeGenScope): MethodSpec {
+        return MethodSpec.methodBuilder("compute").apply {
+            addAnnotation(Override::class.java)
+            addModifiers(Modifier.PROTECTED)
+            returns(typeName)
+
+            beginControlFlow("if ($N == null)", observerField).apply {
+                addStatement("$N = $L", observerField, createAnonymousObserver())
+                addStatement("$N.getInvalidationTracker().addWeakObserver($N)",
+                        dbField, observerField)
+            }
+            endControlFlow()
+
+            createRunQueryAndReturnStatements(this, roomSQLiteQueryVar, scope)
+        }.build()
+    }
+
+    private fun createAnonymousObserver(): TypeSpec {
+        val tableNamesList = tableNames.joinToString(",") { "\"$it\"" }
+        return TypeSpec.anonymousClassBuilder(tableNamesList).apply {
+            superclass(INVALIDATION_OBSERVER)
+            addMethod(MethodSpec.methodBuilder("onInvalidated").apply {
+                returns(TypeName.VOID)
+                addAnnotation(Override::class.java)
+                addParameter(ParameterSpec.builder(
+                        ParameterizedTypeName.get(Set::class.java, String::class.java), "tables")
+                        .addAnnotation(NonNull::class.java)
+                        .build())
+                addModifiers(Modifier.PUBLIC)
+                addStatement("invalidate()")
+            }.build())
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveLazyListQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveLazyListQueryResultBinder.kt
new file mode 100644
index 0000000..c46698b
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/LiveLazyListQueryResultBinder.kt
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.PagingTypeNames
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+
+class LiveLazyListQueryResultBinder(
+        val countedDataSourceQueryResultBinder: CountedDataSourceQueryResultBinder)
+    : QueryResultBinder(countedDataSourceQueryResultBinder.listAdapter) {
+    @Suppress("HasPlatformType")
+    val typeName = countedDataSourceQueryResultBinder.itemTypeName
+    override fun convertAndReturn(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        scope.builder().apply {
+            val lazyListProvider = TypeSpec
+                    .anonymousClassBuilder("").apply {
+                superclass(ParameterizedTypeName.get(PagingTypeNames.LIVE_LAZY_LIST_PROVIDER,
+                        typeName))
+                addMethod(createCreateDataSourceMethod(roomSQLiteQueryVar, dbField, scope))
+            }.build()
+            addStatement("return $L", lazyListProvider)
+        }
+    }
+
+    private fun createCreateDataSourceMethod(roomSQLiteQueryVar: String,
+                                             dbField: FieldSpec,
+                                             scope: CodeGenScope): MethodSpec
+            = MethodSpec.methodBuilder("createDataSource").apply {
+        addAnnotation(Override::class.java)
+        addModifiers(Modifier.PROTECTED)
+        returns(countedDataSourceQueryResultBinder.typeName)
+        val countedBinderScope = scope.fork()
+        countedDataSourceQueryResultBinder.convertAndReturn(roomSQLiteQueryVar, dbField,
+                countedBinderScope)
+        addCode(countedBinderScope.builder().build())
+    }.build()
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/PojoRowAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/PojoRowAdapter.kt
new file mode 100644
index 0000000..062b179
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/PojoRowAdapter.kt
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.ProcessorErrors
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.verifier.QueryResultInfo
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.FieldWithIndex
+import android.arch.persistence.room.vo.Pojo
+import android.arch.persistence.room.vo.RelationCollector
+import android.arch.persistence.room.vo.Warning
+import android.arch.persistence.room.writer.FieldReadWriteWriter
+import com.squareup.javapoet.TypeName
+import stripNonJava
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Creates the entity from the given info.
+ * <p>
+ * The info comes from the query processor so we know about the order of columns in the result etc.
+ */
+class PojoRowAdapter(context: Context, val info: QueryResultInfo,
+                     val pojo: Pojo, out: TypeMirror) : RowAdapter(out) {
+    val mapping: Mapping
+    val relationCollectors: List<RelationCollector>
+
+    init {
+        // toMutableList documentation is not clear if it copies so lets be safe.
+        val remainingFields = pojo.fields.mapTo(mutableListOf<Field>(), { it })
+        val unusedColumns = arrayListOf<String>()
+        val matchedFields = info.columns.map { column ->
+            // first check remaining, otherwise check any. maybe developer wants to map the same
+            // column into 2 fields. (if they want to post process etc)
+            val field = remainingFields.firstOrNull { it.columnName == column.name } ?:
+                    pojo.fields.firstOrNull { it.columnName == column.name }
+            if (field == null) {
+                unusedColumns.add(column.name)
+                null
+            } else {
+                remainingFields.remove(field)
+                field
+            }
+        }.filterNotNull()
+        if (unusedColumns.isNotEmpty() || remainingFields.isNotEmpty()) {
+            val warningMsg = ProcessorErrors.cursorPojoMismatch(
+                    pojoTypeName = pojo.typeName,
+                    unusedColumns = unusedColumns,
+                    allColumns = info.columns.map { it.name },
+                    unusedFields = remainingFields,
+                    allFields = pojo.fields
+            )
+            context.logger.w(Warning.CURSOR_MISMATCH, null, warningMsg)
+        }
+        if (matchedFields.isEmpty()) {
+            context.logger.e(ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER)
+        }
+
+        relationCollectors = RelationCollector.createCollectors(context, pojo.relations)
+
+        mapping = Mapping(
+                matchedFields = matchedFields,
+                unusedColumns = unusedColumns,
+                unusedFields = remainingFields
+        )
+    }
+
+    fun relationTableNames(): List<String> {
+        return relationCollectors.flatMap {
+            val queryTableNames = it.loadAllQuery.tables.map { it.name }
+            if (it.rowAdapter is PojoRowAdapter) {
+                it.rowAdapter.relationTableNames() + queryTableNames
+            } else {
+                queryTableNames
+            }
+        }.distinct()
+    }
+
+    override fun onCursorReady(cursorVarName: String, scope: CodeGenScope) {
+        relationCollectors.forEach { it.writeInitCode(scope) }
+        mapping.fieldsWithIndices = mapping.matchedFields.map {
+            val indexVar = scope.getTmpVar("_cursorIndexOf${it.name.stripNonJava().capitalize()}")
+            scope.builder().addStatement("final $T $L = $L.getColumnIndexOrThrow($S)",
+                    TypeName.INT, indexVar, cursorVarName, it.columnName)
+            FieldWithIndex(field = it, indexVar = indexVar, alwaysExists = true)
+        }
+    }
+
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            FieldReadWriteWriter.readFromCursor(
+                    outVar = outVarName,
+                    outPojo = pojo,
+                    cursorVar = cursorVarName,
+                    fieldsWithIndices = mapping.fieldsWithIndices,
+                    relationCollectors = relationCollectors,
+                    scope = scope)
+        }
+    }
+
+    override fun onCursorFinished(): ((CodeGenScope) -> Unit)? =
+            if (relationCollectors.isEmpty()) {
+                // it is important to return empty to notify that we don't need any post process
+                // task
+                null
+            } else {
+                { scope ->
+                    relationCollectors.forEach { collector ->
+                        collector.writeCollectionCode(scope)
+                    }
+                }
+            }
+
+    data class Mapping(val matchedFields: List<Field>,
+                       val unusedColumns: List<String>,
+                       val unusedFields: List<Field>) {
+        // set when cursor is ready.
+        lateinit var fieldsWithIndices: List<FieldWithIndex>
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultAdapter.kt
new file mode 100644
index 0000000..aaf17cd
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultAdapter.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.solver.CodeGenScope
+
+/**
+ * Gets a Cursor and converts it into the return type of a method annotated with @Query.
+ */
+abstract class QueryResultAdapter(val rowAdapter : RowAdapter?) {
+    abstract fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope)
+    fun accessedTableNames(): List<String> {
+        return (rowAdapter as? PojoRowAdapter)?.relationTableNames() ?: emptyList<String>()
+    }
+
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultBinder.kt
new file mode 100644
index 0000000..205bd88
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/QueryResultBinder.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.FieldSpec
+
+/**
+ * Connects the query, db and the ResultAdapter.
+ * <p>
+ * The default implementation is InstantResultBinder. If the query is deferred rather than executed
+ * directly, such alternative implementations can be implement using this interface (e.g. LiveData,
+ * Rx, caching etc)
+ */
+abstract class QueryResultBinder(val adapter: QueryResultAdapter?) {
+    /**
+     * receives the sql, bind args and adapter and generates the code that runs the query
+     * and returns the result.
+     */
+    abstract fun convertAndReturn(roomSQLiteQueryVar: String,
+                                  dbField: FieldSpec, scope: CodeGenScope)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RowAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RowAdapter.kt
new file mode 100644
index 0000000..581baf2
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RowAdapter.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Converts a row of a cursor result into an Entity or a primitive.
+ * <p>
+ * An instance of this is created for each usage so that it can keep local variables.
+ */
+abstract class RowAdapter(val out : TypeMirror) {
+    /**
+     * Called when cursor variable is ready, good place to put initialization code.
+     */
+    open fun onCursorReady(cursorVarName: String, scope : CodeGenScope) {}
+
+    /**
+     * Called to convert a single row.
+     */
+    abstract fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope)
+
+    /**
+     * Called when the cursor is finished. It is important to return null if no operation is
+     * necessary so that caller can understand that we can do lazy loading.
+     */
+    open fun onCursorFinished() : ((scope : CodeGenScope) -> Unit)? = null
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RxCallableQueryResultBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RxCallableQueryResultBinder.kt
new file mode 100644
index 0000000..da960f6
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/RxCallableQueryResultBinder.kt
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomRxJava2TypeNames
+import android.arch.persistence.room.ext.RxJava2TypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Generic Result binder for Rx classes that accept a callable.
+ */
+class RxCallableQueryResultBinder(val rxType: RxType,
+                                  val typeArg: TypeMirror,
+                                  val instantBinder : InstantQueryResultBinder,
+                                  adapter: QueryResultAdapter?) : QueryResultBinder(adapter) {
+    override fun convertAndReturn(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                                  scope: CodeGenScope) {
+        val callable = TypeSpec.anonymousClassBuilder("").apply {
+            val typeName = typeArg.typeName()
+            superclass(ParameterizedTypeName.get(java.util.concurrent.Callable::class.typeName(),
+                    typeName))
+            addMethod(createCallMethod(roomSQLiteQueryVar, dbField, scope))
+        }.build()
+        scope.builder().apply {
+            addStatement("return $T.fromCallable($L)", rxType.className, callable)
+        }
+    }
+
+    fun createCallMethod(roomSQLiteQueryVar: String, dbField: FieldSpec,
+                         scope: CodeGenScope): MethodSpec {
+        val adapterScope = scope.fork()
+        return MethodSpec.methodBuilder("call").apply {
+            returns(typeArg.typeName())
+            addException(Exception::class.typeName())
+            addModifiers(Modifier.PUBLIC)
+            val outVar = scope.getTmpVar("_result")
+            val cursorVar = scope.getTmpVar("_cursor")
+            addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar,
+                    dbField, roomSQLiteQueryVar)
+            beginControlFlow("try").apply {
+                adapter?.convert(outVar, cursorVar, adapterScope)
+                addCode(adapterScope.generate())
+                if (!rxType.canBeNull) {
+                    beginControlFlow("if($L == null)", outVar).apply {
+                        addStatement("throw new $T($S + $L.getSql())",
+                                RoomRxJava2TypeNames.RX_EMPTY_RESULT_SET_EXCEPTION,
+                                "Query returned empty result set: ",
+                                roomSQLiteQueryVar)
+                    }
+                    endControlFlow()
+                }
+                addStatement("return $L", outVar)
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$L.close()", cursorVar)
+                addStatement("$L.release()", roomSQLiteQueryVar)
+            }
+            endControlFlow()
+        }.build()
+    }
+
+    enum class RxType(val className : ClassName, val canBeNull : Boolean) {
+        SINGLE(RxJava2TypeNames.SINGLE, canBeNull = false),
+        MAYBE(RxJava2TypeNames.MAYBE, canBeNull = true);
+    }
+}
\ No newline at end of file
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleColumnRowAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleColumnRowAdapter.kt
new file mode 100644
index 0000000..8237177
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleColumnRowAdapter.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.solver.types.CursorValueReader
+
+/**
+ * Wraps a row adapter when there is only 1 item  with 1 column in the response.
+ */
+class SingleColumnRowAdapter(val reader: CursorValueReader) : RowAdapter(reader.typeMirror()) {
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        reader.readFromCursor(outVarName, cursorVarName, "0", scope)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleEntityQueryResultAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleEntityQueryResultAdapter.kt
new file mode 100644
index 0000000..3086894
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/query/result/SingleEntityQueryResultAdapter.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query.result
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import defaultValue
+
+/**
+ * Wraps a row adapter when there is only 1 item in the result
+ */
+class SingleEntityQueryResultAdapter(rowAdapter: RowAdapter) : QueryResultAdapter(rowAdapter) {
+    val type = rowAdapter.out
+    override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            rowAdapter?.onCursorReady(cursorVarName, scope)
+            addStatement("final $T $L", type.typeName(), outVarName)
+            beginControlFlow("if($L.moveToFirst())", cursorVarName)
+                rowAdapter?.convert(outVarName, cursorVarName, scope)
+            nextControlFlow("else").apply {
+                addStatement("$L = $L", outVarName, rowAdapter?.out?.defaultValue())
+            }
+            endControlFlow()
+            rowAdapter?.onCursorFinished()?.invoke(scope)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedBooleanToBoxedIntConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedBooleanToBoxedIntConverter.kt
new file mode 100644
index 0000000..552da9e
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedBooleanToBoxedIntConverter.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+
+/**
+ * int to boolean adapter.
+ */
+object BoxedBooleanToBoxedIntConverter {
+    fun create(processingEnvironment: ProcessingEnvironment): List<TypeConverter> {
+        val tBoolean = processingEnvironment.elementUtils.getTypeElement("java.lang.Boolean")
+                .asType()
+        val tInt = processingEnvironment.elementUtils.getTypeElement("java.lang.Integer")
+                .asType()
+        return listOf(
+                object : TypeConverter(tBoolean, tInt) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().addStatement("$L = $L == null ? null : ($L ? 1 : 0)",
+                                outputVarName, inputVarName, inputVarName)
+                    }
+                },
+                object : TypeConverter(tInt, tBoolean) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().addStatement("$L = $L == null ? null : $L != 0",
+                                outputVarName, inputVarName, inputVarName)
+                    }
+
+                }
+        )
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedPrimitiveColumnTypeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedPrimitiveColumnTypeAdapter.kt
new file mode 100644
index 0000000..1b34b46
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/BoxedPrimitiveColumnTypeAdapter.kt
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.solver.CodeGenScope
+import com.google.auto.common.MoreTypes
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Adapters for all boxed primitives that has direct cursor mappings.
+ */
+open class BoxedPrimitiveColumnTypeAdapter(boxed : TypeMirror,
+                                           val primitiveAdapter : PrimitiveColumnTypeAdapter)
+            : ColumnTypeAdapter(boxed, primitiveAdapter.typeAffinity) {
+    companion object {
+        fun createBoxedPrimitiveAdapters(processingEnvironment: ProcessingEnvironment,
+                                    primitiveAdapters : List<PrimitiveColumnTypeAdapter>)
+                : List<ColumnTypeAdapter> {
+
+            return primitiveAdapters.map {
+                BoxedPrimitiveColumnTypeAdapter(
+                        processingEnvironment.typeUtils
+                                .boxedClass(MoreTypes.asPrimitiveType(it.out)).asType(),
+                        it
+                )
+            }
+        }
+    }
+
+    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            beginControlFlow("if ($L == null)", valueVarName).apply {
+                addStatement("$L.bindNull($L)", stmtName, indexVarName)
+            }
+            nextControlFlow("else").apply {
+                primitiveAdapter.bindToStmt(stmtName, indexVarName, valueVarName, scope)
+            }
+            endControlFlow()
+        }
+    }
+
+    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope) {
+        scope.builder().apply {
+            beginControlFlow("if ($L.isNull($L))", cursorVarName, indexVarName).apply {
+                addStatement("$L = null", outVarName)
+            }
+            nextControlFlow("else").apply {
+                primitiveAdapter.readFromCursor(outVarName, cursorVarName, indexVarName, scope)
+            }
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ByteArrayColumnTypeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ByteArrayColumnTypeAdapter.kt
new file mode 100644
index 0000000..014ea44
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ByteArrayColumnTypeAdapter.kt
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.TypeKind
+
+class ByteArrayColumnTypeAdapter(env : ProcessingEnvironment) : ColumnTypeAdapter(
+        out = env.typeUtils.getArrayType(env.typeUtils.getPrimitiveType(TypeKind.BYTE)),
+        typeAffinity = SQLTypeAffinity.BLOB) {
+    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L = $L.getBlob($L)", outVarName, cursorVarName, indexVarName)
+    }
+
+    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            beginControlFlow("if ($L == null)", valueVarName)
+                    .addStatement("$L.bindNull($L)", stmtName, indexVarName)
+            nextControlFlow("else")
+                    .addStatement("$L.bindBlob($L, $L)", stmtName, indexVarName, valueVarName)
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ColumnTypeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ColumnTypeAdapter.kt
new file mode 100644
index 0000000..d82dc79
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/ColumnTypeAdapter.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.TypeMirror
+
+/**
+ * A code generator that can read a field from Cursor and write a field to a Statement
+ */
+abstract class ColumnTypeAdapter(val out: TypeMirror, val typeAffinity: SQLTypeAffinity) :
+        StatementValueBinder, CursorValueReader {
+    val outTypeName: TypeName by lazy { TypeName.get(out) }
+    override fun typeMirror() = out
+    override fun affinity(): SQLTypeAffinity = typeAffinity
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeAdapter.kt
new file mode 100644
index 0000000..a8678ff
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeAdapter.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.lang.model.type.TypeMirror
+
+/**
+ * A column adapter that uses a type converter to do the conversion. The type converter may be
+ * a composite one.
+ */
+class CompositeAdapter(out: TypeMirror, val columnTypeAdapter: ColumnTypeAdapter,
+                       val intoStatementConverter: TypeConverter?,
+                       val fromCursorConverter: TypeConverter?)
+    : ColumnTypeAdapter(out, columnTypeAdapter.typeAffinity) {
+    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope) {
+        if (fromCursorConverter == null) {
+            return
+        }
+        scope.builder().apply {
+            val tmpCursorValue = scope.getTmpVar()
+            addStatement("final $T $L", columnTypeAdapter.outTypeName, tmpCursorValue)
+            columnTypeAdapter.readFromCursor(tmpCursorValue, cursorVarName, indexVarName, scope)
+            fromCursorConverter.convert(tmpCursorValue, outVarName, scope)
+        }
+    }
+
+    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope) {
+        if (intoStatementConverter == null) {
+            return
+        }
+        scope.builder().apply {
+            val tmpVar = scope.getTmpVar()
+            addStatement("final $T $L", columnTypeAdapter.out, tmpVar)
+            intoStatementConverter.convert(valueVarName, tmpVar, scope)
+            columnTypeAdapter.bindToStmt(stmtName, indexVarName, tmpVar, scope)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeTypeConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeTypeConverter.kt
new file mode 100644
index 0000000..86a5272
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CompositeTypeConverter.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+
+/**
+ * combines 2 type converters
+ */
+class CompositeTypeConverter(val conv1 : TypeConverter, val conv2 : TypeConverter) : TypeConverter(
+        conv1.from, conv2.to) {
+    override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            val tmp = scope.getTmpVar()
+            addStatement("final $T $L", conv1.to.typeName(), tmp)
+            conv1.convert(inputVarName, tmp, scope)
+            conv2.convert(tmp, outputVarName, scope)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CursorValueReader.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CursorValueReader.kt
new file mode 100644
index 0000000..e6726cd
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CursorValueReader.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Reads value from a cursor at the given index.
+ * see: StatementValueBinder
+ */
+interface CursorValueReader {
+    fun affinity() : SQLTypeAffinity
+    fun typeMirror() : TypeMirror
+    fun readFromCursor(outVarName : String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CustomTypeConverterWrapper.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CustomTypeConverterWrapper.kt
new file mode 100644
index 0000000..b4c7dc2
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/CustomTypeConverterWrapper.kt
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.CustomTypeConverter
+import android.arch.persistence.room.writer.ClassWriter
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import javax.lang.model.element.Modifier
+
+/**
+ * Wraps a type converter specified by the developer and forwards calls to it.
+ */
+class CustomTypeConverterWrapper(val custom: CustomTypeConverter)
+    : TypeConverter(custom.from, custom.to) {
+
+    override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) {
+        scope.builder().apply {
+            if (custom.isStatic) {
+                addStatement("$L = $T.$L($L)",
+                        outputVarName, custom.typeName,
+                        custom.methodName, inputVarName)
+            } else {
+                addStatement("$L = $N.$L($L)",
+                        outputVarName, typeConverter(scope),
+                        custom.methodName, inputVarName)
+            }
+        }
+    }
+
+    fun typeConverter(scope: CodeGenScope) : FieldSpec {
+        val baseName = (custom.typeName as ClassName).simpleName().decapitalize()
+        return scope.writer.getOrCreateField(object : ClassWriter.SharedFieldSpec(
+                baseName, custom.typeName) {
+            override fun getUniqueKey(): String {
+                return "converter_${custom.typeName}"
+            }
+
+            override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) {
+                builder.addModifiers(Modifier.PRIVATE)
+                builder.addModifiers(Modifier.FINAL)
+                builder.initializer("new $T()", custom.typeName)
+            }
+        })
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/NoOpConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/NoOpConverter.kt
new file mode 100644
index 0000000..e803d30
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/NoOpConverter.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Yes, we need this when user input is the same as the desired output.
+ * <p>
+ * Each query parameter receives an adapter that converts it into a String (or String[]). This
+ * TypeAdapter basically serves as a wrapper for converting String parameter into the String[] of
+ * the query. Not having this would require us to special case handle String, String[], List<String>
+ * etc.
+ */
+class NoOpConverter(type : TypeMirror) : TypeConverter(
+        type, type) {
+    override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L = $L", outputVarName, inputVarName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveBooleanToIntConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveBooleanToIntConverter.kt
new file mode 100644
index 0000000..c65df5c
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveBooleanToIntConverter.kt
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.TypeKind.BOOLEAN
+import javax.lang.model.type.TypeKind.INT
+
+/**
+ * int to boolean adapter.
+ */
+object PrimitiveBooleanToIntConverter {
+    fun create(processingEnvironment: ProcessingEnvironment): List<TypeConverter> {
+        val tBoolean = processingEnvironment.typeUtils.getPrimitiveType(BOOLEAN)
+        val tInt = processingEnvironment.typeUtils.getPrimitiveType(INT)
+        return listOf(
+                object : TypeConverter(tBoolean, tInt) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().addStatement("$L = $L ? 1 : 0", outputVarName, inputVarName)
+                    }
+                },
+                object : TypeConverter(tInt, tBoolean) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().addStatement("$L = $L != 0", outputVarName, inputVarName)
+                    }
+                })
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveColumnTypeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveColumnTypeAdapter.kt
new file mode 100644
index 0000000..c04e7bb
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/PrimitiveColumnTypeAdapter.kt
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.parser.SQLTypeAffinity.REAL
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.PrimitiveType
+import javax.lang.model.type.TypeKind.BYTE
+import javax.lang.model.type.TypeKind.CHAR
+import javax.lang.model.type.TypeKind.DOUBLE
+import javax.lang.model.type.TypeKind.FLOAT
+import javax.lang.model.type.TypeKind.INT
+import javax.lang.model.type.TypeKind.LONG
+import javax.lang.model.type.TypeKind.SHORT
+
+/**
+ * Adapters for all primitives that has direct cursor mappings.
+ */
+open class PrimitiveColumnTypeAdapter(out: PrimitiveType,
+                                      val cursorGetter: String,
+                                      val stmtSetter: String,
+                                      typeAffinity : SQLTypeAffinity)
+        : ColumnTypeAdapter(out, typeAffinity) {
+    val cast =  if (cursorGetter == "get${out.typeName().toString().capitalize()}")
+                    ""
+                else
+                    "(${out.typeName()}) "
+
+    companion object {
+        fun createPrimitiveAdapters(processingEnvironment: ProcessingEnvironment)
+                : List<PrimitiveColumnTypeAdapter> {
+            return listOf(
+                    Triple(INT, "getInt", "bindLong"),
+                    Triple(SHORT, "getShort", "bindLong"),
+                    Triple(BYTE, "getShort", "bindLong"),
+                    Triple(LONG, "getLong", "bindLong"),
+                    Triple(CHAR, "getInt", "bindLong"),
+                    Triple(FLOAT, "getFloat", "bindDouble"),
+                    Triple(DOUBLE, "getDouble", "bindDouble")
+            ).map {
+                PrimitiveColumnTypeAdapter(
+                        out = processingEnvironment.typeUtils.getPrimitiveType(it.first),
+                        cursorGetter = it.second,
+                        stmtSetter = it.third,
+                        typeAffinity = when(it.first) {
+                            INT, SHORT, BYTE, LONG, CHAR -> SQLTypeAffinity.INTEGER
+                            FLOAT, DOUBLE -> REAL
+                            else -> throw IllegalArgumentException("invalid type")
+                        }
+                )
+            }
+        }
+    }
+
+    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L.$L($L, $L)", stmtName, stmtSetter, indexVarName, valueVarName)
+    }
+
+    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L = $L$L.$L($L)", outVarName, cast, cursorVarName,
+                        cursorGetter, indexVarName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StatementValueBinder.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StatementValueBinder.kt
new file mode 100644
index 0000000..c898268
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StatementValueBinder.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Binds a value into a statement
+ * see: CursorValueReader
+ */
+interface StatementValueBinder {
+    fun typeMirror() : TypeMirror
+    fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StringColumnTypeAdapter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StringColumnTypeAdapter.kt
new file mode 100644
index 0000000..34ca61f
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/StringColumnTypeAdapter.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.parser.SQLTypeAffinity.TEXT
+import android.arch.persistence.room.solver.CodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+
+class StringColumnTypeAdapter(processingEnvironment: ProcessingEnvironment)
+    : ColumnTypeAdapter((processingEnvironment.elementUtils.getTypeElement(
+        String::class.java.canonicalName)).asType(), TEXT) {
+    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
+                                scope: CodeGenScope) {
+        scope.builder()
+                .addStatement("$L = $L.getString($L)", outVarName, cursorVarName, indexVarName)
+    }
+
+    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
+                            scope: CodeGenScope) {
+        scope.builder().apply {
+            beginControlFlow("if ($L == null)", valueVarName)
+                    .addStatement("$L.bindNull($L)", stmtName, indexVarName)
+            nextControlFlow("else")
+                    .addStatement("$L.bindString($L, $L)", stmtName, indexVarName, valueVarName)
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/TypeConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/TypeConverter.kt
new file mode 100644
index 0000000..134daf4
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/solver/types/TypeConverter.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.types
+
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.TypeMirror
+
+/**
+ * A code generator that can convert from 1 type to another
+ */
+abstract class TypeConverter(val from: TypeMirror, val to: TypeMirror) {
+    abstract fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope)
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/ColumnInfo.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/ColumnInfo.kt
new file mode 100644
index 0000000..e249871
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/ColumnInfo.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.verifier
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+
+/**
+ * Represents a column in a query response
+ */
+data class ColumnInfo(val name : String, val type : SQLTypeAffinity)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerificaitonErrors.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerificaitonErrors.kt
new file mode 100644
index 0000000..a744894
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerificaitonErrors.kt
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.verifier
+
+import java.sql.SQLException
+
+object DatabaseVerificaitonErrors {
+    private val CANNOT_CREATE_TABLE : String = "Create table statement had an error: %s"
+    fun cannotCreateTable(exception: SQLException) : String {
+        return CANNOT_CREATE_TABLE.format(exception.message)
+    }
+
+    private val CANNOT_VERIFY_QUERY : String = "There is a problem with the query: %s"
+    fun cannotVerifyQuery(exception: SQLException) : String {
+        return CANNOT_VERIFY_QUERY.format(exception.message)
+    }
+
+    private val CANNOT_CREATE_SQLITE_CONNECTION : String = "Room cannot create an SQLite" +
+            " connection to verify the queries. Query verification will be disabled. Error: %s"
+    fun cannotCreateConnection(exception: Exception) : String {
+        return CANNOT_CREATE_SQLITE_CONNECTION.format(exception.message)
+    }
+
+    val CANNOT_GET_TMP_JAVA_DIR = "Cannot read tmp java dir which is necessary to load sqlite" +
+            " lib. Database SQL verification will be disabled"
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerifier.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerifier.kt
new file mode 100644
index 0000000..8475f3a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/DatabaseVerifier.kt
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.verifier
+
+import columnInfo
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.Warning
+import java.io.File
+import java.sql.Connection
+import java.sql.DriverManager
+import java.sql.SQLException
+import java.util.UUID
+import javax.lang.model.element.Element
+
+/**
+ * Builds an in-memory version of the database and verifies the queries against it.
+ * This class is also used to resolve the return types.
+ */
+class DatabaseVerifier private constructor(
+        val connection : Connection, val context : Context, val entities : List<Entity>) {
+    companion object {
+        /**
+         * Tries to create a verifier but returns null if it cannot find the driver.
+         */
+        fun create(context: Context, element: Element, entities: List<Entity>) : DatabaseVerifier? {
+            return try {
+                // see: https://github.com/xerial/sqlite-jdbc/issues/97
+                val tmpDir = System.getProperty("java.io.tmpdir")
+                if (tmpDir == null) {
+                    context.logger.w(Warning.MISSING_JAVA_TMP_DIR,
+                            element, DatabaseVerificaitonErrors.CANNOT_GET_TMP_JAVA_DIR)
+                    return null
+                }
+                val outDir = File(tmpDir, "room-${UUID.randomUUID()}")
+                outDir.mkdirs()
+                outDir.deleteOnExit()
+                System.setProperty("org.sqlite.tmpdir", outDir.absolutePath)
+                //force load:
+                Class.forName("org.sqlite.JDBC")
+                val connection = DriverManager.getConnection("jdbc:sqlite::memory:")
+                DatabaseVerifier(connection, context, entities)
+            } catch (ex : Exception) {
+                context.logger.w(Warning.CANNOT_CREATE_VERIFICATION_DATABASE, element,
+                        DatabaseVerificaitonErrors.cannotCreateConnection(ex))
+                null
+            }
+        }
+    }
+    init {
+        entities.forEach { entity ->
+            val stmt = connection.createStatement()
+            stmt.executeUpdate(entity.createTableQuery)
+        }
+    }
+
+    fun analyze(sql : String) : QueryResultInfo {
+        return try {
+            val stmt = connection.prepareStatement(sql)
+            QueryResultInfo(stmt.columnInfo())
+        } catch (ex : SQLException) {
+            QueryResultInfo(emptyList(), ex)
+        }
+    }
+
+    fun closeConnection() {
+        if (!connection.isClosed) {
+            try {
+                connection.close()
+            } catch (t : Throwable) {
+                //ignore.
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/QueryResultInfo.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/QueryResultInfo.kt
new file mode 100644
index 0000000..4a99243
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/QueryResultInfo.kt
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.verifier
+
+import java.sql.SQLException
+
+/**
+ * Represents the result of a query.
+ * <p>
+ * This information is obtained by preparing the query against an in memory database at compile
+ * time.
+ */
+data class QueryResultInfo(val columns : List<ColumnInfo>, val error : SQLException? = null)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/jdbc_ext.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/jdbc_ext.kt
new file mode 100644
index 0000000..5ae9d6a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/verifier/jdbc_ext.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.verifier.ColumnInfo
+import java.sql.PreparedStatement
+import java.sql.ResultSet
+import java.sql.ResultSetMetaData
+import java.sql.SQLException
+
+internal fun <T> ResultSet.collect(f: (ResultSet) -> T): List<T> {
+    val result = arrayListOf<T>()
+    try {
+        while (next()) {
+            result.add(f.invoke(this))
+        }
+    } finally {
+        close()
+    }
+    return result
+}
+
+private fun <T> PreparedStatement.map(f : (Int, ResultSetMetaData) ->  T) : List<T> {
+    val columnCount = try {
+        metaData.columnCount
+    } catch (ex : SQLException) {
+        // ignore, no-result query
+        0
+    }
+    // return is separate than data creation because we want to know who throws the exception
+    return (1.rangeTo(columnCount)).map { f(it, metaData) }
+}
+
+internal fun PreparedStatement.columnNames(): List<String> {
+    return map { index, data -> data.getColumnName(index) }
+}
+
+private fun PreparedStatement.tryGetAffinity(columnIndex : Int) : SQLTypeAffinity {
+    return try {
+        SQLTypeAffinity.valueOf(metaData.getColumnTypeName(columnIndex).capitalize())
+    } catch (ex : IllegalArgumentException) {
+        SQLTypeAffinity.NULL
+    }
+}
+
+internal fun PreparedStatement.columnInfo(): List<ColumnInfo> {
+    //see: http://sqlite.1065341.n5.nabble.com/Column-order-in-resultset-td23127.html
+    return map { index, data -> ColumnInfo(data.getColumnName(index), tryGetAffinity(index)) }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CallType.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CallType.kt
new file mode 100644
index 0000000..40cbcc4
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CallType.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+enum class CallType {
+    FIELD,
+    METHOD,
+    CONSTRUCTOR
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Constructor.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Constructor.kt
new file mode 100644
index 0000000..fdc2a11
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Constructor.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import javax.lang.model.element.ExecutableElement
+
+/**
+ * For each Entity / Pojo we process has a constructor. It might be the empty constructor or a
+ * constructor with fields.
+ */
+data class Constructor(val element : ExecutableElement, val params : List<Param>) {
+
+    fun hasField(field : Field) : Boolean {
+        return params.any {
+            when (it) {
+                is FieldParam -> it.field === field
+                is EmbeddedParam -> it.embedded.field === field
+                else -> false
+            }
+        }
+    }
+
+    class FieldParam(val field : Field) : Param(ParamType.FIELD) {
+        override fun log(): String = field.getPath()
+
+    }
+
+    class EmbeddedParam(val embedded: EmbeddedField) : Param(ParamType.EMBEDDED) {
+        override fun log(): String = embedded.field.getPath()
+
+    }
+
+    abstract class Param(val type : ParamType) {
+        abstract fun log() : String;
+    }
+
+    enum class ParamType {
+        FIELD,
+        EMBEDDED
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CustomTypeConverter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CustomTypeConverter.kt
new file mode 100644
index 0000000..5a1f0e6
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/CustomTypeConverter.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.hasAnyOf
+import android.arch.persistence.room.ext.typeName
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Generated when we parse a method annotated with TypeConverter.
+ */
+data class CustomTypeConverter(val type: TypeMirror,
+                               val method : ExecutableElement,
+                               val from: TypeMirror, val to: TypeMirror) {
+    val typeName: TypeName by lazy { type.typeName() }
+    val fromTypeName: TypeName by lazy { from.typeName() }
+    val toTypeName: TypeName by lazy { to.typeName() }
+    val methodName by lazy { method.simpleName.toString() }
+    val isStatic by lazy { method.hasAnyOf(Modifier.STATIC) }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Dao.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Dao.kt
new file mode 100644
index 0000000..227fa49
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Dao.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+
+data class Dao(val element : TypeElement, val type : DeclaredType,
+               val queryMethods: List<QueryMethod>,
+               val insertionMethods : List<InsertionMethod>,
+               val deletionMethods : List<DeletionMethod>,
+               val updateMethods : List<UpdateMethod>,
+               val constructorParamType : TypeName?) {
+    // parsed dao might have a suffix if it is used in multiple databases.
+    private var suffix : String? = null
+    fun setSuffix(newSuffix : String) {
+        if (this.suffix != null) {
+            throw IllegalStateException("cannot set suffix twice")
+        }
+        this.suffix = if (newSuffix == "") "" else "_$newSuffix"
+    }
+
+    val typeName : ClassName by lazy { ClassName.get(element) }
+
+    val shortcutMethods : List<ShortcutMethod> by lazy {
+        deletionMethods + updateMethods
+    }
+
+    private val implClassName by lazy {
+        if (suffix == null) {
+            suffix = ""
+        }
+        "${typeName.simpleName()}${suffix}_Impl"
+    }
+
+    val implTypeName by lazy {
+        ClassName.get(typeName.packageName(), implClassName)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DaoMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DaoMethod.kt
new file mode 100644
index 0000000..bd5e6b8
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DaoMethod.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import javax.lang.model.element.Element
+
+/**
+ * References a method that returns a dao in a Database
+ */
+data class DaoMethod(val element : Element, val name : String, val dao : Dao)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Database.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Database.kt
new file mode 100644
index 0000000..b118a32
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Database.kt
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.RoomMasterTable
+import android.arch.persistence.room.migration.bundle.DatabaseBundle
+import android.arch.persistence.room.migration.bundle.SchemaBundle
+import com.squareup.javapoet.ClassName
+import org.apache.commons.codec.digest.DigestUtils
+import java.io.File
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Holds information about a class annotated with Database.
+ */
+data class Database(val element: TypeElement,
+                    val type: TypeMirror,
+                    val entities: List<Entity>,
+                    val daoMethods: List<DaoMethod>,
+                    val version: Int,
+                    val exportSchema: Boolean,
+                    val enableForeignKeys : Boolean) {
+    val typeName: ClassName by lazy { ClassName.get(element) }
+
+    private val implClassName by lazy {
+        "${typeName.simpleNames().joinToString("_")}_Impl"
+    }
+
+    val implTypeName: ClassName by lazy {
+        ClassName.get(typeName.packageName(), implClassName)
+    }
+
+    val bundle by lazy {
+        DatabaseBundle(version, identityHash, entities.map(Entity::toBundle),
+                listOf(RoomMasterTable.CREATE_QUERY,
+                        RoomMasterTable.createInsertQuery(identityHash)))
+    }
+
+    /**
+     * Create a has that identifies this database definition so that at runtime we can check to
+     * ensure developer didn't forget to update the version.
+     */
+    val identityHash: String by lazy {
+        val entityDescriptions = entities
+                .sortedBy { it.tableName }
+                .map { it.createTableQuery }
+        val indexDescriptions = entities
+                .flatMap { entity ->
+                    entity.indices.map { index ->
+                        index.createQuery(entity.tableName)
+                    }
+                }
+        val input = (entityDescriptions + indexDescriptions).joinToString("¯\\_(ツ)_/¯")
+        DigestUtils.md5Hex(input)
+    }
+
+    fun exportSchema(file: File) {
+        val schemaBundle = SchemaBundle(SchemaBundle.LATEST_FORMAT, bundle)
+        SchemaBundle.serialize(schemaBundle, file)
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DeletionMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DeletionMethod.kt
new file mode 100644
index 0000000..c4adc54
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/DeletionMethod.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import javax.lang.model.element.ExecutableElement
+
+class DeletionMethod(element: ExecutableElement, name: String,
+                          entities: Map<String, Entity>, returnCount : Boolean,
+                          parameters: List<ShortcutQueryParameter>) : ShortcutMethod(
+        element, name, entities, returnCount, parameters
+)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/EmbeddedField.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/EmbeddedField.kt
new file mode 100644
index 0000000..55e9cc4
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/EmbeddedField.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.support.annotation.NonNull
+import android.arch.persistence.room.ext.hasAnnotation
+
+/**
+ * Used when a field is embedded inside an Entity or Pojo.
+ */
+// used in cache matching, must stay as a data class or implement equals
+data class EmbeddedField(val field : Field, val prefix : String = "",
+                         val parent : EmbeddedField?) {
+    val getter by lazy { field.getter }
+    val setter by lazy { field.setter }
+    val nonNull = field.element.hasAnnotation(NonNull::class)
+    lateinit var pojo: Pojo
+    val mRootParent: EmbeddedField by lazy {
+        parent?.mRootParent ?: this
+    }
+
+    fun isDescendantOf(other : EmbeddedField) : Boolean {
+        if (parent == other) {
+            return true
+        } else if (parent == null) {
+            return false
+        } else {
+            return parent.isDescendantOf(other)
+        }
+    }
+
+    fun isNonNullRecursively(): Boolean {
+        return field.nonNull && (parent == null || parent.isNonNullRecursively())
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Entity.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Entity.kt
new file mode 100644
index 0000000..06e7484
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Entity.kt
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.migration.bundle.BundleUtil
+import android.arch.persistence.room.migration.bundle.EntityBundle
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+
+// TODO make data class when move to kotlin 1.1
+class Entity(element: TypeElement, val tableName: String, type: DeclaredType,
+             fields: List<Field>, embeddedFields: List<EmbeddedField>,
+             val primaryKey: PrimaryKey, val indices: List<Index>,
+             val foreignKeys: List<ForeignKey>,
+             constructor: Constructor?)
+    : Pojo(element, type, fields, embeddedFields, emptyList(), constructor) {
+
+    val createTableQuery by lazy {
+        createTableQuery(tableName)
+    }
+
+    fun createTableQuery(tableName : String) : String {
+        val definitions = (fields.map {
+            val autoIncrement = primaryKey.autoGenerateId && primaryKey.fields.contains(it)
+            it.databaseDefinition(autoIncrement)
+        } + createPrimaryKeyDefinition() + createForeignKeyDefinitions()).filterNotNull()
+        return "CREATE TABLE IF NOT EXISTS `$tableName` (${definitions.joinToString(", ")})"
+    }
+
+    private fun createForeignKeyDefinitions() : List<String> {
+        return foreignKeys.map { it.databaseDefinition() }
+    }
+
+    private fun createPrimaryKeyDefinition(): String? {
+        return if (primaryKey.fields.isEmpty() || primaryKey.autoGenerateId) {
+            null
+        } else {
+            val keys = primaryKey.fields
+                    .map { "`${it.columnName}`" }
+                    .joinToString(", ")
+            "PRIMARY KEY($keys)"
+        }
+    }
+
+    fun toBundle(): EntityBundle = EntityBundle(
+            tableName,
+            createTableQuery(BundleUtil.TABLE_NAME_PLACEHOLDER),
+            fields.map {it.toBundle()},
+            primaryKey.toBundle(),
+            indices.map { it.toBundle() },
+            foreignKeys.map { it.toBundle() })
+
+    fun isUnique(columns: List<String>) : Boolean {
+        return if (primaryKey.columnNames.size == columns.size
+                && primaryKey.columnNames.containsAll(columns)) {
+            true
+        } else {
+            indices.any { index ->
+                index.unique
+                        && index.fields.size == columns.size
+                        && index.columnNames.containsAll(columns)
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Field.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Field.kt
new file mode 100644
index 0000000..ee6f8a1
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Field.kt
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.isNonNull
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.migration.bundle.FieldBundle
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.solver.types.CursorValueReader
+import android.arch.persistence.room.solver.types.StatementValueBinder
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.Element
+import javax.lang.model.type.TypeMirror
+// used in cache matching, must stay as a data class or implement equals
+data class Field(val element: Element, val name: String, val type: TypeMirror,
+                 var affinity: SQLTypeAffinity?,
+                 val columnName: String = name,
+                 /* means that this field does not belong to parent, instead, it belongs to a
+                 * embedded child of the main Pojo*/
+                 val parent: EmbeddedField? = null,
+                 // index might be removed when being merged into an Entity
+                 var indexed : Boolean = false) {
+    lateinit var getter: FieldGetter
+    lateinit var setter: FieldSetter
+    // binds the field into a statement
+    var statementBinder: StatementValueBinder? = null
+    // reads this field from a cursor column
+    var cursorValueReader: CursorValueReader? = null
+    val typeName: TypeName by lazy { type.typeName() }
+
+    /** Whether the table column for this field should be NOT NULL */
+    val nonNull = element.isNonNull() && (parent == null || parent.isNonNullRecursively())
+
+    /**
+     * Used when reporting errors on duplicate names
+     */
+    fun getPath() : String {
+        return if (parent == null) {
+            name
+        } else {
+            "${parent.field.getPath()} > $name"
+        }
+    }
+
+    private val pathWithDotNotation : String by lazy {
+        if (parent == null) {
+            name
+        } else {
+            "${parent.field.pathWithDotNotation}.$name"
+        }
+    }
+
+    /**
+     * List of names that include variations.
+     * e.g. if it is mUser, user is added to the list
+     * or if it is isAdmin, admin is added to the list
+     */
+    val nameWithVariations by lazy {
+        val result = arrayListOf(name)
+        if (name.length > 1) {
+            if (name.startsWith('_')) {
+                result.add(name.substring(1))
+            }
+            if (name.startsWith("m") && name[1].isUpperCase()) {
+                result.add(name.substring(1).decapitalize())
+            }
+
+            if (typeName == TypeName.BOOLEAN || typeName == TypeName.BOOLEAN.box()) {
+                if (name.length > 2 && name.startsWith("is") && name[2].isUpperCase()) {
+                    result.add(name.substring(2).decapitalize())
+                }
+                if (name.length > 3 && name.startsWith("has") && name[3].isUpperCase()) {
+                    result.add(name.substring(3).decapitalize())
+                }
+            }
+        }
+        result
+    }
+
+    val getterNameWithVariations by lazy {
+        nameWithVariations.map { "get${it.capitalize()}" } +
+                if (typeName == TypeName.BOOLEAN || typeName == TypeName.BOOLEAN.box()) {
+                    nameWithVariations.flatMap {
+                        listOf("is${it.capitalize()}", "has${it.capitalize()}")
+                    }
+                } else {
+                    emptyList()
+                }
+    }
+
+    val setterNameWithVariations by lazy {
+        nameWithVariations.map { "set${it.capitalize()}" }
+    }
+
+    /**
+     * definition to be used in create query
+     */
+    fun databaseDefinition(autoIncrementPKey : Boolean) : String {
+        val columnSpec = StringBuilder("")
+        if (autoIncrementPKey) {
+            columnSpec.append(" PRIMARY KEY AUTOINCREMENT")
+        }
+        if (nonNull) {
+            columnSpec.append(" NOT NULL")
+        }
+        return "`$columnName` ${(affinity ?: SQLTypeAffinity.TEXT).name}$columnSpec"
+    }
+
+    fun toBundle(): FieldBundle = FieldBundle(pathWithDotNotation, columnName,
+            affinity?.name ?: SQLTypeAffinity.TEXT.name, nonNull
+    )
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldGetter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldGetter.kt
new file mode 100644
index 0000000..6713c2c
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldGetter.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import com.squareup.javapoet.CodeBlock
+import com.squareup.javapoet.TypeName
+import javax.lang.model.type.TypeMirror
+
+data class FieldGetter(val name : String, val type : TypeMirror, val callType: CallType) {
+    fun writeGet(ownerVar: String, outVar: String, builder: CodeBlock.Builder) {
+        val stmt = when (callType) {
+            CallType.FIELD -> "final $T $L = $L.$L"
+            CallType.METHOD -> "final $T $L = $L.$L()"
+            CallType.CONSTRUCTOR -> null
+        }
+        stmt?.let {
+            builder.addStatement(stmt, TypeName.get(type), outVar, ownerVar, name)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldSetter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldSetter.kt
new file mode 100644
index 0000000..5aa1806
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldSetter.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.L
+import com.squareup.javapoet.CodeBlock
+import javax.lang.model.type.TypeMirror
+
+data class FieldSetter(val name: String, val type: TypeMirror, val callType: CallType) {
+    fun writeSet(ownerVar: String, inVar: String, builder: CodeBlock.Builder) {
+        val stmt = when (callType) {
+            CallType.FIELD -> "$L.$L = $L"
+            CallType.METHOD -> "$L.$L($L)"
+            CallType.CONSTRUCTOR -> null
+        }
+        stmt?.let {
+            builder.addStatement(stmt, ownerVar, name, inVar)
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldWithIndex.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldWithIndex.kt
new file mode 100644
index 0000000..6ef6979
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/FieldWithIndex.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+/**
+ * A common value object when we need to associate a Field with an Index
+ * variable.
+ * <p>
+ * If we are sure that the field will be there at compile time, we set it to always Exists so that
+ * the generated code does not check for -1 column indices.
+ */
+data class FieldWithIndex(val field : Field, val indexVar : String, val alwaysExists : Boolean) {
+    companion object {
+        fun byOrder(fields : List<Field>) : List<FieldWithIndex> {
+            return fields.mapIndexed { index, field ->
+                FieldWithIndex(field = field,
+                        indexVar = "${index + 1}",
+                        alwaysExists = true)
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKey.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKey.kt
new file mode 100644
index 0000000..66cf3a0
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKey.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.migration.bundle.ForeignKeyBundle
+
+/**
+ * Keeps information about a foreign key.
+ */
+data class ForeignKey(val parentTable: String,
+                      val parentColumns: List<String>,
+                      val childFields: List<Field>,
+                      val onDelete: ForeignKeyAction,
+                      val onUpdate: ForeignKeyAction,
+                      val deferred: Boolean) {
+    fun databaseDefinition(): String {
+        return "FOREIGN KEY(${joinEscaped(childFields.map { it.columnName })})" +
+                " REFERENCES `$parentTable`(${joinEscaped(parentColumns)})" +
+                " ON UPDATE ${onUpdate.sqlName}" +
+                " ON DELETE ${onDelete.sqlName}" +
+                " ${deferredDeclaration()}"
+    }
+
+    private fun deferredDeclaration(): String {
+        return if (deferred) {
+            "DEFERRABLE INITIALLY DEFERRED"
+        } else {
+            ""
+        }
+    }
+
+    private fun joinEscaped(values: Iterable<String>) = values.joinToString(", ") { "`$it`" }
+
+    fun toBundle(): ForeignKeyBundle = ForeignKeyBundle(
+            parentTable, onDelete.sqlName, onUpdate.sqlName,
+            childFields.map { it.columnName },
+            parentColumns
+    )
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKeyAction.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKeyAction.kt
new file mode 100644
index 0000000..1b85910
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ForeignKeyAction.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ForeignKey
+
+/**
+ * Compiler representation of ForeignKey#Action.
+ */
+enum class ForeignKeyAction(val annotationValue : Int, val sqlName : String) {
+    NO_ACTION(ForeignKey.NO_ACTION, "NO ACTION"),
+    RESTRICT(ForeignKey.RESTRICT, "RESTRICT"),
+    SET_NULL(ForeignKey.SET_NULL, "SET NULL"),
+    SET_DEFAULT(ForeignKey.SET_DEFAULT, "SET DEFAULT"),
+    CASCADE(ForeignKey.CASCADE, "CASCADE");
+    companion object {
+        private val mapping by lazy {
+            ForeignKeyAction.values().associateBy { it.annotationValue }
+        }
+        fun fromAnnotationValue(value : Int?) = mapping[value]
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Index.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Index.kt
new file mode 100644
index 0000000..60adf2b
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Index.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.migration.bundle.BundleUtil
+import android.arch.persistence.room.migration.bundle.IndexBundle
+
+/**
+ * Represents a processed index.
+ */
+data class Index(val name : String, val unique : Boolean, val fields : List<Field>) {
+
+    fun createQuery(tableName : String) : String {
+        val uniqueSQL = if (unique) {
+            "UNIQUE"
+        } else {
+            ""
+        }
+        return """
+            CREATE $uniqueSQL INDEX `$name`
+            ON `$tableName` (${fields.map { it.columnName }.joinToString(", ") { "`$it`"}})
+            """.trimIndent().replace(System.lineSeparator(), " ")
+    }
+
+    val columnNames by lazy { fields.map {it.columnName} }
+
+    fun toBundle(): IndexBundle = IndexBundle(name, unique, fields.map { it.columnName },
+            createQuery(BundleUtil.TABLE_NAME_PLACEHOLDER))
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/InsertionMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/InsertionMethod.kt
new file mode 100644
index 0000000..ad3688d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/InsertionMethod.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.OnConflictStrategy
+import android.arch.persistence.room.ext.typeName
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.TypeMirror
+
+data class InsertionMethod(val element: ExecutableElement, val name: String,
+                           @OnConflictStrategy val onConflict: Int,
+                           val entities: Map<String, Entity>, val returnType: TypeMirror,
+                           val insertionType: Type?,
+                           val parameters: List<ShortcutQueryParameter>) {
+    fun insertMethodTypeFor(param : ShortcutQueryParameter) : Type {
+        return if (insertionType == Type.INSERT_VOID || insertionType == null) {
+            Type.INSERT_VOID
+        } else if (!param.isMultiple) {
+            Type.INSERT_SINGLE_ID
+        } else {
+            insertionType
+        }
+    }
+
+    enum class Type(
+            // methodName matches EntityInsertionAdapter methods
+            val methodName : String, val returnTypeName : TypeName) {
+        INSERT_VOID("insert", TypeName.VOID), // return void
+        INSERT_SINGLE_ID("insertAndReturnId", TypeName.LONG), // return long
+        INSERT_ID_ARRAY("insertAndReturnIdsArray",
+                ArrayTypeName.of(TypeName.LONG)), // return long[]
+        INSERT_ID_ARRAY_BOX("insertAndReturnIdsArrayBox",
+                ArrayTypeName.of(TypeName.LONG.box())), // return Long[]
+        INSERT_ID_LIST("insertAndReturnIdsList", // return List<Long>
+                ParameterizedTypeName.get(List::class.typeName(), TypeName.LONG.box()))
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Pojo.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Pojo.kt
new file mode 100644
index 0000000..acc63af
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Pojo.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.typeName
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+
+/**
+ * A class is turned into a Pojo if it is used in a query response.
+ */
+// TODO make data class when move to kotlin 1.1
+open class Pojo(val element : TypeElement, val type: DeclaredType, val fields : List<Field>,
+                val embeddedFields: List<EmbeddedField>, val relations: List<Relation>,
+                val constructor : Constructor? = null) {
+    val typeName: TypeName by lazy { type.typeName() }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/PrimaryKey.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/PrimaryKey.kt
new file mode 100644
index 0000000..9735668
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/PrimaryKey.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.migration.bundle.PrimaryKeyBundle
+import javax.lang.model.element.Element
+
+/**
+ * Represents a PrimaryKey for an Entity.
+ */
+data class PrimaryKey(val declaredIn : Element?, val fields: List<Field>,
+                      val autoGenerateId: Boolean) {
+    companion object {
+        val MISSING = PrimaryKey(null, emptyList(), false)
+    }
+
+    val columnNames by lazy { fields.map {it.columnName} }
+
+    fun toHumanReadableString(): String {
+        return "PrimaryKey[" +
+                fields.joinToString(separator = ", ", transform = Field::getPath) + "]"
+    }
+
+    fun toBundle(): PrimaryKeyBundle = PrimaryKeyBundle(
+            autoGenerateId, fields.map { it.columnName })
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryMethod.kt
new file mode 100644
index 0000000..1aa8430
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryMethod.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.solver.query.result.QueryResultBinder
+import com.squareup.javapoet.TypeName
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.TypeMirror
+
+/**
+ * A class that holds information about a QueryMethod.
+ * It is self sufficient and must have all generics etc resolved once created.
+ */
+data class QueryMethod(val element: ExecutableElement, val query: ParsedQuery, val name: String,
+                       val returnType: TypeMirror, val parameters: List<QueryParameter>,
+                       val queryResultBinder : QueryResultBinder) {
+    val sectionToParamMapping by lazy {
+        query.bindSections.map {
+            if (it.text.trim() == "?") {
+                Pair(it, parameters.firstOrNull())
+            } else if (it.text.startsWith(":")) {
+                val subName = it.text.substring(1)
+                Pair(it, parameters.firstOrNull {
+                    it.name == subName
+                })
+            } else {
+                Pair(it, null)
+            }
+        }
+    }
+
+    val returnsValue by lazy {
+        returnType.typeName() != TypeName.VOID
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryParameter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryParameter.kt
new file mode 100644
index 0000000..60ab55e
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/QueryParameter.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.solver.query.parameter.QueryParameterAdapter
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Holds the parameter for a {@link QueryMethod}.
+ */
+data class QueryParameter(val name: String, val type: TypeMirror,
+                          val queryParamAdapter : QueryParameterAdapter?)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Relation.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Relation.kt
new file mode 100644
index 0000000..940db31
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Relation.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+/**
+ * Value object created from processing a @Relation annotation.
+ */
+class Relation(
+        val entity: Entity,
+        val pojo: Pojo,
+        // field in Pojo that holds these relations (e.g. List<Pet> pets)
+        val field: Field,
+        // the parent field referenced for matching
+        val parentField: Field,
+        // the field referenced for querying. does not need to be in the response but the query
+        // we generate always has it in the response.
+        val entityField: Field,
+        // the projection for the query
+        val projection: List<String>) {
+
+    fun createLoadAllSql(): String {
+        var resultFields = if (projection.isNotEmpty()) {
+            projection
+        } else {
+            pojo.fields.map { it.columnName }
+        }
+        val entityFieldInResponse = pojo.fields.any { it.columnName == entityField.columnName }
+        if (!entityFieldInResponse) {
+            resultFields += entityField.columnName
+        }
+        return createSelect(resultFields)
+    }
+
+    private fun createSelect(resultFields: List<String>): String {
+        return "SELECT ${resultFields.joinToString(",")}" +
+                " FROM `${entity.tableName}`" +
+                " WHERE ${entityField.columnName} IN (:args)"
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/RelationCollector.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/RelationCollector.kt
new file mode 100644
index 0000000..c11091c
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/RelationCollector.kt
@@ -0,0 +1,262 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.CommonTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.parser.SqlParser
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER
+import android.arch.persistence.room.processor.ProcessorErrors.relationAffinityMismatch
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.solver.query.result.RowAdapter
+import android.arch.persistence.room.solver.query.result.SingleColumnRowAdapter
+import android.arch.persistence.room.verifier.DatabaseVerificaitonErrors
+import android.arch.persistence.room.writer.QueryWriter
+import android.arch.persistence.room.writer.RelationCollectorMethodWriter
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.CodeBlock
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import stripNonJava
+import java.util.ArrayList
+import java.util.HashSet
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Internal class that is used to manage fetching 1/N to N relationships.
+ */
+data class RelationCollector(val relation: Relation,
+                             val affinity : SQLTypeAffinity,
+                             val mapTypeName: ParameterizedTypeName,
+                             val keyTypeName: TypeName,
+                             val collectionTypeName: ParameterizedTypeName,
+                             val queryWriter: QueryWriter,
+                             val rowAdapter: RowAdapter,
+                             val loadAllQuery : ParsedQuery) {
+    // set when writing the code generator in writeInitCode
+    lateinit var varName: String
+
+    fun writeInitCode(scope: CodeGenScope) {
+        val tmpVar = scope.getTmpVar(
+                "_collection${relation.field.getPath().stripNonJava().capitalize()}")
+        scope.builder().addStatement("final $T $L = new $T()", mapTypeName, tmpVar, mapTypeName)
+        varName = tmpVar
+    }
+
+    // called after reading each item to extract the key if it exists
+    fun writeReadParentKeyCode(cursorVarName: String, itemVar : String,
+                               fieldsWithIndices : List<FieldWithIndex>, scope: CodeGenScope) {
+        val indexVar = fieldsWithIndices.firstOrNull {
+            it.field === relation.parentField
+        }?.indexVar
+        scope.builder().apply {
+            readKey(
+                    cursorVarName = cursorVarName,
+                    indexVar = indexVar,
+                    scope = scope
+            ) { tmpVar ->
+                val tmpCollectionVar = scope.getTmpVar("_tmpCollection")
+                addStatement("$T $L = $L.get($L)", collectionTypeName, tmpCollectionVar,
+                        varName, tmpVar)
+                beginControlFlow("if($L == null)", tmpCollectionVar).apply {
+                    addStatement("$L = new $T()", tmpCollectionVar, collectionTypeName)
+                    addStatement("$L.put($L, $L)", varName, tmpVar, tmpCollectionVar)
+                }
+                endControlFlow()
+                // set it on the item
+                relation.field.setter.writeSet(itemVar, tmpCollectionVar, this)
+            }
+        }
+    }
+
+    fun writeCollectionCode(scope: CodeGenScope) {
+        val method = scope.writer
+                .getOrCreateMethod(RelationCollectorMethodWriter(this))
+        scope.builder().apply {
+            addStatement("$N($L)", method, varName)
+        }
+    }
+
+    fun readKey(cursorVarName: String, indexVar: String?, scope: CodeGenScope,
+                postRead: CodeBlock.Builder.(String) -> Unit) {
+        val cursorGetter = when (affinity) {
+            SQLTypeAffinity.INTEGER -> "getLong"
+            SQLTypeAffinity.REAL -> "getDouble"
+            SQLTypeAffinity.TEXT -> "getString"
+            SQLTypeAffinity.BLOB -> "getBlob"
+            else -> {
+                "getString"
+            }
+        }
+        scope.builder().apply {
+            beginControlFlow("if (!$L.isNull($L))", cursorVarName, indexVar).apply {
+                val tmpVar = scope.getTmpVar("_tmpKey")
+                addStatement("final $T $L = $L.$L($L)", keyTypeName,
+                        tmpVar, cursorVarName, cursorGetter, indexVar)
+                this.postRead(tmpVar)
+            }
+            endControlFlow()
+        }
+    }
+
+    companion object {
+        fun createCollectors(baseContext : Context, relations: List<Relation>)
+                : List<RelationCollector> {
+            return relations.map { relation ->
+                // decide on the affinity
+                val context = baseContext.fork(relation.field.element)
+                val parentAffinity = relation.parentField.cursorValueReader?.affinity()
+                val childAffinity = relation.entityField.cursorValueReader?.affinity()
+                val affinity = if (parentAffinity != null && parentAffinity == childAffinity) {
+                    parentAffinity
+                } else {
+                    context.logger.w(Warning.RELATION_TYPE_MISMATCH, relation.field.element,
+                            relationAffinityMismatch(
+                                    parentColumn = relation.parentField.columnName,
+                                    childColumn = relation.entityField.columnName,
+                                    parentAffinity = parentAffinity,
+                                    childAffinity = childAffinity))
+                    SQLTypeAffinity.TEXT
+                }
+                val keyType = keyTypeFor(context, affinity)
+                val collectionTypeName = if (relation.field.typeName is ParameterizedTypeName) {
+                    val paramType = relation.field.typeName as ParameterizedTypeName
+                    if (paramType.rawType == CommonTypeNames.LIST) {
+                        ParameterizedTypeName.get(ClassName.get(ArrayList::class.java),
+                                relation.pojo.typeName)
+                    } else if (paramType.rawType == CommonTypeNames.SET) {
+                        ParameterizedTypeName.get(ClassName.get(HashSet::class.java),
+                                relation.pojo.typeName)
+                    } else {
+                        ParameterizedTypeName.get(ClassName.get(ArrayList::class.java),
+                                relation.pojo.typeName)
+                    }
+                } else {
+                    ParameterizedTypeName.get(ClassName.get(ArrayList::class.java),
+                            relation.pojo.typeName)
+                }
+
+                val canUseArrayMap = context.processingEnv.elementUtils
+                        .getTypeElement(AndroidTypeNames.ARRAY_MAP.toString()) != null
+                val mapClass = if (canUseArrayMap) {
+                    AndroidTypeNames.ARRAY_MAP
+                } else {
+                    ClassName.get(java.util.HashMap::class.java)
+                }
+                val tmpMapType = ParameterizedTypeName.get(mapClass, keyType, collectionTypeName)
+                val keyTypeMirror = keyTypeMirrorFor(context, affinity)
+                val set = context.processingEnv.elementUtils.getTypeElement("java.util.Set")
+                val keySet = context.processingEnv.typeUtils.getDeclaredType(set, keyTypeMirror)
+                val loadAllQuery = relation.createLoadAllSql()
+                val parsedQuery = SqlParser.parse(loadAllQuery)
+                context.checker.check(parsedQuery.errors.isEmpty(), relation.field.element,
+                        parsedQuery.errors.joinToString("\n"))
+                if (parsedQuery.errors.isEmpty()) {
+                    val resultInfo = context.databaseVerifier?.analyze(loadAllQuery)
+                    parsedQuery.resultInfo = resultInfo
+                    if (resultInfo?.error != null) {
+                        context.logger.e(relation.field.element,
+                                DatabaseVerificaitonErrors.cannotVerifyQuery(resultInfo.error))
+                    }
+                }
+                val resultInfo = parsedQuery.resultInfo
+
+                val queryParam = QueryParameter(RelationCollectorMethodWriter.KEY_SET_VARIABLE,
+                        keySet, context.typeAdapterStore.findQueryParameterAdapter(keySet))
+                val queryWriter = QueryWriter(
+                        parameters = listOf(queryParam),
+                        sectionToParamMapping = listOf(Pair(parsedQuery.bindSections.first(),
+                                queryParam)),
+                        query = parsedQuery
+                )
+
+                // row adapter that matches full response
+                fun getDefaultRowAdapter() : RowAdapter? {
+                    return context.typeAdapterStore.findRowAdapter(relation.pojo.type, parsedQuery)
+                }
+                val rowAdapter = if (relation.projection.size == 1 && resultInfo != null &&
+                        (resultInfo.columns.size == 1 || resultInfo.columns.size == 2)) {
+                    // check for a column adapter first
+                    val cursorReader = context.typeAdapterStore.findCursorValueReader(
+                            relation.pojo.type, resultInfo.columns.first().type)
+                    if (cursorReader == null) {
+                        getDefaultRowAdapter()
+                    } else {
+                        context.logger.d("Choosing cursor adapter for the return value since" +
+                                " the query returns only 1 or 2 columns and there is a cursor" +
+                                " adapter for the return type.")
+                        SingleColumnRowAdapter(cursorReader)
+                    }
+                } else {
+                    getDefaultRowAdapter()
+                }
+
+                if (rowAdapter == null) {
+                    context.logger.e(relation.field.element, CANNOT_FIND_QUERY_RESULT_ADAPTER)
+                    null
+                } else {
+                    RelationCollector(
+                            relation = relation,
+                            affinity = affinity,
+                            mapTypeName = tmpMapType,
+                            keyTypeName = keyType,
+                            collectionTypeName = collectionTypeName,
+                            queryWriter = queryWriter,
+                            rowAdapter = rowAdapter,
+                            loadAllQuery = parsedQuery
+                    )
+                }
+            }.filterNotNull()
+        }
+
+        private fun keyTypeMirrorFor(context: Context, affinity: SQLTypeAffinity): TypeMirror {
+            val types = context.processingEnv.typeUtils
+            val elements = context.processingEnv.elementUtils
+            return when (affinity) {
+                SQLTypeAffinity.INTEGER -> elements.getTypeElement("java.lang.Long").asType()
+                SQLTypeAffinity.REAL -> elements.getTypeElement("java.lang.Double").asType()
+                SQLTypeAffinity.TEXT -> context.COMMON_TYPES.STRING
+                SQLTypeAffinity.BLOB -> types.getArrayType(types.getPrimitiveType(TypeKind.BYTE))
+                else -> {
+                    context.COMMON_TYPES.STRING
+                }
+            }
+        }
+
+        private fun keyTypeFor(context : Context, affinity: SQLTypeAffinity): TypeName {
+            return when (affinity) {
+                SQLTypeAffinity.INTEGER -> TypeName.LONG.box()
+                SQLTypeAffinity.REAL -> TypeName.DOUBLE.box()
+                SQLTypeAffinity.TEXT -> TypeName.get(String::class.java)
+                SQLTypeAffinity.BLOB -> ArrayTypeName.of(TypeName.BYTE)
+                else -> {
+                    // no affinity select from type
+                    context.COMMON_TYPES.STRING.typeName()
+                }
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutMethod.kt
new file mode 100644
index 0000000..121f993
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutMethod.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import javax.lang.model.element.ExecutableElement
+
+/**
+ * Base class for shortcut methods in @DAO.
+ */
+abstract class ShortcutMethod(val element: ExecutableElement, val name: String,
+                              val entities: Map<String, Entity>, val returnCount: Boolean,
+                              val parameters: List<ShortcutQueryParameter>)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutQueryParameter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutQueryParameter.kt
new file mode 100644
index 0000000..29fc759
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/ShortcutQueryParameter.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.vo
+
+import javax.lang.model.type.TypeMirror
+
+/**
+ * Parameters used in DAO methods that are annotated with Insert, Delete, Update.
+ */
+data class ShortcutQueryParameter(val name: String, val type: TypeMirror,
+                                  val entityType: TypeMirror?, val isMultiple: Boolean) {
+    /**
+     * Method name in entity insertion or update adapter.
+     */
+    fun handleMethodName() : String {
+        return if (isMultiple) {
+            "handleMultiple"
+        } else {
+            "handle"
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/UpdateMethod.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/UpdateMethod.kt
new file mode 100644
index 0000000..ed8eb8b
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/UpdateMethod.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.OnConflictStrategy
+import javax.lang.model.element.ExecutableElement
+
+class UpdateMethod(element: ExecutableElement, name: String,
+                   entities: Map<String, Entity>, returnCount: Boolean,
+                   parameters: List<ShortcutQueryParameter>,
+                   @OnConflictStrategy val onConflictStrategy: Int) : ShortcutMethod(
+        element, name, entities, returnCount, parameters)
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Warning.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Warning.kt
new file mode 100644
index 0000000..9cf137d
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/vo/Warning.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+/**
+ * Internal representation of supported warnings
+ */
+enum class Warning(val publicKey: String) {
+    ALL("ALL"),
+    CURSOR_MISMATCH("ROOM_CURSOR_MISMATCH"),
+    MISSING_JAVA_TMP_DIR("ROOM_MISSING_JAVA_TMP_DIR"),
+    CANNOT_CREATE_VERIFICATION_DATABASE("ROOM_CANNOT_CREATE_VERIFICATION_DATABASE"),
+    PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED("ROOM_EMBEDDED_PRIMARY_KEY_IS_DROPPED"),
+    INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED("ROOM_EMBEDDED_INDEX_IS_DROPPED"),
+    INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED("ROOM_EMBEDDED_ENTITY_INDEX_IS_DROPPED"),
+    INDEX_FROM_PARENT_IS_DROPPED("ROOM_PARENT_INDEX_IS_DROPPED"),
+    INDEX_FROM_PARENT_FIELD_IS_DROPPED("ROOM_PARENT_FIELD_INDEX_IS_DROPPED"),
+    RELATION_TYPE_MISMATCH("ROOM_RELATION_TYPE_MISMATCH"),
+    MISSING_SCHEMA_LOCATION("ROOM_MISSING_SCHEMA_LOCATION"),
+    MISSING_INDEX_ON_FOREIGN_KEY_CHILD("ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX");
+
+    companion object {
+        val PUBLIC_KEY_MAP = Warning.values().associateBy { it.publicKey }
+        fun fromPublicKey(publicKey: String): Warning? {
+            return PUBLIC_KEY_MAP[publicKey.toUpperCase()]
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/ClassWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/ClassWriter.kt
new file mode 100644
index 0000000..7f386bd
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/ClassWriter.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.solver.CodeGenScope.Companion.CLASS_PROPERTY_PREFIX
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.JavaFile
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.annotation.processing.ProcessingEnvironment
+
+/**
+ * Base class for all writers that can produce a class.
+ */
+abstract class ClassWriter(val className: ClassName) {
+    private val sharedFieldSpecs = mutableMapOf<String, FieldSpec>()
+    private val sharedMethodSpecs = mutableMapOf<String, MethodSpec>()
+    private val sharedFieldNames = mutableSetOf<String>()
+    private val sharedMethodNames = mutableSetOf<String>()
+
+    abstract fun createTypeSpecBuilder(): TypeSpec.Builder
+
+    fun write(processingEnv: ProcessingEnvironment) {
+        val builder = createTypeSpecBuilder()
+        sharedFieldSpecs.values.forEach { builder.addField(it) }
+        sharedMethodSpecs.values.forEach { builder.addMethod(it) }
+        JavaFile.builder(className.packageName(), builder.build())
+                .build()
+                .writeTo(processingEnv.filer)
+    }
+
+    private fun makeUnique(set: MutableSet<String>, value: String): String {
+        if (!value.startsWith(CLASS_PROPERTY_PREFIX)) {
+            return makeUnique(set, "$CLASS_PROPERTY_PREFIX$value")
+        }
+        if (set.add(value)) {
+            return value
+        }
+        var index = 1
+        while (true) {
+            if (set.add("${value}_$index")) {
+                return "${value}_$index"
+            }
+            index++
+        }
+    }
+
+    fun getOrCreateField(sharedField: SharedFieldSpec): FieldSpec {
+        return sharedFieldSpecs.getOrPut(sharedField.getUniqueKey(), {
+            sharedField.build(this, makeUnique(sharedFieldNames, sharedField.baseName))
+        })
+    }
+
+    fun getOrCreateMethod(sharedMethod: SharedMethodSpec): MethodSpec {
+        return sharedMethodSpecs.getOrPut(sharedMethod.getUniqueKey(), {
+            sharedMethod.build(this, makeUnique(sharedMethodNames, sharedMethod.baseName))
+        })
+    }
+
+    abstract class SharedFieldSpec(val baseName: String, val type: TypeName) {
+
+        abstract fun getUniqueKey(): String
+
+        abstract fun prepare(writer: ClassWriter, builder: FieldSpec.Builder)
+
+        fun build(classWriter: ClassWriter, name: String): FieldSpec {
+            val builder = FieldSpec.builder(type, name)
+            prepare(classWriter, builder)
+            return builder.build()
+        }
+    }
+
+    abstract class SharedMethodSpec(val baseName: String) {
+
+        abstract fun getUniqueKey(): String
+        abstract fun prepare(writer: ClassWriter, builder: MethodSpec.Builder)
+
+        fun build(writer: ClassWriter, name: String): MethodSpec {
+            val builder = MethodSpec.methodBuilder(name)
+            prepare(writer, builder)
+            return builder.build()
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DaoWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DaoWriter.kt
new file mode 100644
index 0000000..29a6ba7
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DaoWriter.kt
@@ -0,0 +1,459 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.QueryType
+import android.arch.persistence.room.processor.OnConflictProcessor
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Dao
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.InsertionMethod
+import android.arch.persistence.room.vo.QueryMethod
+import android.arch.persistence.room.vo.ShortcutMethod
+import com.google.auto.common.MoreTypes
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.CodeBlock
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import stripNonJava
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.element.ElementKind
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.Modifier.FINAL
+import javax.lang.model.element.Modifier.PRIVATE
+import javax.lang.model.element.Modifier.PUBLIC
+import javax.lang.model.type.DeclaredType
+
+/**
+ * Creates the implementation for a class annotated with Dao.
+ */
+class DaoWriter(val dao: Dao, val processingEnv: ProcessingEnvironment)
+    : ClassWriter(dao.typeName) {
+    val declaredDao = MoreTypes.asDeclared(dao.element.asType())
+    companion object {
+        // TODO nothing prevents this from conflicting, we should fix.
+        val dbField: FieldSpec = FieldSpec
+                .builder(RoomTypeNames.ROOM_DB, "__db", PRIVATE, FINAL)
+                .build()
+
+        private fun typeNameToFieldName(typeName: TypeName?): String {
+            if (typeName is ClassName) {
+                return typeName.simpleName()
+            } else {
+                return typeName.toString().replace('.', '_').stripNonJava()
+            }
+        }
+    }
+
+    override fun createTypeSpecBuilder(): TypeSpec.Builder {
+        val builder = TypeSpec.classBuilder(dao.implTypeName)
+        /**
+         * if delete / update query method wants to return modified rows, we need prepared query.
+         * in that case, if args are dynamic, we cannot re-use the query, if not, we should re-use
+         * it. this requires more work but creates good performance.
+         */
+        val groupedDeleteUpdate = dao.queryMethods
+                .filter { it.query.type == QueryType.DELETE || it.query.type == QueryType.UPDATE }
+                .groupBy { it.parameters.any { it.queryParamAdapter?.isMultiple ?: true } }
+        // delete queries that can be prepared ahead of time
+        val preparedDeleteOrUpdateQueries = groupedDeleteUpdate[false] ?: emptyList()
+        // delete queries that must be rebuild every single time
+        val oneOffDeleteOrUpdateQueries = groupedDeleteUpdate[true] ?: emptyList()
+        val shortcutMethods = createInsertionMethods() +
+                createDeletionMethods() + createUpdateMethods() +
+                createPreparedDeleteOrUpdateQueries(preparedDeleteOrUpdateQueries)
+
+        builder.apply {
+            addModifiers(PUBLIC)
+            if (dao.element.kind == ElementKind.INTERFACE) {
+                addSuperinterface(dao.typeName)
+            } else {
+                superclass(dao.typeName)
+            }
+            addField(dbField)
+            val dbParam = ParameterSpec
+                    .builder(dao.constructorParamType ?: dbField.type, dbField.name).build()
+
+            addMethod(createConstructor(dbParam, shortcutMethods, dao.constructorParamType != null))
+
+            shortcutMethods.forEach {
+                addMethod(it.methodImpl)
+            }
+
+            dao.queryMethods.filter { it.query.type == QueryType.SELECT }.forEach { method ->
+                addMethod(createSelectMethod(method))
+            }
+            oneOffDeleteOrUpdateQueries.forEach {
+                addMethod(createDeleteOrUpdateQueryMethod(it))
+            }
+        }
+        return builder
+    }
+
+    private fun createPreparedDeleteOrUpdateQueries(preparedDeleteQueries: List<QueryMethod>)
+            : List<PreparedStmtQuery> {
+        return preparedDeleteQueries.map { method ->
+            val fieldSpec = getOrCreateField(PreparedStatementField(method))
+            val queryWriter = QueryWriter(method)
+            val fieldImpl = PreparedStatementWriter(queryWriter)
+                    .createAnonymous(this@DaoWriter, dbField)
+            val methodBody = createPreparedDeleteQueryMethodBody(method, fieldSpec, queryWriter)
+            PreparedStmtQuery(mapOf(PreparedStmtQuery.NO_PARAM_FIELD
+                    to (fieldSpec to fieldImpl)), methodBody)
+        }
+    }
+
+    private fun createPreparedDeleteQueryMethodBody(method: QueryMethod,
+                                                    preparedStmtField: FieldSpec,
+                                                    queryWriter: QueryWriter): MethodSpec {
+        val scope = CodeGenScope(this)
+        val methodBuilder = overrideWithoutAnnotations(method.element, declaredDao).apply {
+            val stmtName = scope.getTmpVar("_stmt")
+            addStatement("final $T $L = $N.acquire()",
+                    SupportDbTypeNames.SQLITE_STMT, stmtName, preparedStmtField)
+            addStatement("$N.beginTransaction()", dbField)
+            beginControlFlow("try").apply {
+                val bindScope = scope.fork()
+                queryWriter.bindArgs(stmtName, emptyList(), bindScope)
+                addCode(bindScope.builder().build())
+                if (method.returnsValue) {
+                    val resultVar = scope.getTmpVar("_result")
+                    addStatement("final $L $L = $L.executeUpdateDelete()",
+                            method.returnType.typeName(), resultVar, stmtName)
+                    addStatement("$N.setTransactionSuccessful()", dbField)
+                    addStatement("return $L", resultVar)
+                } else {
+                    addStatement("$L.executeUpdateDelete()", stmtName)
+                    addStatement("$N.setTransactionSuccessful()", dbField)
+                }
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$N.endTransaction()", dbField)
+                addStatement("$N.release($L)", preparedStmtField, stmtName)
+            }
+            endControlFlow()
+        }
+        return methodBuilder.build()
+    }
+
+    private fun createConstructor(dbParam: ParameterSpec,
+                                  shortcutMethods: List<PreparedStmtQuery>,
+                                  callSuper: Boolean): MethodSpec {
+        return MethodSpec.constructorBuilder().apply {
+            addParameter(dbParam)
+            addModifiers(PUBLIC)
+            if (callSuper) {
+                addStatement("super($N)", dbParam)
+            }
+            addStatement("this.$N = $N", dbField, dbParam)
+            shortcutMethods.filterNot {
+                it.fields.isEmpty()
+            }.map {
+                it.fields.values
+            }.flatten().groupBy {
+                it.first.name
+            }.map {
+                it.value.first()
+            }.forEach {
+                addStatement("this.$N = $L", it.first, it.second)
+            }
+        }.build()
+    }
+
+    private fun createSelectMethod(method: QueryMethod): MethodSpec {
+        return overrideWithoutAnnotations(method.element, declaredDao).apply {
+            addCode(createQueryMethodBody(method))
+        }.build()
+    }
+
+    private fun createDeleteOrUpdateQueryMethod(method: QueryMethod): MethodSpec {
+        return overrideWithoutAnnotations(method.element, declaredDao).apply {
+            addCode(createDeleteOrUpdateQueryMethodBody(method))
+        }.build()
+    }
+
+    /**
+     * Groups all insertion methods based on the insert statement they will use then creates all
+     * field specs, EntityInsertionAdapterWriter and actual insert methods.
+     */
+    private fun createInsertionMethods(): List<PreparedStmtQuery> {
+        return dao.insertionMethods
+                .map { insertionMethod ->
+                    val onConflict = OnConflictProcessor.onConflictText(insertionMethod.onConflict)
+                    val entities = insertionMethod.entities
+
+                    val fields = entities.mapValues {
+                        val spec = getOrCreateField(InsertionMethodField(it.value, onConflict))
+                        val impl = EntityInsertionAdapterWriter(it.value, onConflict)
+                                .createAnonymous(this@DaoWriter, dbField.name)
+                        spec to impl
+                    }
+                    val methodImpl = overrideWithoutAnnotations(insertionMethod.element,
+                            declaredDao).apply {
+                        addCode(createInsertionMethodBody(insertionMethod, fields))
+                    }.build()
+                    PreparedStmtQuery(fields, methodImpl)
+                }.filterNotNull()
+    }
+
+    private fun createInsertionMethodBody(method: InsertionMethod,
+                                          insertionAdapters: Map<String, Pair<FieldSpec, TypeSpec>>)
+            : CodeBlock {
+        val insertionType = method.insertionType
+        if (insertionAdapters.isEmpty() || insertionType == null) {
+            return CodeBlock.builder().build()
+        }
+        val scope = CodeGenScope(this)
+
+        return scope.builder().apply {
+            // TODO assert thread
+            // TODO collect results
+            addStatement("$N.beginTransaction()", dbField)
+            val needsReturnType = insertionType != InsertionMethod.Type.INSERT_VOID
+            val resultVar = if (needsReturnType) {
+                scope.getTmpVar("_result")
+            } else {
+                null
+            }
+
+            beginControlFlow("try").apply {
+                method.parameters.forEach { param ->
+                    val insertionAdapter = insertionAdapters[param.name]?.first
+                    if (needsReturnType) {
+                        // if it has more than 1 parameter, we would've already printed the error
+                        // so we don't care about re-declaring the variable here
+                        addStatement("$T $L = $N.$L($L)",
+                                insertionType.returnTypeName, resultVar,
+                                insertionAdapter, insertionType.methodName,
+                                param.name)
+                    } else {
+                        addStatement("$N.$L($L)", insertionAdapter, insertionType.methodName,
+                                param.name)
+                    }
+                }
+                addStatement("$N.setTransactionSuccessful()", dbField)
+                if (needsReturnType) {
+                    addStatement("return $L", resultVar)
+                }
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$N.endTransaction()", dbField)
+            }
+            endControlFlow()
+        }.build()
+    }
+
+    /**
+     * Creates EntityUpdateAdapter for each deletion method.
+     */
+    private fun createDeletionMethods(): List<PreparedStmtQuery> {
+        return createShortcutMethods(dao.deletionMethods, "deletion", { deletionMethod, entity ->
+            EntityDeletionAdapterWriter(entity)
+                    .createAnonymous(this@DaoWriter, dbField.name)
+        })
+    }
+
+    /**
+     * Creates EntityUpdateAdapter for each @Update method.
+     */
+    private fun createUpdateMethods(): List<PreparedStmtQuery> {
+        return createShortcutMethods(dao.updateMethods, "update", { update, entity ->
+            val onConflict = OnConflictProcessor.onConflictText(update.onConflictStrategy)
+            EntityUpdateAdapterWriter(entity, onConflict)
+                    .createAnonymous(this@DaoWriter, dbField.name)
+        })
+    }
+
+    private fun <T : ShortcutMethod> createShortcutMethods(methods: List<T>, methodPrefix: String,
+                                                           implCallback: (T, Entity) -> TypeSpec)
+            : List<PreparedStmtQuery> {
+        return methods.map { method ->
+            val entities = method.entities
+
+            if (entities.isEmpty()) {
+                null
+            } else {
+                val fields = entities.mapValues {
+                    val spec = getOrCreateField(DeleteOrUpdateAdapterField(it.value, methodPrefix))
+                    val impl = implCallback(method, it.value)
+                    spec to impl
+                }
+                val methodSpec = overrideWithoutAnnotations(method.element, declaredDao).apply {
+                    addCode(createDeleteOrUpdateMethodBody(method, fields))
+                }.build()
+                PreparedStmtQuery(fields, methodSpec)
+            }
+        }.filterNotNull()
+    }
+
+    private fun createDeleteOrUpdateMethodBody(method: ShortcutMethod,
+                                               adapters: Map<String, Pair<FieldSpec, TypeSpec>>)
+            : CodeBlock {
+        if (adapters.isEmpty()) {
+            return CodeBlock.builder().build()
+        }
+        val scope = CodeGenScope(this)
+        val resultVar = if (method.returnCount) {
+            scope.getTmpVar("_total")
+        } else {
+            null
+        }
+        return scope.builder().apply {
+            if (resultVar != null) {
+                addStatement("$T $L = 0", TypeName.INT, resultVar)
+            }
+            addStatement("$N.beginTransaction()", dbField)
+            beginControlFlow("try").apply {
+                method.parameters.forEach { param ->
+                    val adapter = adapters[param.name]?.first
+                    addStatement("$L$N.$L($L)",
+                            if (resultVar == null) "" else "$resultVar +=",
+                            adapter, param.handleMethodName(), param.name)
+                }
+                addStatement("$N.setTransactionSuccessful()", dbField)
+                if (resultVar != null) {
+                    addStatement("return $L", resultVar)
+                }
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$N.endTransaction()", dbField)
+            }
+            endControlFlow()
+        }.build()
+    }
+
+    /**
+     * @Query with delete action
+     */
+    private fun createDeleteOrUpdateQueryMethodBody(method: QueryMethod): CodeBlock {
+        val queryWriter = QueryWriter(method)
+        val scope = CodeGenScope(this)
+        val sqlVar = scope.getTmpVar("_sql")
+        val stmtVar = scope.getTmpVar("_stmt")
+        val listSizeArgs = queryWriter.prepareQuery(sqlVar, scope)
+        scope.builder().apply {
+            addStatement("$T $L = $N.compileStatement($L)",
+                    SupportDbTypeNames.SQLITE_STMT, stmtVar, dbField, sqlVar)
+            queryWriter.bindArgs(stmtVar, listSizeArgs, scope)
+            addStatement("$N.beginTransaction()", dbField)
+            beginControlFlow("try").apply {
+                if (method.returnsValue) {
+                    val resultVar = scope.getTmpVar("_result")
+                    addStatement("final $L $L = $L.executeUpdateDelete()",
+                            method.returnType.typeName(), resultVar, stmtVar)
+                    addStatement("$N.setTransactionSuccessful()", dbField)
+                    addStatement("return $L", resultVar)
+                } else {
+                    addStatement("$L.executeUpdateDelete()", stmtVar)
+                    addStatement("$N.setTransactionSuccessful()", dbField)
+                }
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$N.endTransaction()", dbField)
+            }
+            endControlFlow()
+
+        }
+        return scope.builder().build()
+    }
+
+    private fun createQueryMethodBody(method: QueryMethod): CodeBlock {
+        val queryWriter = QueryWriter(method)
+        val scope = CodeGenScope(this)
+        val sqlVar = scope.getTmpVar("_sql")
+        val roomSQLiteQueryVar = scope.getTmpVar("_statement")
+        queryWriter.prepareReadAndBind(sqlVar, roomSQLiteQueryVar, scope)
+        method.queryResultBinder.convertAndReturn(roomSQLiteQueryVar, dbField, scope)
+        return scope.builder().build()
+    }
+
+    private fun overrideWithoutAnnotations(elm: ExecutableElement,
+                                           owner : DeclaredType): MethodSpec.Builder {
+        val baseSpec = MethodSpec.overriding(elm, owner, processingEnv.typeUtils).build()
+        return MethodSpec.methodBuilder(baseSpec.name).apply {
+            addAnnotation(Override::class.java)
+            addModifiers(baseSpec.modifiers)
+            addParameters(baseSpec.parameters)
+            varargs(baseSpec.varargs)
+            returns(baseSpec.returnType)
+        }
+    }
+
+    /**
+     * Represents a query statement prepared in Dao implementation.
+     *
+     * @param fields This map holds all the member fields necessary for this query. The key is the
+     * corresponding parameter name in the defining query method. The value is a pair from the field
+     * declaration to definition.
+     * @param methodImpl The body of the query method implementation.
+     */
+    data class PreparedStmtQuery(val fields: Map<String, Pair<FieldSpec, TypeSpec>>,
+                                 val methodImpl: MethodSpec) {
+        companion object {
+            // The key to be used in `fields` where the method requires a field that is not
+            // associated with any of its parameters
+            const val NO_PARAM_FIELD = "-"
+        }
+    }
+
+    private class InsertionMethodField(val entity: Entity, val onConflictText: String)
+        : SharedFieldSpec(
+            "insertionAdapterOf${Companion.typeNameToFieldName(entity.typeName)}",
+            RoomTypeNames.INSERTION_ADAPTER) {
+
+        override fun getUniqueKey(): String {
+            return "${entity.typeName} $onConflictText"
+        }
+
+        override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) {
+            builder.addModifiers(FINAL, PRIVATE)
+        }
+    }
+
+    class DeleteOrUpdateAdapterField(val entity: Entity, val methodPrefix: String)
+        : SharedFieldSpec(
+            "${methodPrefix}AdapterOf${Companion.typeNameToFieldName(entity.typeName)}",
+            RoomTypeNames.DELETE_OR_UPDATE_ADAPTER) {
+        override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) {
+            builder.addModifiers(PRIVATE, FINAL)
+        }
+
+        override fun getUniqueKey(): String {
+            return entity.typeName.toString() + methodPrefix
+        }
+    }
+
+    class PreparedStatementField(val method: QueryMethod) : SharedFieldSpec(
+            "preparedStmtOf${method.name.capitalize()}", RoomTypeNames.SHARED_SQLITE_STMT) {
+        override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) {
+            builder.addModifiers(PRIVATE, FINAL)
+        }
+
+        override fun getUniqueKey(): String {
+            return method.query.original
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DatabaseWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DatabaseWriter.kt
new file mode 100644
index 0000000..e40bd71
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/DatabaseWriter.kt
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.DaoMethod
+import android.arch.persistence.room.vo.Database
+import com.google.auto.common.MoreElements
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeSpec
+import stripNonJava
+import javax.lang.model.element.Modifier
+import javax.lang.model.element.Modifier.PRIVATE
+import javax.lang.model.element.Modifier.PROTECTED
+import javax.lang.model.element.Modifier.PUBLIC
+import javax.lang.model.element.Modifier.VOLATILE
+
+/**
+ * Writes implementation of classes that were annotated with @Database.
+ */
+class DatabaseWriter(val database : Database) : ClassWriter(database.implTypeName) {
+    override fun createTypeSpecBuilder(): TypeSpec.Builder {
+        val builder = TypeSpec.classBuilder(database.implTypeName)
+        builder.apply {
+            addModifiers(PUBLIC)
+            superclass(database.typeName)
+            addMethod(createCreateOpenHelper())
+            addMethod(createCreateInvalidationTracker())
+        }
+        addDaoImpls(builder)
+        return builder
+    }
+
+    private fun createCreateInvalidationTracker(): MethodSpec {
+        return MethodSpec.methodBuilder("createInvalidationTracker").apply {
+            addAnnotation(Override::class.java)
+            addModifiers(PROTECTED)
+            returns(RoomTypeNames.INVALIDATION_TRACKER)
+            val tableNames = database.entities.joinToString(",") {
+                "\"${it.tableName}\""
+            }
+            addStatement("return new $T(this, $L)", RoomTypeNames.INVALIDATION_TRACKER, tableNames)
+        }.build()
+    }
+
+    private fun  addDaoImpls(builder: TypeSpec.Builder) {
+        val scope = CodeGenScope(this)
+        builder.apply {
+            database.daoMethods.forEach { method ->
+                val name = method.dao.typeName.simpleName().decapitalize().stripNonJava()
+                val fieldName = scope.getTmpVar("_$name")
+                val field = FieldSpec.builder(method.dao.typeName, fieldName,
+                        PRIVATE, VOLATILE).build()
+                addField(field)
+                addMethod(createDaoGetter(field, method))
+            }
+        }
+    }
+
+    private fun createDaoGetter(field: FieldSpec, method: DaoMethod) : MethodSpec {
+        return MethodSpec.overriding(MoreElements.asExecutable(method.element)).apply {
+            beginControlFlow("if ($N != null)", field).apply {
+                addStatement("return $N", field)
+            }
+            nextControlFlow("else").apply {
+                beginControlFlow("synchronized(this)").apply {
+                    beginControlFlow("if($N == null)", field).apply {
+                        addStatement("$N = new $T(this)", field, method.dao.implTypeName)
+                    }
+                    endControlFlow()
+                    addStatement("return $N", field)
+                }
+                endControlFlow()
+            }
+            endControlFlow()
+        }.build()
+    }
+
+    private fun createCreateOpenHelper() : MethodSpec {
+        val scope = CodeGenScope(this)
+        return MethodSpec.methodBuilder("createOpenHelper").apply {
+            addModifiers(Modifier.PROTECTED)
+            returns(SupportDbTypeNames.SQLITE_OPEN_HELPER)
+
+            val configParam = ParameterSpec.builder(RoomTypeNames.ROOM_DB_CONFIG,
+                    "configuration").build()
+            addParameter(configParam)
+
+            val openHelperVar = scope.getTmpVar("_helper")
+            val openHelperCode = scope.fork()
+            SQLiteOpenHelperWriter(database)
+                    .write(openHelperVar, configParam, openHelperCode)
+            addCode(openHelperCode.builder().build())
+            addStatement("return $L", openHelperVar)
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriter.kt
new file mode 100644
index 0000000..a83d191
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriter.kt
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.FieldWithIndex
+import com.squareup.javapoet.CodeBlock
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeName
+import stripNonJava
+import javax.lang.model.element.Modifier.PRIVATE
+
+class EntityCursorConverterWriter(val entity: Entity) : ClassWriter.SharedMethodSpec(
+        "entityCursorConverter_${entity.typeName.toString().stripNonJava()}") {
+    override fun getUniqueKey(): String {
+        return "generic_entity_converter_of_${entity.element.qualifiedName}"
+    }
+
+    override fun prepare(writer: ClassWriter, builder: MethodSpec.Builder) {
+        builder.apply {
+            val cursorParam = ParameterSpec
+                    .builder(AndroidTypeNames.CURSOR, "cursor").build()
+            addParameter(cursorParam)
+            addModifiers(PRIVATE)
+            returns(entity.typeName)
+            addCode(buildConvertMethodBody(writer, cursorParam))
+        }
+    }
+
+    private fun depth(parent: EmbeddedField?): Int {
+        return if (parent == null) {
+            0
+        } else {
+            1 + depth(parent.parent)
+        }
+    }
+
+    private fun buildConvertMethodBody(writer: ClassWriter, cursorParam: ParameterSpec)
+            : CodeBlock {
+        val scope = CodeGenScope(writer)
+        val entityVar = scope.getTmpVar("_entity")
+        scope.builder().apply {
+            scope.builder().addStatement("final $T $L", entity.typeName, entityVar)
+            val fieldsWithIndices = entity.fields.map {
+                val indexVar = scope.getTmpVar(
+                        "_cursorIndexOf${it.name.stripNonJava().capitalize()}")
+                scope.builder().addStatement("final $T $L = $N.getColumnIndex($S)",
+                        TypeName.INT, indexVar, cursorParam, it.columnName)
+                FieldWithIndex(field = it,
+                        indexVar = indexVar,
+                        alwaysExists = false)
+            }
+            FieldReadWriteWriter.readFromCursor(
+                    outVar = entityVar,
+                    outPojo = entity,
+                    cursorVar = cursorParam.name,
+                    fieldsWithIndices = fieldsWithIndices,
+                    relationCollectors = emptyList(), // no relationship for entities
+                    scope = scope)
+            addStatement("return $L", entityVar)
+        }
+        return scope.builder().build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityDeletionAdapterWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityDeletionAdapterWriter.kt
new file mode 100644
index 0000000..29ba984
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityDeletionAdapterWriter.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.FieldWithIndex
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier.PUBLIC
+
+class EntityDeletionAdapterWriter(val entity: Entity) {
+    fun createAnonymous(classWriter: ClassWriter, dbParam: String): TypeSpec {
+        @Suppress("RemoveSingleExpressionStringTemplate")
+        return TypeSpec.anonymousClassBuilder("$L", dbParam).apply {
+            superclass(ParameterizedTypeName.get(RoomTypeNames.DELETE_OR_UPDATE_ADAPTER,
+                    entity.typeName)
+            )
+            addMethod(MethodSpec.methodBuilder("createQuery").apply {
+                addAnnotation(Override::class.java)
+                returns(ClassName.get("java.lang", "String"))
+                addModifiers(PUBLIC)
+                val query = "DELETE FROM `${entity.tableName}` WHERE " +
+                        entity.primaryKey.fields.joinToString(" AND ") {
+                            "`${it.columnName}` = ?"
+                        }
+                addStatement("return $S", query)
+            }.build())
+            addMethod(MethodSpec.methodBuilder("bind").apply {
+                val bindScope = CodeGenScope(classWriter)
+                addAnnotation(Override::class.java)
+                val stmtParam = "stmt"
+                addParameter(ParameterSpec.builder(SupportDbTypeNames.SQLITE_STMT,
+                        stmtParam).build())
+                val valueParam = "value"
+                addParameter(ParameterSpec.builder(entity.typeName, valueParam).build())
+                returns(TypeName.VOID)
+                addModifiers(PUBLIC)
+                val mapped = FieldWithIndex.byOrder(entity.primaryKey.fields)
+                FieldReadWriteWriter.bindToStatement(ownerVar = valueParam,
+                        stmtParamVar = stmtParam,
+                        fieldsWithIndices = mapped,
+                        scope = bindScope)
+                addCode(bindScope.builder().build())
+            }.build())
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityInsertionAdapterWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityInsertionAdapterWriter.kt
new file mode 100644
index 0000000..cd3e771
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityInsertionAdapterWriter.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.FieldWithIndex
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier.PUBLIC
+
+class EntityInsertionAdapterWriter(val entity: Entity, val onConflict: String) {
+    fun createAnonymous(classWriter: ClassWriter, dbParam : String): TypeSpec {
+        @Suppress("RemoveSingleExpressionStringTemplate")
+        return TypeSpec.anonymousClassBuilder("$L", dbParam).apply {
+            superclass(
+                    ParameterizedTypeName.get(RoomTypeNames.INSERTION_ADAPTER, entity.typeName)
+            )
+
+            // If there is an auto-increment primary key with primitive type, we consider 0 as
+            // not set. For such fields, we must generate a slightly different insertion SQL.
+            val primitiveAutoGenerateField = if (entity.primaryKey.autoGenerateId) {
+                entity.primaryKey.fields.firstOrNull()?.let { field ->
+                    field.statementBinder?.typeMirror()?.let { binderType ->
+                        if (binderType.kind.isPrimitive) {
+                            field
+                        } else {
+                            null
+                        }
+                    }
+                }
+            } else {
+                null
+            }
+            addMethod(MethodSpec.methodBuilder("createQuery").apply {
+                addAnnotation(Override::class.java)
+                returns(ClassName.get("java.lang", "String"))
+                addModifiers(PUBLIC)
+                val query =
+                        "INSERT OR $onConflict INTO `${entity.tableName}`(" +
+                                entity.fields.joinToString(",") {
+                                    "`${it.columnName}`"
+                                } + ") VALUES (" +
+                                entity.fields.joinToString(",") {
+                                    if (primitiveAutoGenerateField == it) {
+                                        "nullif(?, 0)"
+                                    } else {
+                                        "?"
+                                    }
+                                } + ")"
+                addStatement("return $S", query)
+            }.build())
+            addMethod(MethodSpec.methodBuilder("bind").apply {
+                val bindScope = CodeGenScope(classWriter)
+                addAnnotation(Override::class.java)
+                val stmtParam = "stmt"
+                addParameter(ParameterSpec.builder(SupportDbTypeNames.SQLITE_STMT,
+                        stmtParam).build())
+                val valueParam = "value"
+                addParameter(ParameterSpec.builder(entity.typeName, valueParam).build())
+                returns(TypeName.VOID)
+                addModifiers(PUBLIC)
+                val mapped = FieldWithIndex.byOrder(entity.fields)
+                FieldReadWriteWriter.bindToStatement(
+                        ownerVar = valueParam,
+                        stmtParamVar = stmtParam,
+                        fieldsWithIndices = mapped,
+                        scope = bindScope
+                )
+                addCode(bindScope.builder().build())
+            }.build())
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityUpdateAdapterWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityUpdateAdapterWriter.kt
new file mode 100644
index 0000000..b5711dc
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/EntityUpdateAdapterWriter.kt
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.FieldWithIndex
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier.PUBLIC
+
+class EntityUpdateAdapterWriter(val entity: Entity, val onConflict : String) {
+    fun createAnonymous(classWriter: ClassWriter, dbParam: String): TypeSpec {
+        @Suppress("RemoveSingleExpressionStringTemplate")
+        return TypeSpec.anonymousClassBuilder("$L", dbParam).apply {
+            superclass(ParameterizedTypeName.get(RoomTypeNames.DELETE_OR_UPDATE_ADAPTER,
+                    entity.typeName)
+            )
+            addMethod(MethodSpec.methodBuilder("createQuery").apply {
+                addAnnotation(Override::class.java)
+                returns(ClassName.get("java.lang", "String"))
+                addModifiers(PUBLIC)
+                val query = "UPDATE OR $onConflict `${entity.tableName}` SET " +
+                        entity.fields.joinToString(",") { field ->
+                            "`${field.columnName}` = ?"
+                        } + " WHERE " + entity.primaryKey.fields.joinToString(" AND ") {
+                            "`${it.columnName}` = ?"
+                        }
+                addStatement("return $S", query)
+            }.build())
+            addMethod(MethodSpec.methodBuilder("bind").apply {
+                val bindScope = CodeGenScope(classWriter)
+                addAnnotation(Override::class.java)
+                val stmtParam = "stmt"
+                addParameter(ParameterSpec.builder(SupportDbTypeNames.SQLITE_STMT,
+                        stmtParam).build())
+                val valueParam = "value"
+                addParameter(ParameterSpec.builder(entity.typeName, valueParam).build())
+                returns(TypeName.VOID)
+                addModifiers(PUBLIC)
+                val mappedField = FieldWithIndex.byOrder(entity.fields)
+                FieldReadWriteWriter.bindToStatement(
+                        ownerVar = valueParam,
+                        stmtParamVar = stmtParam,
+                        fieldsWithIndices = mappedField,
+                        scope = bindScope
+                )
+                val pkeyStart = entity.fields.size
+                val mappedPrimaryKeys = entity.primaryKey.fields.mapIndexed { index, field ->
+                    FieldWithIndex(field = field,
+                            indexVar = "${pkeyStart + index + 1}",
+                            alwaysExists = true)
+                }
+                FieldReadWriteWriter.bindToStatement(
+                        ownerVar = valueParam,
+                        stmtParamVar = stmtParam,
+                        fieldsWithIndices = mappedPrimaryKeys,
+                        scope = bindScope
+                )
+                addCode(bindScope.builder().build())
+            }.build())
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/FieldReadWriteWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/FieldReadWriteWriter.kt
new file mode 100644
index 0000000..8df3feb
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/FieldReadWriteWriter.kt
@@ -0,0 +1,368 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.defaultValue
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Constructor
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.FieldWithIndex
+import android.arch.persistence.room.vo.Pojo
+import android.arch.persistence.room.vo.RelationCollector
+import com.squareup.javapoet.TypeName
+
+/**
+ * Handles writing a field into statement or reading it form statement.
+ */
+class FieldReadWriteWriter(fieldWithIndex: FieldWithIndex) {
+    val field = fieldWithIndex.field
+    val indexVar = fieldWithIndex.indexVar
+    val alwaysExists = fieldWithIndex.alwaysExists
+
+    companion object {
+        /*
+         * Get all parents including the ones which have grand children in this list but does not
+         * have any direct children in the list.
+         */
+        fun getAllParents(fields: List<Field>): Set<EmbeddedField> {
+            val allParents = mutableSetOf<EmbeddedField>()
+            fun addAllParents(field: Field) {
+                var parent = field.parent
+                while (parent != null) {
+                    if (allParents.add(parent)) {
+                        parent = parent.parent
+                    } else {
+                        break
+                    }
+                }
+            }
+            fields.forEach(::addAllParents)
+            return allParents
+        }
+
+        /**
+         * Convert the fields with indices into a Node tree so that we can recursively process
+         * them. This work is done here instead of parsing because the result may include arbitrary
+         * fields.
+         */
+        private fun createNodeTree(rootVar: String,
+                           fieldsWithIndices: List<FieldWithIndex>,
+                           scope: CodeGenScope): Node {
+            val allParents = getAllParents(fieldsWithIndices.map { it.field })
+            val rootNode = Node(rootVar, null)
+            rootNode.directFields = fieldsWithIndices.filter { it.field.parent == null }
+            val parentNodes = allParents.associate {
+                Pair(it, Node(
+                        varName = scope.getTmpVar("_tmp${it.field.name.capitalize()}"),
+                        fieldParent = it))
+            }
+            parentNodes.values.forEach { node ->
+                val fieldParent = node.fieldParent!!
+                val grandParent = fieldParent.parent
+                val grandParentNode = grandParent?.let {
+                    parentNodes[it]
+                } ?: rootNode
+                node.directFields = fieldsWithIndices.filter { it.field.parent == fieldParent }
+                node.parentNode = grandParentNode
+                grandParentNode.subNodes.add(node)
+            }
+            return rootNode
+        }
+
+        fun bindToStatement(ownerVar: String, stmtParamVar: String,
+                            fieldsWithIndices: List<FieldWithIndex>,
+                            scope: CodeGenScope) {
+            fun visitNode(node: Node) {
+                fun bindWithDescendants() {
+                    node.directFields.forEach {
+                        FieldReadWriteWriter(it).bindToStatement(
+                                ownerVar = node.varName,
+                                stmtParamVar = stmtParamVar,
+                                scope = scope
+                        )
+                    }
+                    node.subNodes.forEach(::visitNode)
+                }
+
+                val fieldParent = node.fieldParent
+                if (fieldParent != null) {
+                    fieldParent.getter.writeGet(
+                            ownerVar = node.parentNode!!.varName,
+                            outVar = node.varName,
+                            builder = scope.builder()
+                    )
+                    scope.builder().apply {
+                        beginControlFlow("if($L != null)", node.varName).apply {
+                            bindWithDescendants()
+                        }
+                        nextControlFlow("else").apply {
+                            node.allFields().forEach {
+                                addStatement("$L.bindNull($L)", stmtParamVar, it.indexVar)
+                            }
+                        }
+                        endControlFlow()
+                    }
+                } else {
+                    bindWithDescendants()
+                }
+            }
+            visitNode(createNodeTree(ownerVar, fieldsWithIndices, scope))
+        }
+
+        /**
+         * Just constructs the given item, does NOT DECLARE. Declaration happens outside the
+         * reading statement since we may never read if the cursor does not have necessary
+         * columns.
+         */
+        private fun construct(outVar : String, constructor : Constructor?, typeName : TypeName,
+                              localVariableNames : Map<String, FieldWithIndex>,
+                              localEmbeddeds: List<Node>, scope: CodeGenScope) {
+            if (constructor == null) {
+                // best hope code generation
+                scope.builder().apply {
+                    addStatement("$L = new $T()", outVar, typeName)
+                }
+                return
+            }
+            val variableNames = constructor.params.map { param ->
+                when(param) {
+                    is Constructor.FieldParam -> localVariableNames.entries.firstOrNull {
+                        it.value.field === param.field
+                    }?.key
+                    is Constructor.EmbeddedParam -> localEmbeddeds.firstOrNull {
+                        it.fieldParent === param.embedded
+                    }?.varName
+                    else -> null
+                }
+            }
+            val args = variableNames.joinToString(",") { it ?: "null"}
+            scope.builder().apply {
+                addStatement("$L = new $T($L)", outVar, typeName, args)
+            }
+        }
+
+        /**
+         * Reads the row into the given variable. It does not declare it but constructs it.
+         */
+        fun readFromCursor(outVar: String,
+                           outPojo : Pojo,
+                           cursorVar: String,
+                           fieldsWithIndices: List<FieldWithIndex>,
+                           scope: CodeGenScope,
+                           relationCollectors : List<RelationCollector>) {
+            fun visitNode(node: Node) {
+                val fieldParent = node.fieldParent
+                fun readNode() {
+                    // read constructor parameters into local fields
+                    val constructorFields = node.directFields.filter {
+                        it.field.setter.callType == CallType.CONSTRUCTOR
+                    }.associateBy { fwi ->
+                        FieldReadWriteWriter(fwi).readIntoTmpVar(cursorVar, scope)
+                    }
+                    // read decomposed fields
+                    node.subNodes.forEach(::visitNode)
+                    // construct the object
+                    if (fieldParent != null) {
+                        construct(outVar = node.varName,
+                                constructor = fieldParent.pojo.constructor,
+                                typeName = fieldParent.field.typeName,
+                                localEmbeddeds = node.subNodes,
+                                localVariableNames = constructorFields,
+                                scope = scope)
+                    } else {
+                        construct(outVar = node.varName,
+                                constructor = outPojo.constructor,
+                                typeName = outPojo.typeName,
+                                localEmbeddeds = node.subNodes,
+                                localVariableNames = constructorFields,
+                                scope = scope)
+                    }
+                    // ready any field that was not part of the constructor
+                    node.directFields.filterNot {
+                        it.field.setter.callType == CallType.CONSTRUCTOR
+                    }.forEach { fwi ->
+                        FieldReadWriteWriter(fwi).readFromCursor(
+                                ownerVar = node.varName,
+                                cursorVar = cursorVar,
+                                scope = scope)
+                    }
+                    // assign relationship fields which will be read later
+                    relationCollectors.filter { (relation) ->
+                        relation.field.parent === fieldParent
+                    }.forEach {
+                        it.writeReadParentKeyCode(
+                                cursorVarName = cursorVar,
+                                itemVar = node.varName,
+                                fieldsWithIndices = fieldsWithIndices,
+                                scope = scope)
+                    }
+                    // assign sub modes to fields if they were not part of the constructor.
+                    node.subNodes.map {
+                        val setter = it.fieldParent?.setter
+                        if (setter != null && setter.callType != CallType.CONSTRUCTOR) {
+                            Pair(it.varName, setter)
+                        } else {
+                            null
+                        }
+                    }.filterNotNull().forEach { (varName, setter) ->
+                        setter.writeSet(
+                                ownerVar = node.varName,
+                                inVar = varName,
+                                builder = scope.builder())
+                    }
+                }
+                if (fieldParent == null) {
+                    // root element
+                    // always declared by the caller so we don't declare this
+                    readNode()
+                } else {
+                    // always declare, we'll set below
+                    scope.builder().addStatement("final $T $L", fieldParent.pojo.typeName,
+                                        node.varName)
+                    if (fieldParent.nonNull) {
+                        readNode()
+                    } else {
+                        val myDescendants = node.allFields()
+                        val allNullCheck = myDescendants.joinToString(" && ") {
+                            if (it.alwaysExists) {
+                                "$cursorVar.isNull(${it.indexVar})"
+                            } else {
+                                "( ${it.indexVar} == -1 || $cursorVar.isNull(${it.indexVar}))"
+                            }
+
+                        }
+                        scope.builder().apply {
+                            beginControlFlow("if (! ($L))", allNullCheck).apply {
+                                readNode()
+                            }
+                            nextControlFlow(" else ").apply {
+                                addStatement("$L = null", node.varName)
+                            }
+                            endControlFlow()
+                        }
+                    }
+                }
+            }
+            visitNode(createNodeTree(outVar, fieldsWithIndices, scope))
+        }
+    }
+
+    /**
+     * @param ownerVar The entity / pojo that owns this field. It must own this field! (not the
+     * container pojo)
+     * @param stmtParamVar The statement variable
+     * @param scope The code generation scope
+     */
+    private fun bindToStatement(ownerVar: String, stmtParamVar: String, scope: CodeGenScope) {
+        field.statementBinder?.let { binder ->
+            val varName = if (field.getter.callType == CallType.FIELD) {
+                "$ownerVar.${field.name}"
+            } else {
+                "$ownerVar.${field.getter.name}()"
+            }
+            binder.bindToStmt(stmtParamVar, indexVar, varName, scope)
+        }
+    }
+
+    /**
+     * @param ownerVar The entity / pojo that owns this field. It must own this field (not the
+     * container pojo)
+     * @param cursorVar The cursor variable
+     * @param scope The code generation scope
+     */
+    private fun readFromCursor(ownerVar: String, cursorVar: String, scope: CodeGenScope) {
+        fun toRead() {
+            field.cursorValueReader?.let { reader ->
+                scope.builder().apply {
+                    when (field.setter.callType) {
+                        CallType.FIELD -> {
+                            reader.readFromCursor("$ownerVar.${field.getter.name}", cursorVar,
+                                    indexVar, scope)
+                        }
+                        CallType.METHOD -> {
+                            val tmpField = scope.getTmpVar("_tmp${field.name.capitalize()}")
+                            addStatement("final $T $L", field.getter.type.typeName(), tmpField)
+                            reader.readFromCursor(tmpField, cursorVar, indexVar, scope)
+                            addStatement("$L.$L($L)", ownerVar, field.setter.name, tmpField)
+                        }
+                        CallType.CONSTRUCTOR -> {
+                            // no-op
+                        }
+                    }
+                }
+            }
+        }
+        if (alwaysExists) {
+            toRead()
+        } else {
+            scope.builder().apply {
+                beginControlFlow("if ($L != -1)", indexVar).apply {
+                    toRead()
+                }
+                endControlFlow()
+            }
+        }
+    }
+
+    /**
+     * Reads the value into a temporary local variable.
+     */
+    fun readIntoTmpVar(cursorVar: String, scope: CodeGenScope) : String {
+        val tmpField = scope.getTmpVar("_tmp${field.name.capitalize()}")
+        val typeName = field.getter.type.typeName()
+        scope.builder().apply {
+            addStatement("final $T $L", typeName, tmpField)
+            if (alwaysExists) {
+                field.cursorValueReader?.readFromCursor(tmpField, cursorVar, indexVar, scope)
+            } else {
+                beginControlFlow("if ($L == -1)", indexVar).apply {
+                    addStatement("$L = $L", tmpField, typeName.defaultValue())
+                }
+                nextControlFlow("else").apply {
+                    field.cursorValueReader?.readFromCursor(tmpField, cursorVar, indexVar, scope)
+                }
+                endControlFlow()
+            }
+        }
+        return tmpField
+    }
+
+    /**
+     * On demand node which is created based on the fields that were passed into this class.
+     */
+    private class Node(
+            // root for me
+            val varName: String,
+            // set if I'm a FieldParent
+            val fieldParent: EmbeddedField?) {
+        // whom do i belong
+        var parentNode: Node? = null
+        // these fields are my direct fields
+        lateinit var directFields: List<FieldWithIndex>
+        // these nodes are under me
+        val subNodes = mutableListOf<Node>()
+
+        fun allFields(): List<FieldWithIndex> {
+            return directFields + subNodes.flatMap { it.allFields() }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/PreparedStatementWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/PreparedStatementWriter.kt
new file mode 100644
index 0000000..9c3e612
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/PreparedStatementWriter.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.solver.CodeGenScope
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier
+
+/**
+ * Creates anonymous classes for RoomTypeNames#SHARED_SQLITE_STMT.
+ */
+class PreparedStatementWriter(val queryWriter: QueryWriter) {
+    fun createAnonymous(classWriter: ClassWriter, dbParam : FieldSpec): TypeSpec {
+        val scope = CodeGenScope(classWriter)
+        @Suppress("RemoveSingleExpressionStringTemplate")
+        return TypeSpec.anonymousClassBuilder("$N", dbParam).apply {
+            superclass(RoomTypeNames.SHARED_SQLITE_STMT)
+            addMethod(MethodSpec.methodBuilder("createQuery").apply {
+                addAnnotation(Override::class.java)
+                returns(ClassName.get("java.lang", "String"))
+                addModifiers(Modifier.PUBLIC)
+                val queryName = scope.getTmpVar("_query")
+                val queryGenScope = scope.fork()
+                queryWriter.prepareQuery(queryName, queryGenScope)
+                addCode(queryGenScope.builder().build())
+                addStatement("return $L", queryName)
+            }.build())
+        }.build()
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/QueryWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/QueryWriter.kt
new file mode 100644
index 0000000..2bf471a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/QueryWriter.kt
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.RoomTypeNames.ROOM_SQL_QUERY
+import android.arch.persistence.room.ext.RoomTypeNames.STRING_UTIL
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.ParsedQuery
+import android.arch.persistence.room.parser.Section
+import android.arch.persistence.room.parser.SectionType.BIND_VAR
+import android.arch.persistence.room.parser.SectionType.NEWLINE
+import android.arch.persistence.room.parser.SectionType.TEXT
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.QueryMethod
+import android.arch.persistence.room.vo.QueryParameter
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.TypeName
+
+/**
+ * Writes the SQL query and arguments for a QueryMethod.
+ */
+class QueryWriter constructor(val parameters : List<QueryParameter>,
+                              val sectionToParamMapping : List<Pair<Section, QueryParameter?>>,
+                              val query : ParsedQuery) {
+
+    constructor(queryMethod: QueryMethod) : this(queryMethod.parameters,
+            queryMethod.sectionToParamMapping, queryMethod.query) {
+    }
+
+    fun prepareReadAndBind(outSqlQueryName: String, outRoomSQLiteQueryVar: String,
+                           scope: CodeGenScope) {
+        val listSizeVars = createSqlQueryAndArgs(outSqlQueryName, outRoomSQLiteQueryVar, scope)
+        bindArgs(outRoomSQLiteQueryVar, listSizeVars, scope)
+    }
+
+    fun prepareQuery(outSqlQueryName: String, scope: CodeGenScope)
+            : List<Pair<QueryParameter, String>> {
+        return createSqlQueryAndArgs(outSqlQueryName, null, scope)
+    }
+
+    private fun createSqlQueryAndArgs(outSqlQueryName: String, outArgsName: String?,
+                                      scope: CodeGenScope): List<Pair<QueryParameter, String>> {
+        val listSizeVars = arrayListOf<Pair<QueryParameter, String>>()
+        val varargParams = parameters
+                .filter { it.queryParamAdapter?.isMultiple ?: false }
+        val sectionToParamMapping = sectionToParamMapping
+        val knownQueryArgsCount = sectionToParamMapping.filterNot {
+            it.second?.queryParamAdapter?.isMultiple ?: false
+        }.size
+        scope.builder().apply {
+            if (varargParams.isNotEmpty()) {
+                val stringBuilderVar = scope.getTmpVar("_stringBuilder")
+                addStatement("$T $L = $T.newStringBuilder()",
+                        ClassName.get(StringBuilder::class.java), stringBuilderVar, STRING_UTIL)
+                query.sections.forEach {
+                    when (it.type) {
+                        TEXT -> addStatement("$L.append($S)", stringBuilderVar, it.text)
+                        NEWLINE -> addStatement("$L.append($S)", "\n")
+                        BIND_VAR -> {
+                            // If it is null, will be reported as error before. We just try out
+                            // best to generate as much code as possible.
+                            sectionToParamMapping.firstOrNull { mapping ->
+                                mapping.first == it
+                            }?.let { pair ->
+                                if (pair.second?.queryParamAdapter?.isMultiple ?: false) {
+                                    val tmpCount = scope.getTmpVar("_inputSize")
+                                    listSizeVars.add(Pair(pair.second!!, tmpCount))
+                                    pair.second
+                                            ?.queryParamAdapter
+                                            ?.getArgCount(pair.second!!.name, tmpCount, scope)
+                                    addStatement("$T.appendPlaceholders($L, $L)",
+                                            STRING_UTIL, stringBuilderVar, tmpCount)
+                                } else {
+                                    addStatement("$L.append($S)", stringBuilderVar, "?")
+                                }
+                            }
+                        }
+                    }
+                }
+
+                addStatement("final $T $L = $L.toString()", String::class.typeName(),
+                        outSqlQueryName, stringBuilderVar)
+                if (outArgsName != null) {
+                    val argCount = scope.getTmpVar("_argCount")
+                    addStatement("final $T $L = $L$L", TypeName.INT, argCount, knownQueryArgsCount,
+                            listSizeVars.joinToString("") { " + ${it.second}" })
+                    addStatement("final $T $L = $T.acquire($L, $L)",
+                            ROOM_SQL_QUERY, outArgsName, ROOM_SQL_QUERY, outSqlQueryName,
+                            argCount)
+                }
+            } else {
+                addStatement("final $T $L = $S", String::class.typeName(),
+                        outSqlQueryName, query.queryWithReplacedBindParams)
+                if (outArgsName != null) {
+                    addStatement("final $T $L = $T.acquire($L, $L)",
+                            ROOM_SQL_QUERY, outArgsName, ROOM_SQL_QUERY, outSqlQueryName,
+                            knownQueryArgsCount)
+                }
+            }
+        }
+        return listSizeVars
+    }
+
+    fun bindArgs(outArgsName: String, listSizeVars : List<Pair<QueryParameter, String>>,
+                         scope: CodeGenScope) {
+        if (parameters.isEmpty()) {
+            return
+        }
+        scope.builder().apply {
+            val argIndex = scope.getTmpVar("_argIndex")
+            addStatement("$T $L = $L", TypeName.INT, argIndex, 1)
+            // # of bindings with 1 placeholder
+            var constInputs = 0
+            // variable names for size of the bindings that have multiple  args
+            val varInputs = arrayListOf<String>()
+            sectionToParamMapping.forEach { pair ->
+                // reset the argIndex to the correct start index
+                if (constInputs > 0 || varInputs.isNotEmpty()) {
+                    addStatement("$L = $L$L", argIndex,
+                            if (constInputs > 0) (1 + constInputs) else "1",
+                            varInputs.joinToString("") { " + $it" })
+                }
+                val param = pair.second
+                param?.let {
+                    param.queryParamAdapter?.bindToStmt(param.name, outArgsName, argIndex, scope)
+                }
+                // add these to the list so that we can use them to calculate the next count.
+                val sizeVar = listSizeVars.firstOrNull { it.first == param }
+                if (sizeVar == null) {
+                    constInputs ++
+                } else {
+                    varInputs.add(sizeVar.second)
+                }
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/RelationCollectorMethodWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/RelationCollectorMethodWriter.kt
new file mode 100644
index 0000000..092cbb0
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/RelationCollectorMethodWriter.kt
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.AndroidTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.RelationCollector
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import stripNonJava
+import javax.lang.model.element.Modifier
+
+/**
+ * Writes the method that fetches the relations of a POJO and assigns them into the given map.
+ */
+class RelationCollectorMethodWriter(val collector: RelationCollector)
+    : ClassWriter.SharedMethodSpec(
+        "fetchRelationship${collector.relation.entity.tableName.stripNonJava()}" +
+                "As${collector.relation.pojo.typeName.toString().stripNonJava()}") {
+    companion object {
+        val KEY_SET_VARIABLE = "__mapKeySet"
+    }
+    override fun getUniqueKey(): String {
+        val relation = collector.relation
+        return "RelationCollectorMethodWriter" +
+                "-${collector.mapTypeName}" +
+                "-${relation.entity.typeName}" +
+                "-${relation.entityField.columnName}" +
+                "-${relation.pojo.typeName}" +
+                "-${relation.createLoadAllSql()}"
+    }
+
+    override fun prepare(writer: ClassWriter, builder: MethodSpec.Builder) {
+        val scope = CodeGenScope(writer)
+        val relation = collector.relation
+
+        val param = ParameterSpec.builder(collector.mapTypeName, "_map")
+                .addModifiers(Modifier.FINAL)
+                .build()
+        val sqlQueryVar = scope.getTmpVar("_sql")
+        val keySetVar = KEY_SET_VARIABLE
+
+        val cursorVar = "_cursor"
+        val itemKeyIndexVar = "_itemKeyIndex"
+        val stmtVar = scope.getTmpVar("_stmt")
+        scope.builder().apply {
+
+            val keySetType = ParameterizedTypeName.get(
+                    ClassName.get(Set::class.java), collector.keyTypeName
+            )
+            addStatement("final $T $L = $N.keySet()", keySetType, keySetVar, param)
+            beginControlFlow("if ($L.isEmpty())", keySetVar).apply {
+                addStatement("return")
+            }
+            endControlFlow()
+            collector.queryWriter.prepareReadAndBind(sqlQueryVar, stmtVar, scope)
+
+            addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar,
+                    DaoWriter.dbField, stmtVar)
+
+            beginControlFlow("try").apply {
+                addStatement("final $T $L = $L.getColumnIndex($S)",
+                        TypeName.INT, itemKeyIndexVar, cursorVar, relation.entityField.columnName)
+
+                beginControlFlow("if ($L == -1)", itemKeyIndexVar).apply {
+                    addStatement("return")
+                }
+                endControlFlow()
+
+                collector.rowAdapter.onCursorReady(cursorVar, scope)
+                val tmpVarName = scope.getTmpVar("_item")
+                beginControlFlow("while($L.moveToNext())", cursorVar).apply {
+                    // read key from the cursor
+                    collector.readKey(
+                            cursorVarName = cursorVar,
+                            indexVar = itemKeyIndexVar,
+                            scope = scope
+                    ) { keyVar ->
+                        val collectionVar = scope.getTmpVar("_tmpCollection")
+                        addStatement("$T $L = $N.get($L)", collector.collectionTypeName,
+                                collectionVar, param, keyVar)
+                        beginControlFlow("if ($L != null)", collectionVar).apply {
+                            addStatement("final $T $L", relation.pojo.typeName, tmpVarName)
+                            collector.rowAdapter.convert(tmpVarName, cursorVar, scope)
+                            addStatement("$L.add($L)", collectionVar, tmpVarName)
+                        }
+                        endControlFlow()
+                    }
+                }
+                endControlFlow()
+                collector.rowAdapter.onCursorFinished()?.invoke(scope)
+            }
+            nextControlFlow("finally").apply {
+                addStatement("$L.close()", cursorVar)
+            }
+            endControlFlow()
+        }
+        builder.apply {
+            addModifiers(Modifier.PRIVATE)
+            addParameter(param)
+            returns(TypeName.VOID)
+            addCode(scope.builder().build())
+        }
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriter.kt
new file mode 100644
index 0000000..afb12e9
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriter.kt
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.SupportDbTypeNames
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Database
+import android.arch.persistence.room.vo.Entity
+import android.support.annotation.VisibleForTesting
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeSpec
+import javax.lang.model.element.Modifier.PROTECTED
+import javax.lang.model.element.Modifier.PUBLIC
+
+/**
+ * Create an open helper using SupportSQLiteOpenHelperFactory
+ */
+class SQLiteOpenHelperWriter(val database : Database) {
+    fun write(outVar : String, configuration : ParameterSpec, scope: CodeGenScope) {
+        scope.builder().apply {
+            val sqliteConfigVar = scope.getTmpVar("_sqliteConfig")
+            val callbackVar = scope.getTmpVar("_openCallback")
+            addStatement("final $T $L = new $T($N, $L, $S)",
+                    SupportDbTypeNames.SQLITE_OPEN_HELPER_CALLBACK,
+                    callbackVar, RoomTypeNames.OPEN_HELPER, configuration,
+                    createOpenCallback(scope), database.identityHash)
+            // build configuration
+            addStatement(
+                    """
+                    final $T $L = $T.builder($N.context)
+                    .name($N.name)
+                    .version($L)
+                    .callback($L)
+                    .build()
+                    """.trimIndent(),
+                    SupportDbTypeNames.SQLITE_OPEN_HELPER_CONFIG, sqliteConfigVar,
+                    SupportDbTypeNames.SQLITE_OPEN_HELPER_CONFIG,
+                    configuration, configuration, database.version, callbackVar)
+            addStatement("final $T $N = $N.sqliteOpenHelperFactory.create($L)",
+                    SupportDbTypeNames.SQLITE_OPEN_HELPER, outVar,
+                    configuration, sqliteConfigVar)
+        }
+    }
+
+    private fun createOpenCallback(scope: CodeGenScope) : TypeSpec {
+        return TypeSpec.anonymousClassBuilder("").apply {
+            superclass(RoomTypeNames.OPEN_HELPER_DELEGATE)
+            addMethod(createCreateAllTables())
+            addMethod(createDropAllTables())
+            addMethod(createOnCreate(scope.fork()))
+            addMethod(createOnOpen(scope.fork()))
+            addMethod(createValidateMigration(scope.fork()))
+        }.build()
+    }
+
+    private fun createValidateMigration(scope: CodeGenScope): MethodSpec {
+        return MethodSpec.methodBuilder("validateMigration").apply {
+            addModifiers(PROTECTED)
+            val dbParam = ParameterSpec.builder(SupportDbTypeNames.DB, "_db").build()
+            addParameter(dbParam)
+            database.entities.forEach { entity ->
+                val methodScope = scope.fork()
+                TableInfoValidationWriter(entity).write(dbParam, methodScope)
+                addCode(methodScope.builder().build())
+            }
+        }.build()
+    }
+
+    private fun createOnCreate(scope: CodeGenScope): MethodSpec {
+        return MethodSpec.methodBuilder("onCreate").apply {
+            addModifiers(PROTECTED)
+            addParameter(SupportDbTypeNames.DB, "_db")
+            invokeCallbacks(scope, "onCreate")
+        }.build()
+    }
+
+    private fun createOnOpen(scope: CodeGenScope): MethodSpec {
+        return MethodSpec.methodBuilder("onOpen").apply {
+            addModifiers(PUBLIC)
+            addParameter(SupportDbTypeNames.DB, "_db")
+            addStatement("mDatabase = _db")
+            if (database.enableForeignKeys) {
+                addStatement("_db.execSQL($S)", "PRAGMA foreign_keys = ON")
+            }
+            addStatement("internalInitInvalidationTracker(_db)")
+            invokeCallbacks(scope, "onOpen")
+        }.build()
+    }
+
+    private fun createCreateAllTables() : MethodSpec {
+        return MethodSpec.methodBuilder("createAllTables").apply {
+            addModifiers(PUBLIC)
+            addParameter(SupportDbTypeNames.DB, "_db")
+            database.bundle.buildCreateQueries().forEach {
+                addStatement("_db.execSQL($S)", it)
+            }
+        }.build()
+    }
+
+    private fun createDropAllTables() : MethodSpec {
+        return MethodSpec.methodBuilder("dropAllTables").apply {
+            addModifiers(PUBLIC)
+            addParameter(SupportDbTypeNames.DB, "_db")
+            database.entities.forEach {
+                addStatement("_db.execSQL($S)", createDropTableQuery(it))
+            }
+        }.build()
+    }
+
+    private fun MethodSpec.Builder.invokeCallbacks(scope: CodeGenScope, methodName: String) {
+        val iVar = scope.getTmpVar("_i")
+        val sizeVar = scope.getTmpVar("_size")
+        beginControlFlow("if (mCallbacks != null)").apply {
+            beginControlFlow("for (int $N = 0, $N = mCallbacks.size(); $N < $N; $N++)",
+                    iVar, sizeVar, iVar, sizeVar, iVar).apply {
+                addStatement("mCallbacks.get($N).$N(_db)", iVar, methodName)
+            }
+            endControlFlow()
+        }
+        endControlFlow()
+    }
+
+    @VisibleForTesting
+    fun createQuery(entity : Entity) : String {
+        return entity.createTableQuery
+    }
+
+    @VisibleForTesting
+    fun createDropTableQuery(entity: Entity) : String {
+        return "DROP TABLE IF EXISTS `${entity.tableName}`"
+    }
+}
diff --git a/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/TableInfoValidationWriter.kt b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/TableInfoValidationWriter.kt
new file mode 100644
index 0000000..e27600a
--- /dev/null
+++ b/room/compiler/src/main/kotlin/android/arch/persistence/room/writer/TableInfoValidationWriter.kt
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.ext.CommonTypeNames
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.N
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.vo.Entity
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import stripNonJava
+import java.util.Arrays
+import java.util.HashMap
+import java.util.HashSet
+
+class TableInfoValidationWriter(val entity : Entity) {
+    fun write(dbParam : ParameterSpec, scope : CodeGenScope) {
+        val suffix = entity.tableName.stripNonJava().capitalize()
+        val expectedInfoVar = scope.getTmpVar("_info$suffix")
+        scope.builder().apply {
+            val columnListVar = scope.getTmpVar("_columns$suffix")
+            val columnListType = ParameterizedTypeName.get(HashMap::class.typeName(),
+                    CommonTypeNames.STRING, RoomTypeNames.TABLE_INFO_COLUMN)
+
+            addStatement("final $T $L = new $T($L)", columnListType, columnListVar,
+                    columnListType, entity.fields.size)
+            entity.fields.forEachIndexed { index, field ->
+                addStatement("$L.put($S, new $T($S, $S, $L, $L))",
+                        columnListVar, field.columnName, RoomTypeNames.TABLE_INFO_COLUMN,
+                        /*name*/ field.columnName,
+                        /*type*/ field.affinity?.name ?: SQLTypeAffinity.TEXT.name,
+                        /*nonNull*/ field.nonNull,
+                        /*pkeyPos*/ entity.primaryKey.fields.indexOf(field) + 1)
+            }
+
+            val foreignKeySetVar = scope.getTmpVar("_foreignKeys$suffix")
+            val foreignKeySetType = ParameterizedTypeName.get(HashSet::class.typeName(),
+                    RoomTypeNames.TABLE_INFO_FOREIGN_KEY)
+            addStatement("final $T $L = new $T($L)", foreignKeySetType, foreignKeySetVar,
+                    foreignKeySetType, entity.foreignKeys.size)
+            entity.foreignKeys.forEach {
+                val myColumnNames = it.childFields
+                        .joinToString(",") { "\"${it.columnName}\"" }
+                val refColumnNames = it.parentColumns
+                        .joinToString(",") { "\"$it\"" }
+                addStatement("$L.add(new $T($S, $S, $S," +
+                        "$T.asList($L), $T.asList($L)))", foreignKeySetVar,
+                        RoomTypeNames.TABLE_INFO_FOREIGN_KEY,
+                        /*parent table*/ it.parentTable,
+                        /*on delete*/ it.onDelete.sqlName,
+                        /*on update*/ it.onUpdate.sqlName,
+                        Arrays::class.typeName(),
+                        /*parent names*/ myColumnNames,
+                        Arrays::class.typeName(),
+                        /*parent column names*/ refColumnNames)
+            }
+
+            addStatement("final $T $L = new $T($S, $L, $L)",
+                    RoomTypeNames.TABLE_INFO, expectedInfoVar, RoomTypeNames.TABLE_INFO,
+                    entity.tableName, columnListVar, foreignKeySetVar)
+
+            val existingVar = scope.getTmpVar("_existing$suffix")
+            addStatement("final $T $L = $T.read($N, $S)",
+                    RoomTypeNames.TABLE_INFO, existingVar, RoomTypeNames.TABLE_INFO,
+                    dbParam, entity.tableName)
+
+            beginControlFlow("if (! $L.equals($L))", expectedInfoVar, existingVar).apply {
+                addStatement("throw new $T($S + $L + $S + $L)",
+                        IllegalStateException::class.typeName(),
+                        "Migration didn't properly handle ${entity.tableName}" +
+                                "(${entity.element.qualifiedName}).\n Expected:\n",
+                        expectedInfoVar, "\n Found:\n", existingVar)
+            }
+            endControlFlow()
+        }
+    }
+}
diff --git a/room/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/room/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 0000000..f628f64
--- /dev/null
+++ b/room/compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1 @@
+android.arch.persistence.room.RoomProcessor
diff --git a/room/compiler/src/main/resources/NOTICE.txt b/room/compiler/src/main/resources/NOTICE.txt
new file mode 100644
index 0000000..fd8adbc
--- /dev/null
+++ b/room/compiler/src/main/resources/NOTICE.txt
@@ -0,0 +1,1812 @@
+List of 3rd party licenses:
+-----------------------------------------------------------------------------
+* commons-codec.jar (commons-codec:commons-codec:1.10)
+
+ ****** NOTICE:
+Apache Commons Codec
+Copyright 2002-2016 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+src/test/org/apache/commons/codec/language/DoubleMetaphoneTest.java
+contains test data from http://aspell.net/test/orig/batch0.tab.
+Copyright (C) 2002 Kevin Atkinson (kevina@gnu.org)
+
+===============================================================================
+
+The content of package org.apache.commons.codec.language.bm has been translated
+from the original php source code available at http://stevemorse.org/phoneticinfo.htm
+with permission from the original authors.
+Original source copyright:
+Copyright (c) 2008 Alexander Beider & Stephen P. Morse.
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* javapoet.jar (com.squareup:javapoet:1.8.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* antlr4.jar (org.antlr:antlr4:4.5.3)
+
+ ****** LICENSE:
+[The "BSD 3-clause license"]
+Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holder nor the names of its contributors
+    may be used to endorse or promote products derived from this software
+    without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+=====
+
+MIT License for codepointat.js from https://git.io/codepointat
+MIT License for fromcodepoint.js from https://git.io/vDW1m
+
+Copyright Mathias Bynens <https://mathiasbynens.be/>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+
+
+-----------------------------------------------------------------------------
+* kotlin-stdlib.jar (org.jetbrains.kotlin:kotlin-stdlib:1.1.1)
+
+ ****** NOTICE:
+   =========================================================================
+   ==  NOTICE file corresponding to the section 4 d of                    ==
+   ==  the Apache License, Version 2.0,                                   ==
+   ==  in this case for the Kotlin Compiler distribution.                 ==
+   =========================================================================
+
+   Kotlin Compiler
+   Copyright 2010-2015 JetBrains s.r.o and respective authors and developers
+
+ ****** LICENSE:
+/*
+ * Copyright 2010-2017 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* auto-common.jar (com.google.auto:auto-common:0.6)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* annotations.jar (org.jetbrains:annotations:13.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* gson.jar (com.google.code.gson:gson:2.8.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
+
+-----------------------------------------------------------------------------
+* sqlite-jdbc.jar (org.xerial:sqlite-jdbc:3.16.1)
+
+ ****** LICENSE:
+

+                                 Apache License

+                           Version 2.0, January 2004

+                        http://www.apache.org/licenses/

+

+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

+

+   1. Definitions.

+

+      "License" shall mean the terms and conditions for use, reproduction,

+      and distribution as defined by Sections 1 through 9 of this document.

+

+      "Licensor" shall mean the copyright owner or entity authorized by

+      the copyright owner that is granting the License.

+

+      "Legal Entity" shall mean the union of the acting entity and all

+      other entities that control, are controlled by, or are under common

+      control with that entity. For the purposes of this definition,

+      "control" means (i) the power, direct or indirect, to cause the

+      direction or management of such entity, whether by contract or

+      otherwise, or (ii) ownership of fifty percent (50%) or more of the

+      outstanding shares, or (iii) beneficial ownership of such entity.

+

+      "You" (or "Your") shall mean an individual or Legal Entity

+      exercising permissions granted by this License.

+

+      "Source" form shall mean the preferred form for making modifications,

+      including but not limited to software source code, documentation

+      source, and configuration files.

+

+      "Object" form shall mean any form resulting from mechanical

+      transformation or translation of a Source form, including but

+      not limited to compiled object code, generated documentation,

+      and conversions to other media types.

+

+      "Work" shall mean the work of authorship, whether in Source or

+      Object form, made available under the License, as indicated by a

+      copyright notice that is included in or attached to the work

+      (an example is provided in the Appendix below).

+

+      "Derivative Works" shall mean any work, whether in Source or Object

+      form, that is based on (or derived from) the Work and for which the

+      editorial revisions, annotations, elaborations, or other modifications

+      represent, as a whole, an original work of authorship. For the purposes

+      of this License, Derivative Works shall not include works that remain

+      separable from, or merely link (or bind by name) to the interfaces of,

+      the Work and Derivative Works thereof.

+

+      "Contribution" shall mean any work of authorship, including

+      the original version of the Work and any modifications or additions

+      to that Work or Derivative Works thereof, that is intentionally

+      submitted to Licensor for inclusion in the Work by the copyright owner

+      or by an individual or Legal Entity authorized to submit on behalf of

+      the copyright owner. For the purposes of this definition, "submitted"

+      means any form of electronic, verbal, or written communication sent

+      to the Licensor or its representatives, including but not limited to

+      communication on electronic mailing lists, source code control systems,

+      and issue tracking systems that are managed by, or on behalf of, the

+      Licensor for the purpose of discussing and improving the Work, but

+      excluding communication that is conspicuously marked or otherwise

+      designated in writing by the copyright owner as "Not a Contribution."

+

+      "Contributor" shall mean Licensor and any individual or Legal Entity

+      on behalf of whom a Contribution has been received by Licensor and

+      subsequently incorporated within the Work.

+

+   2. Grant of Copyright License. Subject to the terms and conditions of

+      this License, each Contributor hereby grants to You a perpetual,

+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable

+      copyright license to reproduce, prepare Derivative Works of,

+      publicly display, publicly perform, sublicense, and distribute the

+      Work and such Derivative Works in Source or Object form.

+

+   3. Grant of Patent License. Subject to the terms and conditions of

+      this License, each Contributor hereby grants to You a perpetual,

+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable

+      (except as stated in this section) patent license to make, have made,

+      use, offer to sell, sell, import, and otherwise transfer the Work,

+      where such license applies only to those patent claims licensable

+      by such Contributor that are necessarily infringed by their

+      Contribution(s) alone or by combination of their Contribution(s)

+      with the Work to which such Contribution(s) was submitted. If You

+      institute patent litigation against any entity (including a

+      cross-claim or counterclaim in a lawsuit) alleging that the Work

+      or a Contribution incorporated within the Work constitutes direct

+      or contributory patent infringement, then any patent licenses

+      granted to You under this License for that Work shall terminate

+      as of the date such litigation is filed.

+

+   4. Redistribution. You may reproduce and distribute copies of the

+      Work or Derivative Works thereof in any medium, with or without

+      modifications, and in Source or Object form, provided that You

+      meet the following conditions:

+

+      (a) You must give any other recipients of the Work or

+          Derivative Works a copy of this License; and

+

+      (b) You must cause any modified files to carry prominent notices

+          stating that You changed the files; and

+

+      (c) You must retain, in the Source form of any Derivative Works

+          that You distribute, all copyright, patent, trademark, and

+          attribution notices from the Source form of the Work,

+          excluding those notices that do not pertain to any part of

+          the Derivative Works; and

+

+      (d) If the Work includes a "NOTICE" text file as part of its

+          distribution, then any Derivative Works that You distribute must

+          include a readable copy of the attribution notices contained

+          within such NOTICE file, excluding those notices that do not

+          pertain to any part of the Derivative Works, in at least one

+          of the following places: within a NOTICE text file distributed

+          as part of the Derivative Works; within the Source form or

+          documentation, if provided along with the Derivative Works; or,

+          within a display generated by the Derivative Works, if and

+          wherever such third-party notices normally appear. The contents

+          of the NOTICE file are for informational purposes only and

+          do not modify the License. You may add Your own attribution

+          notices within Derivative Works that You distribute, alongside

+          or as an addendum to the NOTICE text from the Work, provided

+          that such additional attribution notices cannot be construed

+          as modifying the License.

+

+      You may add Your own copyright statement to Your modifications and

+      may provide additional or different license terms and conditions

+      for use, reproduction, or distribution of Your modifications, or

+      for any such Derivative Works as a whole, provided Your use,

+      reproduction, and distribution of the Work otherwise complies with

+      the conditions stated in this License.

+

+   5. Submission of Contributions. Unless You explicitly state otherwise,

+      any Contribution intentionally submitted for inclusion in the Work

+      by You to the Licensor shall be under the terms and conditions of

+      this License, without any additional terms or conditions.

+      Notwithstanding the above, nothing herein shall supersede or modify

+      the terms of any separate license agreement you may have executed

+      with Licensor regarding such Contributions.

+

+   6. Trademarks. This License does not grant permission to use the trade

+      names, trademarks, service marks, or product names of the Licensor,

+      except as required for reasonable and customary use in describing the

+      origin of the Work and reproducing the content of the NOTICE file.

+

+   7. Disclaimer of Warranty. Unless required by applicable law or

+      agreed to in writing, Licensor provides the Work (and each

+      Contributor provides its Contributions) on an "AS IS" BASIS,

+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or

+      implied, including, without limitation, any warranties or conditions

+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A

+      PARTICULAR PURPOSE. You are solely responsible for determining the

+      appropriateness of using or redistributing the Work and assume any

+      risks associated with Your exercise of permissions under this License.

+

+   8. Limitation of Liability. In no event and under no legal theory,

+      whether in tort (including negligence), contract, or otherwise,

+      unless required by applicable law (such as deliberate and grossly

+      negligent acts) or agreed to in writing, shall any Contributor be

+      liable to You for damages, including any direct, indirect, special,

+      incidental, or consequential damages of any character arising as a

+      result of this License or out of the use or inability to use the

+      Work (including but not limited to damages for loss of goodwill,

+      work stoppage, computer failure or malfunction, or any and all

+      other commercial damages or losses), even if such Contributor

+      has been advised of the possibility of such damages.

+

+   9. Accepting Warranty or Additional Liability. While redistributing

+      the Work or Derivative Works thereof, You may choose to offer,

+      and charge a fee for, acceptance of support, warranty, indemnity,

+      or other liability obligations and/or rights consistent with this

+      License. However, in accepting such obligations, You may act only

+      on Your own behalf and on Your sole responsibility, not on behalf

+      of any other Contributor, and only if You agree to indemnify,

+      defend, and hold each Contributor harmless for any liability

+      incurred by, or claims asserted against, such Contributor by reason

+      of your accepting any such warranty or additional liability.

+

+   END OF TERMS AND CONDITIONS

+

+   APPENDIX: How to apply the Apache License to your work.

+

+      To apply the Apache License to your work, attach the following

+      boilerplate notice, with the fields enclosed by brackets "[]"

+      replaced with your own identifying information. (Don't include

+      the brackets!)  The text should be enclosed in the appropriate

+      comment syntax for the file format. We also recommend that a

+      file or class name and description of purpose be included on the

+      same "printed page" as the copyright notice for easier

+      identification within third-party archives.

+

+   Copyright [yyyy] [name of copyright owner]

+

+   Licensed under the Apache License, Version 2.0 (the "License");

+   you may not use this file except in compliance with the License.

+   You may obtain a copy of the License at

+

+       http://www.apache.org/licenses/LICENSE-2.0

+

+   Unless required by applicable law or agreed to in writing, software

+   distributed under the License is distributed on an "AS IS" BASIS,

+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+   See the License for the specific language governing permissions and

+   limitations under the License.

+
+ ****** LICENSE:
+Copyright (c) 2006, David Crawshaw.  All rights reserved.

+

+Redistribution and use in source and binary forms, with or without

+modification, are permitted provided that the following conditions

+are met:

+

+1. Redistributions of source code must retain the above copyright

+   notice, this list of conditions and the following disclaimer.

+2. Redistributions in binary form must reproduce the above copyright

+   notice, this list of conditions and the following disclaimer in the

+   documentation and/or other materials provided with the distribution.

+

+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND

+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE

+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE

+ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE

+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL

+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS

+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)

+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT

+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY

+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF

+SUCH DAMAGE.

+

+
+
+
+
+-----------------------------------------------------------------------------
+* guava.jar (com.google.guava:guava:18.0)
+
+ ****** LICENSE:
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
diff --git a/room/compiler/src/test/data/IGNORE_CHECKSTYLE b/room/compiler/src/test/data/IGNORE_CHECKSTYLE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/room/compiler/src/test/data/IGNORE_CHECKSTYLE
diff --git a/room/compiler/src/test/data/common/input/Book.java b/room/compiler/src/test/data/common/input/Book.java
new file mode 100644
index 0000000..00cf8b6
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/Book.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+@Entity
+public class Book {
+    @PrimaryKey
+    int bookId;
+    int uid;
+}
diff --git a/room/compiler/src/test/data/common/input/ComputableLiveData.java b/room/compiler/src/test/data/common/input/ComputableLiveData.java
new file mode 100644
index 0000000..f135244
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/ComputableLiveData.java
@@ -0,0 +1,9 @@
+//ComputableLiveData interface for tests
+package android.arch.lifecycle;
+import android.arch.lifecycle.LiveData;
+public abstract class ComputableLiveData<T> {
+    public ComputableLiveData(){}
+    abstract protected T compute();
+    public LiveData<T> getLiveData() {return null;}
+    public void invalidate() {}
+}
diff --git a/room/compiler/src/test/data/common/input/LiveData.java b/room/compiler/src/test/data/common/input/LiveData.java
new file mode 100644
index 0000000..3aea6ac
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/LiveData.java
@@ -0,0 +1,4 @@
+//LiveData interface for tests
+package android.arch.lifecycle;
+public class LiveData<T> {
+}
diff --git a/room/compiler/src/test/data/common/input/LiveLazyListProvider.java b/room/compiler/src/test/data/common/input/LiveLazyListProvider.java
new file mode 100644
index 0000000..4c12f05
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/LiveLazyListProvider.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2017 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 android.arch.util.paging;
+
+abstract public class LiveLazyListProvider<T> {
+}
\ No newline at end of file
diff --git a/room/compiler/src/test/data/common/input/MultiPKeyEntity.java b/room/compiler/src/test/data/common/input/MultiPKeyEntity.java
new file mode 100644
index 0000000..dccb9dd
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/MultiPKeyEntity.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+@Entity(primaryKeys = {"name", "lastName"})
+public class MultiPKeyEntity {
+    String name;
+    String lastName;
+}
diff --git a/room/compiler/src/test/data/common/input/NotAnEntity.java b/room/compiler/src/test/data/common/input/NotAnEntity.java
new file mode 100644
index 0000000..90c1dd4
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/NotAnEntity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+public class NotAnEntity {
+    int bookId;
+    int uid;
+}
diff --git a/room/compiler/src/test/data/common/input/Rx2Room.java b/room/compiler/src/test/data/common/input/Rx2Room.java
new file mode 100644
index 0000000..da474fd
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/Rx2Room.java
@@ -0,0 +1,5 @@
+// mock rx2 helper
+package android.arch.persistence.room;
+
+class RxRoom {
+}
diff --git a/room/compiler/src/test/data/common/input/User.java b/room/compiler/src/test/data/common/input/User.java
new file mode 100644
index 0000000..ce487d3
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/User.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+@Entity
+public class User {
+    @PrimaryKey
+    int uid;
+    String name;
+    private String lastName;
+    @ColumnInfo(name = "ageColumn")
+    public int age;
+
+    public String getLastName() {
+        return lastName;
+    }
+    public void setLastName(String lastName) {
+        this.lastName = lastName;
+    }
+}
diff --git a/room/compiler/src/test/data/common/input/reactivestreams/Publisher.java b/room/compiler/src/test/data/common/input/reactivestreams/Publisher.java
new file mode 100644
index 0000000..4ecc9f5
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/reactivestreams/Publisher.java
@@ -0,0 +1,4 @@
+// fake reactivestreams publisher
+package org.reactivestreams;
+public interface Publisher<T> {
+}
\ No newline at end of file
diff --git a/room/compiler/src/test/data/common/input/rxjava2/Flowable.java b/room/compiler/src/test/data/common/input/rxjava2/Flowable.java
new file mode 100644
index 0000000..2d9d4d0
--- /dev/null
+++ b/room/compiler/src/test/data/common/input/rxjava2/Flowable.java
@@ -0,0 +1,6 @@
+// fake rx flowable
+package io.reactivex;
+import org.reactivestreams.Publisher;
+
+public abstract class Flowable<T> implements Publisher<T> {
+}
\ No newline at end of file
diff --git a/room/compiler/src/test/data/daoWriter/input/ComplexDao.java b/room/compiler/src/test/data/daoWriter/input/ComplexDao.java
new file mode 100644
index 0000000..ca90163
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/input/ComplexDao.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+import java.util.List;
+import android.arch.lifecycle.LiveData;
+@Dao
+abstract class ComplexDao {
+    static class FullName {
+        public int id;
+        public String fullName;
+    }
+
+    private final ComplexDatabase mDb;
+
+    public ComplexDao(ComplexDatabase db) {
+        mDb = db;
+    }
+
+    @Query("SELECT name || lastName as fullName, uid as id FROM user where uid = :id")
+    abstract public List<FullName> fullNames(int id);
+
+    @Query("SELECT * FROM user where uid = :id")
+    abstract public User getById(int id);
+
+    @Query("SELECT * FROM user where name LIKE :name AND lastName LIKE :lastName")
+    abstract public User findByName(String name, String lastName);
+
+    @Query("SELECT * FROM user where uid IN (:ids)")
+    abstract public List<User> loadAllByIds(int... ids);
+
+    @Query("SELECT ageColumn FROM user where uid = :id")
+    abstract int getAge(int id);
+
+    @Query("SELECT ageColumn FROM user where uid IN(:ids)")
+    abstract public int[] getAllAges(int... ids);
+
+    @Query("SELECT ageColumn FROM user where uid IN(:ids)")
+    abstract public List<Integer> getAllAgesAsList(List<Integer> ids);
+
+    @Query("SELECT * FROM user where uid = :id")
+    abstract public LiveData<User> getByIdLive(int id);
+
+    @Query("SELECT * FROM user where uid IN (:ids)")
+    abstract public LiveData<List<User>> loadUsersByIdsLive(int... ids);
+
+    @Query("SELECT ageColumn FROM user where uid IN(:ids1) OR uid IN (:ids2) OR uid IN (:ids3)")
+    abstract public List<Integer> getAllAgesAsList(List<Integer> ids1,
+            int[] ids2, int... ids3);
+}
diff --git a/room/compiler/src/test/data/daoWriter/input/DeletionDao.java b/room/compiler/src/test/data/daoWriter/input/DeletionDao.java
new file mode 100644
index 0000000..997f290
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/input/DeletionDao.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+import java.util.List;
+
+@Dao
+abstract interface DeletionDao {
+    @Delete
+    void deleteUser(User user);
+    @Delete
+    void deleteUsers(User user1, List<User> others);
+    @Delete
+    void deleteArrayOfUsers(User[] users);
+
+    @Delete
+    int deleteUserAndReturnCount(User user);
+    @Delete
+    int deleteUserAndReturnCount(User user1, List<User> others);
+    @Delete
+    int deleteUserAndReturnCount(User[] users);
+
+    @Delete
+    int multiPKey(MultiPKeyEntity entity);
+
+    @Query("DELETE FROM user where uid = :uid")
+    int deleteByUid(int uid);
+
+    @Query("DELETE FROM user where uid IN(:uid)")
+    int deleteByUidList(int... uid);
+
+    @Delete
+    void deleteUserAndBook(User user, Book book);
+
+    @Query("DELETE FROM user")
+    int deleteEverything();
+}
diff --git a/room/compiler/src/test/data/daoWriter/input/UpdateDao.java b/room/compiler/src/test/data/daoWriter/input/UpdateDao.java
new file mode 100644
index 0000000..040b5c7
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/input/UpdateDao.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 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 foo.bar;
+import android.arch.persistence.room.*;
+import java.util.List;
+
+@Dao
+abstract interface UpdateDao {
+    @Update
+    void updateUser(User user);
+    @Update
+    void updateUsers(User user1, List<User> others);
+    @Update
+    void updateArrayOfUsers(User[] users);
+
+    @Update
+    int updateUserAndReturnCount(User user);
+    @Update
+    int updateUserAndReturnCount(User user1, List<User> others);
+    @Update
+    int updateUserAndReturnCount(User[] users);
+
+    @Update
+    int multiPKey(MultiPKeyEntity entity);
+
+    @Update
+    void updateUserAndBook(User user, Book book);
+
+    @Query("UPDATE User SET ageColumn = ageColumn + 1 WHERE uid = :uid")
+    void ageUserByUid(String uid);
+
+    @Query("UPDATE User SET ageColumn = ageColumn + 1")
+    void ageUserAll();
+}
diff --git a/room/compiler/src/test/data/daoWriter/input/WriterDao.java b/room/compiler/src/test/data/daoWriter/input/WriterDao.java
new file mode 100644
index 0000000..e122479
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/input/WriterDao.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+import java.util.List;
+
+@Dao
+abstract interface WriterDao {
+    @Insert
+    void insertUser(User user);
+    @Insert
+    void insertUsers(User user1, List<User> others);
+    @Insert(onConflict=OnConflictStrategy.REPLACE)
+    void insertUsers(User[] users);
+    @Insert
+    void insertUserAndBook(User user, Book book);
+}
diff --git a/room/compiler/src/test/data/daoWriter/output/ComplexDao.java b/room/compiler/src/test/data/daoWriter/output/ComplexDao.java
new file mode 100644
index 0000000..61594d2
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/output/ComplexDao.java
@@ -0,0 +1,419 @@
+package foo.bar;
+
+import android.arch.lifecycle.ComputableLiveData;
+import android.arch.lifecycle.LiveData;
+import android.arch.persistence.room.InvalidationTracker.Observer;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.RoomSQLiteQuery;
+import android.arch.persistence.room.util.StringUtil;
+import android.database.Cursor;
+import android.support.annotation.NonNull;
+import java.lang.Integer;
+import java.lang.Override;
+import java.lang.String;
+import java.lang.StringBuilder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+public class ComplexDao_Impl extends ComplexDao {
+    private final RoomDatabase __db;
+
+    public ComplexDao_Impl(ComplexDatabase __db) {
+        super(__db);
+        this.__db = __db;
+    }
+
+    @Override
+    public List<ComplexDao.FullName> fullNames(int id) {
+        final String _sql = "SELECT name || lastName as fullName, uid as id FROM user where uid = ?";
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
+        int _argIndex = 1;
+        _statement.bindLong(_argIndex, id);
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int _cursorIndexOfFullName = _cursor.getColumnIndexOrThrow("fullName");
+            final int _cursorIndexOfId = _cursor.getColumnIndexOrThrow("id");
+            final List<ComplexDao.FullName> _result = new ArrayList<ComplexDao.FullName>(_cursor.getCount());
+            while(_cursor.moveToNext()) {
+                final ComplexDao.FullName _item;
+                _item = new ComplexDao.FullName();
+                _item.fullName = _cursor.getString(_cursorIndexOfFullName);
+                _item.id = _cursor.getInt(_cursorIndexOfId);
+                _result.add(_item);
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public User getById(int id) {
+        final String _sql = "SELECT * FROM user where uid = ?";
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
+        int _argIndex = 1;
+        _statement.bindLong(_argIndex, id);
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int _cursorIndexOfUid = _cursor.getColumnIndexOrThrow("uid");
+            final int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
+            final int _cursorIndexOfLastName = _cursor.getColumnIndexOrThrow("lastName");
+            final int _cursorIndexOfAge = _cursor.getColumnIndexOrThrow("ageColumn");
+            final User _result;
+            if(_cursor.moveToFirst()) {
+                _result = new User();
+                _result.uid = _cursor.getInt(_cursorIndexOfUid);
+                _result.name = _cursor.getString(_cursorIndexOfName);
+                final String _tmpLastName;
+                _tmpLastName = _cursor.getString(_cursorIndexOfLastName);
+                _result.setLastName(_tmpLastName);
+                _result.age = _cursor.getInt(_cursorIndexOfAge);
+            } else {
+                _result = null;
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public User findByName(String name, String lastName) {
+        final String _sql = "SELECT * FROM user where name LIKE ? AND lastName LIKE ?";
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
+        int _argIndex = 1;
+        if (name == null) {
+            _statement.bindNull(_argIndex);
+        } else {
+            _statement.bindString(_argIndex, name);
+        }
+        _argIndex = 2;
+        if (lastName == null) {
+            _statement.bindNull(_argIndex);
+        } else {
+            _statement.bindString(_argIndex, lastName);
+        }
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int _cursorIndexOfUid = _cursor.getColumnIndexOrThrow("uid");
+            final int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
+            final int _cursorIndexOfLastName = _cursor.getColumnIndexOrThrow("lastName");
+            final int _cursorIndexOfAge = _cursor.getColumnIndexOrThrow("ageColumn");
+            final User _result;
+            if(_cursor.moveToFirst()) {
+                _result = new User();
+                _result.uid = _cursor.getInt(_cursorIndexOfUid);
+                _result.name = _cursor.getString(_cursorIndexOfName);
+                final String _tmpLastName;
+                _tmpLastName = _cursor.getString(_cursorIndexOfLastName);
+                _result.setLastName(_tmpLastName);
+                _result.age = _cursor.getInt(_cursorIndexOfAge);
+            } else {
+                _result = null;
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public List<User> loadAllByIds(int... ids) {
+        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+        _stringBuilder.append("SELECT * FROM user where uid IN (");
+        final int _inputSize = ids.length;
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+        _stringBuilder.append(")");
+        final String _sql = _stringBuilder.toString();
+        final int _argCount = 0 + _inputSize;
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, _argCount);
+        int _argIndex = 1;
+        for (int _item : ids) {
+            _statement.bindLong(_argIndex, _item);
+            _argIndex ++;
+        }
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int _cursorIndexOfUid = _cursor.getColumnIndexOrThrow("uid");
+            final int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
+            final int _cursorIndexOfLastName = _cursor.getColumnIndexOrThrow("lastName");
+            final int _cursorIndexOfAge = _cursor.getColumnIndexOrThrow("ageColumn");
+            final List<User> _result = new ArrayList<User>(_cursor.getCount());
+            while(_cursor.moveToNext()) {
+                final User _item_1;
+                _item_1 = new User();
+                _item_1.uid = _cursor.getInt(_cursorIndexOfUid);
+                _item_1.name = _cursor.getString(_cursorIndexOfName);
+                final String _tmpLastName;
+                _tmpLastName = _cursor.getString(_cursorIndexOfLastName);
+                _item_1.setLastName(_tmpLastName);
+                _item_1.age = _cursor.getInt(_cursorIndexOfAge);
+                _result.add(_item_1);
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    int getAge(int id) {
+        final String _sql = "SELECT ageColumn FROM user where uid = ?";
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
+        int _argIndex = 1;
+        _statement.bindLong(_argIndex, id);
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int _result;
+            if(_cursor.moveToFirst()) {
+                _result = _cursor.getInt(0);
+            } else {
+                _result = 0;
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public int[] getAllAges(int... ids) {
+        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+        _stringBuilder.append("SELECT ageColumn FROM user where uid IN(");
+        final int _inputSize = ids.length;
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+        _stringBuilder.append(")");
+        final String _sql = _stringBuilder.toString();
+        final int _argCount = 0 + _inputSize;
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, _argCount);
+        int _argIndex = 1;
+        for (int _item : ids) {
+            _statement.bindLong(_argIndex, _item);
+            _argIndex ++;
+        }
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final int[] _result = new int[_cursor.getCount()];
+            int _index = 0;
+            while(_cursor.moveToNext()) {
+                final int _item_1;
+                _item_1 = _cursor.getInt(0);
+                _result[_index] = _item_1;
+                _index ++;
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public List<Integer> getAllAgesAsList(List<Integer> ids) {
+        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+        _stringBuilder.append("SELECT ageColumn FROM user where uid IN(");
+        final int _inputSize = ids.size();
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+        _stringBuilder.append(")");
+        final String _sql = _stringBuilder.toString();
+        final int _argCount = 0 + _inputSize;
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, _argCount);
+        int _argIndex = 1;
+        for (Integer _item : ids) {
+            if (_item == null) {
+                _statement.bindNull(_argIndex);
+            } else {
+                _statement.bindLong(_argIndex, _item);
+            }
+            _argIndex ++;
+        }
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final List<Integer> _result = new ArrayList<Integer>(_cursor.getCount());
+            while(_cursor.moveToNext()) {
+                final Integer _item_1;
+                if (_cursor.isNull(0)) {
+                    _item_1 = null;
+                } else {
+                    _item_1 = _cursor.getInt(0);
+                }
+                _result.add(_item_1);
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+
+    @Override
+    public LiveData<User> getByIdLive(int id) {
+        final String _sql = "SELECT * FROM user where uid = ?";
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
+        int _argIndex = 1;
+        _statement.bindLong(_argIndex, id);
+        return new ComputableLiveData<User>() {
+            private Observer _observer;
+
+            @Override
+            protected User compute() {
+                if (_observer == null) {
+                    _observer = new Observer("user") {
+                        @Override
+                        public void onInvalidated(@NonNull Set<String> tables) {
+                            invalidate();
+                        }
+                    };
+                    __db.getInvalidationTracker().addWeakObserver(_observer);
+                }
+                final Cursor _cursor = __db.query(_statement);
+                try {
+                    final int _cursorIndexOfUid = _cursor.getColumnIndexOrThrow("uid");
+                    final int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
+                    final int _cursorIndexOfLastName = _cursor.getColumnIndexOrThrow("lastName");
+                    final int _cursorIndexOfAge = _cursor.getColumnIndexOrThrow("ageColumn");
+                    final User _result;
+                    if(_cursor.moveToFirst()) {
+                        _result = new User();
+                        _result.uid = _cursor.getInt(_cursorIndexOfUid);
+                        _result.name = _cursor.getString(_cursorIndexOfName);
+                        final String _tmpLastName;
+                        _tmpLastName = _cursor.getString(_cursorIndexOfLastName);
+                        _result.setLastName(_tmpLastName);
+                        _result.age = _cursor.getInt(_cursorIndexOfAge);
+                    } else {
+                        _result = null;
+                    }
+                    return _result;
+                } finally {
+                    _cursor.close();
+                }
+            }
+
+            @Override
+            protected void finalize() {
+                _statement.release();
+            }
+        }.getLiveData();
+    }
+
+    @Override
+    public LiveData<List<User>> loadUsersByIdsLive(int... ids) {
+        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+        _stringBuilder.append("SELECT * FROM user where uid IN (");
+        final int _inputSize = ids.length;
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+        _stringBuilder.append(")");
+        final String _sql = _stringBuilder.toString();
+        final int _argCount = 0 + _inputSize;
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, _argCount);
+        int _argIndex = 1;
+        for (int _item : ids) {
+            _statement.bindLong(_argIndex, _item);
+            _argIndex ++;
+        }
+        return new ComputableLiveData<List<User>>() {
+            private Observer _observer;
+
+            @Override
+            protected List<User> compute() {
+                if (_observer == null) {
+                    _observer = new Observer("user") {
+                        @Override
+                        public void onInvalidated(@NonNull Set<String> tables) {
+                            invalidate();
+                        }
+                    };
+                    __db.getInvalidationTracker().addWeakObserver(_observer);
+                }
+                final Cursor _cursor = __db.query(_statement);
+                try {
+                    final int _cursorIndexOfUid = _cursor.getColumnIndexOrThrow("uid");
+                    final int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
+                    final int _cursorIndexOfLastName = _cursor.getColumnIndexOrThrow("lastName");
+                    final int _cursorIndexOfAge = _cursor.getColumnIndexOrThrow("ageColumn");
+                    final List<User> _result = new ArrayList<User>(_cursor.getCount());
+                    while(_cursor.moveToNext()) {
+                        final User _item_1;
+                        _item_1 = new User();
+                        _item_1.uid = _cursor.getInt(_cursorIndexOfUid);
+                        _item_1.name = _cursor.getString(_cursorIndexOfName);
+                        final String _tmpLastName;
+                        _tmpLastName = _cursor.getString(_cursorIndexOfLastName);
+                        _item_1.setLastName(_tmpLastName);
+                        _item_1.age = _cursor.getInt(_cursorIndexOfAge);
+                        _result.add(_item_1);
+                    }
+                    return _result;
+                } finally {
+                    _cursor.close();
+                }
+            }
+
+            @Override
+            protected void finalize() {
+                _statement.release();
+            }
+        }.getLiveData();
+    }
+
+    @Override
+    public List<Integer> getAllAgesAsList(List<Integer> ids1, int[] ids2, int... ids3) {
+        StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+        _stringBuilder.append("SELECT ageColumn FROM user where uid IN(");
+        final int _inputSize = ids1.size();
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+        _stringBuilder.append(") OR uid IN (");
+        final int _inputSize_1 = ids2.length;
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize_1);
+        _stringBuilder.append(") OR uid IN (");
+        final int _inputSize_2 = ids3.length;
+        StringUtil.appendPlaceholders(_stringBuilder, _inputSize_2);
+        _stringBuilder.append(")");
+        final String _sql = _stringBuilder.toString();
+        final int _argCount = 0 + _inputSize + _inputSize_1 + _inputSize_2;
+        final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, _argCount);
+        int _argIndex = 1;
+        for (Integer _item : ids1) {
+            if (_item == null) {
+                _statement.bindNull(_argIndex);
+            } else {
+                _statement.bindLong(_argIndex, _item);
+            }
+            _argIndex ++;
+        }
+        _argIndex = 1 + _inputSize;
+        for (int _item_1 : ids2) {
+            _statement.bindLong(_argIndex, _item_1);
+            _argIndex ++;
+        }
+        _argIndex = 1 + _inputSize + _inputSize_1;
+        for (int _item_2 : ids3) {
+            _statement.bindLong(_argIndex, _item_2);
+            _argIndex ++;
+        }
+        final Cursor _cursor = __db.query(_statement);
+        try {
+            final List<Integer> _result = new ArrayList<Integer>(_cursor.getCount());
+            while(_cursor.moveToNext()) {
+                final Integer _item_3;
+                if (_cursor.isNull(0)) {
+                    _item_3 = null;
+                } else {
+                    _item_3 = _cursor.getInt(0);
+                }
+                _result.add(_item_3);
+            }
+            return _result;
+        } finally {
+            _cursor.close();
+            _statement.release();
+        }
+    }
+}
diff --git a/room/compiler/src/test/data/daoWriter/output/DeletionDao.java b/room/compiler/src/test/data/daoWriter/output/DeletionDao.java
new file mode 100644
index 0000000..d5e173f
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/output/DeletionDao.java
@@ -0,0 +1,238 @@
+package foo.bar;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.arch.persistence.room.EntityDeletionOrUpdateAdapter;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.SharedSQLiteStatement;
+import android.arch.persistence.room.util.StringUtil;
+import java.lang.Override;
+import java.lang.String;
+import java.lang.StringBuilder;
+import java.util.List;
+
+public class DeletionDao_Impl implements DeletionDao {
+  private final RoomDatabase __db;
+
+  private final EntityDeletionOrUpdateAdapter __deletionAdapterOfUser;
+
+  private final EntityDeletionOrUpdateAdapter __deletionAdapterOfMultiPKeyEntity;
+
+  private final EntityDeletionOrUpdateAdapter __deletionAdapterOfBook;
+
+  private final SharedSQLiteStatement __preparedStmtOfDeleteByUid;
+
+  private final SharedSQLiteStatement __preparedStmtOfDeleteEverything;
+
+  public DeletionDao_Impl(RoomDatabase __db) {
+    this.__db = __db;
+    this.__deletionAdapterOfUser = new EntityDeletionOrUpdateAdapter<User>(__db) {
+      @Override
+      public String createQuery() {
+        return "DELETE FROM `User` WHERE `uid` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, User value) {
+        stmt.bindLong(1, value.uid);
+      }
+    };
+    this.__deletionAdapterOfMultiPKeyEntity = new EntityDeletionOrUpdateAdapter<MultiPKeyEntity>(__db) {
+      @Override
+      public String createQuery() {
+        return "DELETE FROM `MultiPKeyEntity` WHERE `name` = ? AND `lastName` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, MultiPKeyEntity value) {
+        if (value.name == null) {
+          stmt.bindNull(1);
+        } else {
+          stmt.bindString(1, value.name);
+        }
+        if (value.lastName == null) {
+          stmt.bindNull(2);
+        } else {
+          stmt.bindString(2, value.lastName);
+        }
+      }
+    };
+    this.__deletionAdapterOfBook = new EntityDeletionOrUpdateAdapter<Book>(__db) {
+      @Override
+      public String createQuery() {
+        return "DELETE FROM `Book` WHERE `bookId` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, Book value) {
+        stmt.bindLong(1, value.bookId);
+      }
+    };
+    this.__preparedStmtOfDeleteByUid = new SharedSQLiteStatement(__db) {
+      @Override
+      public String createQuery() {
+        final String _query = "DELETE FROM user where uid = ?";
+        return _query;
+      }
+    };
+    this.__preparedStmtOfDeleteEverything = new SharedSQLiteStatement(__db) {
+      @Override
+      public String createQuery() {
+        final String _query = "DELETE FROM user";
+        return _query;
+      }
+    };
+  }
+
+  @Override
+  public void deleteUser(User user) {
+    __db.beginTransaction();
+    try {
+      __deletionAdapterOfUser.handle(user);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void deleteUsers(User user1, List<User> others) {
+    __db.beginTransaction();
+    try {
+      __deletionAdapterOfUser.handle(user1);
+      __deletionAdapterOfUser.handleMultiple(others);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void deleteArrayOfUsers(User[] users) {
+    __db.beginTransaction();
+    try {
+      __deletionAdapterOfUser.handleMultiple(users);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int deleteUserAndReturnCount(User user) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__deletionAdapterOfUser.handle(user);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int deleteUserAndReturnCount(User user1, List<User> others) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__deletionAdapterOfUser.handle(user1);
+      _total +=__deletionAdapterOfUser.handleMultiple(others);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int deleteUserAndReturnCount(User[] users) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__deletionAdapterOfUser.handleMultiple(users);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int multiPKey(MultiPKeyEntity entity) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__deletionAdapterOfMultiPKeyEntity.handle(entity);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void deleteUserAndBook(User user, Book book) {
+    __db.beginTransaction();
+    try {
+      __deletionAdapterOfUser.handle(user);
+      __deletionAdapterOfBook.handle(book);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int deleteByUid(int uid) {
+    final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteByUid.acquire();
+    __db.beginTransaction();
+    try {
+      int _argIndex = 1;
+      _stmt.bindLong(_argIndex, uid);
+      final int _result = _stmt.executeUpdateDelete();
+      __db.setTransactionSuccessful();
+      return _result;
+    } finally {
+      __db.endTransaction();
+      __preparedStmtOfDeleteByUid.release(_stmt);
+    }
+  }
+
+  @Override
+  public int deleteEverything() {
+    final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteEverything.acquire();
+    __db.beginTransaction();
+    try {
+      final int _result = _stmt.executeUpdateDelete();
+      __db.setTransactionSuccessful();
+      return _result;
+    } finally {
+      __db.endTransaction();
+      __preparedStmtOfDeleteEverything.release(_stmt);
+    }
+  }
+
+  @Override
+  public int deleteByUidList(int... uid) {
+    StringBuilder _stringBuilder = StringUtil.newStringBuilder();
+    _stringBuilder.append("DELETE FROM user where uid IN(");
+    final int _inputSize = uid.length;
+    StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
+    _stringBuilder.append(")");
+    final String _sql = _stringBuilder.toString();
+    SupportSQLiteStatement _stmt = __db.compileStatement(_sql);
+    int _argIndex = 1;
+    for (int _item : uid) {
+      _stmt.bindLong(_argIndex, _item);
+      _argIndex ++;
+    }
+    __db.beginTransaction();
+    try {
+      final int _result = _stmt.executeUpdateDelete();
+      __db.setTransactionSuccessful();
+      return _result;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+}
diff --git a/room/compiler/src/test/data/daoWriter/output/UpdateDao.java b/room/compiler/src/test/data/daoWriter/output/UpdateDao.java
new file mode 100644
index 0000000..1b26b6a
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/output/UpdateDao.java
@@ -0,0 +1,238 @@
+package foo.bar;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.arch.persistence.room.EntityDeletionOrUpdateAdapter;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.SharedSQLiteStatement;
+import java.lang.Override;
+import java.lang.String;
+import java.util.List;
+
+public class UpdateDao_Impl implements UpdateDao {
+  private final RoomDatabase __db;
+
+  private final EntityDeletionOrUpdateAdapter __updateAdapterOfUser;
+
+  private final EntityDeletionOrUpdateAdapter __updateAdapterOfMultiPKeyEntity;
+
+  private final EntityDeletionOrUpdateAdapter __updateAdapterOfBook;
+
+  private final SharedSQLiteStatement __preparedStmtOfAgeUserByUid;
+
+  private final SharedSQLiteStatement __preparedStmtOfAgeUserAll;
+
+  public UpdateDao_Impl(RoomDatabase __db) {
+    this.__db = __db;
+    this.__updateAdapterOfUser = new EntityDeletionOrUpdateAdapter<User>(__db) {
+      @Override
+      public String createQuery() {
+        return "UPDATE OR ABORT `User` SET `uid` = ?,`name` = ?,`lastName` = ?,`ageColumn` = ? WHERE `uid` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, User value) {
+        stmt.bindLong(1, value.uid);
+        if (value.name == null) {
+          stmt.bindNull(2);
+        } else {
+          stmt.bindString(2, value.name);
+        }
+        if (value.getLastName() == null) {
+          stmt.bindNull(3);
+        } else {
+          stmt.bindString(3, value.getLastName());
+        }
+        stmt.bindLong(4, value.age);
+        stmt.bindLong(5, value.uid);
+      }
+    };
+    this.__updateAdapterOfMultiPKeyEntity = new EntityDeletionOrUpdateAdapter<MultiPKeyEntity>(__db) {
+      @Override
+      public String createQuery() {
+        return "UPDATE OR ABORT `MultiPKeyEntity` SET `name` = ?,`lastName` = ? WHERE `name` = ? AND `lastName` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, MultiPKeyEntity value) {
+        if (value.name == null) {
+          stmt.bindNull(1);
+        } else {
+          stmt.bindString(1, value.name);
+        }
+        if (value.lastName == null) {
+          stmt.bindNull(2);
+        } else {
+          stmt.bindString(2, value.lastName);
+        }
+        if (value.name == null) {
+          stmt.bindNull(3);
+        } else {
+          stmt.bindString(3, value.name);
+        }
+        if (value.lastName == null) {
+          stmt.bindNull(4);
+        } else {
+          stmt.bindString(4, value.lastName);
+        }
+      }
+    };
+    this.__updateAdapterOfBook = new EntityDeletionOrUpdateAdapter<Book>(__db) {
+      @Override
+      public String createQuery() {
+        return "UPDATE OR ABORT `Book` SET `bookId` = ?,`uid` = ? WHERE `bookId` = ?";
+      }
+
+      @Override
+      public void bind(SupportSQLiteStatement stmt, Book value) {
+        stmt.bindLong(1, value.bookId);
+        stmt.bindLong(2, value.uid);
+        stmt.bindLong(3, value.bookId);
+      }
+    };
+    this.__preparedStmtOfAgeUserByUid = new SharedSQLiteStatement(__db) {
+      @Override
+      public String createQuery() {
+        final String _query = "UPDATE User SET ageColumn = ageColumn + 1 WHERE uid = ?";
+        return _query;
+      }
+    };
+    this.__preparedStmtOfAgeUserAll = new SharedSQLiteStatement(__db) {
+      @Override
+      public String createQuery() {
+        final String _query = "UPDATE User SET ageColumn = ageColumn + 1";
+        return _query;
+      }
+    };
+  }
+
+  @Override
+  public void updateUser(User user) {
+    __db.beginTransaction();
+    try {
+      __updateAdapterOfUser.handle(user);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void updateUsers(User user1, List<User> others) {
+    __db.beginTransaction();
+    try {
+      __updateAdapterOfUser.handle(user1);
+      __updateAdapterOfUser.handleMultiple(others);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void updateArrayOfUsers(User[] users) {
+    __db.beginTransaction();
+    try {
+      __updateAdapterOfUser.handleMultiple(users);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int updateUserAndReturnCount(User user) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__updateAdapterOfUser.handle(user);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int updateUserAndReturnCount(User user1, List<User> others) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__updateAdapterOfUser.handle(user1);
+      _total +=__updateAdapterOfUser.handleMultiple(others);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int updateUserAndReturnCount(User[] users) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__updateAdapterOfUser.handleMultiple(users);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public int multiPKey(MultiPKeyEntity entity) {
+    int _total = 0;
+    __db.beginTransaction();
+    try {
+      _total +=__updateAdapterOfMultiPKeyEntity.handle(entity);
+      __db.setTransactionSuccessful();
+      return _total;
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void updateUserAndBook(User user, Book book) {
+    __db.beginTransaction();
+    try {
+      __updateAdapterOfUser.handle(user);
+      __updateAdapterOfBook.handle(book);
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+    }
+  }
+
+  @Override
+  public void ageUserByUid(String uid) {
+    final SupportSQLiteStatement _stmt = __preparedStmtOfAgeUserByUid.acquire();
+    __db.beginTransaction();
+    try {
+      int _argIndex = 1;
+      if (uid == null) {
+        _stmt.bindNull(_argIndex);
+      } else {
+        _stmt.bindString(_argIndex, uid);
+      }
+      _stmt.executeUpdateDelete();
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+      __preparedStmtOfAgeUserByUid.release(_stmt);
+    }
+  }
+
+  @Override
+  public void ageUserAll() {
+    final SupportSQLiteStatement _stmt = __preparedStmtOfAgeUserAll.acquire();
+    __db.beginTransaction();
+    try {
+      _stmt.executeUpdateDelete();
+      __db.setTransactionSuccessful();
+    } finally {
+      __db.endTransaction();
+      __preparedStmtOfAgeUserAll.release(_stmt);
+    }
+  }
+}
diff --git a/room/compiler/src/test/data/daoWriter/output/WriterDao.java b/room/compiler/src/test/data/daoWriter/output/WriterDao.java
new file mode 100644
index 0000000..76b9975
--- /dev/null
+++ b/room/compiler/src/test/data/daoWriter/output/WriterDao.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.arch.persistence.room.EntityInsertionAdapter;
+import android.arch.persistence.room.RoomDatabase;
+
+import java.lang.Override;
+import java.lang.String;
+import java.util.List;
+
+public class WriterDao_Impl implements WriterDao {
+    private final RoomDatabase __db;
+
+    private final EntityInsertionAdapter __insertionAdapterOfUser;
+
+    private final EntityInsertionAdapter __insertionAdapterOfUser_1;
+
+    private final EntityInsertionAdapter __insertionAdapterOfBook;
+
+    public WriterDao_Impl(RoomDatabase __db) {
+        this.__db = __db;
+        this.__insertionAdapterOfUser = new EntityInsertionAdapter<User>(__db) {
+            @Override
+            public String createQuery() {
+                return "INSERT OR ABORT INTO `User`(`uid`,`name`,`lastName`,`ageColumn`) VALUES"
+                        + " (?,?,?,?)";
+            }
+
+            @Override
+            public void bind(SupportSQLiteStatement stmt, User value) {
+                stmt.bindLong(1, value.uid);
+                if (value.name == null) {
+                    stmt.bindNull(2);
+                } else {
+                    stmt.bindString(2, value.name);
+                }
+                if (value.getLastName() == null) {
+                    stmt.bindNull(3);
+                } else {
+                    stmt.bindString(3, value.getLastName());
+                }
+                stmt.bindLong(4, value.age);
+            }
+        };
+        this.__insertionAdapterOfUser_1 = new EntityInsertionAdapter<User>(__db) {
+            @Override
+            public String createQuery() {
+                return "INSERT OR REPLACE INTO `User`(`uid`,`name`,`lastName`,`ageColumn`) VALUES"
+                        + " (?,?,?,?)";
+            }
+
+            @Override
+            public void bind(SupportSQLiteStatement stmt, User value) {
+                stmt.bindLong(1, value.uid);
+                if (value.name == null) {
+                    stmt.bindNull(2);
+                } else {
+                    stmt.bindString(2, value.name);
+                }
+                if (value.getLastName() == null) {
+                    stmt.bindNull(3);
+                } else {
+                    stmt.bindString(3, value.getLastName());
+                }
+                stmt.bindLong(4, value.age);
+            }
+        };
+        this.__insertionAdapterOfBook = new EntityInsertionAdapter<Book>(__db) {
+            @Override
+            public String createQuery() {
+                return "INSERT OR ABORT INTO `Book`(`bookId`,`uid`) VALUES (?,?)";
+            }
+
+            @Override
+            public void bind(SupportSQLiteStatement stmt, Book value) {
+                stmt.bindLong(1, value.bookId);
+                stmt.bindLong(2, value.uid);
+            }
+        };
+    }
+
+    @Override
+    public void insertUser(User user) {
+        __db.beginTransaction();
+        try {
+            __insertionAdapterOfUser.insert(user);
+            __db.setTransactionSuccessful();
+        } finally {
+            __db.endTransaction();
+        }
+    }
+
+    @Override
+    public void insertUsers(User user1, List<User> others) {
+        __db.beginTransaction();
+        try {
+            __insertionAdapterOfUser.insert(user1);
+            __insertionAdapterOfUser.insert(others);
+            __db.setTransactionSuccessful();
+        } finally {
+            __db.endTransaction();
+        }
+    }
+
+    @Override
+    public void insertUsers(User[] users) {
+        __db.beginTransaction();
+        try {
+            __insertionAdapterOfUser_1.insert(users);
+            __db.setTransactionSuccessful();
+        } finally {
+            __db.endTransaction();
+        }
+    }
+
+    @Override
+    public void insertUserAndBook(User user, Book book) {
+        __db.beginTransaction();
+        try {
+            __insertionAdapterOfUser.insert(user);
+            __insertionAdapterOfBook.insert(book);
+            __db.setTransactionSuccessful();
+        } finally {
+            __db.endTransaction();
+        }
+    }
+}
diff --git a/room/compiler/src/test/data/databasewriter/input/ComplexDatabase.java b/room/compiler/src/test/data/databasewriter/input/ComplexDatabase.java
new file mode 100644
index 0000000..f35e0b8
--- /dev/null
+++ b/room/compiler/src/test/data/databasewriter/input/ComplexDatabase.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2016 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 foo.bar;
+import android.arch.persistence.room.*;
+import java.util.List;
+@Database(entities = {User.class}, version = 1923)
+abstract class ComplexDatabase extends RoomDatabase {
+    abstract ComplexDao getComplexDao();
+}
diff --git a/room/compiler/src/test/data/databasewriter/output/ComplexDatabase.java b/room/compiler/src/test/data/databasewriter/output/ComplexDatabase.java
new file mode 100644
index 0000000..0846dff
--- /dev/null
+++ b/room/compiler/src/test/data/databasewriter/output/ComplexDatabase.java
@@ -0,0 +1,96 @@
+package foo.bar;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.SupportSQLiteOpenHelper.Callback;
+import android.arch.persistence.db.SupportSQLiteOpenHelper.Configuration;
+import android.arch.persistence.room.DatabaseConfiguration;
+import android.arch.persistence.room.InvalidationTracker;
+import android.arch.persistence.room.RoomOpenHelper;
+import android.arch.persistence.room.RoomOpenHelper.Delegate;
+import android.arch.persistence.room.util.TableInfo;
+import android.arch.persistence.room.util.TableInfo.Column;
+import android.arch.persistence.room.util.TableInfo.ForeignKey;
+import java.lang.IllegalStateException;
+import java.lang.Override;
+import java.lang.String;
+import java.util.HashMap;
+import java.util.HashSet;
+
+public class ComplexDatabase_Impl extends ComplexDatabase {
+    private volatile ComplexDao _complexDao;
+
+    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {
+        final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate() {
+            public void createAllTables(SupportSQLiteDatabase _db) {
+                _db.execSQL("CREATE TABLE IF NOT EXISTS `User` (`uid` INTEGER NOT NULL, `name` TEXT, `lastName` TEXT, `ageColumn` INTEGER NOT NULL, PRIMARY KEY(`uid`))");
+                _db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
+                _db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"6773601c5bcf94c71ee4eb0de04f21a4\")");
+            }
+
+            public void dropAllTables(SupportSQLiteDatabase _db) {
+                _db.execSQL("DROP TABLE IF EXISTS `User`");
+            }
+
+            protected void onCreate(SupportSQLiteDatabase _db) {
+                if (mCallbacks != null) {
+                    for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
+                        mCallbacks.get(_i).onCreate(_db);
+                    }
+                }
+            }
+
+            public void onOpen(SupportSQLiteDatabase _db) {
+                mDatabase = _db;
+                internalInitInvalidationTracker(_db);
+                if (mCallbacks != null) {
+                    for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
+                        mCallbacks.get(_i).onOpen(_db);
+                    }
+                }
+            }
+
+            protected void validateMigration(SupportSQLiteDatabase _db) {
+                final HashMap<String, TableInfo.Column> _columnsUser = new HashMap<String, TableInfo.Column>(4);
+                _columnsUser.put("uid", new TableInfo.Column("uid", "INTEGER", true, 1));
+                _columnsUser.put("name", new TableInfo.Column("name", "TEXT", false, 0));
+                _columnsUser.put("lastName", new TableInfo.Column("lastName", "TEXT", false, 0));
+                _columnsUser.put("ageColumn", new TableInfo.Column("ageColumn", "INTEGER", true, 0));
+                final HashSet<TableInfo.ForeignKey> _foreignKeysUser = new HashSet<TableInfo.ForeignKey>(0);
+                final TableInfo _infoUser = new TableInfo("User", _columnsUser, _foreignKeysUser);
+                final TableInfo _existingUser = TableInfo.read(_db, "User");
+                if (! _infoUser.equals(_existingUser)) {
+                    throw new IllegalStateException("Migration didn't properly handle User(foo.bar.User).\n"
+                            + " Expected:\n" + _infoUser + "\n"
+                            + " Found:\n" + _existingUser);
+                }
+            }
+        }, "6773601c5bcf94c71ee4eb0de04f21a4");
+        final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context)
+                .name(configuration.name)
+                .version(1923)
+                .callback(_openCallback)
+                .build();
+        final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig);
+        return _helper;
+    }
+
+    @Override
+    protected InvalidationTracker createInvalidationTracker() {
+        return new InvalidationTracker(this, "User");
+    }
+
+    @Override
+    ComplexDao getComplexDao() {
+        if (_complexDao != null) {
+            return _complexDao;
+        } else {
+            synchronized(this) {
+                if(_complexDao == null) {
+                    _complexDao = new ComplexDao_Impl(this);
+                }
+                return _complexDao;
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/parser/SqlParserTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/parser/SqlParserTest.kt
new file mode 100644
index 0000000..68b1868
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/parser/SqlParserTest.kt
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.parser
+
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class SqlParserTest {
+
+    @Test
+    fun multipleQueries() {
+        assertErrors("SELECT * FROM users; SELECT * FROM books;",
+                ParserErrors.NOT_ONE_QUERY)
+    }
+
+    @Test
+    fun empty() {
+        assertErrors("", ParserErrors.NOT_ONE_QUERY)
+    }
+
+    @Test
+    fun deleteQuery() {
+        val parsed = SqlParser.parse("DELETE FROM users where id > 3")
+        assertThat(parsed.errors, `is`(emptyList()))
+        assertThat(parsed.type, `is`(QueryType.DELETE))
+    }
+
+    @Test
+    fun badDeleteQuery() {
+        assertErrors("delete from user where mAge >= :min && mAge <= :max",
+                "no viable alternative at input 'delete from user where mAge >= :min &&'")
+    }
+
+    @Test
+    fun updateQuery() {
+        val parsed = SqlParser.parse("UPDATE users set name = :name where id = :id")
+        assertThat(parsed.errors, `is`(emptyList()))
+        assertThat(parsed.type, `is`(QueryType.UPDATE))
+    }
+
+    @Test
+    fun explain() {
+        assertErrors("EXPLAIN QUERY PLAN SELECT * FROM users",
+                ParserErrors.invalidQueryType(QueryType.EXPLAIN))
+    }
+
+    @Test
+    fun extractTableNames() {
+        assertThat(SqlParser.parse("select * from users").tables,
+                `is`(setOf(Table("users", "users"))))
+        assertThat(SqlParser.parse("select * from users as ux").tables,
+                `is`(setOf(Table("users", "ux"))))
+        assertThat(SqlParser.parse("select * from (select * from books)").tables,
+                `is`(setOf(Table("books", "books"))))
+        assertThat(SqlParser.parse("select x.id from (select * from books) as x").tables,
+                `is`(setOf(Table("books", "books"))))
+    }
+
+    @Test
+    fun unescapeTableNames() {
+        assertThat(SqlParser.parse("select * from `users`").tables,
+                `is`(setOf(Table("users", "users"))))
+        assertThat(SqlParser.parse("select * from \"users\"").tables,
+                `is`(setOf(Table("users", "users"))))
+    }
+
+    @Test
+    fun findBindVariables() {
+        assertVariables("select * from users")
+        assertVariables("select * from users where name like ?", "?")
+        assertVariables("select * from users where name like :name", ":name")
+        assertVariables("select * from users where name like ?2", "?2")
+        assertVariables("select * from users where name like ?2 OR name LIKE ?1", "?2", "?1")
+        assertVariables("select * from users where name like @a", "@a")
+        assertVariables("select * from users where name like \$a", "\$a")
+    }
+
+    @Test
+    fun  indexedVariablesError() {
+        assertErrors("select * from users where name like ?",
+                ParserErrors.ANONYMOUS_BIND_ARGUMENT)
+        assertErrors("select * from users where name like ? or last_name like ?",
+                ParserErrors.ANONYMOUS_BIND_ARGUMENT)
+        assertErrors("select * from users where name like ?1",
+                ParserErrors.cannotUseVariableIndices("?1", 36))
+    }
+
+    @Test
+    fun foo() {
+        assertSections("select * from users where name like ?",
+                Section.text("select * from users where name like "),
+                Section.bindVar("?"))
+
+        assertSections("select * from users where name like :name AND last_name like :lastName",
+                Section.text("select * from users where name like "),
+                Section.bindVar(":name"),
+                Section.text(" AND last_name like "),
+                Section.bindVar(":lastName"))
+
+        assertSections("select * from users where name \nlike :name AND last_name like :lastName",
+                Section.text("select * from users where name "),
+                Section.newline(),
+                Section.text("like "),
+                Section.bindVar(":name"),
+                Section.text(" AND last_name like "),
+                Section.bindVar(":lastName"))
+
+        assertSections("select * from users where name like :name \nAND last_name like :lastName",
+                Section.text("select * from users where name like "),
+                Section.bindVar(":name"),
+                Section.text(" "),
+                Section.newline(),
+                Section.text("AND last_name like "),
+                Section.bindVar(":lastName"))
+
+        assertSections("select * from users where name like :name \nAND last_name like \n:lastName",
+                Section.text("select * from users where name like "),
+                Section.bindVar(":name"),
+                Section.text(" "),
+                Section.newline(),
+                Section.text("AND last_name like "),
+                Section.newline(),
+                Section.bindVar(":lastName"))
+    }
+
+    fun assertVariables(query: String, vararg expected: String) {
+        assertThat((SqlParser.parse(query)).inputs.map { it.text }, `is`(expected.toList()))
+    }
+
+    fun assertErrors(query: String, vararg errors: String) {
+        assertThat((SqlParser.parse(query)).errors, `is`(errors.toList()))
+    }
+
+    fun assertSections(query: String, vararg sections: Section) {
+        assertThat(SqlParser.parse(query).sections, `is`(sections.toList()))
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseDaoTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseDaoTest.kt
new file mode 100644
index 0000000..ae648f7
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseDaoTest.kt
@@ -0,0 +1,169 @@
+package android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.vo.Dao
+import android.arch.persistence.room.writer.DaoWriter
+import com.google.auto.common.MoreTypes
+import com.google.testing.compile.JavaFileObjects
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import simpleRun
+
+/**
+ * we don't assert much in these tests since if type resolution fails, compilation fails.
+ */
+@RunWith(JUnit4::class)
+class BaseDaoTest {
+    private fun String.toJFO(qName: String) = JavaFileObjects.forSourceLines(qName, this)
+
+    @Test
+    fun insert() {
+        baseDao("""
+            @Insert
+            void insertMe(T t);
+        """) { dao ->
+            assertThat(dao.insertionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun insertArray() {
+        baseDao("""
+            @Insert
+            void insertMe(T[] t);
+        """) { dao ->
+            assertThat(dao.insertionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun insertVarArg() {
+        baseDao("""
+            @Insert
+            void insertMe(T... t);
+        """) { dao ->
+            assertThat(dao.insertionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun insertList() {
+        baseDao("""
+            @Insert
+            void insertMe(List<T> t);
+        """) { dao ->
+            assertThat(dao.insertionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun delete() {
+        baseDao("""
+            @Delete
+            void deleteMe(T t);
+        """) { dao ->
+            assertThat(dao.deletionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun deleteArray() {
+        baseDao("""
+            @Delete
+            void deleteMe(T[] t);
+        """) { dao ->
+            assertThat(dao.deletionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun deleteVarArg() {
+        baseDao("""
+            @Delete
+            void deleteMe(T... t);
+        """) { dao ->
+            assertThat(dao.deletionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun deleteList() {
+        baseDao("""
+            @Delete
+            void deleteMe(List<T> t);
+        """) { dao ->
+            assertThat(dao.deletionMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun update() {
+        baseDao("""
+            @Update
+            void updateMe(T t);
+        """) { dao ->
+            assertThat(dao.updateMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun updateArray() {
+        baseDao("""
+            @Update
+            void updateMe(T[] t);
+        """) { dao ->
+            assertThat(dao.updateMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun updateVarArg() {
+        baseDao("""
+            @Update
+            void updateMe(T... t);
+        """) { dao ->
+            assertThat(dao.updateMethods.size, `is`(1))
+        }
+    }
+
+    @Test
+    fun updateList() {
+        baseDao("""
+            @Update
+            void updateMe(List<T> t);
+        """) { dao ->
+            assertThat(dao.updateMethods.size, `is`(1))
+        }
+    }
+
+    fun baseDao(code : String, handler : (Dao) -> Unit) {
+        val baseClass = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            import java.util.List;
+
+            interface BaseDao<K, T> {
+                $code
+            }
+        """.toJFO("foo.bar.BaseDao")
+        val extension = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            @Dao
+            interface MyDao extends BaseDao<Integer, User> {
+            }
+        """.toJFO("foo.bar.MyDao")
+        simpleRun(baseClass, extension, COMMON.USER) { invocation ->
+            val daoElm = invocation.processingEnv.elementUtils.getTypeElement("foo.bar.MyDao")
+            val dbType = MoreTypes.asDeclared(invocation.context.processingEnv.elementUtils
+                    .getTypeElement(RoomTypeNames.ROOM_DB.toString()).asType())
+            val processedDao = DaoProcessor(invocation.context, daoElm, dbType, null).process()
+            handler(processedDao)
+            DaoWriter(processedDao, invocation.processingEnv).write(invocation.processingEnv)
+        }.compilesWithoutError()
+    }
+}
\ No newline at end of file
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseEntityParserTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseEntityParserTest.kt
new file mode 100644
index 0000000..9bfc0e7
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/BaseEntityParserTest.kt
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Embedded
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Entity
+import com.google.auto.common.MoreElements
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourceSubjectFactory
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import javax.tools.JavaFileObject
+
+abstract class BaseEntityParserTest {
+    companion object {
+        const val ENTITY_PREFIX = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            import android.support.annotation.NonNull;
+            @Entity%s
+            public class MyEntity %s {
+            """
+        const val ENTITY_SUFFIX = "}"
+    }
+
+    fun singleEntity(input: String, attributes: Map<String, String> = mapOf(),
+                     baseClass : String = "",
+                     jfos : List<JavaFileObject> = emptyList(),
+                     handler: (Entity, TestInvocation) -> Unit): CompileTester {
+        val attributesReplacement : String
+        if (attributes.isEmpty()) {
+            attributesReplacement = ""
+        } else {
+            attributesReplacement = "(" +
+                    attributes.entries.map { "${it.key} = ${it.value}" }.joinToString(",") +
+                    ")".trimIndent()
+        }
+        val baseClassReplacement : String
+        if (baseClass == "") {
+            baseClassReplacement = ""
+        } else {
+            baseClassReplacement = " extends $baseClass"
+        }
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(jfos + JavaFileObjects.forSourceString("foo.bar.MyEntity",
+                        ENTITY_PREFIX.format(attributesReplacement, baseClassReplacement)
+                                + input + ENTITY_SUFFIX
+                ))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Entity::class,
+                                android.arch.persistence.room.PrimaryKey::class,
+                                android.arch.persistence.room.Ignore::class,
+                                Embedded::class,
+                                android.arch.persistence.room.ColumnInfo::class)
+                        .nextRunHandler { invocation ->
+                            val entity = invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Entity::class.java)
+                                    .first { it.toString() == "foo.bar.MyEntity" }
+                            val parser = EntityProcessor(invocation.context,
+                                    MoreElements.asType(entity))
+                            val parsedQuery = parser.process()
+                            handler(parsedQuery, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/CustomConverterProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/CustomConverterProcessorTest.kt
new file mode 100644
index 0000000..34bbd24
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/CustomConverterProcessorTest.kt
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.TypeConverter
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_EMPTY_CLASS
+import android.arch.persistence.room.processor.ProcessorErrors
+        .TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_MUST_BE_PUBLIC
+import android.arch.persistence.room.processor.ProcessorErrors.TYPE_CONVERTER_UNBOUND_GENERIC
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.vo.CustomTypeConverter
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import com.squareup.javapoet.TypeVariableName
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import simpleRun
+import java.util.Date
+import javax.lang.model.element.Modifier
+import javax.tools.JavaFileObject
+
+@RunWith(JUnit4::class)
+class CustomConverterProcessorTest {
+    companion object {
+        val CONVERTER = ClassName.get("foo.bar", "MyConverter")!!
+        val CONVERTER_QNAME = CONVERTER.packageName() + "." + CONVERTER.simpleName()
+        val CONTAINER = JavaFileObjects.forSourceString("foo.bar.Container",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @TypeConverters(foo.bar.MyConverter.class)
+                public class Container {}
+                """)
+    }
+
+    @Test
+    fun validCase() {
+        singleClass(createConverter(TypeName.SHORT.box(), TypeName.CHAR.box()))
+        { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.SHORT.box()))
+            assertThat(converter?.toTypeName, `is`(TypeName.CHAR.box()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun primitiveFrom() {
+        singleClass(createConverter(TypeName.SHORT, TypeName.CHAR.box())) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.SHORT))
+            assertThat(converter?.toTypeName, `is`(TypeName.CHAR.box()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun primitiveTo() {
+        singleClass(createConverter(TypeName.INT.box(), TypeName.DOUBLE)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.INT.box()))
+            assertThat(converter?.toTypeName, `is`(TypeName.DOUBLE))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun primitiveBoth() {
+        singleClass(createConverter(TypeName.INT, TypeName.DOUBLE)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.INT))
+            assertThat(converter?.toTypeName, `is`(TypeName.DOUBLE))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun nonNullButNotBoxed() {
+        val string = String::class.typeName()
+        val date = Date::class.typeName()
+        singleClass(createConverter(string, date)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(string as TypeName))
+            assertThat(converter?.toTypeName, `is`(date as TypeName))
+        }
+    }
+
+    @Test
+    fun parametrizedTypeUnbound() {
+        val typeVarT = TypeVariableName.get("T")
+        val list = ParameterizedTypeName.get(List::class.typeName(), typeVarT)
+        val typeVarK = TypeVariableName.get("K")
+        val map = ParameterizedTypeName.get(Map::class.typeName(), typeVarK, typeVarT)
+        singleClass(createConverter(list, map, listOf(typeVarK, typeVarT))) {
+            converter, invocation ->
+        }.failsToCompile().withErrorContaining(TYPE_CONVERTER_UNBOUND_GENERIC)
+    }
+
+    @Test
+    fun parametrizedTypeSpecific() {
+        val string = String::class.typeName()
+        val date = Date::class.typeName()
+        val list = ParameterizedTypeName.get(List::class.typeName(), string)
+        val map = ParameterizedTypeName.get(Map::class.typeName(), string, date)
+        singleClass(createConverter(list, map)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(list as TypeName))
+            assertThat(converter?.toTypeName, `is`(map as TypeName))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testNoConverters() {
+        singleClass(JavaFileObjects.forSourceString(CONVERTER_QNAME,
+                """
+                package ${CONVERTER.packageName()};
+                public class ${CONVERTER.simpleName()} {
+                }
+                """)) { converter, invocation ->
+        }.failsToCompile().withErrorContaining(TYPE_CONVERTER_EMPTY_CLASS)
+    }
+
+    @Test
+    fun checkNoArgConstructor() {
+        singleClass(JavaFileObjects.forSourceString(CONVERTER_QNAME,
+                """
+                package ${CONVERTER.packageName()};
+                import android.arch.persistence.room.TypeConverter;
+
+                public class ${CONVERTER.simpleName()} {
+                    public ${CONVERTER.simpleName()}(int x) {}
+                    @TypeConverter
+                    public int x(short y) {return 0;}
+                }
+                """)) { converter, invocation ->
+        }.failsToCompile().withErrorContaining(TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR)
+    }
+
+    @Test
+    fun checkNoArgConstructor_withStatic() {
+        singleClass(JavaFileObjects.forSourceString(CONVERTER_QNAME,
+                """
+                package ${CONVERTER.packageName()};
+                import android.arch.persistence.room.TypeConverter;
+
+                public class ${CONVERTER.simpleName()} {
+                    public ${CONVERTER.simpleName()}(int x) {}
+                    @TypeConverter
+                    public static int x(short y) {return 0;}
+                }
+                """)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.SHORT))
+            assertThat(converter?.toTypeName, `is`(TypeName.INT))
+            assertThat(converter?.isStatic, `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun checkPublic() {
+        singleClass(JavaFileObjects.forSourceString(CONVERTER_QNAME,
+                """
+                package ${CONVERTER.packageName()};
+                import android.arch.persistence.room.TypeConverter;
+
+                public class ${CONVERTER.simpleName()} {
+                    @TypeConverter static int x(short y) {return 0;}
+                    @TypeConverter private static int y(boolean y) {return 0;}
+                }
+                """)) { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.SHORT))
+            assertThat(converter?.toTypeName, `is`(TypeName.INT))
+            assertThat(converter?.isStatic, `is`(true))
+        }.failsToCompile().withErrorContaining(TYPE_CONVERTER_MUST_BE_PUBLIC).and()
+                .withErrorCount(2)
+    }
+
+    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+    @Test
+    fun parametrizedTypeBoundViaParent() {
+        val typeVarT = TypeVariableName.get("T")
+        val list = ParameterizedTypeName.get(List::class.typeName(), typeVarT)
+        val typeVarK = TypeVariableName.get("K")
+        val map = ParameterizedTypeName.get(Map::class.typeName(), typeVarK, typeVarT)
+
+        val baseConverter = createConverter(list, map, listOf(typeVarT, typeVarK))
+        val extendingQName = "foo.bar.Extending"
+        val extendingClass = JavaFileObjects.forSourceString(extendingQName,
+                "package foo.bar;\n" +
+                        TypeSpec.classBuilder(ClassName.bestGuess(extendingQName)).apply {
+                            superclass(
+                                    ParameterizedTypeName.get(CONVERTER, String::class.typeName(),
+                                    Integer::class.typeName()))
+                        }.build().toString())
+
+        simpleRun(baseConverter, extendingClass) { invocation ->
+            val element = invocation.processingEnv.elementUtils.getTypeElement(extendingQName)
+            val converter = CustomConverterProcessor(invocation.context, element)
+                    .process().firstOrNull()
+            assertThat(converter?.fromTypeName, `is`(ParameterizedTypeName.get(
+                    List::class.typeName(), String::class.typeName()) as TypeName
+            ))
+            assertThat(converter?.toTypeName, `is`(ParameterizedTypeName.get(Map::class.typeName(),
+                    Integer::class.typeName(), String::class.typeName()) as TypeName
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun checkDuplicates() {
+        singleClass(createConverter(TypeName.SHORT.box(), TypeName.CHAR.box(), duplicate = true))
+        { converter, invocation ->
+            assertThat(converter?.fromTypeName, `is`(TypeName.SHORT.box()))
+            assertThat(converter?.toTypeName, `is`(TypeName.CHAR.box()))
+        }.failsToCompile().withErrorContaining("Multiple methods define the same conversion")
+    }
+
+    private fun createConverter(from: TypeName, to: TypeName,
+                                typeVariables: List<TypeVariableName> = emptyList(),
+                                duplicate : Boolean = false)
+            : JavaFileObject {
+        val code = TypeSpec.classBuilder(CONVERTER).apply {
+            addTypeVariables(typeVariables)
+            addModifiers(Modifier.PUBLIC)
+            fun buildMethod(name : String) = MethodSpec.methodBuilder(name).apply {
+                addAnnotation(TypeConverter::class.java)
+                addModifiers(Modifier.PUBLIC)
+                returns(to)
+                addParameter(ParameterSpec.builder(from, "input").build())
+                if (to.isPrimitive) {
+                    addStatement("return 0")
+                } else {
+                    addStatement("return null")
+                }
+            }.build()
+            addMethod(buildMethod("convertF"))
+            if (duplicate) {
+                addMethod(buildMethod("convertF2"))
+            }
+        }.build().toString()
+        return JavaFileObjects.forSourceString(CONVERTER.toString(),
+                "package ${CONVERTER.packageName()};\n$code")
+    }
+
+    private fun singleClass(vararg jfo: JavaFileObject,
+                            handler: (CustomTypeConverter?, TestInvocation) -> Unit)
+            : CompileTester {
+        return simpleRun(*((jfo.toList() + CONTAINER).toTypedArray())) { invocation ->
+            val processed = CustomConverterProcessor.findConverters(invocation.context,
+                    invocation.processingEnv.elementUtils.getTypeElement("foo.bar.Container"))
+            handler(processed.converters.firstOrNull()?.custom, invocation)
+        }
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DaoProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DaoProcessorTest.kt
new file mode 100644
index 0000000..a53cc1e
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DaoProcessorTest.kt
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Dao
+import android.arch.persistence.room.vo.Warning
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import createVerifierFromEntities
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+
+@RunWith(Parameterized::class)
+class DaoProcessorTest(val enableVerification : Boolean) {
+    companion object {
+        const val DAO_PREFIX = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            """
+        @Parameterized.Parameters(name = "enableDbVerification={0}")
+        @JvmStatic
+        fun getParams() = arrayOf(true, false)
+    }
+
+    @Test
+    fun testNonAbstract() {
+        singleDao("@Dao public class MyDao {}") { dao, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.DAO_MUST_BE_AN_ABSTRACT_CLASS_OR_AN_INTERFACE)
+    }
+
+    @Test
+    fun testAbstractMethodWithoutQuery() {
+        singleDao("""
+                @Dao public interface MyDao {
+                    int getFoo();
+                }
+        """) { dao, invocation ->
+        }.failsToCompile()
+                .withErrorContaining(ProcessorErrors.ABSTRACT_METHOD_IN_DAO_MISSING_ANY_ANNOTATION)
+    }
+
+    @Test
+    fun testBothAnnotations() {
+        singleDao("""
+                @Dao public interface MyDao {
+                    @Query("select 1")
+                    @Insert
+                    int getFoo(int x);
+                }
+        """) { dao, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_DAO_METHOD_ANNOTATION)
+    }
+
+    @Test
+    fun testAbstractClass() {
+        singleDao("""
+                @Dao abstract class MyDao {
+                    @Query("SELECT uid FROM User")
+                    abstract int[] getIds();
+                }
+                """) { dao, invocation ->
+            assertThat(dao.queryMethods.size, `is`(1))
+            val method = dao.queryMethods.first()
+            assertThat(method.name, `is`("getIds"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testInterface() {
+        singleDao("""
+                @Dao interface MyDao {
+                    @Query("SELECT uid FROM User")
+                    abstract int[] getIds();
+                }
+                """) { dao, invocation ->
+            assertThat(dao.queryMethods.size, `is`(1))
+            val method = dao.queryMethods.first()
+            assertThat(method.name, `is`("getIds"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testWithInsertAndQuery() {
+        singleDao("""
+                @Dao abstract class MyDao {
+                    @Query("SELECT uid FROM User")
+                    abstract int[] getIds();
+                    @Insert
+                    abstract void insert(User user);
+                }
+                """) { dao, invocation ->
+            assertThat(dao.queryMethods.size, `is`(1))
+            val method = dao.queryMethods.first()
+            assertThat(method.name, `is`("getIds"))
+            assertThat(dao.insertionMethods.size, `is`(1))
+            val insertMethod = dao.insertionMethods.first()
+            assertThat(insertMethod.name, `is`("insert"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun skipQueryVerification() {
+        singleDao("""
+                @Dao @SkipQueryVerification interface MyDao {
+                    @Query("SELECT nonExistingField FROM User")
+                    abstract int[] getIds();
+                }
+                """) { dao, invocation ->
+            assertThat(dao.queryMethods.size, `is`(1))
+            val method = dao.queryMethods.first()
+            assertThat(method.name, `is`("getIds"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun suppressedWarnings() {
+        singleDao("""
+            @SuppressWarnings({"ALL", RoomWarnings.CURSOR_MISMATCH})
+            @Dao interface MyDao {
+                @Query("SELECT * from user")
+                abstract User users();
+            }
+            """) { dao, invocation ->
+            val dbType = MoreTypes.asDeclared(invocation.context.processingEnv.elementUtils
+                    .getTypeElement(RoomTypeNames.ROOM_DB.toString()).asType())
+            val daoProcessor = DaoProcessor(invocation.context, dao.element, dbType, null)
+            assertThat(daoProcessor.context.logger
+                    .suppressedWarnings, `is`(setOf(Warning.ALL, Warning.CURSOR_MISMATCH)))
+
+            dao.queryMethods.forEach {
+                assertThat(QueryMethodProcessor(
+                        baseContext = daoProcessor.context,
+                        containing = MoreTypes.asDeclared(dao.element.asType()),
+                        executableElement = it.element,
+                        dbVerifier = null).context.logger.suppressedWarnings,
+                        `is`(setOf(Warning.ALL, Warning.CURSOR_MISMATCH)))
+            }
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun suppressedWarningsInheritance() {
+        singleDao("""
+            @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
+            @Dao interface MyDao {
+                @SuppressWarnings("ALL")
+                @Query("SELECT * from user")
+                abstract User users();
+            }
+            """) { dao, invocation ->
+            val dbType = MoreTypes.asDeclared(invocation.context.processingEnv.elementUtils
+                    .getTypeElement(RoomTypeNames.ROOM_DB.toString()).asType())
+            val daoProcessor = DaoProcessor(invocation.context, dao.element, dbType, null)
+            assertThat(daoProcessor.context.logger
+                    .suppressedWarnings, `is`(setOf(Warning.CURSOR_MISMATCH)))
+
+            dao.queryMethods.forEach {
+                assertThat(QueryMethodProcessor(
+                        baseContext = daoProcessor.context,
+                        containing = MoreTypes.asDeclared(dao.element.asType()),
+                        executableElement = it.element,
+                        dbVerifier = null).context.logger.suppressedWarnings,
+                        `is`(setOf(Warning.ALL, Warning.CURSOR_MISMATCH)))
+            }
+        }.compilesWithoutError()
+    }
+
+    fun singleDao(vararg inputs: String, handler: (Dao, TestInvocation) -> Unit):
+            CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyDao",
+                        DAO_PREFIX + inputs.joinToString("\n")
+                ), COMMON.USER))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Dao::class,
+                                android.arch.persistence.room.Entity::class)
+                        .nextRunHandler { invocation ->
+                            val dao = invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Dao::class.java)
+                                    .first()
+                            val dbVerifier = if (enableVerification) {
+                                createVerifierFromEntities(invocation)
+                            } else {
+                                null
+                            }
+                            val dbType = MoreTypes.asDeclared(
+                                    invocation.context.processingEnv.elementUtils
+                                            .getTypeElement(RoomTypeNames.ROOM_DB.toString())
+                                            .asType())
+                            val parser = DaoProcessor(invocation.context,
+                                    MoreElements.asType(dao), dbType, dbVerifier)
+
+                            val parsedDao = parser.process()
+                            handler(parsedDao, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DatabaseProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DatabaseProcessorTest.kt
new file mode 100644
index 0000000..56e6641
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DatabaseProcessorTest.kt
@@ -0,0 +1,717 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.RoomProcessor
+import android.arch.persistence.room.solver.query.result.EntityRowAdapter
+import android.arch.persistence.room.solver.query.result.PojoRowAdapter
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Database
+import android.arch.persistence.room.vo.Warning
+import com.google.auto.common.MoreElements
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.ClassName
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.instanceOf
+import org.hamcrest.CoreMatchers.not
+import org.hamcrest.CoreMatchers.notNullValue
+import org.hamcrest.CoreMatchers.sameInstance
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.tools.JavaFileObject
+import javax.tools.StandardLocation
+
+@RunWith(JUnit4::class)
+class DatabaseProcessorTest {
+    companion object {
+        const val DATABASE_PREFIX = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            """
+        val DB1: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.Db1",
+                """
+                $DATABASE_PREFIX
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class Db1 extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """)
+        val DB2: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.Db2",
+                """
+                $DATABASE_PREFIX
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class Db2 extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """)
+        val DB3: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.Db3",
+                """
+                $DATABASE_PREFIX
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class Db3 extends RoomDatabase {
+                }
+                """)
+        val USER: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.User",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity
+                public class User {
+                    @PrimaryKey
+                    int uid;
+                }
+                """)
+        val USER_DAO: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.UserDao",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                public interface UserDao {
+                    @Query("SELECT * FROM user")
+                    public java.util.List<User> loadAll();
+
+                    @Insert
+                    public void insert(User... users);
+
+                    @Query("SELECT * FROM user where uid = :uid")
+                    public User loadOne(int uid);
+
+                    @TypeConverters(Converter.class)
+                    @Query("SELECT * FROM user where uid = :uid")
+                    public User loadWithConverter(int uid);
+
+                    @Query("SELECT * FROM user where uid = :uid")
+                    public Pojo loadOnePojo(int uid);
+
+                    @Query("SELECT * FROM user")
+                    public java.util.List<Pojo> loadAllPojos();
+
+                    @TypeConverters(Converter.class)
+                    @Query("SELECT * FROM user where uid = :uid")
+                    public Pojo loadPojoWithConverter(int uid);
+
+                    public static class Converter {
+                        @TypeConverter
+                        public static java.util.Date foo(Long input) {return null;}
+                    }
+
+                    public static class Pojo {
+                        public int uid;
+                    }
+                }
+                """)
+        val BOOK: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.Book",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity
+                public class Book {
+                    @PrimaryKey
+                    int bookId;
+                }
+                """)
+        val BOOK_DAO: JavaFileObject = JavaFileObjects.forSourceString("foo.bar.BookDao",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                public interface BookDao {
+                    @Query("SELECT * FROM book")
+                    public java.util.List<Book> loadAllBooks();
+                    @Insert
+                    public void insert(Book book);
+                }
+                """)
+    }
+
+    @Test
+    fun simple() {
+        singleDb("""
+            @Database(entities = {User.class}, version = 42)
+            public abstract class MyDb extends RoomDatabase {
+                abstract UserDao userDao();
+            }
+            """, USER, USER_DAO) { db, invocation ->
+            assertThat(db.daoMethods.size, `is`(1))
+            assertThat(db.entities.size, `is`(1))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun multiple() {
+        singleDb("""
+            @Database(entities = {User.class, Book.class}, version = 42)
+            public abstract class MyDb extends RoomDatabase {
+                abstract UserDao userDao();
+                abstract BookDao bookDao();
+            }
+            """, USER, USER_DAO, BOOK, BOOK_DAO) { db, invocation ->
+            assertThat(db.daoMethods.size, `is`(2))
+            assertThat(db.entities.size, `is`(2))
+            assertThat(db.daoMethods.map { it.name }, `is`(listOf("userDao", "bookDao")))
+            assertThat(db.entities.map { it.type.toString() },
+                    `is`(listOf("foo.bar.User", "foo.bar.Book")))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun detectMissingBaseClass() {
+        singleDb("""
+            @Database(entities = {User.class, Book.class}, version = 42)
+            public abstract class MyDb {
+            }
+            """, USER, BOOK) { db, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.DB_MUST_EXTEND_ROOM_DB)
+    }
+
+    @Test
+    fun detectMissingTable() {
+        singleDb(
+                """
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """, BOOK, JavaFileObjects.forSourceString("foo.bar.BookDao",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                public interface BookDao {
+                    @Query("SELECT * FROM nonExistentTable")
+                    public java.util.List<Book> loadAllBooks();
+                }
+                """)){ db, invocation ->
+
+        }.failsToCompile().withErrorContaining("no such table: nonExistentTable")
+    }
+
+    @Test
+    fun detectDuplicateTableNames() {
+        singleDb("""
+                @Database(entities = {User.class, AnotherClass.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract UserDao userDao();
+                }
+                """, USER, USER_DAO, JavaFileObjects.forSourceString("foo.bar.AnotherClass",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(tableName="user")
+                public class AnotherClass {
+                    @PrimaryKey
+                    int uid;
+                }
+                """)) { db, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.duplicateTableNames("user",
+                        listOf("foo.bar.User", "foo.bar.AnotherClass"))
+        )
+    }
+
+    @Test
+    fun skipBadQueryVerification() {
+        singleDb(
+                """
+                @SkipQueryVerification
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """, BOOK, JavaFileObjects.forSourceString("foo.bar.BookDao",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                public interface BookDao {
+                    @Query("SELECT nonExistingField FROM Book")
+                    public java.util.List<Book> loadAllBooks();
+                }
+                """)){ db, invocation ->
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun multipleDatabases() {
+        val db1_2 = JavaFileObjects.forSourceString("foo.barx.Db1",
+                """
+                package foo.barx;
+                import android.arch.persistence.room.*;
+                import foo.bar.*;
+                @Database(entities = {Book.class}, version = 42)
+                public abstract class Db1 extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """)
+        Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(BOOK, BOOK_DAO, DB1, DB2, db1_2))
+                .processedWith(RoomProcessor())
+                .compilesWithoutError()
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.bar", "Db1_Impl.class")
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.bar", "Db2_Impl.class")
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.barx", "Db1_Impl.class")
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.bar",
+                        "BookDao_Db1_0_Impl.class")
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.bar",
+                        "BookDao_Db1_1_Impl.class")
+                .and()
+                .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "foo.bar",
+                        "BookDao_Db2_Impl.class")
+    }
+
+    @Test
+    fun twoDaoMethodsForTheSameDao() {
+        singleDb(
+                """
+                @Database(entities = {User.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract UserDao userDao();
+                    abstract UserDao userDao2();
+                }
+                """, USER, USER_DAO){db, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.DAO_METHOD_CONFLICTS_WITH_OTHERS)
+                .and()
+                .withErrorContaining(ProcessorErrors.duplicateDao(
+                        ClassName.get("foo.bar", "UserDao"), listOf("userDao", "userDao2")
+                ))
+    }
+
+    @Test
+    fun suppressedWarnings() {
+        singleDb(
+                """
+                @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
+                @Database(entities = {User.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract UserDao userDao();
+                }
+                """, USER, USER_DAO) {db, invocation ->
+            assertThat(DatabaseProcessor(invocation.context, db.element)
+                    .context.logger.suppressedWarnings, `is`(setOf(Warning.CURSOR_MISMATCH)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun duplicateIndexNames() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = {@Index(name ="index_name", value = {"name"})})
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    String name;
+                }
+                """)
+
+        val entity2 = JavaFileObjects.forSourceString("foo.bar.Entity2",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = {@Index(name ="index_name", value = {"anotherName"})})
+                public class Entity2 {
+                    @PrimaryKey
+                    int uid;
+                    String anotherName;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class, Entity2.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, entity2){ db, invocation ->
+
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.duplicateIndexInDatabase("index_name",
+                        listOf("foo.bar.Entity1 > index_name", "foo.bar.Entity2 > index_name"))
+        )
+    }
+
+    @Test
+    fun foreignKey_missingParent() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(foreignKeys = @ForeignKey(entity = ${COMMON.USER_TYPE_NAME}.class,
+                        parentColumns = "lastName",
+                        childColumns = "name"))
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    String name;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, COMMON.USER){ db, invocation ->
+
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.foreignKeyMissingParentEntityInDatabase("User", "foo.bar.Entity1")
+        )
+    }
+
+    @Test
+    fun foreignKey_missingParentIndex() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(foreignKeys = @ForeignKey(entity = ${COMMON.USER_TYPE_NAME}.class,
+                        parentColumns = "lastName",
+                        childColumns = "name"))
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    String name;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class, User.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, COMMON.USER){ db, invocation ->
+
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.foreignKeyMissingIndexInParent(
+                        parentEntity = COMMON.USER_TYPE_NAME.toString(),
+                        parentColumns = listOf("lastName"),
+                        childEntity = "foo.bar.Entity1",
+                        childColumns = listOf("name")
+                )
+        )
+    }
+
+    @Test
+    fun foreignKey_goodWithPrimaryKey() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(foreignKeys = @ForeignKey(entity = Entity2.class,
+                    parentColumns = "uid",
+                    childColumns = "parentId"))
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    int parentId;
+                    String name;
+                }
+                """)
+
+        val entity2 = JavaFileObjects.forSourceString("foo.bar.Entity2",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity
+                public class Entity2 {
+                    @PrimaryKey
+                    int uid;
+                    String anotherName;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class, Entity2.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, entity2){ db, invocation ->
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun foreignKey_missingParentColumn() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(foreignKeys = @ForeignKey(entity = Entity2.class,
+                    parentColumns = {"anotherName", "anotherName2"},
+                    childColumns = {"name", "name2"}))
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    String name;
+                    String name2;
+                }
+                """)
+
+        val entity2 = JavaFileObjects.forSourceString("foo.bar.Entity2",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity
+                public class Entity2 {
+                    @PrimaryKey
+                    int uid;
+                    String anotherName;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class, Entity2.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, entity2){ db, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.foreignKeyParentColumnDoesNotExist("foo.bar.Entity2",
+                        "anotherName2", listOf("uid", "anotherName"))
+        )
+    }
+
+    @Test
+    fun foreignKey_goodWithIndex() {
+        val entity1 = JavaFileObjects.forSourceString("foo.bar.Entity1",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(foreignKeys = @ForeignKey(entity = Entity2.class,
+                    parentColumns = {"anotherName", "anotherName2"},
+                    childColumns = {"name", "name2"}))
+                public class Entity1 {
+                    @PrimaryKey
+                    int uid;
+                    String name;
+                    String name2;
+                }
+                """)
+
+        val entity2 = JavaFileObjects.forSourceString("foo.bar.Entity2",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = @Index(value = {"anotherName2", "anotherName"}, unique = true))
+                public class Entity2 {
+                    @PrimaryKey
+                    int uid;
+                    String anotherName;
+                    String anotherName2;
+                }
+                """)
+        singleDb("""
+                @Database(entities = {Entity1.class, Entity2.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                }
+                """, entity1, entity2){ db, invocation ->
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertNotAReferencedEntity() {
+        singleDb("""
+                @Database(entities = {User.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    abstract BookDao bookDao();
+                }
+                """, USER, USER_DAO, BOOK, BOOK_DAO){ db, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.shortcutEntityIsNotInDatabase(
+                        database = "foo.bar.MyDb",
+                        dao = "foo.bar.BookDao",
+                        entity = "foo.bar.Book"
+                )
+        )
+    }
+
+    @Test
+    fun cache_entity() {
+        singleDb("""
+                @Database(entities = {User.class}, version = 42)
+                @SkipQueryVerification
+                public abstract class MyDb extends RoomDatabase {
+                    public abstract MyUserDao userDao();
+                    @Dao
+                    interface MyUserDao {
+                        @Insert
+                        public void insert(User... users);
+
+                        @Query("SELECT * FROM user where uid = :uid")
+                        public User loadOne(int uid);
+
+                        @TypeConverters(Converter.class)
+                        @Query("SELECT * FROM user where uid = :uid")
+                        public User loadWithConverter(int uid);
+                    }
+                    public static class Converter {
+                        @TypeConverter
+                        public static java.util.Date foo(Long input) {return null;}
+                    }
+                }
+                """, USER, USER_DAO){ db, invocation ->
+            val userDao = db.daoMethods.first().dao
+            val insertionMethod = userDao.insertionMethods.find { it.name == "insert" }
+            assertThat(insertionMethod, notNullValue())
+            val loadOne = userDao.queryMethods.find { it.name == "loadOne" }
+            assertThat(loadOne, notNullValue())
+            val adapter = loadOne?.queryResultBinder?.adapter?.rowAdapter
+            assertThat("test sanity", adapter, instanceOf(EntityRowAdapter::class.java))
+            val adapterEntity = (adapter as EntityRowAdapter).entity
+            assertThat(insertionMethod?.entities?.values?.first(), sameInstance(adapterEntity))
+
+            val withConverter = userDao.queryMethods.find { it.name == "loadWithConverter" }
+            assertThat(withConverter, notNullValue())
+            val convAdapter = withConverter?.queryResultBinder?.adapter?.rowAdapter
+            assertThat("test sanity", adapter, instanceOf(EntityRowAdapter::class.java))
+            val convAdapterEntity = (convAdapter as EntityRowAdapter).entity
+            assertThat(insertionMethod?.entities?.values?.first(),
+                    not(sameInstance(convAdapterEntity)))
+
+            assertThat(convAdapterEntity, notNullValue())
+            assertThat(adapterEntity, notNullValue())
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun cache_pojo() {
+        singleDb("""
+                @Database(entities = {User.class}, version = 42)
+                public abstract class MyDb extends RoomDatabase {
+                    public abstract UserDao userDao();
+                }
+                """, USER, USER_DAO){ db, invocation ->
+            val userDao = db.daoMethods.first().dao
+            val loadOne = userDao.queryMethods.find { it.name == "loadOnePojo" }
+            assertThat(loadOne, notNullValue())
+            val adapter = loadOne?.queryResultBinder?.adapter?.rowAdapter
+            assertThat("test sanity", adapter, instanceOf(PojoRowAdapter::class.java))
+            val adapterPojo = (adapter as PojoRowAdapter).pojo
+
+            val loadAll = userDao.queryMethods.find { it.name == "loadAllPojos" }
+            assertThat(loadAll, notNullValue())
+            val loadAllAdapter = loadAll?.queryResultBinder?.adapter?.rowAdapter
+            assertThat("test sanity", loadAllAdapter, instanceOf(PojoRowAdapter::class.java))
+            val loadAllPojo = (loadAllAdapter as PojoRowAdapter).pojo
+            assertThat(adapter, not(sameInstance(loadAllAdapter)))
+            assertThat(adapterPojo, sameInstance(loadAllPojo))
+
+            val withConverter = userDao.queryMethods.find { it.name == "loadPojoWithConverter" }
+            assertThat(withConverter, notNullValue())
+            val convAdapter = withConverter?.queryResultBinder?.adapter?.rowAdapter
+            assertThat("test sanity", adapter, instanceOf(PojoRowAdapter::class.java))
+            val convAdapterPojo = (convAdapter as PojoRowAdapter).pojo
+            assertThat(convAdapterPojo, notNullValue())
+            assertThat(convAdapterPojo, not(sameInstance(adapterPojo)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_RoomDatabase() {
+        assertConstructor(listOf(DB1), "BookDao(RoomDatabase db) {}")
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_specificDatabase() {
+        assertConstructor(listOf(DB1), "BookDao(Db1 db) {}")
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_wrongDatabase() {
+        assertConstructor(listOf(DB1, DB3), "BookDao(Db3 db) {}")
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors
+                        .daoMustHaveMatchingConstructor("foo.bar.BookDao", "foo.bar.Db1"))
+    }
+
+    @Test
+    fun daoConstructor_multipleDatabases_RoomDatabase() {
+        assertConstructor(listOf(DB1, DB2), "BookDao(RoomDatabase db) {}")
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_multipleDatabases_specificDatabases() {
+        assertConstructor(listOf(DB1, DB2), """
+                    BookDao(Db1 db) {}
+                    BookDao(Db2 db) {}
+                """)
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_multipleDatabases_empty() {
+        assertConstructor(listOf(DB1, DB2), """
+                    BookDao(Db1 db) {}
+                    BookDao() {} // Db2 uses this
+                """)
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun daoConstructor_multipleDatabases_noMatch() {
+        assertConstructor(listOf(DB1, DB2), """
+                    BookDao(Db1 db) {}
+                """)
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors
+                        .daoMustHaveMatchingConstructor("foo.bar.BookDao", "foo.bar.Db2"))
+    }
+
+    fun assertConstructor(dbs: List<JavaFileObject>, constructor: String): CompileTester {
+        val bookDao = JavaFileObjects.forSourceString("foo.bar.BookDao",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                public abstract class BookDao {
+                    $constructor
+                }
+                """)
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(BOOK, bookDao) + dbs)
+                .processedWith(RoomProcessor())
+    }
+
+    fun singleDb(input: String, vararg otherFiles: JavaFileObject,
+                 handler: (Database, TestInvocation) -> Unit): CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(otherFiles.toMutableList()
+                        + JavaFileObjects.forSourceString("foo.bar.MyDb",
+                        DATABASE_PREFIX + input
+                ))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Database::class)
+                        .nextRunHandler { invocation ->
+                            val entity = invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Database::class.java)
+                                    .first()
+                            val parser = DatabaseProcessor(invocation.context,
+                                    MoreElements.asType(entity))
+                            val parsedDb = parser.process()
+                            handler(parsedDb, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessorTest.kt
new file mode 100644
index 0000000..864ea9b
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/DeletionMethodProcessorTest.kt
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Delete
+import android.arch.persistence.room.processor.ProcessorErrors.DELETION_MISSING_PARAMS
+import android.arch.persistence.room.processor.ProcessorErrors
+        .DELETION_METHODS_MUST_RETURN_VOID_OR_INT
+import android.arch.persistence.room.vo.DeletionMethod
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+@RunWith(JUnit4::class)
+class DeletionMethodProcessorTest : ShortcutMethodProcessorTest<DeletionMethod>(Delete::class) {
+    override fun invalidReturnTypeError(): String = DELETION_METHODS_MUST_RETURN_VOID_OR_INT
+
+    override fun noParamsError(): String = DELETION_MISSING_PARAMS
+
+    override fun process(baseContext: Context, containing: DeclaredType,
+                         executableElement: ExecutableElement): DeletionMethod {
+        return DeletionMethodProcessor(baseContext, containing, executableElement).process()
+    }
+
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityNameMatchingVariationsTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityNameMatchingVariationsTest.kt
new file mode 100644
index 0000000..e6a2ff3
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityNameMatchingVariationsTest.kt
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.FieldGetter
+import android.arch.persistence.room.vo.FieldSetter
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import javax.lang.model.type.TypeKind.INT
+
+@RunWith(Parameterized::class)
+class EntityNameMatchingVariationsTest(triple: Triple<String, String, String>) :
+        BaseEntityParserTest() {
+    val fieldName = triple.first
+    val getterName = triple.second
+    val setterName = triple.third
+
+    companion object {
+        @JvmStatic
+        @Parameterized.Parameters(name = "{0}")
+        fun params() : List<Triple<String, String, String>> {
+            val result = arrayListOf<Triple<String, String, String>>()
+            arrayListOf("x", "_x", "mX").forEach { field ->
+                arrayListOf("getX", "x").forEach { getter ->
+                    arrayListOf("setX", "x").forEach { setter ->
+                        result.add(Triple(field, getter, setter))
+                    }
+                }
+            }
+            return result
+        }
+    }
+
+    @Test
+    fun testSuccessfulParamToMethodMatching() {
+        singleEntity("""
+                @PrimaryKey
+                private int $fieldName;
+                public int $getterName() { return $fieldName; }
+                public void $setterName(int id) { this.$fieldName = id; }
+            """) { entity, invocation ->
+            assertThat(entity.type.toString(), `is`("foo.bar.MyEntity"))
+            assertThat(entity.fields.size, `is`(1))
+            val field = entity.fields.first()
+            val intType = invocation.processingEnv.typeUtils.getPrimitiveType(INT)
+            assertThat(field, `is`(Field(
+                    element = field.element,
+                    name = fieldName,
+                    type = intType,
+                    columnName = fieldName,
+                    affinity = SQLTypeAffinity.INTEGER)))
+            assertThat(field.setter, `is`(FieldSetter(setterName, intType, CallType.METHOD)))
+            assertThat(field.getter, `is`(FieldGetter(getterName, intType, CallType.METHOD)))
+        }.compilesWithoutError()
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityProcessorTest.kt
new file mode 100644
index 0000000..34c522e
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/EntityProcessorTest.kt
@@ -0,0 +1,1472 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.ProcessorErrors.RELATION_IN_ENTITY
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.FieldGetter
+import android.arch.persistence.room.vo.FieldSetter
+import android.arch.persistence.room.vo.Index
+import android.arch.persistence.room.vo.Pojo
+import com.google.testing.compile.JavaFileObjects
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.lang.model.type.TypeKind.INT
+
+@RunWith(JUnit4::class)
+class EntityProcessorTest : BaseEntityParserTest() {
+    @Test
+    fun simple() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public int getId() { return id; }
+                public void setId(int id) { this.id = id; }
+            """) { entity, invocation ->
+            assertThat(entity.type.toString(), `is`("foo.bar.MyEntity"))
+            assertThat(entity.fields.size, `is`(1))
+            val field = entity.fields.first()
+            val intType = invocation.processingEnv.typeUtils.getPrimitiveType(INT)
+            assertThat(field, `is`(Field(
+                    element = field.element,
+                    name = "id",
+                    type = intType,
+                    columnName = "id",
+                    affinity = SQLTypeAffinity.INTEGER)))
+            assertThat(field.setter, `is`(FieldSetter("setId", intType, CallType.METHOD)))
+            assertThat(field.getter, `is`(FieldGetter("getId", intType, CallType.METHOD)))
+            assertThat(entity.primaryKey.fields, `is`(listOf(field)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun noGetter() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {this.id = id;}
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_FIND_GETTER_FOR_FIELD)
+    }
+
+    @Test
+    fun getterWithBadType() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public float getId() {return 0f;}
+                public void setId(int id) {this.id = id;}
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_FIND_GETTER_FOR_FIELD)
+    }
+
+    @Test
+    fun setterWithBadType() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public int getId() {return id;}
+                public void setId(float id) {}
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_FIND_SETTER_FOR_FIELD)
+    }
+
+    @Test
+    fun setterWithAssignableType() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public int getId() {return id;}
+                public void setId(Integer id) {}
+                """) { entity, invocation -> }
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun getterWithAssignableType() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public Integer getId() {return id;}
+                public void setId(int id) {}
+                """) { entity, invocation -> }
+                .compilesWithoutError()
+    }
+
+    @Test
+    fun noSetter() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public int getId(){ return id; }
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_FIND_SETTER_FOR_FIELD)
+    }
+
+    @Test
+    fun tooManyGetters() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                public int id(){ return id; }
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining("getId, id")
+    }
+
+    @Test
+    fun tooManyGettersWithIgnore() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                @Ignore public int id(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().getter.name, `is`("getId"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun tooManyGettersWithDifferentVisibility() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                protected int id(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().getter.name, `is`("getId"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun tooManyGettersWithDifferentTypes() {
+        singleEntity("""
+                @PrimaryKey
+                public int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().getter.name, `is`("id"))
+            assertThat(entity.fields.first().getter.callType, `is`(CallType.FIELD))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun tooManySetters() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                public void id(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation -> }
+                .failsToCompile()
+                .withErrorContaining("setId, id")
+    }
+
+    @Test
+    fun tooManySettersWithIgnore() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                @Ignore public void id(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().setter.name, `is`("setId"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun tooManySettersWithDifferentVisibility() {
+        singleEntity("""
+                @PrimaryKey
+                private int id;
+                public void setId(int id) {}
+                protected void id(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().setter.name, `is`("setId"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun tooManySettersWithDifferentTypes() {
+        singleEntity("""
+                @PrimaryKey
+                public int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().setter.name, `is`("id"))
+            assertThat(entity.fields.first().setter.callType, `is`(CallType.FIELD))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun preferPublicOverProtected() {
+        singleEntity("""
+                @PrimaryKey
+                int id;
+                public void setId(int id) {}
+                public int getId(){ return id; }
+                """) { entity, invocation ->
+            assertThat(entity.fields.first().setter.name, `is`("setId"))
+            assertThat(entity.fields.first().getter.name, `is`("getId"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun customName() {
+        singleEntity("""
+                @PrimaryKey
+                int x;
+                """, hashMapOf(Pair("tableName", "\"foo_table\""))) { entity, invocation ->
+            assertThat(entity.tableName, `is`("foo_table"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun emptyCustomName() {
+        singleEntity("""
+                @PrimaryKey
+                int x;
+                """, hashMapOf(Pair("tableName", "\" \""))) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.ENTITY_TABLE_NAME_CANNOT_BE_EMPTY)
+    }
+
+    @Test
+    fun missingPrimaryKey() {
+        singleEntity("""
+                """) { entity, invocation ->
+        }.failsToCompile()
+                .withErrorContaining(ProcessorErrors.MISSING_PRIMARY_KEY)
+    }
+
+    @Test
+    fun missingColumnAdapter() {
+        singleEntity("""
+                @PrimaryKey
+                public java.util.Date myDate;
+                """) { entity, invocation ->
+
+        }.failsToCompile().withErrorContaining(ProcessorErrors.CANNOT_FIND_COLUMN_TYPE_ADAPTER)
+    }
+
+    @Test
+    fun dropSubPrimaryKey() {
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                @Embedded
+                Point myPoint;
+                static class Point {
+                    @PrimaryKey
+                    int x;
+                    int y;
+                }
+                """
+        ) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.name }, `is`(listOf("id")))
+        }.compilesWithoutError()
+                .withWarningCount(1)
+                .withWarningContaining(ProcessorErrors.embeddedPrimaryKeyIsDropped(
+                        "foo.bar.MyEntity", "x"))
+    }
+
+    @Test
+    fun ignoreDropSubPrimaryKey() {
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                @Embedded
+                @SuppressWarnings(RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED)
+                Point myPoint;
+                static class Point {
+                    @PrimaryKey
+                    int x;
+                    int y;
+                }
+                """
+        ) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.name }, `is`(listOf("id")))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun notNull() {
+        singleEntity(
+                """
+                @PrimaryKey int id;
+                @NonNull public String name;
+                """
+        ) { entity, _ ->
+            val field = fieldsByName(entity, "name").first()
+            assertThat(field.name, `is`("name"))
+            assertThat(field.columnName, `is`("name"))
+            assertThat(field.nonNull, `is`(true))
+        }.compilesWithoutError()
+    }
+
+    private fun fieldsByName(entity : Pojo, vararg fieldNames : String) : List<Field> {
+        return fieldNames
+                .map { name -> entity.fields.find { it.name == name } }
+                .filterNotNull()
+    }
+
+    @Test
+    fun index_simple() {
+        val annotation = mapOf(
+                "indices" to """@Index("foo")"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyEntity_foo",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo")))))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_fromField() {
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @ColumnInfo(index = true)
+                public String foo;
+                """) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyEntity_foo",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_multiColumn() {
+        val annotation = mapOf(
+                "indices" to """@Index({"foo", "id"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyEntity_foo_id",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo", "id")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_multiple() {
+        val annotation = mapOf(
+                "indices" to """{@Index({"foo", "id"}), @Index({"bar_column", "foo"})}"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                @ColumnInfo(name = "bar_column")
+                public String bar;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyEntity_foo_id",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo", "id")),
+                            Index(name = "index_MyEntity_bar_column_foo",
+                                    unique = false,
+                                    fields = fieldsByName(entity, "bar", "foo")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_unique() {
+        val annotation = mapOf(
+                "indices" to """@Index(value = {"foo", "id"}, unique = true)"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyEntity_foo_id",
+                            unique = true,
+                           fields = fieldsByName(entity, "foo", "id")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_customName() {
+        val annotation = mapOf(
+                "indices" to """@Index(value = {"foo"}, name = "myName")"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "myName",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_customTableName() {
+        val annotation = mapOf(
+                "tableName" to "\"MyTable\"",
+                "indices" to """@Index(value = {"foo"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+            assertThat(entity.indices, `is`(
+                    listOf(Index(name = "index_MyTable_foo",
+                            unique = false,
+                            fields = fieldsByName(entity, "foo")))
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun index_empty() {
+        val annotation = mapOf(
+                "indices" to """@Index({})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.INDEX_COLUMNS_CANNOT_BE_EMPTY
+        )
+    }
+
+    @Test
+    fun index_missingColumn() {
+        val annotation = mapOf(
+                "indices" to """@Index({"foo", "bar"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.indexColumnDoesNotExist("bar", listOf("id, foo"))
+        )
+    }
+
+    @Test
+    fun index_nameConflict() {
+        val annotation = mapOf(
+                "indices" to """@Index({"foo"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @ColumnInfo(index = true)
+                public String foo;
+                """
+                , annotation) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.duplicateIndexInEntity("index_MyEntity_foo")
+        )
+    }
+
+    @Test
+    fun index_droppedParentFieldIndex() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    @ColumnInfo(index = true)
+                    String name;
+                    String lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """, baseClass = "foo.bar.Base", jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.compilesWithoutError()
+                .withWarningContaining(
+                        ProcessorErrors.droppedSuperClassFieldIndex(
+                                fieldName = "name",
+                                childEntity = "foo.bar.MyEntity",
+                                superEntity = "foo.bar.Base")
+                )
+    }
+
+    @Test
+    fun index_keptGrandParentEntityIndex() {
+        val grandParent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = @Index({"name", "lastName"}))
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Parent",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+
+                public class Parent extends Base {
+                    String iHaveAField;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Parent",
+                attributes = hashMapOf("inheritSuperIndices" to "true"),
+                jfos = listOf(parent, grandParent)) {
+            entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+            assertThat(entity.indices.first(),
+                    `is`(Index(name = "index_MyEntity_name_lastName",
+                            unique = false,
+                            fields = fieldsByName(entity, "name", "lastName"))))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun index_keptParentEntityIndex() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = @Index({"name", "lastName"}))
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                attributes = hashMapOf("inheritSuperIndices" to "true"),
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+            assertThat(entity.indices.first(),
+                    `is`(Index(name = "index_MyEntity_name_lastName",
+                            unique = false,
+                            fields = fieldsByName(entity, "name", "lastName"))))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun index_keptParentFieldIndex() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    @ColumnInfo(index = true)
+                    String name;
+                    String lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                attributes = hashMapOf("inheritSuperIndices" to "true"),
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+            assertThat(entity.indices.first(),
+                    `is`(Index(name = "index_MyEntity_name",
+                            unique = false,
+                            fields = fieldsByName(entity, "name"))))
+        }.compilesWithoutError().withWarningCount(0)
+
+    }
+
+    @Test
+    fun index_droppedGrandParentEntityIndex() {
+        val grandParent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = @Index({"name", "lastName"}))
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Parent",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+
+                public class Parent extends Base {
+                    String iHaveAField;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """, baseClass = "foo.bar.Parent", jfos = listOf(parent, grandParent)) {
+            entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.compilesWithoutError()
+                .withWarningContaining(
+                        ProcessorErrors.droppedSuperClassIndex(
+                                childEntity = "foo.bar.MyEntity",
+                                superEntity = "foo.bar.Base")
+                )
+    }
+
+    @Test
+    fun index_droppedParentEntityIndex() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(indices = @Index({"name", "lastName"}))
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """, baseClass = "foo.bar.Base", jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.compilesWithoutError()
+                .withWarningContaining(
+                        ProcessorErrors.droppedSuperClassIndex(
+                                childEntity = "foo.bar.MyEntity",
+                                superEntity = "foo.bar.Base")
+                )
+    }
+
+    @Test
+    fun index_droppedEmbeddedEntityIndex() {
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @Embedded
+                public Foo foo;
+                @Entity(indices = {@Index("a")})
+                static class Foo {
+                    @PrimaryKey
+                    @ColumnInfo(name = "foo_id")
+                    int id;
+                    @ColumnInfo(index = true)
+                    public int a;
+                }
+                """) { entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.compilesWithoutError()
+                .withWarningContaining(
+                        ProcessorErrors.droppedEmbeddedIndex(
+                                entityName = "foo.bar.MyEntity.Foo",
+                                fieldPath = "foo",
+                                grandParent = "foo.bar.MyEntity")
+                )
+    }
+
+    @Test
+    fun index_onEmbeddedField() {
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @Embedded
+                @ColumnInfo(index = true)
+                public Foo foo;
+                static class Foo {
+                    @ColumnInfo(index = true)
+                    public int a;
+                }
+                """) { entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION
+        )
+    }
+
+    @Test
+    fun index_droppedEmbeddedFieldIndex() {
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @Embedded
+                public Foo foo;
+                static class Foo {
+                    @ColumnInfo(index = true)
+                    public int a;
+                }
+                """) { entity, invocation ->
+            assertThat(entity.indices.isEmpty(), `is`(true))
+        }.compilesWithoutError()
+                .withWarningContaining(
+                        ProcessorErrors.droppedEmbeddedFieldIndex("foo > a", "foo.bar.MyEntity")
+                )
+    }
+
+    @Test
+    fun index_referenceEmbeddedField() {
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                @Embedded
+                public Foo foo;
+                static class Foo {
+                    public int a;
+                }
+                """, attributes = mapOf("indices" to "@Index(\"a\")")) { entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+            assertThat(entity.indices.first(), `is`(
+                    Index(
+                            name = "index_MyEntity_a",
+                            unique = false,
+                            fields = fieldsByName(entity, "a")
+                    )
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun primaryKey_definedInBothWays() {
+        singleEntity(
+                """
+                public int id;
+                @PrimaryKey
+                public String foo;
+                """,
+                attributes = mapOf("primaryKeys" to "\"id\"")) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.multiplePrimaryKeyAnnotations(
+                        listOf("PrimaryKey[id]", "PrimaryKey[foo]")
+                ))
+    }
+
+    @Test
+    fun primaryKey_badColumnName() {
+        singleEntity(
+                """
+                public int id;
+                """,
+                attributes = mapOf("primaryKeys" to "\"foo\"")) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.primaryKeyColumnDoesNotExist("foo", listOf("id")))
+    }
+
+    @Test
+    fun primaryKey_multipleAnnotations() {
+        singleEntity("""
+                @PrimaryKey
+                int x;
+                @PrimaryKey
+                int y;
+                """) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.isEmpty(), `is`(true))
+        }.failsToCompile()
+                .withErrorContaining(
+                        ProcessorErrors.multiplePrimaryKeyAnnotations(
+                                listOf("PrimaryKey[x]", "PrimaryKey[y]")))
+    }
+
+    @Test
+    fun primaryKey_fromParentField() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("baseId"))
+
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun primaryKey_fromParentEntity() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(primaryKeys = "baseId")
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("baseId"))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun primaryKey_overrideFromParentField() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class Base {
+                    @PrimaryKey
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.size, `is`(1))
+            assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("id"))
+            assertThat(entity.primaryKey.autoGenerateId, `is`(false))
+        }.compilesWithoutError().withNoteContaining(
+                "PrimaryKey[baseId] is overridden by PrimaryKey[id]"
+        )
+    }
+
+    @Test
+    fun primaryKey_overrideFromParentEntityViaField() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(primaryKeys = "baseId")
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.size, `is`(1))
+            assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("id"))
+        }.compilesWithoutError().withNoteContaining(
+                "PrimaryKey[baseId] is overridden by PrimaryKey[id]"
+        )
+    }
+
+    @Test
+    fun primaryKey_overrideFromParentEntityViaEntity() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity(primaryKeys = "baseId")
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent),
+                attributes = mapOf("primaryKeys" to "\"id\"")) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.size, `is`(1))
+            assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("id"))
+            assertThat(entity.primaryKey.autoGenerateId, `is`(false))
+        }.compilesWithoutError().withNoteContaining(
+                "PrimaryKey[baseId] is overridden by PrimaryKey[id]"
+        )
+    }
+
+    @Test
+    fun primaryKey_autoGenerate() {
+        listOf("long", "Long", "Integer", "int").forEach { type ->
+            singleEntity(
+                    """
+                @PrimaryKey(autoGenerate = true)
+                public $type id;
+                """) { entity, invocation ->
+                assertThat(entity.primaryKey.fields.size, `is`(1))
+                assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("id"))
+                assertThat(entity.primaryKey.autoGenerateId, `is`(true))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun primaryKey_autoGenerateBadType() {
+        listOf("String", "float", "Float", "Double", "double").forEach { type ->
+            singleEntity(
+                    """
+                @PrimaryKey(autoGenerate = true)
+                public $type id;
+                """) { entity, invocation ->
+                assertThat(entity.primaryKey.fields.size, `is`(1))
+                assertThat(entity.primaryKey.fields.firstOrNull()?.name, `is`("id"))
+                assertThat(entity.primaryKey.autoGenerateId, `is`(true))
+            }.failsToCompile().withErrorContaining(
+                    ProcessorErrors.AUTO_INCREMENTED_PRIMARY_KEY_IS_NOT_INT)
+        }
+    }
+
+    @Test
+    fun primaryKey_embedded(){
+        singleEntity(
+                """
+                public int id;
+
+                @Embedded(prefix = "bar_")
+                @PrimaryKey
+                public Foo foo;
+
+                static class Foo {
+                    public int a;
+                    public int b;
+                }
+                """) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.columnName },
+                    `is`(listOf("bar_a", "bar_b")))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun primaryKey_embeddedInherited(){
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                    @Embedded(prefix = "bar_")
+                    @PrimaryKey
+                    public Foo foo;
+
+                    static class Foo {
+                        public int a;
+                        public int b;
+                    }
+                }
+                """)
+        singleEntity(
+                """
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.columnName },
+                    `is`(listOf("bar_a", "bar_b")))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun primaryKey_overrideViaEmbedded() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+
+                @Entity(primaryKeys = "baseId")
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                }
+                """)
+        singleEntity(
+                """
+                public int id;
+                @Embedded(prefix = "bar_")
+                @PrimaryKey
+                public Foo foo;
+
+                static class Foo {
+                    public int a;
+                    public int b;
+                }
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.columnName },
+                    `is`(listOf("bar_a", "bar_b")))
+        }.compilesWithoutError().withNoteContaining(
+                "PrimaryKey[baseId] is overridden by PrimaryKey[foo > a, foo > b]")
+    }
+
+    @Test
+    fun primaryKey_overrideEmbedded() {
+        val parent = JavaFileObjects.forSourceLines("foo.bar.Base",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+
+                public class Base {
+                    long baseId;
+                    String name, lastName;
+                    @Embedded(prefix = "bar_")
+                    @PrimaryKey
+                    public Foo foo;
+
+                    static class Foo {
+                        public int a;
+                        public int b;
+                    }
+                }
+                """)
+        singleEntity(
+                """
+                @PrimaryKey
+                public int id;
+                """,
+                baseClass = "foo.bar.Base",
+                jfos = listOf(parent)) { entity, invocation ->
+            assertThat(entity.primaryKey.fields.map { it.columnName },
+                    `is`(listOf("id")))
+        }.compilesWithoutError().withNoteContaining(
+                "PrimaryKey[foo > a, foo > b] is overridden by PrimaryKey[id]")
+    }
+
+    @Test
+    fun relationInEntity() {
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                java.util.List<User> users;
+                """, jfos = listOf(COMMON.USER)
+        ) { entity, invocation ->
+        }.failsToCompile().withErrorContaining(RELATION_IN_ENTITY)
+    }
+
+    @Test
+    fun foreignKey_invalidAction() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "name",
+                    onDelete = 101
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.INVALID_FOREIGN_KEY_ACTION)
+    }
+
+    @Test
+    fun foreignKey_badEntity() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = dsa.class,
+                    parentColumns = "lastName",
+                    childColumns = "name"
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining("cannot find symbol")
+    }
+
+    @Test
+    fun foreignKey_notAnEntity() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.NOT_AN_ENTITY_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "name"
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.NOT_AN_ENTITY)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.foreignKeyNotAnEntity(
+                COMMON.NOT_AN_ENTITY_TYPE_NAME.toString()))
+    }
+
+    @Test
+    fun foreignKey_invalidChildColumn() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "namex"
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.foreignKeyChildColumnDoesNotExist(
+                "namex", listOf("id", "name")))
+    }
+
+    @Test
+    fun foreignKey_columnCountMismatch() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = {"name", "id"}
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.foreignKeyColumnNumberMismatch(
+                listOf("name", "id"), listOf("lastName")))
+    }
+
+    @Test
+    fun foreignKey_emptyChildColumns() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = {}
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.FOREIGN_KEY_EMPTY_CHILD_COLUMN_LIST)
+    }
+
+    @Test
+    fun foreignKey_emptyParentColumns() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = {},
+                    childColumns = {"name"}
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.FOREIGN_KEY_EMPTY_PARENT_COLUMN_LIST)
+    }
+
+    @Test
+    fun foreignKey_simple() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "name",
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+            assertThat(entity.foreignKeys.size, `is`(1))
+            val fKey = entity.foreignKeys.first()
+            assertThat(fKey.parentTable, `is`("User"))
+            assertThat(fKey.parentColumns, `is`(listOf("lastName")))
+            assertThat(fKey.deferred, `is`(true))
+            assertThat(fKey.childFields.size, `is`(1))
+            val field = fKey.childFields.first()
+            assertThat(field.name, `is`("name"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun foreignKey_dontDuplicationChildIndex_SingleColumn() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "name",
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent(),
+                "indices" to """@Index("name")"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ) { entity, invocation ->
+        }.compilesWithoutWarnings()
+    }
+
+    @Test
+    fun foreignKey_dontDuplicationChildIndex_MultipleColumns() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = {"lastName", "name"},
+                    childColumns = {"lName", "name"},
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent(),
+                "indices" to """@Index({"lName", "name"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                String lName;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ) { entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+        }.compilesWithoutWarnings()
+    }
+
+    @Test
+    fun foreignKey_dontDuplicationChildIndex_WhenCovered() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = {"lastName"},
+                    childColumns = {"name"},
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent(),
+                "indices" to """@Index({"name", "lName"})"""
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                String lName;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ) { entity, invocation ->
+            assertThat(entity.indices.size, `is`(1))
+        }.compilesWithoutWarnings()
+    }
+
+    @Test
+    fun foreignKey_warnMissingChildIndex() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "name",
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+            assertThat(entity.indices, `is`(emptyList()))
+        }.compilesWithoutError().withWarningContaining(
+                ProcessorErrors.foreignKeyMissingIndexInChildColumn("name"))
+    }
+
+    @Test
+    fun foreignKey_warnMissingChildrenIndex() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = {"lastName", "name"},
+                    childColumns = {"lName", "name"}
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                String lName;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+            assertThat(entity.indices, `is`(emptyList()))
+        }.compilesWithoutError().withWarningContaining(
+                ProcessorErrors.foreignKeyMissingIndexInChildColumns(listOf("lName", "name")))
+    }
+
+    @Test
+    fun foreignKey_dontIndexIfAlreadyPrimaryKey() {
+        val annotation = mapOf(
+                "foreignKeys" to """{@ForeignKey(
+                    entity = ${COMMON.USER_TYPE_NAME}.class,
+                    parentColumns = "lastName",
+                    childColumns = "id",
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE,
+                    deferred = true
+                )}""".trimIndent()
+        )
+        singleEntity(
+                """
+                @PrimaryKey
+                int id;
+                String name;
+                """,
+                attributes = annotation, jfos = listOf(COMMON.USER)
+        ){ entity, invocation ->
+            assertThat(entity.indices, `is`(emptyList()))
+        }.compilesWithoutWarnings()
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/FieldProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/FieldProcessorTest.kt
new file mode 100644
index 0000000..fb64c7c
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/FieldProcessorTest.kt
@@ -0,0 +1,364 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.solver.types.ColumnTypeAdapter
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Field
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.mockito.Mockito.mock
+import simpleRun
+import javax.lang.model.element.Element
+import javax.lang.model.element.ElementKind
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+@Suppress("HasPlatformType")
+@RunWith(JUnit4::class)
+class FieldProcessorTest {
+    companion object {
+        const val ENTITY_PREFIX = """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Entity
+                abstract class MyEntity {
+                """
+        const val ENTITY_SUFFIX = "}"
+        val ALL_PRIMITIVES = arrayListOf(
+                TypeKind.INT,
+                TypeKind.BYTE,
+                TypeKind.SHORT,
+                TypeKind.LONG,
+                TypeKind.CHAR,
+                TypeKind.FLOAT,
+                TypeKind.DOUBLE)
+        val ARRAY_CONVERTER = JavaFileObjects.forSourceLines("foo.bar.MyConverter",
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class MyConverter {
+                ${ALL_PRIMITIVES.joinToString("\n") {
+                    val arrayDef = "${it.name.toLowerCase()}[]"
+                    "@TypeConverter public static String" +
+                            " arrayIntoString($arrayDef input) { return null;}" +
+                            "@TypeConverter public static $arrayDef" +
+                            " stringIntoArray${it.name}(String input) { return null;}"
+                }}
+                ${ALL_PRIMITIVES.joinToString("\n") {
+                    val arrayDef = "${it.box()}[]"
+                    "@TypeConverter public static String" +
+                            " arrayIntoString($arrayDef input) { return null;}" +
+                            "@TypeConverter public static $arrayDef" +
+                            " stringIntoArray${it.name}Boxed(String input) { return null;}"
+                }}
+                }
+                """)
+
+        private fun TypeKind.box(): String {
+            return "java.lang." + when (this) {
+                TypeKind.INT -> "Integer"
+                TypeKind.CHAR -> "Character"
+                else -> this.name.toLowerCase().capitalize()
+            }
+        }
+
+        // these 2 box methods are ugly but makes tests nicer and they are private
+        private fun TypeKind.typeMirror(invocation: TestInvocation): TypeMirror {
+            return invocation.processingEnv.typeUtils.getPrimitiveType(this)
+        }
+
+        private fun TypeKind.affinity(): SQLTypeAffinity {
+            return when (this) {
+                TypeKind.FLOAT, TypeKind.DOUBLE -> SQLTypeAffinity.REAL
+                else -> SQLTypeAffinity.INTEGER
+            }
+        }
+
+        private fun TypeKind.box(invocation: TestInvocation): TypeMirror {
+            return invocation.processingEnv.elementUtils.getTypeElement(box()).asType()
+        }
+    }
+
+    @Test
+    fun primitives() {
+        ALL_PRIMITIVES.forEach { primitive ->
+            singleEntity("${primitive.name.toLowerCase()} x;") { field, invocation ->
+                assertThat(field, `is`(
+                        Field(name = "x",
+                                type = primitive.typeMirror(invocation),
+                                element = field.element,
+                                affinity = primitive.affinity()
+                        )))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun boxed() {
+        ALL_PRIMITIVES.forEach { primitive ->
+            singleEntity("${primitive.box()} y;") { field, invocation ->
+                assertThat(field, `is`(
+                        Field(name = "y",
+                                type = primitive.box(invocation),
+                                element = field.element,
+                                affinity = primitive.affinity())))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun columnName() {
+        singleEntity("""
+            @ColumnInfo(name = "foo")
+            @PrimaryKey
+            int x;
+            """) { field, invocation ->
+            assertThat(field, `is`(
+                    Field(name = "x",
+                            type = TypeKind.INT.typeMirror(invocation),
+                            element = field.element,
+                            columnName = "foo",
+                            affinity = SQLTypeAffinity.INTEGER)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun indexed() {
+        singleEntity("""
+            @ColumnInfo(name = "foo", index = true)
+            int x;
+            """) { field, invocation ->
+            assertThat(field, `is`(
+                    Field(name = "x",
+                            type = TypeKind.INT.typeMirror(invocation),
+                            element = field.element,
+                            columnName = "foo",
+                            affinity = SQLTypeAffinity.INTEGER,
+                            indexed = true)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun emptyColumnName() {
+        singleEntity("""
+            @ColumnInfo(name = "")
+            int x;
+            """) { field, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.COLUMN_NAME_CANNOT_BE_EMPTY)
+    }
+
+    @Test
+    fun byteArrayWithEnforcedType() {
+        singleEntity("@TypeConverters(foo.bar.MyConverter.class)" +
+                "@ColumnInfo(typeAffinity = ColumnInfo.TEXT) byte[] arr;") { field, invocation ->
+            assertThat(field, `is`(Field(name = "arr",
+                    type = invocation.processingEnv.typeUtils.getArrayType(
+                            TypeKind.BYTE.typeMirror(invocation)),
+                    element = field.element,
+                    affinity = SQLTypeAffinity.TEXT)))
+            assertThat((field.cursorValueReader as? ColumnTypeAdapter)?.typeAffinity,
+                    `is`(SQLTypeAffinity.TEXT))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun primitiveArray() {
+        ALL_PRIMITIVES.forEach { primitive ->
+            singleEntity("@TypeConverters(foo.bar.MyConverter.class) " +
+                    "${primitive.toString().toLowerCase()}[] arr;") { field, invocation ->
+                assertThat(field, `is`(
+                        Field(name = "arr",
+                                type = invocation.processingEnv.typeUtils.getArrayType(
+                                        primitive.typeMirror(invocation)),
+                                element = field.element,
+                                affinity = if (primitive == TypeKind.BYTE) {
+                                    SQLTypeAffinity.BLOB
+                                } else {
+                                    SQLTypeAffinity.TEXT
+                                })))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun boxedArray() {
+        ALL_PRIMITIVES.forEach { primitive ->
+            singleEntity("@TypeConverters(foo.bar.MyConverter.class) " +
+                    "${primitive.box()}[] arr;") { field, invocation ->
+                assertThat(field, `is`(
+                        Field(name = "arr",
+                                type = invocation.processingEnv.typeUtils.getArrayType(
+                                        primitive.box(invocation)),
+                                element = field.element,
+                                affinity = SQLTypeAffinity.TEXT)))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun generic() {
+        singleEntity("""
+                static class BaseClass<T> {
+                    T item;
+                }
+                @Entity
+                static class Extending extends BaseClass<java.lang.Integer> {
+                }
+                """) { field, invocation ->
+            assertThat(field, `is`(Field(name = "item",
+                    type = TypeKind.INT.box(invocation),
+                    element = field.element,
+                    affinity = SQLTypeAffinity.INTEGER)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun unboundGeneric() {
+        singleEntity("""
+                @Entity
+                static class BaseClass<T> {
+                    T item;
+                }
+                """) { field, invocation -> }.failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS)
+    }
+
+    @Test
+    fun nameVariations() {
+        simpleRun {
+            assertThat(Field(mock(Element::class.java), "x", TypeKind.INT.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("x")))
+            assertThat(Field(mock(Element::class.java), "x", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("x")))
+            assertThat(Field(mock(Element::class.java), "xAll",
+                    TypeKind.BOOLEAN.typeMirror(it), SQLTypeAffinity.INTEGER)
+                    .nameWithVariations, `is`(arrayListOf("xAll")))
+        }
+    }
+
+    @Test
+    fun nameVariations_is() {
+        val elm = mock(Element::class.java)
+        simpleRun {
+            assertThat(Field(elm, "isX", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("isX", "x")))
+            assertThat(Field(elm, "isX", TypeKind.INT.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("isX")))
+            assertThat(Field(elm, "is", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("is")))
+            assertThat(Field(elm, "isAllItems", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations,
+                    `is`(arrayListOf("isAllItems", "allItems")))
+        }
+    }
+
+    @Test
+    fun nameVariations_has() {
+        val elm = mock(Element::class.java)
+        simpleRun {
+            assertThat(Field(elm, "hasX", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("hasX", "x")))
+            assertThat(Field(elm, "hasX", TypeKind.INT.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("hasX")))
+            assertThat(Field(elm, "has", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("has")))
+            assertThat(Field(elm, "hasAllItems", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations,
+                    `is`(arrayListOf("hasAllItems", "allItems")))
+        }
+    }
+
+    @Test
+    fun nameVariations_m() {
+        val elm = mock(Element::class.java)
+        simpleRun {
+            assertThat(Field(elm, "mall", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mall")))
+            assertThat(Field(elm, "mallVars", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mallVars")))
+            assertThat(Field(elm, "mAll", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("mAll", "all")))
+            assertThat(Field(elm, "m", TypeKind.INT.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("m")))
+            assertThat(Field(elm, "mallItems", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations,
+                    `is`(arrayListOf("mallItems")))
+            assertThat(Field(elm, "mAllItems", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations,
+                    `is`(arrayListOf("mAllItems", "allItems")))
+        }
+    }
+
+    @Test
+    fun nameVariations_underscore() {
+        val elm = mock(Element::class.java)
+        simpleRun {
+            assertThat(Field(elm, "_all", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("_all", "all")))
+            assertThat(Field(elm, "_", TypeKind.INT.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations, `is`(arrayListOf("_")))
+            assertThat(Field(elm, "_allItems", TypeKind.BOOLEAN.typeMirror(it),
+                    SQLTypeAffinity.INTEGER).nameWithVariations,
+                    `is`(arrayListOf("_allItems", "allItems")))
+        }
+    }
+
+    fun singleEntity(vararg input: String, handler: (Field, invocation: TestInvocation) -> Unit):
+            CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyEntity",
+                        ENTITY_PREFIX + input.joinToString("\n") + ENTITY_SUFFIX
+                ), ARRAY_CONVERTER))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Entity::class)
+                        .nextRunHandler { invocation ->
+                            val (owner, field) = invocation.roundEnv
+                                    .getElementsAnnotatedWith(Entity::class.java)
+                                    .map {
+                                        Pair(it, invocation.processingEnv.elementUtils
+                                                .getAllMembers(MoreElements.asType(it))
+                                                .firstOrNull { it.kind == ElementKind.FIELD })
+                                    }
+                                    .first { it.second != null }
+                            val entityContext =
+                                    EntityProcessor(invocation.context, MoreElements.asType(owner))
+                                            .context
+                            val parser = FieldProcessor(
+                                    baseContext = entityContext,
+                                    containing = MoreTypes.asDeclared(owner.asType()),
+                                    element = field!!,
+                                    bindingScope = FieldProcessor.BindingScope.TWO_WAY,
+                                    fieldParent = null)
+                            handler(parser.process(), invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessorTest.kt
new file mode 100644
index 0000000..aff6346
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/InsertionMethodProcessorTest.kt
@@ -0,0 +1,422 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.OnConflictStrategy
+import android.arch.persistence.room.ext.CommonTypeNames
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.InsertionMethod
+import android.arch.persistence.room.vo.InsertionMethod.Type
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth.assertAbout
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.nullValue
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+@RunWith(JUnit4::class)
+class InsertionMethodProcessorTest {
+    companion object {
+        const val DAO_PREFIX = """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                import java.util.*;
+                @Dao
+                abstract class MyClass {
+                """
+        const val DAO_SUFFIX = "}"
+        val USER_TYPE_NAME : TypeName = COMMON.USER_TYPE_NAME
+        val BOOK_TYPE_NAME : TypeName = ClassName.get("foo.bar", "Book")
+    }
+
+    @Test
+    fun readNoParams() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void foo();
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("foo"))
+            assertThat(insertion.parameters.size, `is`(0))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+            assertThat(insertion.entities.size, `is`(0))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT)
+    }
+
+    @Test
+    fun insertSingle() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public long foo(User user);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("foo"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(param.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(insertion.entities["user"]?.typeName,
+                    `is`(ClassName.get("foo.bar", "User") as TypeName))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.LONG))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertNotAnEntity() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void foo(NotAnEntity notValid);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("foo"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.entityType, `is`(nullValue()))
+            assertThat(insertion.entities.size, `is`(0))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER
+        )
+    }
+
+    @Test
+    fun insertTwo() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void foo(User u1, User u2);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("foo"))
+
+            assertThat(insertion.parameters.size, `is`(2))
+            insertion.parameters.forEach {
+                assertThat(it.type.typeName(), `is`(USER_TYPE_NAME))
+                assertThat(it.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            }
+            assertThat(insertion.entities.size, `is`(2))
+            assertThat(insertion.entities["u1"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.entities["u2"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.parameters.map { it.name }, `is`(listOf("u1", "u2")))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertList() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public List<Long> insertUsers(List<User> users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insertUsers"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(
+                            ClassName.get("java.util", "List"), USER_TYPE_NAME) as TypeName))
+            assertThat(param.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("java.util", "List"),
+                            ClassName.get("java.lang", "Long")) as TypeName
+            ))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertArray() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void insertUsers(User[] users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insertUsers"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ArrayTypeName.of(COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertSet() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void insertUsers(Set<User> users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insertUsers"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("java.util", "Set")
+                            , COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertQueue() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void insertUsers(Queue<User> users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insertUsers"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("java.util", "Queue")
+                            , USER_TYPE_NAME) as TypeName))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertIterable() {
+        singleInsertMethod("""
+                @Insert
+                abstract public void insert(Iterable<User> users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insert"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(ParameterizedTypeName.get(
+                    ClassName.get("java.lang", "Iterable"), USER_TYPE_NAME) as TypeName))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertCustomCollection() {
+        singleInsertMethod("""
+                static class MyList<Irrelevant, Item> extends ArrayList<Item> {}
+                @Insert
+                abstract public void insert(MyList<String, User> users);
+                """) { insertion, invocation ->
+            assertThat(insertion.name, `is`("insert"))
+            assertThat(insertion.parameters.size, `is`(1))
+            val param = insertion.parameters.first()
+            assertThat(param.type.typeName(), `is`(ParameterizedTypeName.get(
+                    ClassName.get("foo.bar", "MyClass.MyList"),
+                    CommonTypeNames.STRING, USER_TYPE_NAME) as TypeName))
+            assertThat(insertion.entities.size, `is`(1))
+            assertThat(insertion.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun insertDifferentTypes() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void foo(User u1, Book b1);
+                """) { insertion, invocation ->
+            assertThat(insertion.parameters.size, `is`(2))
+            assertThat(insertion.parameters[0].type.typeName().toString(),
+                    `is`("foo.bar.User"))
+            assertThat(insertion.parameters[1].type.typeName().toString(),
+                    `is`("foo.bar.Book"))
+            assertThat(insertion.parameters.map { it.name }, `is`(listOf("u1", "b1")))
+            assertThat(insertion.returnType.typeName(), `is`(TypeName.VOID))
+            assertThat(insertion.entities.size, `is`(2))
+            assertThat(insertion.entities["u1"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(insertion.entities["b1"]?.typeName, `is`(BOOK_TYPE_NAME))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun onConflict_Default() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public void foo(User user);
+                """) { insertion, invocation ->
+            assertThat(insertion.onConflict, `is`(OnConflictStrategy.ABORT))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun onConflict_Invalid() {
+        singleInsertMethod(
+                """
+                @Insert(onConflict = -1)
+                abstract public void foo(User user);
+                """) { insertion, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.INVALID_ON_CONFLICT_VALUE)
+    }
+
+    @Test
+    fun onConflict_EachValue() {
+        listOf(
+                Pair("REPLACE", 1),
+                Pair("ROLLBACK", 2),
+                Pair("ABORT", 3),
+                Pair("FAIL", 4),
+                Pair("IGNORE", 5)
+        ).forEach { pair ->
+            singleInsertMethod(
+                    """
+                @Insert(onConflict=OnConflictStrategy.${pair.first})
+                abstract public void foo(User user);
+                """) { insertion, invocation ->
+                assertThat(insertion.onConflict, `is`(pair.second))
+            }.compilesWithoutError()
+        }
+    }
+
+    @Test
+    fun invalidReturnType() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public int foo(User user);
+                """) { insertion, invocation ->
+            assertThat(insertion.insertionType, `is`(nullValue()))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.INVALID_INSERTION_METHOD_RETURN_TYPE)
+    }
+
+    @Test
+    fun mismatchedReturnType() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public long[] foo(User user);
+                """) { insertion, invocation ->
+            assertThat(insertion.insertionType, `is`(nullValue()))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.insertionMethodReturnTypeMismatch(
+                        ArrayTypeName.of(TypeName.LONG),
+                        InsertionMethodProcessor.SINGLE_ITEM_SET.map { it.returnTypeName }))
+    }
+
+    @Test
+    fun mismatchedReturnType2() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public long foo(User... user);
+                """) { insertion, invocation ->
+            assertThat(insertion.insertionType, `is`(nullValue()))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.insertionMethodReturnTypeMismatch(
+                        TypeName.LONG,
+                        InsertionMethodProcessor.MULTIPLE_ITEM_SET.map { it.returnTypeName }))
+    }
+
+    @Test
+    fun mismatchedReturnType3() {
+        singleInsertMethod(
+                """
+                @Insert
+                abstract public long foo(User user1, User user2);
+                """) { insertion, invocation ->
+            assertThat(insertion.insertionType, `is`(nullValue()))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.insertionMethodReturnTypeMismatch(
+                        TypeName.LONG,
+                        InsertionMethodProcessor.VOID_SET.map { it.returnTypeName }))
+    }
+
+    @Test
+    fun validReturnTypes() {
+        listOf(
+                Pair("void", Type.INSERT_VOID),
+                Pair("long", Type.INSERT_SINGLE_ID),
+                Pair("long[]", Type.INSERT_ID_ARRAY),
+                Pair("Long[]", Type.INSERT_ID_ARRAY_BOX),
+                Pair("List<Long>", Type.INSERT_ID_LIST)
+        ).forEach { pair ->
+            val dots = if (pair.second in setOf(Type.INSERT_ID_LIST, Type.INSERT_ID_ARRAY,
+                    Type.INSERT_ID_ARRAY_BOX)) {
+                "..."
+            } else {
+                ""
+            }
+            singleInsertMethod(
+                    """
+                @Insert
+                abstract public ${pair.first} foo(User$dots user);
+                """) { insertion, invocation ->
+                assertThat(insertion.insertMethodTypeFor(insertion.parameters.first()),
+                        `is`(pair.second))
+                assertThat(pair.toString(), insertion.insertionType, `is`(pair.second))
+            }.compilesWithoutError()
+        }
+    }
+
+    fun singleInsertMethod(vararg input: String,
+                          handler: (InsertionMethod, TestInvocation) -> Unit):
+            CompileTester {
+        return assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyClass",
+                        DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX
+                ), COMMON.USER, COMMON.BOOK, COMMON.NOT_AN_ENTITY))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(Insert::class, Dao::class)
+                        .nextRunHandler { invocation ->
+                            val (owner, methods) = invocation.roundEnv
+                                    .getElementsAnnotatedWith(Dao::class.java)
+                                    .map {
+                                        Pair(it,
+                                                invocation.processingEnv.elementUtils
+                                                        .getAllMembers(MoreElements.asType(it))
+                                                        .filter {
+                                                            MoreElements.isAnnotationPresent(it,
+                                                                    Insert::class.java)
+                                                        }
+                                        )
+                                    }.filter { it.second.isNotEmpty() }.first()
+                            val processor = InsertionMethodProcessor(
+                                    baseContext = invocation.context,
+                                    containing = MoreTypes.asDeclared(owner.asType()),
+                                    executableElement = MoreElements.asExecutable(methods.first()))
+                            val processed = processor.process()
+                            handler(processed, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/PojoProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/PojoProcessorTest.kt
new file mode 100644
index 0000000..0a5026a
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/PojoProcessorTest.kt
@@ -0,0 +1,640 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_TYPE
+import android.arch.persistence.room.processor.ProcessorErrors.ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY
+import android.arch.persistence.room.processor.ProcessorErrors.POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME
+import android.arch.persistence.room.processor.ProcessorErrors.RELATION_NOT_COLLECTION
+import android.arch.persistence.room.processor.ProcessorErrors.relationCannotFindEntityField
+import android.arch.persistence.room.processor.ProcessorErrors.relationCannotFindParentEntityField
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Constructor
+import android.arch.persistence.room.vo.EmbeddedField
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.Pojo
+import android.arch.persistence.room.vo.RelationCollector
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.TypeName
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.instanceOf
+import org.hamcrest.CoreMatchers.not
+import org.hamcrest.CoreMatchers.notNullValue
+import org.hamcrest.CoreMatchers.nullValue
+import org.hamcrest.CoreMatchers.sameInstance
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.mockito.Mockito.doReturn
+import org.mockito.Mockito.mock
+import simpleRun
+import javax.lang.model.element.Element
+import javax.tools.JavaFileObject
+
+/**
+ * Some of the functionality is tested via EntityProcessor.
+ */
+@RunWith(JUnit4::class)
+class PojoProcessorTest {
+
+    companion object {
+        val MY_POJO = ClassName.get("foo.bar", "MyPojo")
+        val HEADER = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            import java.util.*;
+            public class MyPojo {
+            """
+        val FOOTER = "\n}"
+    }
+
+    private fun String.toJFO(qName: String) = JavaFileObjects.forSourceLines(qName, this)
+
+    @Test
+    fun inheritedPrivate() {
+        val parent = """
+            package foo.bar.x;
+            import android.arch.persistence.room.*;
+            public class BaseClass {
+                private String baseField;
+                public String getBaseField(){ return baseField; }
+                public void setBaseField(String baseField){ }
+            }
+        """
+        simpleRun(
+                """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                public class ${MY_POJO.simpleName()} extends foo.bar.x.BaseClass {
+                    public String myField;
+                }
+                """.toJFO(MY_POJO.toString()),
+                parent.toJFO("foo.bar.x.BaseClass")) { invocation ->
+            val pojo = PojoProcessor(baseContext = invocation.context,
+                    element = invocation.typeElement(MY_POJO.toString()),
+                    bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR,
+                    parent = null).process()
+            assertThat(pojo.fields.find { it.name == "myField" }, notNullValue())
+            assertThat(pojo.fields.find { it.name == "baseField" }, notNullValue())
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun embedded() {
+        singleRun(
+                """
+                int id;
+                @Embedded
+                Point myPoint;
+                static class Point {
+                    int x;
+                    int y;
+                }
+                """
+        ) { pojo ->
+            assertThat(pojo.fields.size, `is`(3))
+            assertThat(pojo.fields[1].name, `is`("x"))
+            assertThat(pojo.fields[2].name, `is`("y"))
+            assertThat(pojo.fields[0].parent, nullValue())
+            assertThat(pojo.fields[1].parent, notNullValue())
+            assertThat(pojo.fields[2].parent, notNullValue())
+            val parent = pojo.fields[2].parent!!
+            assertThat(parent.prefix, `is`(""))
+            assertThat(parent.field.name, `is`("myPoint"))
+            assertThat(parent.pojo.typeName,
+                    `is`(ClassName.get("foo.bar.MyPojo", "Point") as TypeName))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun embeddedWithPrefix() {
+        singleRun(
+                """
+                int id;
+                @Embedded(prefix = "foo")
+                Point myPoint;
+                static class Point {
+                    int x;
+                    @ColumnInfo(name = "y2")
+                    int y;
+                }
+                """
+        ) { pojo ->
+            assertThat(pojo.fields.size, `is`(3))
+            assertThat(pojo.fields[1].name, `is`("x"))
+            assertThat(pojo.fields[2].name, `is`("y"))
+            assertThat(pojo.fields[1].columnName, `is`("foox"))
+            assertThat(pojo.fields[2].columnName, `is`("fooy2"))
+            val parent = pojo.fields[2].parent!!
+            assertThat(parent.prefix, `is`("foo"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun nestedEmbedded() {
+        singleRun(
+                """
+                int id;
+                @Embedded(prefix = "foo")
+                Point myPoint;
+                static class Point {
+                    int x;
+                    @ColumnInfo(name = "y2")
+                    int y;
+                    @Embedded(prefix = "bar")
+                    Coordinate coordinate;
+                }
+                static class Coordinate {
+                    double lat;
+                    double lng;
+                    @Ignore
+                    String ignored;
+                }
+                """
+        ) { pojo ->
+            assertThat(pojo.fields.size, `is`(5))
+            assertThat(pojo.fields.map { it.columnName }, `is`(
+                    listOf("id", "foox", "fooy2", "foobarlat", "foobarlng")))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun duplicateColumnNames() {
+        singleRun(
+                """
+                int id;
+                @ColumnInfo(name = "id")
+                int another;
+                """
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.pojoDuplicateFieldNames("id", listOf("id", "another"))
+        ).and().withErrorContaining(
+                POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME
+        ).and().withErrorCount(3)
+    }
+
+    @Test
+    fun duplicateColumnNamesFromEmbedded() {
+        singleRun(
+                """
+                int id;
+                @Embedded
+                Foo foo;
+                static class Foo {
+                    @ColumnInfo(name = "id")
+                    int x;
+                }
+                """
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.pojoDuplicateFieldNames("id", listOf("id", "foo > x"))
+        ).and().withErrorContaining(
+                POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME
+        ).and().withErrorCount(3)
+    }
+
+    @Test
+    fun dropSubPrimaryKeyNoWarningForPojo() {
+        singleRun(
+                """
+                @PrimaryKey
+                int id;
+                @Embedded
+                Point myPoint;
+                static class Point {
+                    @PrimaryKey
+                    int x;
+                    int y;
+                }
+                """
+        ) { pojo ->
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun relation_notCollection() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public User user;
+                """, COMMON.USER
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(RELATION_NOT_COLLECTION)
+    }
+
+    @Test
+    fun relation_columnInfo() {
+        singleRun(
+                """
+                int id;
+                @ColumnInfo
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION)
+    }
+
+    @Test
+    fun relation_notEntity() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public List<NotAnEntity> user;
+                """, COMMON.NOT_AN_ENTITY
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY)
+    }
+
+    @Test
+    fun relation_missingParent() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "idk", entityColumn = "uid")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                relationCannotFindParentEntityField("foo.bar.MyPojo", "idk", listOf("id"))
+        )
+    }
+
+    @Test
+    fun relation_missingEntityField() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "idk")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                relationCannotFindEntityField("foo.bar.User", "idk",
+                        listOf("uid", "name", "lastName", "age"))
+        )
+    }
+
+    @Test
+    fun relation_missingType() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public List<User> user;
+                """
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(CANNOT_FIND_TYPE)
+    }
+
+    @Test
+    fun relation_nestedField() {
+        singleRun(
+                """
+                static class Nested {
+                    @ColumnInfo(name = "foo")
+                    public int id;
+                }
+                @Embedded
+                Nested nested;
+                @Relation(parentColumn = "foo", entityColumn = "uid")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+            assertThat(pojo.relations.first().parentField.columnName, `is`("foo"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun relation_nestedRelation() {
+        singleRun(
+                """
+                static class UserWithNested {
+                    @Embedded
+                    public User user;
+                    @Relation(parentColumn = "uid", entityColumn = "uid")
+                    public List<User> selfs;
+                }
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid", entity = User.class)
+                public List<UserWithNested> user;
+                """, COMMON.USER
+        ) { pojo, invocation ->
+            assertThat(pojo.relations.first().parentField.name, `is`("id"))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun relation_affinityMismatch() {
+        singleRun(
+                """
+                String id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo, invocation ->
+            // trigger assignment evaluation
+            RelationCollector.createCollectors(invocation.context, pojo.relations)
+            assertThat(pojo.relations.size, `is`(1))
+            assertThat(pojo.relations.first().entityField.name, `is`("uid"))
+            assertThat(pojo.relations.first().parentField.name, `is`("id"))
+        }.compilesWithoutError().withWarningContaining(
+                ProcessorErrors.relationAffinityMismatch(
+                        parentAffinity = SQLTypeAffinity.TEXT,
+                        childAffinity = SQLTypeAffinity.INTEGER,
+                        parentColumn = "id",
+                        childColumn = "uid")
+        )
+    }
+
+    @Test
+    fun relation_simple() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid")
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+            assertThat(pojo.relations.size, `is`(1))
+            assertThat(pojo.relations.first().entityField.name, `is`("uid"))
+            assertThat(pojo.relations.first().parentField.name, `is`("id"))
+        }.compilesWithoutError().withWarningCount(0)
+    }
+
+    @Test
+    fun relation_badProjection() {
+        singleRun(
+                """
+                int id;
+                @Relation(parentColumn = "id", entityColumn = "uid", projection={"i_dont_exist"})
+                public List<User> user;
+                """, COMMON.USER
+        ) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.relationBadProject("foo.bar.User", listOf("i_dont_exist"),
+                        listOf("uid", "name", "lastName", "ageColumn"))
+        )
+    }
+
+    @Test
+    fun cache() {
+        val pojo = """
+            $HEADER
+            int id;
+            $FOOTER
+            """.toJFO(MY_POJO.toString())
+        simpleRun(pojo) { invocation ->
+            val element = invocation.typeElement(MY_POJO.toString())
+            val pojo1 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.BIND_TO_STMT, null).process()
+            assertThat(pojo1, notNullValue())
+            val pojo2 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.BIND_TO_STMT, null).process()
+            assertThat(pojo2, sameInstance(pojo1))
+
+            val pojo3 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.READ_FROM_CURSOR, null).process()
+            assertThat(pojo3, notNullValue())
+            assertThat(pojo3, not(sameInstance(pojo1)))
+
+            val pojo4 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.TWO_WAY, null).process()
+            assertThat(pojo4, notNullValue())
+            assertThat(pojo4, not(sameInstance(pojo1)))
+            assertThat(pojo4, not(sameInstance(pojo3)))
+
+            val pojo5 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.TWO_WAY, null).process()
+            assertThat(pojo5, sameInstance(pojo4))
+
+            val type = invocation.context.COMMON_TYPES.STRING
+            val mockElement = mock(Element::class.java)
+            doReturn(type).`when`(mockElement).asType()
+            val fakeField = Field(
+                    element = mockElement,
+                    name = "foo",
+                    type = type,
+                    affinity = SQLTypeAffinity.TEXT,
+                    columnName = "foo",
+                    parent = null,
+                    indexed =  false
+            )
+            val fakeEmbedded = EmbeddedField(fakeField, "", null)
+
+            val pojo6 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.TWO_WAY, fakeEmbedded).process()
+            assertThat(pojo6, notNullValue())
+            assertThat(pojo6, not(sameInstance(pojo1)))
+            assertThat(pojo6, not(sameInstance(pojo3)))
+            assertThat(pojo6, not(sameInstance(pojo4)))
+
+            val pojo7 = PojoProcessor(invocation.context, element,
+                    FieldProcessor.BindingScope.TWO_WAY, fakeEmbedded).process()
+            assertThat(pojo7, sameInstance(pojo6))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_empty() {
+        val pojo = """
+            public String mName;
+            """
+        singleRun(pojo) { pojo ->
+            assertThat(pojo.constructor, notNullValue())
+            assertThat(pojo.constructor?.params, `is`(emptyList<Constructor.Param>()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_ambiguous_twoFieldsExcatMatch() {
+        val pojo = """
+            public String mName;
+            public String _name;
+            public MyPojo(String mName) {
+            }
+            """
+        singleRun(pojo) { pojo ->
+            val param = pojo.constructor?.params?.first()
+            assertThat(param, instanceOf(Constructor.FieldParam::class.java))
+            assertThat((param as Constructor.FieldParam).field.name,  `is`("mName"))
+            assertThat(pojo.fields.find { it.name == "mName" }?.setter?.callType,
+                    `is`(CallType.CONSTRUCTOR))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_ambiguous_oneTypeMatches() {
+        val pojo = """
+            public String mName;
+            public int _name;
+            public MyPojo(String name) {
+            }
+            """
+        singleRun(pojo) { pojo ->
+            val param = pojo.constructor?.params?.first()
+            assertThat(param, instanceOf(Constructor.FieldParam::class.java))
+            assertThat((param as Constructor.FieldParam).field.name,  `is`("mName"))
+            assertThat(pojo.fields.find { it.name == "mName" }?.setter?.callType,
+                    `is`(CallType.CONSTRUCTOR))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_ambiguous_twoFields() {
+        val pojo = """
+            String mName;
+            String _name;
+            public MyPojo(String name) {
+            }
+            """
+        singleRun(pojo) { pojo ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.ambigiousConstructor(MY_POJO.toString(),
+                        "name", listOf("mName", "_name"))
+        )
+    }
+
+    @Test
+    fun constructor_noMatchBadType() {
+        singleRun("""
+            int foo;
+            public MyPojo(String foo) {
+            }
+        """) { pojo ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.MISSING_POJO_CONSTRUCTOR)
+    }
+
+    @Test
+    fun constructor_noMatch() {
+        singleRun("""
+            String mName;
+            String _name;
+            public MyPojo(String foo) {
+            }
+        """) { pojo ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.MISSING_POJO_CONSTRUCTOR)
+    }
+
+    @Test
+    fun constructor_noMatchMultiArg() {
+        singleRun("""
+            String mName;
+            int bar;
+            public MyPojo(String foo, String name) {
+            }
+        """) { pojo ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.MISSING_POJO_CONSTRUCTOR)
+    }
+
+    @Test
+    fun constructor_multipleMatching() {
+        singleRun("""
+            String mName;
+            String mLastName;
+            public MyPojo(String name) {
+            }
+            public MyPojo(String name, String lastName) {
+            }
+        """) { pojo ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.TOO_MANY_POJO_CONSTRUCTORS)
+    }
+
+    @Test
+    fun constructor_multipleMatchingWithIgnored() {
+        singleRun("""
+            String mName;
+            String mLastName;
+            @Ignore
+            public MyPojo(String name) {
+            }
+            public MyPojo(String name, String lastName) {
+            }
+        """) { pojo ->
+            assertThat(pojo.constructor, notNullValue())
+            assertThat(pojo.constructor?.params?.size, `is`(2))
+            assertThat(pojo.fields.find { it.name == "mName" }?.setter?.callType,
+                    `is`(CallType.CONSTRUCTOR))
+            assertThat(pojo.fields.find { it.name == "mLastName" }?.setter?.callType,
+                    `is`(CallType.CONSTRUCTOR))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_dontTryForBindToScope() {
+        singleRun("""
+            String mName;
+            String mLastName;
+        """) { pojo, invocation ->
+            val process2 = PojoProcessor(baseContext = invocation.context,
+                    element = invocation.typeElement(MY_POJO.toString()),
+                    bindingScope = FieldProcessor.BindingScope.BIND_TO_STMT,
+                    parent = null).process()
+            assertThat(process2.constructor, nullValue())
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun constructor_bindForTwoWay() {
+        singleRun("""
+            String mName;
+            String mLastName;
+        """) { pojo, invocation ->
+            val process2 = PojoProcessor(baseContext = invocation.context,
+                    element = invocation.typeElement(MY_POJO.toString()),
+                    bindingScope = FieldProcessor.BindingScope.TWO_WAY,
+                    parent = null).process()
+            assertThat(process2.constructor, notNullValue())
+        }.compilesWithoutError()
+    }
+
+    fun singleRun(code: String, vararg jfos:JavaFileObject, handler: (Pojo) -> Unit)
+            : CompileTester {
+        return singleRun(code, *jfos) { pojo, invocation ->
+            handler(pojo)
+        }
+    }
+
+    fun singleRun(code: String, vararg jfos:JavaFileObject,
+                  handler: (Pojo, TestInvocation) -> Unit): CompileTester {
+        val pojoJFO = """
+                $HEADER
+                $code
+                $FOOTER
+                """.toJFO(MY_POJO.toString())
+        val all = (jfos.toList() + pojoJFO).toTypedArray()
+        return simpleRun(*all) { invocation ->
+            handler.invoke(
+                    PojoProcessor(baseContext = invocation.context,
+                            element = invocation.typeElement(MY_POJO.toString()),
+                            bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR,
+                            parent = null).process(),
+                    invocation
+            )
+        }
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/QueryMethodProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/QueryMethodProcessorTest.kt
new file mode 100644
index 0000000..f7affbc
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/QueryMethodProcessorTest.kt
@@ -0,0 +1,647 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.processor
+
+import COMMON
+import android.arch.persistence.room.ColumnInfo
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.PrimaryKey
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.ext.LifecyclesTypeNames
+import android.arch.persistence.room.ext.hasAnnotation
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER
+import android.arch.persistence.room.solver.query.result.LiveDataQueryResultBinder
+import android.arch.persistence.room.solver.query.result.PojoRowAdapter
+import android.arch.persistence.room.solver.query.result.SingleEntityQueryResultAdapter
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.QueryMethod
+import android.arch.persistence.room.vo.Warning
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth.assertAbout
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeVariableName
+import createVerifierFromEntities
+import mockElementAndType
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.instanceOf
+import org.hamcrest.CoreMatchers.notNullValue
+import org.hamcrest.CoreMatchers.nullValue
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import org.mockito.Mockito
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.TypeKind.INT
+import javax.lang.model.type.TypeMirror
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+@RunWith(Parameterized::class)
+class QueryMethodProcessorTest(val enableVerification: Boolean) {
+    companion object {
+        const val DAO_PREFIX = """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                @Dao
+                abstract class MyClass {
+                """
+        const val DAO_SUFFIX = "}"
+        val POJO = ClassName.get("foo.bar", "MyClass.Pojo")
+        @Parameterized.Parameters(name = "enableDbVerification={0}")
+        @JvmStatic
+        fun getParams() = arrayOf(true, false)
+
+        fun createField(name: String, columnName: String? = null): Field {
+            val (element, type) = mockElementAndType()
+            return Field(
+                    element = element,
+                    name = name,
+                    type = type,
+                    columnName = columnName ?: name,
+                    affinity = null
+            )
+        }
+    }
+
+    @Test
+    fun testReadNoParams() {
+        singleQueryMethod(
+                """
+                @Query("SELECT * from User")
+                abstract public int[] foo();
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.parameters.size, `is`(0))
+            assertThat(parsedQuery.returnType.typeName(),
+                    `is`(ArrayTypeName.of(TypeName.INT) as TypeName))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testSingleParam() {
+        singleQueryMethod(
+                """
+                @Query("SELECT * from User where uid = :x")
+                abstract public long foo(int x);
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.returnType.typeName(), `is`(TypeName.LONG))
+            assertThat(parsedQuery.parameters.size, `is`(1))
+            val param = parsedQuery.parameters.first()
+            assertThat(param.name, `is`("x"))
+            assertThat(param.type,
+                    `is`(invocation.processingEnv.typeUtils.getPrimitiveType(INT) as TypeMirror))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testVarArgs() {
+        singleQueryMethod(
+                """
+                @Query("SELECT * from User where uid in (:ids)")
+                abstract public long foo(int... ids);
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.returnType.typeName(), `is`(TypeName.LONG))
+            assertThat(parsedQuery.parameters.size, `is`(1))
+            val param = parsedQuery.parameters.first()
+            assertThat(param.name, `is`("ids"))
+            val types = invocation.processingEnv.typeUtils
+            assertThat(param.type,
+                    `is`(types.getArrayType(types.getPrimitiveType(INT)) as TypeMirror))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testParamBindingMatchingNoName() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where uid = :id")
+                abstract public long getIdById(int id);
+                """) { parsedQuery, invocation ->
+            val section = parsedQuery.query.bindSections.first()
+            val param = parsedQuery.parameters.firstOrNull()
+            assertThat(section, notNullValue())
+            assertThat(param, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping, `is`(listOf(Pair(section, param))))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testParamBindingMatchingSimpleBind() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where uid = :id")
+                abstract public long getIdById(int id);
+                """) { parsedQuery, invocation ->
+            val section = parsedQuery.query.bindSections.first()
+            val param = parsedQuery.parameters.firstOrNull()
+            assertThat(section, notNullValue())
+            assertThat(param, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping,
+                    `is`(listOf(Pair(section, param))))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testParamBindingTwoBindVarsIntoTheSameParameter() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where uid = :id OR uid = :id")
+                abstract public long getIdById(int id);
+                """) { parsedQuery, invocation ->
+            val section = parsedQuery.query.bindSections[0]
+            val section2 = parsedQuery.query.bindSections[1]
+            val param = parsedQuery.parameters.firstOrNull()
+            assertThat(section, notNullValue())
+            assertThat(section2, notNullValue())
+            assertThat(param, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping,
+                    `is`(listOf(Pair(section, param), Pair(section2, param))))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testMissingParameterForBinding() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where uid = :id OR uid = :uid")
+                abstract public long getIdById(int id);
+                """) { parsedQuery, invocation ->
+            val section = parsedQuery.query.bindSections[0]
+            val section2 = parsedQuery.query.bindSections[1]
+            val param = parsedQuery.parameters.firstOrNull()
+            assertThat(section, notNullValue())
+            assertThat(section2, notNullValue())
+            assertThat(param, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping,
+                    `is`(listOf(Pair(section, param), Pair(section2, null))))
+        }
+                .failsToCompile()
+                .withErrorContaining(
+                        ProcessorErrors.missingParameterForBindVariable(listOf(":uid")))
+    }
+
+    @Test
+    fun test2MissingParameterForBinding() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where name = :bar AND uid = :id OR uid = :uid")
+                abstract public long getIdById(int id);
+                """) { parsedQuery, invocation ->
+            val bar = parsedQuery.query.bindSections[0]
+            val id = parsedQuery.query.bindSections[1]
+            val uid = parsedQuery.query.bindSections[2]
+            val param = parsedQuery.parameters.firstOrNull()
+            assertThat(bar, notNullValue())
+            assertThat(id, notNullValue())
+            assertThat(uid, notNullValue())
+            assertThat(param, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping,
+                    `is`(listOf(Pair(bar, null), Pair(id, param), Pair(uid, null))))
+        }
+                .failsToCompile()
+                .withErrorContaining(
+                        ProcessorErrors.missingParameterForBindVariable(listOf(":bar", ":uid")))
+    }
+
+    @Test
+    fun testUnusedParameters() {
+        singleQueryMethod(
+                """
+                @Query("SELECT uid from User where name = :bar")
+                abstract public long getIdById(int bar, int whyNotUseMe);
+                """) { parsedQuery, invocation ->
+            val bar = parsedQuery.query.bindSections[0]
+            val barParam = parsedQuery.parameters.firstOrNull()
+            assertThat(bar, notNullValue())
+            assertThat(barParam, notNullValue())
+            assertThat(parsedQuery.sectionToParamMapping,
+                    `is`(listOf(Pair(bar, barParam))))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.unusedQueryMethodParameter(listOf("whyNotUseMe")))
+    }
+
+    @Test
+    fun testNameWithUnderscore() {
+        singleQueryMethod(
+                """
+                @Query("select * from User where uid = :_blah")
+                abstract public long getSth(int _blah);
+                """
+        ) { parsedQuery, invocation -> }
+                .failsToCompile()
+                .withErrorContaining(ProcessorErrors.QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE)
+    }
+
+    @Test
+    fun testGenericReturnType() {
+        singleQueryMethod(
+                """
+                @Query("select * from User")
+                abstract public <T> java.util.List<T> foo(int x);
+                """) { parsedQuery, invocation ->
+            val expected: TypeName = ParameterizedTypeName.get(ClassName.get(List::class.java),
+                    TypeVariableName.get("T"))
+            assertThat(parsedQuery.returnType.typeName(), `is`(expected))
+        }.failsToCompile()
+                .withErrorContaining(ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS)
+    }
+
+    @Test
+    fun testBadQuery() {
+        singleQueryMethod(
+                """
+                @Query("select * from :1 :2")
+                abstract public long foo(int x);
+                """) { parsedQuery, invocation ->
+            // do nothing
+        }.failsToCompile()
+                .withErrorContaining("UNEXPECTED_CHAR=:")
+    }
+
+    @Test
+    fun testBoundGeneric() {
+        singleQueryMethod(
+                """
+                static abstract class BaseModel<T> {
+                    @Query("select COUNT(*) from User")
+                    abstract public T getT();
+                }
+                @Dao
+                static abstract class ExtendingModel extends BaseModel<Integer> {
+                }
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.returnType.typeName(),
+                    `is`(ClassName.get(Integer::class.java) as TypeName))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testBoundGenericParameter() {
+        singleQueryMethod(
+                """
+                static abstract class BaseModel<T> {
+                    @Query("select COUNT(*) from User where :t")
+                    abstract public int getT(T t);
+                }
+                @Dao
+                static abstract class ExtendingModel extends BaseModel<Integer> {
+                }
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.parameters.first().type,
+                    `is`(invocation.processingEnv.elementUtils
+                            .getTypeElement("java.lang.Integer").asType()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testReadDeleteWithBadReturnType() {
+        singleQueryMethod(
+                """
+                @Query("DELETE from User where uid = :id")
+                abstract public float foo(int id);
+                """) { parsedQuery, invocation ->
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.DELETION_METHODS_MUST_RETURN_VOID_OR_INT
+        )
+    }
+
+    @Test
+    fun testSimpleDelete() {
+        singleQueryMethod(
+                """
+                @Query("DELETE from User where uid = :id")
+                abstract public int foo(int id);
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.parameters.size, `is`(1))
+            assertThat(parsedQuery.returnType.typeName(), `is`(TypeName.INT))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testVoidDeleteQuery() {
+        singleQueryMethod(
+                """
+                @Query("DELETE from User where uid = :id")
+                abstract public void foo(int id);
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.parameters.size, `is`(1))
+            assertThat(parsedQuery.returnType.typeName(), `is`(TypeName.VOID))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testVoidUpdateQuery() {
+        singleQueryMethod(
+                """
+                @Query("update user set name = :name")
+                abstract public void updateAllNames(String name);
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("updateAllNames"))
+            assertThat(parsedQuery.parameters.size, `is`(1))
+            assertThat(parsedQuery.returnType.typeName(), `is`(TypeName.VOID))
+            assertThat(parsedQuery.parameters.first().type.typeName(),
+                    `is`(invocation.context.COMMON_TYPES.STRING.typeName()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testLiveDataQuery() {
+        singleQueryMethod(
+                """
+                @Query("select name from user where uid = :id")
+                abstract ${LifecyclesTypeNames.LIVE_DATA}<String> nameLiveData(String id);
+                """
+        ) { parsedQuery, invocation ->
+            assertThat(parsedQuery.returnType.typeName(),
+                    `is`(ParameterizedTypeName.get(LifecyclesTypeNames.LIVE_DATA,
+                            String::class.typeName()) as TypeName))
+            assertThat(parsedQuery.queryResultBinder,
+                    instanceOf(LiveDataQueryResultBinder::class.java))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testNonSelectLiveData() {
+        singleQueryMethod(
+                """
+                @Query("delete from user where uid = :id")
+                abstract ${LifecyclesTypeNames.LIVE_DATA}<Integer> deleteLiveData(String id);
+                """
+        ) { parsedQuery, invocation ->
+        }.failsToCompile()
+                .withErrorContaining(ProcessorErrors.DELETION_METHODS_MUST_RETURN_VOID_OR_INT)
+    }
+
+    @Test
+    fun skipVerification() {
+        singleQueryMethod(
+                """
+                @SkipQueryVerification
+                @Query("SELECT foo from User")
+                abstract public int[] foo();
+                """) { parsedQuery, invocation ->
+            assertThat(parsedQuery.name, `is`("foo"))
+            assertThat(parsedQuery.parameters.size, `is`(0))
+            assertThat(parsedQuery.returnType.typeName(),
+                    `is`(ArrayTypeName.of(TypeName.INT) as TypeName))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun suppressWarnings() {
+        singleQueryMethod("""
+                @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
+                @Query("SELECT uid from User")
+                abstract public int[] foo();
+                """) { method, invocation ->
+            assertThat(QueryMethodProcessor(
+                    baseContext = invocation.context,
+                    containing = Mockito.mock(DeclaredType::class.java),
+                    executableElement = method.element,
+                    dbVerifier = null).context.logger.suppressedWarnings
+                    , `is`(setOf(Warning.CURSOR_MISMATCH)))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun pojo_renamedColumn() {
+        pojoTest("""
+                String name;
+                String lName;
+                """, listOf("name", "lastName as lName")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList()))
+            assertThat(adapter?.mapping?.unusedFields, `is`(emptyList()))
+        }?.compilesWithoutError()?.withWarningCount(0)
+    }
+
+    @Test
+    fun pojo_exactMatch() {
+        pojoTest("""
+                String name;
+                String lastName;
+                """, listOf("name", "lastName")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList()))
+            assertThat(adapter?.mapping?.unusedFields, `is`(emptyList()))
+        }?.compilesWithoutError()?.withWarningCount(0)
+    }
+
+    @Test
+    fun pojo_exactMatchWithStar() {
+        pojoTest("""
+            String name;
+            String lastName;
+            int uid;
+            @ColumnInfo(name = "ageColumn")
+            int age;
+        """, listOf("*")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList()))
+            assertThat(adapter?.mapping?.unusedFields, `is`(emptyList()))
+        }?.compilesWithoutError()?.withWarningCount(0)
+    }
+
+    @Test
+    fun pojo_nonJavaName() {
+        pojoTest("""
+            @ColumnInfo(name = "MAX(ageColumn)")
+            int maxAge;
+            String name;
+            """, listOf("MAX(ageColumn)", "name")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList()))
+            assertThat(adapter?.mapping?.unusedFields, `is`(emptyList()))
+        }?.compilesWithoutError()?.withWarningCount(0)
+    }
+
+    @Test
+    fun pojo_noMatchingFields() {
+        pojoTest("""
+                String nameX;
+                String lastNameX;
+                """, listOf("name", "lastName")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("name", "lastName")))
+            assertThat(adapter?.mapping?.unusedFields, `is`(adapter?.pojo?.fields))
+        }?.failsToCompile()
+                ?.withErrorContaining(CANNOT_FIND_QUERY_RESULT_ADAPTER)
+                ?.and()
+                ?.withWarningContaining(
+                        ProcessorErrors.cursorPojoMismatch(
+                                pojoTypeName = POJO,
+                                unusedColumns = listOf("name", "lastName"),
+                                unusedFields = listOf(createField("nameX"),
+                                        createField("lastNameX")),
+                                allColumns = listOf("name", "lastName"),
+                                allFields = listOf(createField("nameX"), createField("lastNameX"))
+                        )
+                )
+    }
+
+    @Test
+    fun pojo_badQuery() {
+        // do not report mismatch if query is broken
+        pojoTest("""
+            @ColumnInfo(name = "MAX(ageColumn)")
+            int maxAge;
+            String name;
+            """, listOf("MAX(age)", "name")) { adapter, queryMethod, invocation ->
+        }?.failsToCompile()
+                ?.withErrorContaining("no such column: age")
+                ?.and()
+                ?.withErrorCount(1)
+                ?.withWarningCount(0)
+    }
+
+    @Test
+    fun pojo_tooManyColumns() {
+        pojoTest("""
+            String name;
+            String lastName;
+            """, listOf("uid", "name", "lastName")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("uid")))
+            assertThat(adapter?.mapping?.unusedFields, `is`(emptyList()))
+        }?.compilesWithoutError()?.withWarningContaining(
+                ProcessorErrors.cursorPojoMismatch(
+                        pojoTypeName = POJO,
+                        unusedColumns = listOf("uid"),
+                        unusedFields = emptyList(),
+                        allColumns = listOf("uid", "name", "lastName"),
+                        allFields = listOf(createField("name"), createField("lastName"))
+                ))
+    }
+
+    @Test
+    fun pojo_tooManyFields() {
+        pojoTest("""
+            String name;
+            String lastName;
+            """, listOf("lastName")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList()))
+            assertThat(adapter?.mapping?.unusedFields, `is`(
+                    adapter?.pojo?.fields?.filter { it.name == "name" }
+            ))
+        }?.compilesWithoutError()?.withWarningContaining(
+                ProcessorErrors.cursorPojoMismatch(
+                        pojoTypeName = POJO,
+                        unusedColumns = emptyList(),
+                        unusedFields = listOf(createField("name")),
+                        allColumns = listOf("lastName"),
+                        allFields = listOf(createField("name"), createField("lastName"))
+                ))
+    }
+
+    @Test
+    fun pojo_tooManyFieldsAndColumns() {
+        pojoTest("""
+            String name;
+            String lastName;
+            """, listOf("uid", "name")) { adapter, queryMethod, invocation ->
+            assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("uid")))
+            assertThat(adapter?.mapping?.unusedFields, `is`(
+                    adapter?.pojo?.fields?.filter { it.name == "lastName" }
+            ))
+        }?.compilesWithoutError()?.withWarningContaining(
+                ProcessorErrors.cursorPojoMismatch(
+                        pojoTypeName = POJO,
+                        unusedColumns = listOf("uid"),
+                        unusedFields = listOf(createField("lastName")),
+                        allColumns = listOf("uid", "name"),
+                        allFields = listOf(createField("name"), createField("lastName"))
+                ))
+    }
+
+    fun pojoTest(pojoFields: String, queryColumns: List<String>,
+                 handler: (PojoRowAdapter?, QueryMethod, TestInvocation) -> Unit): CompileTester? {
+        val assertion = singleQueryMethod(
+                """
+                static class Pojo {
+                    $pojoFields
+                }
+                @Query("SELECT ${queryColumns.joinToString(", ")} from User LIMIT 1")
+                abstract MyClass.Pojo getNameAndLastNames();
+                """
+        ) { parsedQuery, invocation ->
+            val adapter = parsedQuery.queryResultBinder.adapter
+            if (enableVerification) {
+                if (adapter is SingleEntityQueryResultAdapter) {
+                    handler(adapter.rowAdapter as? PojoRowAdapter, parsedQuery, invocation)
+                } else {
+                    handler(null, parsedQuery, invocation)
+                }
+            } else {
+                assertThat(adapter, nullValue())
+            }
+        }
+        if (enableVerification) {
+            return assertion
+        } else {
+            assertion.failsToCompile().withErrorContaining(CANNOT_FIND_QUERY_RESULT_ADAPTER)
+            return null
+        }
+    }
+
+    fun singleQueryMethod(vararg input: String,
+                          handler: (QueryMethod, TestInvocation) -> Unit):
+            CompileTester {
+        return assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyClass",
+                        DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX
+                ), COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.USER))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(Query::class, Dao::class, ColumnInfo::class,
+                                Entity::class, PrimaryKey::class)
+                        .nextRunHandler { invocation ->
+                            val (owner, methods) = invocation.roundEnv
+                                    .getElementsAnnotatedWith(Dao::class.java)
+                                    .map {
+                                        Pair(it,
+                                                invocation.processingEnv.elementUtils
+                                                        .getAllMembers(MoreElements.asType(it))
+                                                        .filter {
+                                                            it.hasAnnotation(Query::class)
+                                                        }
+                                        )
+                                    }.filter { it.second.isNotEmpty() }.first()
+                            val verifier = if (enableVerification) {
+                                createVerifierFromEntities(invocation)
+                            } else {
+                                null
+                            }
+                            val parser = QueryMethodProcessor(
+                                    baseContext = invocation.context,
+                                    containing = MoreTypes.asDeclared(owner.asType()),
+                                    executableElement = MoreElements.asExecutable(methods.first()),
+                                    dbVerifier = verifier)
+                            val parsedQuery = parser.process()
+                            handler(parsedQuery, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessorTest.kt
new file mode 100644
index 0000000..a4d670c
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/ShortcutMethodProcessorTest.kt
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.ext.CommonTypeNames
+import android.arch.persistence.room.ext.typeName
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.ShortcutMethod
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.ArrayTypeName
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.ParameterizedTypeName
+import com.squareup.javapoet.TypeName
+import org.hamcrest.CoreMatchers
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+import kotlin.reflect.KClass
+
+/**
+ * Base test class for shortcut methods.
+ */
+abstract class ShortcutMethodProcessorTest<out T : ShortcutMethod>(
+        val annotation: KClass<out Annotation>) {
+    companion object {
+        const val DAO_PREFIX = """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                import java.util.*;
+                @Dao
+                abstract class MyClass {
+                """
+        const val DAO_SUFFIX = "}"
+        val USER_TYPE_NAME: TypeName = COMMON.USER_TYPE_NAME
+        val BOOK_TYPE_NAME : TypeName = ClassName.get("foo.bar", "Book")
+    }
+
+    @Test
+    fun noParams() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void foo();
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("foo"))
+            assertThat(shortcut.parameters.size, `is`(0))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.failsToCompile().withErrorContaining(noParamsError())
+    }
+
+    abstract fun noParamsError(): String
+
+    @Test
+    fun single() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public int foo(User user);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("foo"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(param.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["user"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun notAnEntity() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void foo(NotAnEntity notValid);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("foo"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.entityType, `is`(CoreMatchers.nullValue()))
+            assertThat(shortcut.entities.size, `is`(0))
+        }.failsToCompile().withErrorContaining(
+                ProcessorErrors.CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER
+        )
+    }
+
+    @Test
+    fun two() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void foo(User u1, User u2);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("foo"))
+
+            assertThat(shortcut.parameters.size, `is`(2))
+            shortcut.parameters.forEach {
+                assertThat(it.type.typeName(), `is`(USER_TYPE_NAME))
+                assertThat(it.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            }
+            assertThat(shortcut.entities.size, `is`(2))
+            assertThat(shortcut.entities["u1"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.entities["u1"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.parameters.map { it.name },
+                    `is`(listOf("u1", "u2")))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun list() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public int users(List<User> users);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("users"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(
+                            ClassName.get("java.util", "List"), USER_TYPE_NAME) as TypeName))
+            assertThat(param.entityType?.typeName(), `is`(USER_TYPE_NAME))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun array() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void users(User[] users);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("users"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ArrayTypeName.of(COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun set() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void modifyUsers(Set<User> users);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("modifyUsers"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("java.util", "Set")
+                            , COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun iterable() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void modifyUsers(Iterable<User> users);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("modifyUsers"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("java.lang", "Iterable")
+                            , COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun customCollection() {
+        singleShortcutMethod(
+                """
+                static class MyList<Irrelevant, Item> extends ArrayList<Item> {}
+                @${annotation.java.canonicalName}
+                abstract public void modifyUsers(MyList<String, User> users);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.name, `is`("modifyUsers"))
+            assertThat(shortcut.parameters.size, `is`(1))
+            val param = shortcut.parameters.first()
+            assertThat(param.type.typeName(), `is`(
+                    ParameterizedTypeName.get(ClassName.get("foo.bar", "MyClass.MyList")
+                            , CommonTypeNames.STRING
+                            , COMMON.USER_TYPE_NAME) as TypeName))
+            assertThat(shortcut.entities.size, `is`(1))
+            assertThat(shortcut.entities["users"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.returnCount, `is`(false))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun differentTypes() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public void foo(User u1, Book b1);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.parameters.size, `is`(2))
+            assertThat(shortcut.parameters[0].type.typeName().toString(),
+                    `is`("foo.bar.User"))
+            assertThat(shortcut.parameters[1].type.typeName().toString(),
+                    `is`("foo.bar.Book"))
+            assertThat(shortcut.parameters.map { it.name }, `is`(listOf("u1", "b1")))
+            assertThat(shortcut.returnCount, `is`(false))
+            assertThat(shortcut.entities.size, `is`(2))
+            assertThat(shortcut.entities["u1"]?.typeName, `is`(USER_TYPE_NAME))
+            assertThat(shortcut.entities["b1"]?.typeName, `is`(BOOK_TYPE_NAME))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun invalidReturnType() {
+        singleShortcutMethod(
+                """
+                @${annotation.java.canonicalName}
+                abstract public long foo(User user);
+                """) { shortcut, invocation ->
+        }.failsToCompile().withErrorContaining(invalidReturnTypeError())
+    }
+
+    abstract fun invalidReturnTypeError(): String
+
+    abstract fun process(baseContext: Context, containing: DeclaredType,
+                         executableElement: ExecutableElement): T
+
+    fun singleShortcutMethod(vararg input: String,
+                             handler: (T, TestInvocation) -> Unit):
+            CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyClass",
+                        DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX
+                ), COMMON.USER, COMMON.BOOK, COMMON.NOT_AN_ENTITY))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(annotation, Dao::class)
+                        .nextRunHandler { invocation ->
+                            val (owner, methods) = invocation.roundEnv
+                                    .getElementsAnnotatedWith(Dao::class.java)
+                                    .map {
+                                        Pair(it,
+                                                invocation.processingEnv.elementUtils
+                                                        .getAllMembers(MoreElements.asType(it))
+                                                        .filter {
+                                                            MoreElements.isAnnotationPresent(it,
+                                                                    annotation.java)
+                                                        }
+                                        )
+                                    }.filter { it.second.isNotEmpty() }.first()
+                            val processed = process(
+                                    baseContext = invocation.context,
+                                    containing = MoreTypes.asDeclared(owner.asType()),
+                                    executableElement = MoreElements.asExecutable(methods.first()))
+                            handler(processed, invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessorTest.kt
new file mode 100644
index 0000000..c8a88ae
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/processor/UpdateMethodProcessorTest.kt
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.processor
+
+import android.arch.persistence.room.OnConflictStrategy
+import android.arch.persistence.room.Update
+import android.arch.persistence.room.processor.ProcessorErrors
+        .UPDATE_METHODS_MUST_RETURN_VOID_OR_INT
+import android.arch.persistence.room.processor.ProcessorErrors.UPDATE_MISSING_PARAMS
+import android.arch.persistence.room.vo.UpdateMethod
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.type.DeclaredType
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+@RunWith(JUnit4::class)
+class UpdateMethodProcessorTest : ShortcutMethodProcessorTest<UpdateMethod>(Update::class) {
+    override fun invalidReturnTypeError(): String = UPDATE_METHODS_MUST_RETURN_VOID_OR_INT
+
+    override fun noParamsError(): String = UPDATE_MISSING_PARAMS
+
+    override fun process(baseContext: Context, containing: DeclaredType,
+                         executableElement: ExecutableElement): UpdateMethod {
+        return UpdateMethodProcessor(baseContext, containing, executableElement).process()
+    }
+
+    @Test
+    fun goodConflict() {
+        singleShortcutMethod(
+                """
+                @Update(onConflict = OnConflictStrategy.REPLACE)
+                abstract public void foo(User user);
+                """) { shortcut, invocation ->
+            assertThat(shortcut.onConflictStrategy, `is`(OnConflictStrategy.REPLACE))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun badConflict() {
+        singleShortcutMethod(
+                """
+                @Update(onConflict = -1)
+                abstract public void foo(User user);
+                """) { shortcut, invocation ->
+        }.failsToCompile().withErrorContaining(ProcessorErrors.INVALID_ON_CONFLICT_VALUE)
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/BasicColumnTypeAdaptersTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/BasicColumnTypeAdaptersTest.kt
new file mode 100644
index 0000000..024099b
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/BasicColumnTypeAdaptersTest.kt
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver
+
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.testing.TestInvocation
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.JavaFile
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.Parameterized
+import simpleRun
+import testCodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.PrimitiveType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+@RunWith(Parameterized::class)
+class BasicColumnTypeAdaptersTest(val input: Input, val bindCode: String,
+                                  val cursorCode: String) {
+    val scope = testCodeGenScope()
+
+    companion object {
+        val SQLITE_STMT: TypeName = ClassName.get("android.database.sqlite", "SQLiteStatement")
+        val CURSOR: TypeName = ClassName.get("android.database", "Cursor")
+
+        @Parameterized.Parameters(name = "kind:{0},bind:_{1},cursor:_{2}")
+        @JvmStatic
+        fun params(): List<Array<Any>> {
+            return listOf(
+                    arrayOf(Input(TypeKind.INT),
+                            "st.bindLong(6, inp);",
+                            "out = crs.getInt(9);"),
+                    arrayOf(Input(TypeKind.BYTE),
+                            "st.bindLong(6, inp);",
+                            "out = (byte) crs.getShort(9);"),
+                    arrayOf(Input(TypeKind.SHORT),
+                            "st.bindLong(6, inp);",
+                            "out = crs.getShort(9);"),
+                    arrayOf(Input(TypeKind.LONG),
+                            "st.bindLong(6, inp);",
+                            "out = crs.getLong(9);"),
+                    arrayOf(Input(TypeKind.CHAR),
+                            "st.bindLong(6, inp);",
+                            "out = (char) crs.getInt(9);"),
+                    arrayOf(Input(TypeKind.FLOAT),
+                            "st.bindDouble(6, inp);",
+                            "out = crs.getFloat(9);"),
+                    arrayOf(Input(TypeKind.DOUBLE),
+                            "st.bindDouble(6, inp);",
+                            "out = crs.getDouble(9);"),
+                    arrayOf(Input(TypeKind.DECLARED, "java.lang.String"),
+                            """
+                            if (inp == null) {
+                              st.bindNull(6);
+                            } else {
+                              st.bindString(6, inp);
+                            }
+                            """.trimIndent(),
+                            "out = crs.getString(9);")
+            )
+        }
+    }
+
+    @Test
+    fun bind() {
+        simpleRun { invocation ->
+            val adapter = TypeAdapterStore.create(Context(invocation.processingEnv))
+                    .findColumnTypeAdapter(input.getTypeMirror(invocation.processingEnv), null)!!
+            adapter.bindToStmt("st", "6", "inp", scope)
+            assertThat(scope.generate().trim(), `is`(bindCode))
+            generateCode(invocation, false)
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun boxedBind() {
+        if (!input.typeKind.isPrimitive) {
+            return // no-op for those
+        }
+        simpleRun { invocation ->
+            val adapter = TypeAdapterStore.create(Context(invocation.processingEnv))
+                    .findColumnTypeAdapter(
+                            input.getBoxedTypeMirror(invocation.processingEnv), null)!!
+            adapter.bindToStmt("st", "6", "inp", scope)
+            assertThat(scope.generate().trim(), `is`(
+                    """
+                    if (inp == null) {
+                      st.bindNull(6);
+                    } else {
+                      $bindCode
+                    }
+                    """.trimIndent()
+            ))
+            generateCode(invocation, true)
+        }.compilesWithoutError()
+    }
+
+    private fun generateCode(invocation: TestInvocation, boxed: Boolean) {
+        val typeMirror = if (boxed) input.getBoxedTypeMirror(invocation.processingEnv)
+        else input.getTypeMirror(invocation.processingEnv)
+        val spec = TypeSpec.classBuilder("OutClass")
+                .addField(FieldSpec.builder(SQLITE_STMT, "st").build())
+                .addField(FieldSpec.builder(CURSOR, "crs").build())
+                .addField(FieldSpec.builder(TypeName.get(typeMirror), "out").build())
+                .addField(FieldSpec.builder(TypeName.get(typeMirror), "inp").build())
+                .addMethod(
+                        MethodSpec.methodBuilder("foo")
+                                .addCode(scope.builder().build())
+                                .build()
+                )
+                .build()
+        JavaFile.builder("foo.bar", spec).build().writeTo(invocation.processingEnv.filer)
+    }
+
+    @Test
+    fun read() {
+        simpleRun { invocation ->
+            val adapter = TypeAdapterStore.create(Context(invocation.processingEnv))
+                    .findColumnTypeAdapter(input.getTypeMirror(invocation.processingEnv), null)!!
+            adapter.readFromCursor("out", "crs", "9", scope)
+            assertThat(scope.generate().trim(), `is`(cursorCode))
+            generateCode(invocation, false)
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun readBoxed() {
+        if (!input.typeKind.isPrimitive) {
+            return // no-op for those
+        }
+        simpleRun { invocation ->
+            val adapter = TypeAdapterStore.create(Context(invocation.processingEnv))
+                    .findColumnTypeAdapter(
+                            input.getBoxedTypeMirror(invocation.processingEnv), null)!!
+            adapter.readFromCursor("out", "crs", "9", scope)
+            assertThat(scope.generate().trim(), `is`(
+                    """
+                    if (crs.isNull(9)) {
+                      out = null;
+                    } else {
+                      $cursorCode
+                    }
+                    """.trimIndent()
+            ))
+            generateCode(invocation, true)
+        }.compilesWithoutError()
+    }
+
+    data class Input(val typeKind: TypeKind, val qName: String? = null) {
+        fun getTypeMirror(processingEnv: ProcessingEnvironment): TypeMirror {
+            return if (typeKind.isPrimitive) {
+                processingEnv.typeUtils.getPrimitiveType(typeKind)
+            } else {
+                processingEnv.elementUtils.getTypeElement(qName).asType()
+            }
+        }
+
+        fun getBoxedTypeMirror(processingEnv: ProcessingEnvironment): TypeMirror {
+            return if (typeKind.isPrimitive) {
+                processingEnv.typeUtils
+                        .boxedClass(getTypeMirror(processingEnv) as PrimitiveType)
+                        .asType()
+            } else {
+                getTypeMirror(processingEnv)
+            }
+        }
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/CustomTypeConverterResolutionTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/CustomTypeConverterResolutionTest.kt
new file mode 100644
index 0000000..1790788
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/CustomTypeConverterResolutionTest.kt
@@ -0,0 +1,300 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+@file:Suppress("HasPlatformType")
+
+package android.arch.persistence.room.solver
+
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Database
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.PrimaryKey
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.RoomProcessor
+import android.arch.persistence.room.TypeConverter
+import android.arch.persistence.room.TypeConverters
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.ext.S
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.processor.ProcessorErrors.CANNOT_BIND_QUERY_PARAMETER_INTO_STMT
+import android.arch.persistence.room.testing.TestInvocation
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.AnnotationSpec
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.FieldSpec
+import com.squareup.javapoet.MethodSpec
+import com.squareup.javapoet.ParameterSpec
+import com.squareup.javapoet.TypeName
+import com.squareup.javapoet.TypeSpec
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.lang.model.element.Modifier
+import javax.tools.JavaFileObject
+
+@RunWith(JUnit4::class)
+class CustomTypeConverterResolutionTest {
+    fun TypeSpec.toJFO() : JavaFileObject {
+        return JavaFileObjects.forSourceString("foo.bar.${this.name}",
+                "package foo.bar;\n" + toString())
+    }
+
+    companion object {
+        val ENTITY = ClassName.get("foo.bar", "MyEntity")
+        val DB = ClassName.get("foo.bar", "MyDb")
+        val DAO = ClassName.get("foo.bar", "MyDao")
+
+        val CUSTOM_TYPE = ClassName.get("foo.bar", "CustomType")
+        val CUSTOM_TYPE_JFO = JavaFileObjects.forSourceLines(CUSTOM_TYPE.toString(),
+                """
+                package ${CUSTOM_TYPE.packageName()};
+                public class ${CUSTOM_TYPE.simpleName()} {
+                    public int value;
+                }
+                """)
+        val CUSTOM_TYPE_CONVERTER = ClassName.get("foo.bar", "MyConverter")
+        val CUSTOM_TYPE_CONVERTER_JFO = JavaFileObjects.forSourceLines(
+                CUSTOM_TYPE_CONVERTER.toString(),
+                """
+                package ${CUSTOM_TYPE_CONVERTER.packageName()};
+                public class ${CUSTOM_TYPE_CONVERTER.simpleName()} {
+                    @${TypeConverter::class.java.canonicalName}
+                    public static $CUSTOM_TYPE toCustom(int value) {
+                        return null;
+                    }
+                    @${TypeConverter::class.java.canonicalName}
+                    public static int fromCustom($CUSTOM_TYPE input) {
+                        return 0;
+                    }
+                }
+                """)
+    }
+
+    @Test
+    fun useFromDatabase_forEntity() {
+        val entity = createEntity(hasCustomField = true)
+        val database = createDatabase(hasConverters = true, hasDao = true)
+        val dao = createDao(hasQueryReturningEntity = true, hasQueryWithCustomParam = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromDatabase_forQueryParameter() {
+        val entity = createEntity()
+        val database = createDatabase(hasConverters = true, hasDao = true)
+        val dao = createDao(hasQueryWithCustomParam = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromDatabase_forReturnValue() {
+        val entity = createEntity(hasCustomField = true)
+        val database = createDatabase(hasConverters = true, hasDao = true)
+        val dao = createDao(hasQueryReturningEntity = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromDao_forQueryParameter() {
+        val entity = createEntity()
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasConverters = true, hasQueryReturningEntity = true,
+                hasQueryWithCustomParam = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromEntity_forReturnValue() {
+        val entity = createEntity(hasCustomField = true, hasConverters = true)
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryReturningEntity = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromEntityField_forReturnValue() {
+        val entity = createEntity(hasCustomField = true, hasConverterOnField = true)
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryReturningEntity = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromEntity_forQueryParameter() {
+        val entity = createEntity(hasCustomField = true, hasConverters = true)
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryWithCustomParam = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.failsToCompile().withErrorContaining(CANNOT_BIND_QUERY_PARAMETER_INTO_STMT)
+    }
+
+    @Test
+    fun useFromEntityField_forQueryParameter() {
+        val entity = createEntity(hasCustomField = true, hasConverterOnField = true)
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryWithCustomParam = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.failsToCompile().withErrorContaining(CANNOT_BIND_QUERY_PARAMETER_INTO_STMT)
+    }
+
+    @Test
+    fun useFromQueryMethod_forQueryParameter() {
+        val entity = createEntity()
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryWithCustomParam = true, hasMethodConverters = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun useFromQueryParameter_forQueryParameter() {
+        val entity = createEntity()
+        val database = createDatabase(hasDao = true)
+        val dao = createDao(hasQueryWithCustomParam = true, hasParameterConverters = true)
+        run(entity.toJFO(), dao.toJFO(), database.toJFO()){
+
+        }.compilesWithoutError()
+    }
+
+    fun run(vararg jfos : JavaFileObject, f: (TestInvocation) -> Unit): CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(jfos.toList() + CUSTOM_TYPE_JFO + CUSTOM_TYPE_CONVERTER_JFO)
+                .processedWith(RoomProcessor())
+    }
+
+    private fun createEntity(hasCustomField : Boolean = false,
+                             hasConverters : Boolean = false,
+                             hasConverterOnField : Boolean = false) : TypeSpec {
+        if (hasConverterOnField && hasConverters) {
+            throw IllegalArgumentException("cannot have both converters")
+        }
+        return TypeSpec.classBuilder(ENTITY).apply {
+            addAnnotation(Entity::class.java)
+            addModifiers(Modifier.PUBLIC)
+            if (hasCustomField) {
+                addField(FieldSpec.builder(CUSTOM_TYPE, "myCustomField", Modifier.PUBLIC).apply {
+                    if (hasConverterOnField) {
+                        addAnnotation(createConvertersAnnotation())
+                    }
+                }.build())
+            }
+            if (hasConverters) {
+                addAnnotation(createConvertersAnnotation())
+            }
+            addField(FieldSpec.builder(TypeName.INT, "id", Modifier.PUBLIC).apply {
+                addAnnotation(PrimaryKey::class.java)
+            }.build())
+        }.build()
+    }
+
+    private fun createDatabase(hasConverters : Boolean = false,
+                               hasDao : Boolean = false) : TypeSpec {
+        return TypeSpec.classBuilder(DB).apply {
+            addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
+            superclass(RoomTypeNames.ROOM_DB)
+            if (hasConverters) {
+                addAnnotation(createConvertersAnnotation())
+            }
+            addField(FieldSpec.builder(TypeName.INT, "id", Modifier.PUBLIC).apply {
+                addAnnotation(PrimaryKey::class.java)
+            }.build())
+            if (hasDao) {
+                addMethod(MethodSpec.methodBuilder("getDao").apply {
+                    addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
+                    returns(DAO)
+                }.build())
+            }
+            addAnnotation(
+                    AnnotationSpec.builder(Database::class.java).apply {
+                        addMember("entities", "{$T.class}", ENTITY)
+                        addMember("version", "42")
+                    }.build()
+            )
+        }.build()
+    }
+
+    private fun createDao(hasConverters : Boolean = false,
+                          hasQueryReturningEntity : Boolean = false,
+                          hasQueryWithCustomParam : Boolean = false,
+                          hasMethodConverters : Boolean = false,
+                          hasParameterConverters : Boolean = false) : TypeSpec {
+        val annotationCount = listOf(hasMethodConverters, hasConverters, hasParameterConverters)
+                .map { if (it) 1 else 0 }.sum()
+        if (annotationCount > 1) {
+            throw IllegalArgumentException("cannot set both of these")
+        }
+        if (hasParameterConverters && !hasQueryWithCustomParam) {
+            throw IllegalArgumentException("inconsistent")
+        }
+        return TypeSpec.classBuilder(DAO).apply {
+            addAnnotation(Dao::class.java)
+            addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
+            if (hasConverters) {
+                addAnnotation(createConvertersAnnotation())
+            }
+            if (hasQueryReturningEntity) {
+                addMethod(MethodSpec.methodBuilder("loadAll").apply {
+                    addAnnotation(AnnotationSpec.builder(Query::class.java).apply {
+                        addMember("value", S, "SELECT * FROM ${ENTITY.simpleName()} LIMIT 1")
+                    }.build())
+                    addModifiers(Modifier.ABSTRACT)
+                    returns(ENTITY)
+                }.build())
+            }
+            if (hasQueryWithCustomParam) {
+                addMethod(MethodSpec.methodBuilder("queryWithCustom").apply {
+                    addAnnotation(AnnotationSpec.builder(Query::class.java).apply {
+                        addMember("value", S, "SELECT COUNT(*) FROM ${ENTITY.simpleName()} where" +
+                                " id IN(:customs)")
+                    }.build())
+                    if (hasMethodConverters) {
+                        addAnnotation(createConvertersAnnotation())
+                    }
+                    addParameter(ParameterSpec.builder(CUSTOM_TYPE, "customs").apply {
+                        if (hasParameterConverters) {
+                            addAnnotation(createConvertersAnnotation())
+                        }
+                    }.build())
+                    addModifiers(Modifier.ABSTRACT)
+                    returns(TypeName.INT)
+                }.build())
+            }
+        }.build()
+    }
+
+    private fun createConvertersAnnotation(): AnnotationSpec {
+        return AnnotationSpec.builder(TypeConverters::class.java)
+                .addMember("value", "$T.class", CUSTOM_TYPE_CONVERTER).build()
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/TypeAdapterStoreTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/TypeAdapterStoreTest.kt
new file mode 100644
index 0000000..204adc6
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/TypeAdapterStoreTest.kt
@@ -0,0 +1,395 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver
+
+import COMMON
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ext.L
+import android.arch.persistence.room.ext.LifecyclesTypeNames
+import android.arch.persistence.room.ext.PagingTypeNames
+import android.arch.persistence.room.ext.ReactiveStreamsTypeNames
+import android.arch.persistence.room.ext.RoomTypeNames.STRING_UTIL
+import android.arch.persistence.room.ext.RxJava2TypeNames
+import android.arch.persistence.room.ext.T
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.processor.ProcessorErrors
+import android.arch.persistence.room.solver.binderprovider.CountedDataSourceQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.FlowableQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.LiveDataQueryResultBinderProvider
+import android.arch.persistence.room.solver.binderprovider.LiveLazyListQueryResultBinderProvider
+import android.arch.persistence.room.solver.types.CompositeAdapter
+import android.arch.persistence.room.solver.types.TypeConverter
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.util.paging.CountedDataSource
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.instanceOf
+import org.hamcrest.CoreMatchers.notNullValue
+import org.hamcrest.CoreMatchers.nullValue
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import simpleRun
+import testCodeGenScope
+import javax.annotation.processing.ProcessingEnvironment
+import javax.lang.model.type.TypeKind
+
+@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+@RunWith(JUnit4::class)
+class TypeAdapterStoreTest {
+    companion object {
+        fun tmp(index: Int) = CodeGenScope._tmpVar(index)
+    }
+
+    @Test
+    fun testDirect() {
+        singleRun { invocation ->
+            val store = TypeAdapterStore.create(Context(invocation.processingEnv))
+            val primitiveType = invocation.processingEnv.typeUtils.getPrimitiveType(TypeKind.INT)
+            val adapter = store.findColumnTypeAdapter(primitiveType, null)
+            assertThat(adapter, notNullValue())
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testVia1TypeAdapter() {
+        singleRun { invocation ->
+            val store = TypeAdapterStore.create(Context(invocation.processingEnv))
+            val booleanType = invocation.processingEnv.typeUtils
+                    .getPrimitiveType(TypeKind.BOOLEAN)
+            val adapter = store.findColumnTypeAdapter(booleanType, null)
+            assertThat(adapter, notNullValue())
+            assertThat(adapter, instanceOf(CompositeAdapter::class.java))
+            val bindScope = testCodeGenScope()
+            adapter!!.bindToStmt("stmt", "41", "fooVar", bindScope)
+            assertThat(bindScope.generate().trim(), `is`("""
+                    final int ${tmp(0)};
+                    ${tmp(0)} = fooVar ? 1 : 0;
+                    stmt.bindLong(41, ${tmp(0)});
+                    """.trimIndent()))
+
+            val cursorScope = testCodeGenScope()
+            adapter.readFromCursor("res", "curs", "7", cursorScope)
+            assertThat(cursorScope.generate().trim(), `is`("""
+                    final int ${tmp(0)};
+                    ${tmp(0)} = curs.getInt(7);
+                    res = ${tmp(0)} != 0;
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testVia2TypeAdapters() {
+        singleRun { invocation ->
+            val store = TypeAdapterStore.create(Context(invocation.processingEnv),
+                    pointTypeConverters(invocation.processingEnv))
+            val pointType = invocation.processingEnv.elementUtils
+                    .getTypeElement("foo.bar.Point").asType()
+            val adapter = store.findColumnTypeAdapter(pointType, null)
+            assertThat(adapter, notNullValue())
+            assertThat(adapter, instanceOf(CompositeAdapter::class.java))
+
+            val bindScope = testCodeGenScope()
+            adapter!!.bindToStmt("stmt", "41", "fooVar", bindScope)
+            assertThat(bindScope.generate().trim(), `is`("""
+                    final int ${tmp(0)};
+                    final boolean ${tmp(1)};
+                    ${tmp(1)} = foo.bar.Point.toBoolean(fooVar);
+                    ${tmp(0)} = ${tmp(1)} ? 1 : 0;
+                    stmt.bindLong(41, ${tmp(0)});
+                    """.trimIndent()))
+
+            val cursorScope = testCodeGenScope()
+            adapter.readFromCursor("res", "curs", "11", cursorScope).toString()
+            assertThat(cursorScope.generate().trim(), `is`("""
+                    final int ${tmp(0)};
+                    ${tmp(0)} = curs.getInt(11);
+                    final boolean ${tmp(1)};
+                    ${tmp(1)} = ${tmp(0)} != 0;
+                    res = foo.bar.Point.fromBoolean(${tmp(1)});
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testDate() {
+        singleRun { (processingEnv) ->
+            val store = TypeAdapterStore.create(Context(processingEnv),
+                    dateTypeConverters(processingEnv))
+            val tDate = processingEnv.elementUtils.getTypeElement("java.util.Date").asType()
+            val adapter = store.findCursorValueReader(tDate, SQLTypeAffinity.INTEGER)
+            assertThat(adapter, notNullValue())
+            assertThat(adapter?.typeMirror(), `is`(tDate))
+            val bindScope = testCodeGenScope()
+            adapter!!.readFromCursor("outDate", "curs", "0", bindScope)
+            assertThat(bindScope.generate().trim(), `is`("""
+                final java.lang.Long _tmp;
+                if (curs.isNull(0)) {
+                  _tmp = null;
+                } else {
+                  _tmp = curs.getLong(0);
+                }
+                // convert Long to Date;
+            """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testIntList() {
+        singleRun { invocation ->
+            val binders = createIntListToStringBinders(invocation)
+            val store = TypeAdapterStore.create(Context(invocation.processingEnv), binders[0],
+                    binders[1])
+
+            val adapter = store.findColumnTypeAdapter(binders[0].from, null)
+            assertThat(adapter, notNullValue())
+
+            val bindScope = testCodeGenScope()
+            adapter!!.bindToStmt("stmt", "41", "fooVar", bindScope)
+            assertThat(bindScope.generate().trim(), `is`("""
+                final java.lang.String ${tmp(0)};
+                ${tmp(0)} = android.arch.persistence.room.util.StringUtil.joinIntoString(fooVar);
+                if (${tmp(0)} == null) {
+                  stmt.bindNull(41);
+                } else {
+                  stmt.bindString(41, ${tmp(0)});
+                }
+                """.trimIndent()))
+
+            val converter = store.findTypeConverter(binders[0].from,
+                    invocation.context.COMMON_TYPES.STRING)
+            assertThat(converter, notNullValue())
+            assertThat(store.reverse(converter!!), `is`(binders[1]))
+
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testOneWayConversion() {
+        singleRun { invocation ->
+            val binders = createIntListToStringBinders(invocation)
+            val store = TypeAdapterStore.create(Context(invocation.processingEnv), binders[0])
+            val adapter = store.findColumnTypeAdapter(binders[0].from, null)
+            assertThat(adapter, nullValue())
+
+            val stmtBinder = store.findStatementValueBinder(binders[0].from, null)
+            assertThat(stmtBinder, notNullValue())
+
+            val converter = store.findTypeConverter(binders[0].from,
+                    invocation.context.COMMON_TYPES.STRING)
+            assertThat(converter, notNullValue())
+            assertThat(store.reverse(converter!!), nullValue())
+        }
+    }
+
+    @Test
+    fun testMissingRxRoom() {
+        simpleRun(jfos = *arrayOf(COMMON.PUBLISHER, COMMON.FLOWABLE)) { invocation ->
+            val publisherElement = invocation.processingEnv.elementUtils
+                    .getTypeElement(ReactiveStreamsTypeNames.PUBLISHER.toString())
+            assertThat(publisherElement, notNullValue())
+            assertThat(FlowableQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(publisherElement.asType())), `is`(true))
+        }.failsToCompile().withErrorContaining(ProcessorErrors.MISSING_ROOM_RXJAVA2_ARTIFACT)
+    }
+
+    @Test
+    fun testFindPublisher() {
+        simpleRun(jfos = *arrayOf(COMMON.PUBLISHER, COMMON.FLOWABLE, COMMON.RX2_ROOM)) {
+            invocation ->
+            val publisher = invocation.processingEnv.elementUtils
+                    .getTypeElement(ReactiveStreamsTypeNames.PUBLISHER.toString())
+            assertThat(publisher, notNullValue())
+            assertThat(FlowableQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(publisher.asType())), `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testFindFlowable() {
+        simpleRun(jfos = *arrayOf(COMMON.PUBLISHER, COMMON.FLOWABLE, COMMON.RX2_ROOM)) {
+            invocation ->
+            val flowable = invocation.processingEnv.elementUtils
+                    .getTypeElement(RxJava2TypeNames.FLOWABLE.toString())
+            assertThat(flowable, notNullValue())
+            assertThat(FlowableQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(flowable.asType())), `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testFindLiveData() {
+        simpleRun(jfos = *arrayOf(COMMON.COMPUTABLE_LIVE_DATA, COMMON.LIVE_DATA)) {
+            invocation ->
+            val liveData = invocation.processingEnv.elementUtils
+                    .getTypeElement(LifecyclesTypeNames.LIVE_DATA.toString())
+            assertThat(liveData, notNullValue())
+            assertThat(LiveDataQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(liveData.asType())), `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun findCountedDataSource() {
+        simpleRun {
+            invocation ->
+            val countedDataSource = invocation.processingEnv.elementUtils
+                    .getTypeElement(CountedDataSource::class.java.canonicalName)
+            assertThat(countedDataSource, notNullValue())
+            assertThat(CountedDataSourceQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(countedDataSource.asType())), `is`(true))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun findLazyListProvider() {
+        simpleRun(jfos = COMMON.LIVE_LAZY_LIST_PROVIDER) {
+            invocation ->
+            val lazyListProvider = invocation.processingEnv.elementUtils
+                    .getTypeElement(PagingTypeNames.LIVE_LAZY_LIST_PROVIDER.toString())
+            assertThat(lazyListProvider, notNullValue())
+            assertThat(LiveLazyListQueryResultBinderProvider(invocation.context).matches(
+                    MoreTypes.asDeclared(lazyListProvider.asType())), `is`(true))
+        }.compilesWithoutError()
+    }
+
+    private fun createIntListToStringBinders(invocation: TestInvocation): List<TypeConverter> {
+        val intType = invocation.processingEnv.elementUtils
+                .getTypeElement(Integer::class.java.canonicalName)
+                .asType()
+        val listType = invocation.processingEnv.elementUtils
+                .getTypeElement(java.util.List::class.java.canonicalName)
+        val listOfInts = invocation.processingEnv.typeUtils.getDeclaredType(listType, intType)
+
+        val intListConverter = object : TypeConverter(listOfInts,
+                invocation.context.COMMON_TYPES.STRING) {
+            override fun convert(inputVarName: String, outputVarName: String,
+                                 scope: CodeGenScope) {
+                scope.builder().apply {
+                    addStatement("$L = $T.joinIntoString($L)", outputVarName, STRING_UTIL,
+                            inputVarName)
+                }
+            }
+        }
+
+        val stringToIntListConverter = object : TypeConverter(
+                invocation.context.COMMON_TYPES.STRING, listOfInts) {
+            override fun convert(inputVarName: String, outputVarName: String,
+                                 scope: CodeGenScope) {
+                scope.builder().apply {
+                    addStatement("$L = $T.splitToIntList($L)", outputVarName, STRING_UTIL,
+                            inputVarName)
+                }
+            }
+        }
+        return listOf(intListConverter, stringToIntListConverter)
+    }
+
+    fun singleRun(handler: (TestInvocation) -> Unit): CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.DummyClass",
+                        """
+                        package foo.bar;
+                        import android.arch.persistence.room.*;
+                        @Entity
+                        public class DummyClass {}
+                        """
+                ), JavaFileObjects.forSourceString("foo.bar.Point",
+                        """
+                        package foo.bar;
+                        import android.arch.persistence.room.*;
+                        @Entity
+                        public class Point {
+                            public int x, y;
+                            public Point(int x, int y) {
+                                this.x = x;
+                                this.y = y;
+                            }
+                            public static Point fromBoolean(boolean val) {
+                                return val ? new Point(1, 1) : new Point(0, 0);
+                            }
+                            public static boolean toBoolean(Point point) {
+                                return point.x > 0;
+                            }
+                        }
+                        """
+                )))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(Entity::class)
+                        .nextRunHandler { invocation ->
+                            handler(invocation)
+                            true
+                        }
+                        .build())
+    }
+
+    fun pointTypeConverters(env: ProcessingEnvironment): List<TypeConverter> {
+        val tPoint = env.elementUtils.getTypeElement("foo.bar.Point").asType()
+        val tBoolean = env.typeUtils.getPrimitiveType(TypeKind.BOOLEAN)
+        return listOf(
+                object : TypeConverter(tPoint, tBoolean) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().apply {
+                            addStatement("$L = $T.toBoolean($L)", outputVarName, from, inputVarName)
+                        }
+                    }
+
+                },
+                object : TypeConverter(tBoolean, tPoint) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().apply {
+                            addStatement("$L = $T.fromBoolean($L)", outputVarName, tPoint,
+                                    inputVarName)
+                        }
+                    }
+                }
+        )
+    }
+
+    fun dateTypeConverters(env: ProcessingEnvironment): List<TypeConverter> {
+        val tDate = env.elementUtils.getTypeElement("java.util.Date").asType()
+        val tLong = env.elementUtils.getTypeElement("java.lang.Long").asType()
+        return listOf(
+                object : TypeConverter(tDate, tLong) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().apply {
+                            addStatement("// convert Date to Long")
+                        }
+                    }
+
+                },
+                object : TypeConverter(tLong, tDate) {
+                    override fun convert(inputVarName: String, outputVarName: String,
+                                         scope: CodeGenScope) {
+                        scope.builder().apply {
+                            addStatement("// convert Long to Date")
+                        }
+                    }
+                }
+        )
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/query/QueryWriterTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/query/QueryWriterTest.kt
new file mode 100644
index 0000000..6401d96
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/solver/query/QueryWriterTest.kt
@@ -0,0 +1,310 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.solver.query
+
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.ext.RoomTypeNames.ROOM_SQL_QUERY
+import android.arch.persistence.room.ext.RoomTypeNames.STRING_UTIL
+import android.arch.persistence.room.processor.QueryMethodProcessor
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.writer.QueryWriter
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourceSubjectFactory
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import testCodeGenScope
+
+@RunWith(JUnit4::class)
+class QueryWriterTest {
+    companion object {
+        const val DAO_PREFIX = """
+                package foo.bar;
+                import android.arch.persistence.room.*;
+                import java.util.*;
+                @Dao
+                abstract class MyClass {
+                """
+        const val DAO_SUFFIX = "}"
+        val QUERY = ROOM_SQL_QUERY.toString()
+    }
+
+    @Test
+    fun simpleNoArgQuery() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users")
+                abstract java.util.List<Integer> selectAllIds();
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`("""
+                    final java.lang.String _sql = "SELECT id FROM users";
+                    final $QUERY _stmt = $QUERY.acquire(_sql, 0);
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun simpleStringArgs() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE name LIKE :name")
+                abstract java.util.List<Integer> selectAllIds(String name);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`(
+                    """
+                    final java.lang.String _sql = "SELECT id FROM users WHERE name LIKE ?";
+                    final $QUERY _stmt = $QUERY.acquire(_sql, 1);
+                    int _argIndex = 1;
+                    if (name == null) {
+                      _stmt.bindNull(_argIndex);
+                    } else {
+                      _stmt.bindString(_argIndex, name);
+                    }
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun twoIntArgs() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE id IN(:id1,:id2)")
+                abstract java.util.List<Integer> selectAllIds(int id1, int id2);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`(
+                    """
+                    final java.lang.String _sql = "SELECT id FROM users WHERE id IN(?,?)";
+                    final $QUERY _stmt = $QUERY.acquire(_sql, 2);
+                    int _argIndex = 1;
+                    _stmt.bindLong(_argIndex, id1);
+                    _argIndex = 2;
+                    _stmt.bindLong(_argIndex, id2);
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun aLongAndIntVarArg() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
+                abstract java.util.List<Integer> selectAllIds(long time, int... ids);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`(
+                    """
+                    java.lang.StringBuilder _stringBuilder = $STRING_UTIL.newStringBuilder();
+                    _stringBuilder.append("SELECT id FROM users WHERE id IN(");
+                    final int _inputSize = ids.length;
+                    $STRING_UTIL.appendPlaceholders(_stringBuilder, _inputSize);
+                    _stringBuilder.append(") AND age > ");
+                    _stringBuilder.append("?");
+                    final java.lang.String _sql = _stringBuilder.toString();
+                    final int _argCount = 1 + _inputSize;
+                    final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
+                    int _argIndex = 1;
+                    for (int _item : ids) {
+                      _stmt.bindLong(_argIndex, _item);
+                      _argIndex ++;
+                    }
+                    _argIndex = 1 + _inputSize;
+                    _stmt.bindLong(_argIndex, time);
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    val collectionOut = """
+                    java.lang.StringBuilder _stringBuilder = $STRING_UTIL.newStringBuilder();
+                    _stringBuilder.append("SELECT id FROM users WHERE id IN(");
+                    final int _inputSize = ids.size();
+                    $STRING_UTIL.appendPlaceholders(_stringBuilder, _inputSize);
+                    _stringBuilder.append(") AND age > ");
+                    _stringBuilder.append("?");
+                    final java.lang.String _sql = _stringBuilder.toString();
+                    final int _argCount = 1 + _inputSize;
+                    final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
+                    int _argIndex = 1;
+                    for (java.lang.Integer _item : ids) {
+                      if (_item == null) {
+                        _stmt.bindNull(_argIndex);
+                      } else {
+                        _stmt.bindLong(_argIndex, _item);
+                      }
+                      _argIndex ++;
+                    }
+                    _argIndex = 1 + _inputSize;
+                    _stmt.bindLong(_argIndex, time);
+                    """.trimIndent()
+
+    @Test
+    fun aLongAndIntegerList() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
+                abstract List<Integer> selectAllIds(long time, List<Integer> ids);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`(collectionOut))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun aLongAndIntegerSet() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
+                abstract List<Integer> selectAllIds(long time, Set<Integer> ids);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`(collectionOut))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testMultipleBindParamsWithSameName() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE age > :age OR bage > :age")
+                abstract List<Integer> selectAllIds(int age);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`("""
+                    final java.lang.String _sql = "SELECT id FROM users WHERE age > ? OR bage > ?";
+                    final $QUERY _stmt = $QUERY.acquire(_sql, 2);
+                    int _argIndex = 1;
+                    _stmt.bindLong(_argIndex, age);
+                    _argIndex = 2;
+                    _stmt.bindLong(_argIndex, age);
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testMultipleBindParamsWithSameNameWithVarArg() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE age > :age OR bage > :age OR fage IN(:ages)")
+                abstract List<Integer> selectAllIds(int age, int... ages);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`("""
+                    java.lang.StringBuilder _stringBuilder = $STRING_UTIL.newStringBuilder();
+                    _stringBuilder.append("SELECT id FROM users WHERE age > ");
+                    _stringBuilder.append("?");
+                    _stringBuilder.append(" OR bage > ");
+                    _stringBuilder.append("?");
+                    _stringBuilder.append(" OR fage IN(");
+                    final int _inputSize = ages.length;
+                    $STRING_UTIL.appendPlaceholders(_stringBuilder, _inputSize);
+                    _stringBuilder.append(")");
+                    final java.lang.String _sql = _stringBuilder.toString();
+                    final int _argCount = 2 + _inputSize;
+                    final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
+                    int _argIndex = 1;
+                    _stmt.bindLong(_argIndex, age);
+                    _argIndex = 2;
+                    _stmt.bindLong(_argIndex, age);
+                    _argIndex = 3;
+                    for (int _item : ages) {
+                      _stmt.bindLong(_argIndex, _item);
+                      _argIndex ++;
+                    }
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun testMultipleBindParamsWithSameNameWithVarArgInTwoBindings() {
+        singleQueryMethod("""
+                @Query("SELECT id FROM users WHERE age IN (:ages) OR bage > :age OR fage IN(:ages)")
+                abstract List<Integer> selectAllIds(int age, int... ages);
+                """) { writer ->
+            val scope = testCodeGenScope()
+            writer.prepareReadAndBind("_sql", "_stmt", scope)
+            assertThat(scope.generate().trim(), `is`("""
+                    java.lang.StringBuilder _stringBuilder = $STRING_UTIL.newStringBuilder();
+                    _stringBuilder.append("SELECT id FROM users WHERE age IN (");
+                    final int _inputSize = ages.length;
+                    $STRING_UTIL.appendPlaceholders(_stringBuilder, _inputSize);
+                    _stringBuilder.append(") OR bage > ");
+                    _stringBuilder.append("?");
+                    _stringBuilder.append(" OR fage IN(");
+                    final int _inputSize_1 = ages.length;
+                    $STRING_UTIL.appendPlaceholders(_stringBuilder, _inputSize_1);
+                    _stringBuilder.append(")");
+                    final java.lang.String _sql = _stringBuilder.toString();
+                    final int _argCount = 1 + _inputSize + _inputSize_1;
+                    final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
+                    int _argIndex = 1;
+                    for (int _item : ages) {
+                      _stmt.bindLong(_argIndex, _item);
+                      _argIndex ++;
+                    }
+                    _argIndex = 1 + _inputSize;
+                    _stmt.bindLong(_argIndex, age);
+                    _argIndex = 2 + _inputSize;
+                    for (int _item_1 : ages) {
+                      _stmt.bindLong(_argIndex, _item_1);
+                      _argIndex ++;
+                    }
+                    """.trimIndent()))
+        }.compilesWithoutError()
+    }
+
+    fun singleQueryMethod(vararg input: String,
+                          handler: (QueryWriter) -> Unit):
+            CompileTester {
+        return Truth.assertAbout(JavaSourceSubjectFactory.javaSource())
+                .that(JavaFileObjects.forSourceString("foo.bar.MyClass",
+                        DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX
+                ))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(Query::class, Dao::class)
+                        .nextRunHandler { invocation ->
+                            val (owner, methods) = invocation.roundEnv
+                                    .getElementsAnnotatedWith(Dao::class.java)
+                                    .map {
+                                        Pair(it,
+                                                invocation.processingEnv.elementUtils
+                                                        .getAllMembers(MoreElements.asType(it))
+                                                        .filter {
+                                                            MoreElements.isAnnotationPresent(it,
+                                                                    Query::class.java)
+                                                        }
+                                        )
+                                    }.filter { it.second.isNotEmpty() }.first()
+                            val parser = QueryMethodProcessor(
+                                    baseContext = invocation.context,
+                                    containing = MoreTypes.asDeclared(owner.asType()),
+                                    executableElement = MoreElements.asExecutable(methods.first()))
+                            val parsedQuery = parser.process()
+                            handler(QueryWriter(parsedQuery))
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/InProcessorTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/InProcessorTest.kt
new file mode 100644
index 0000000..31e1209
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/InProcessorTest.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.testing
+
+import android.arch.persistence.room.Query
+import com.google.common.truth.Truth
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourceSubjectFactory
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import java.util.concurrent.atomic.AtomicBoolean
+
+@RunWith(JUnit4::class)
+class InProcessorTest {
+    @Test
+    fun testInProcessorTestRuns() {
+        val didRun = AtomicBoolean(false)
+        Truth.assertAbout(JavaSourceSubjectFactory.javaSource())
+                .that(JavaFileObjects.forSourceString("foo.bar.MyClass",
+                        """
+                        package foo.bar;
+                        abstract public class MyClass {
+                        @android.arch.persistence.room.Query("foo")
+                        abstract public void setFoo(String foo);
+                        }
+                        """))
+                .processedWith(TestProcessor.builder()
+                        .nextRunHandler { invocation ->
+                            didRun.set(true)
+                            assertThat(invocation.annotations.size, `is`(1))
+                            true
+                        }
+                        .forAnnotations(Query::class)
+                        .build())
+                .compilesWithoutError()
+        assertThat(didRun.get(), `is`(true))
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestInvocation.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestInvocation.kt
new file mode 100644
index 0000000..b97628e
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestInvocation.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.testing
+
+import android.arch.persistence.room.processor.Context
+import javax.annotation.processing.ProcessingEnvironment
+import javax.annotation.processing.RoundEnvironment
+import javax.lang.model.element.TypeElement
+
+data class TestInvocation(val processingEnv: ProcessingEnvironment,
+                          val annotations: MutableSet<out TypeElement>,
+                          val roundEnv: RoundEnvironment) {
+    val context = Context(processingEnv)
+
+    fun typeElement(qName: String) : TypeElement {
+        return processingEnv.elementUtils.getTypeElement(qName)
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestProcessor.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestProcessor.kt
new file mode 100644
index 0000000..16c0048
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/TestProcessor.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.testing
+
+import javax.annotation.processing.AbstractProcessor
+import javax.annotation.processing.RoundEnvironment
+import javax.annotation.processing.SupportedSourceVersion
+import javax.lang.model.SourceVersion
+import javax.lang.model.element.TypeElement
+import kotlin.reflect.KClass
+
+@SupportedSourceVersion(SourceVersion.RELEASE_8)// test are compiled w/ J_8
+class TestProcessor(val handlers: List<(TestInvocation) -> Boolean>,
+                    val annotations: MutableSet<String>) : AbstractProcessor() {
+    var count = 0
+    override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment)
+            : Boolean {
+        return handlers.getOrNull(count++)?.invoke(
+                    TestInvocation(processingEnv, annotations, roundEnv)) ?: true
+    }
+
+    override fun getSupportedAnnotationTypes(): MutableSet<String> {
+        return annotations
+    }
+
+    class Builder {
+        private var handlers = arrayListOf<(TestInvocation) -> Boolean>()
+        private var annotations = mutableSetOf<String>()
+        fun nextRunHandler(f: (TestInvocation) -> Boolean): Builder {
+            handlers.add(f)
+            return this
+        }
+
+        fun forAnnotations(vararg klasses: KClass<*>): Builder {
+            annotations.addAll(klasses.map { it.java.canonicalName })
+            return this
+        }
+
+        fun build(): TestProcessor {
+            if (annotations.isEmpty()) {
+                throw IllegalStateException("must provide at least 1 annotation")
+            }
+            if (handlers.isEmpty()) {
+                throw IllegalStateException("must provide at least 1 handler")
+            }
+            return TestProcessor(handlers, annotations)
+        }
+    }
+
+    companion object {
+        fun builder(): Builder = Builder()
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/test_util.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/test_util.kt
new file mode 100644
index 0000000..cd30c21
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/testing/test_util.kt
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+import android.arch.persistence.room.ColumnInfo
+import android.arch.persistence.room.Embedded
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.PrimaryKey
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.Relation
+import android.arch.persistence.room.ext.LifecyclesTypeNames
+import android.arch.persistence.room.ext.PagingTypeNames
+import android.arch.persistence.room.ext.ReactiveStreamsTypeNames
+import android.arch.persistence.room.ext.RoomRxJava2TypeNames
+import android.arch.persistence.room.ext.RxJava2TypeNames
+import android.arch.persistence.room.processor.EntityProcessor
+import android.arch.persistence.room.solver.CodeGenScope
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.verifier.DatabaseVerifier
+import android.arch.persistence.room.writer.ClassWriter
+import com.google.auto.common.MoreElements
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import com.squareup.javapoet.ClassName
+import org.mockito.Mockito
+import org.mockito.Mockito.doReturn
+import org.mockito.Mockito.mock
+import java.io.File
+import javax.lang.model.element.Element
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+import javax.tools.JavaFileObject
+
+object COMMON {
+    val USER by lazy {
+        loadJavaCode("common/input/User.java", "foo.bar.User")
+    }
+    val USER_TYPE_NAME by lazy {
+        ClassName.get("foo.bar", "User")
+    }
+    val BOOK by lazy {
+        loadJavaCode("common/input/Book.java", "foo.bar.Book")
+    }
+    val NOT_AN_ENTITY by lazy {
+        loadJavaCode("common/input/NotAnEntity.java", "foo.bar.NotAnEntity")
+    }
+
+    val NOT_AN_ENTITY_TYPE_NAME by lazy {
+        ClassName.get("foo.bar", "NotAnEntity")
+    }
+
+    val MULTI_PKEY_ENTITY by lazy {
+        loadJavaCode("common/input/MultiPKeyEntity.java", "MultiPKeyEntity")
+    }
+    val LIVE_DATA by lazy {
+        loadJavaCode("common/input/LiveData.java", LifecyclesTypeNames.LIVE_DATA.toString())
+    }
+    val COMPUTABLE_LIVE_DATA by lazy {
+        loadJavaCode("common/input/ComputableLiveData.java",
+                LifecyclesTypeNames.COMPUTABLE_LIVE_DATA.toString())
+    }
+    val PUBLISHER by lazy {
+        loadJavaCode("common/input/reactivestreams/Publisher.java",
+                ReactiveStreamsTypeNames.PUBLISHER.toString())
+    }
+    val FLOWABLE by lazy {
+        loadJavaCode("common/input/rxjava2/Flowable.java", RxJava2TypeNames.FLOWABLE.toString())
+    }
+
+    val RX2_ROOM by lazy {
+        loadJavaCode("common/input/Rx2Room.java", RoomRxJava2TypeNames.RX_ROOM.toString())
+    }
+
+    val LIVE_LAZY_LIST_PROVIDER by lazy {
+        loadJavaCode("common/input/LiveLazyListProvider.java",
+                PagingTypeNames.LIVE_LAZY_LIST_PROVIDER.toString())
+    }
+}
+fun testCodeGenScope(): CodeGenScope {
+    return CodeGenScope(Mockito.mock(ClassWriter::class.java))
+}
+
+fun simpleRun(vararg jfos : JavaFileObject, f: (TestInvocation) -> Unit): CompileTester {
+    return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+            .that(jfos.toList() + JavaFileObjects.forSourceString("foo.bar.MyClass",
+                    """
+                    package foo.bar;
+                    abstract public class MyClass {
+                    @android.arch.persistence.room.Query("foo")
+                    abstract public void setFoo(String foo);
+                    }
+                    """))
+            .processedWith(TestProcessor.builder()
+                    .nextRunHandler {
+                        f(it)
+                        true
+                    }
+                    .forAnnotations(Query::class, PrimaryKey::class, Embedded::class,
+                            ColumnInfo::class, Relation::class, Entity::class)
+                    .build())
+}
+
+fun loadJavaCode(fileName : String, qName : String) : JavaFileObject {
+    val contents = File("src/test/data/$fileName").readText(Charsets.UTF_8)
+    return JavaFileObjects.forSourceString(qName, contents)
+}
+
+fun createVerifierFromEntities(invocation: TestInvocation) : DatabaseVerifier {
+    val entities = invocation.roundEnv.getElementsAnnotatedWith(Entity::class.java).map {
+        EntityProcessor(invocation.context, MoreElements.asType(it)).process()
+    }
+    return DatabaseVerifier.create(invocation.context, Mockito.mock(Element::class.java),
+            entities)!!
+}
+
+/**
+ * Create mocks of [Element] and [TypeMirror] so that they can be used for instantiating a fake
+ * [android.arch.persistence.room.vo.Field].
+ */
+fun mockElementAndType(): Pair<Element, TypeMirror> {
+    val element = mock(Element::class.java)
+    val type = mock(TypeMirror::class.java)
+    doReturn(TypeKind.DECLARED).`when`(type).kind
+    doReturn(type).`when`(element).asType()
+    return element to type
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/verifier/DatabaseVerifierTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/verifier/DatabaseVerifierTest.kt
new file mode 100644
index 0000000..604c50f
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/verifier/DatabaseVerifierTest.kt
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.verifier
+
+import collect
+import columnNames
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import android.arch.persistence.room.processor.Context
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.vo.CallType
+import android.arch.persistence.room.vo.Constructor
+import android.arch.persistence.room.vo.Database
+import android.arch.persistence.room.vo.Entity
+import android.arch.persistence.room.vo.Field
+import android.arch.persistence.room.vo.FieldGetter
+import android.arch.persistence.room.vo.FieldSetter
+import android.arch.persistence.room.vo.PrimaryKey
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.hasItem
+import org.hamcrest.CoreMatchers.notNullValue
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.mockito.Mockito.doReturn
+import org.mockito.Mockito.mock
+import simpleRun
+import java.sql.Connection
+import javax.lang.model.element.Element
+import javax.lang.model.element.ExecutableElement
+import javax.lang.model.element.TypeElement
+import javax.lang.model.type.DeclaredType
+import javax.lang.model.type.PrimitiveType
+import javax.lang.model.type.TypeKind
+import javax.lang.model.type.TypeMirror
+
+@RunWith(JUnit4::class)
+class DatabaseVerifierTest {
+    @Test
+    fun testSimpleDatabase() {
+        simpleRun { invocation ->
+            val verifier = createVerifier(invocation)
+            val stmt = verifier.connection.createStatement()
+            val rs = stmt.executeQuery("select * from sqlite_master WHERE type='table'")
+            assertThat(
+                    rs.collect { set -> set.getString("name") }, hasItem(`is`("User")))
+            val table = verifier.connection.prepareStatement("select * from User")
+            assertThat(table.columnNames(), `is`(listOf("id", "name", "lastName", "ratio")))
+
+            assertThat(getPrimaryKeys(verifier.connection, "User"), `is`(listOf("id")))
+        }.compilesWithoutError()
+    }
+
+    fun createVerifier(invocation: TestInvocation): DatabaseVerifier {
+        return DatabaseVerifier.create(invocation.context, mock(Element::class.java),
+                userDb(invocation.context).entities)!!
+    }
+
+    @Test
+    fun testFullEntityQuery() {
+        validQueryTest("select * from User") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            ColumnInfo("id", SQLTypeAffinity.INTEGER),
+                            ColumnInfo("name", SQLTypeAffinity.TEXT),
+                            ColumnInfo("lastName", SQLTypeAffinity.TEXT),
+                            ColumnInfo("ratio", SQLTypeAffinity.REAL)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testPartialFields() {
+        validQueryTest("select id, lastName from User") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            ColumnInfo("id", SQLTypeAffinity.INTEGER),
+                            ColumnInfo("lastName", SQLTypeAffinity.TEXT)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testRenamedField() {
+        validQueryTest("select id as myId, lastName from User") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            ColumnInfo("myId", SQLTypeAffinity.INTEGER),
+                            ColumnInfo("lastName", SQLTypeAffinity.TEXT)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testGrouped() {
+        validQueryTest("select MAX(ratio) from User GROUP BY name") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            // unfortunately, we don't get this information
+                            ColumnInfo("MAX(ratio)", SQLTypeAffinity.NULL)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testConcat() {
+        validQueryTest("select name || lastName as mergedName from User") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            // unfortunately, we don't get this information
+                            ColumnInfo("mergedName", SQLTypeAffinity.NULL)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testResultWithArgs() {
+        validQueryTest("select id, name || lastName as mergedName from User where name LIKE ?") {
+            assertThat(it, `is`(
+                    QueryResultInfo(listOf(
+                            // unfortunately, we don't get this information
+                            ColumnInfo("id", SQLTypeAffinity.INTEGER),
+                            ColumnInfo("mergedName", SQLTypeAffinity.NULL)
+                    ))))
+        }
+    }
+
+    @Test
+    fun testDeleteQuery() {
+        validQueryTest("delete from User where name LIKE ?") {
+            assertThat(it, `is`(QueryResultInfo(emptyList())))
+        }
+    }
+
+    @Test
+    fun testUpdateQuery() {
+        validQueryTest("update User set name = ? WHERE id = ?") {
+            assertThat(it, `is`(QueryResultInfo(emptyList())))
+        }
+    }
+
+    @Test
+    fun testBadQuery() {
+        simpleRun { invocation ->
+            val verifier = createVerifier(invocation)
+            val (columns, error) = verifier.analyze("select foo from User")
+            assertThat(error, notNullValue())
+        }.compilesWithoutError()
+    }
+
+    private fun validQueryTest(sql: String, cb: (QueryResultInfo) -> Unit) {
+        simpleRun { invocation ->
+            val verifier = createVerifier(invocation)
+            val info = verifier.analyze(sql)
+            cb(info)
+        }.compilesWithoutError()
+    }
+
+    private fun userDb(context: Context): Database {
+        return database(entity("User",
+                field("id", primitive(context, TypeKind.INT), SQLTypeAffinity.INTEGER),
+                field("name", context.COMMON_TYPES.STRING, SQLTypeAffinity.TEXT),
+                field("lastName", context.COMMON_TYPES.STRING, SQLTypeAffinity.TEXT),
+                field("ratio", primitive(context, TypeKind.FLOAT), SQLTypeAffinity.REAL)))
+    }
+
+    private fun database(vararg entities: Entity): Database {
+        return Database(
+                element = mock(TypeElement::class.java),
+                type = mock(TypeMirror::class.java),
+                entities = entities.toList(),
+                daoMethods = emptyList(),
+                version = -1,
+                exportSchema = false,
+                enableForeignKeys = false)
+    }
+
+    private fun entity(tableName: String, vararg fields: Field): Entity {
+        return Entity(
+                element = mock(TypeElement::class.java),
+                tableName = tableName,
+                type = mock(DeclaredType::class.java),
+                fields = fields.toList(),
+                embeddedFields = emptyList(),
+                indices = emptyList(),
+                primaryKey = PrimaryKey(null, fields.take(1), false),
+                foreignKeys = emptyList(),
+                constructor = Constructor(mock(ExecutableElement::class.java), emptyList())
+        )
+    }
+
+    private fun field(name: String, type: TypeMirror, affinity: SQLTypeAffinity): Field {
+        val element = mock(Element::class.java)
+        doReturn(type).`when`(element).asType()
+        val f = Field(
+                element = element,
+                name = name,
+                type = type,
+                columnName = name,
+                affinity = affinity
+        )
+        assignGetterSetter(f, name, type)
+        return f
+    }
+
+    private fun assignGetterSetter(f: Field, name: String, type: TypeMirror) {
+        f.getter = FieldGetter(name, type, CallType.FIELD)
+        f.setter = FieldSetter(name, type, CallType.FIELD)
+    }
+
+    private fun primitive(context: Context, kind: TypeKind): PrimitiveType {
+        return context.processingEnv.typeUtils.getPrimitiveType(kind)
+    }
+
+    private fun getPrimaryKeys(connection: Connection, tableName: String): List<String> {
+        val stmt = connection.createStatement()
+        val resultSet = stmt.executeQuery("PRAGMA table_info($tableName)")
+        return resultSet.collect {
+            Pair(it.getString("name"), it.getInt("pk"))
+        }
+                .filter { it.second > 0 }
+                .sortedBy { it.second }
+                .map { it.first }
+
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/vo/IndexTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/vo/IndexTest.kt
new file mode 100644
index 0000000..c1ac029
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/vo/IndexTest.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.vo
+
+import android.arch.persistence.room.parser.SQLTypeAffinity
+import mockElementAndType
+import org.hamcrest.CoreMatchers
+import org.hamcrest.MatcherAssert
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class IndexTest {
+    @Test
+    fun createSimpleSQL() {
+        val index = Index("foo", false, listOf(mockField("bar"), mockField("baz")))
+        MatcherAssert.assertThat(index.createQuery("my_table"), CoreMatchers.`is`(
+                "CREATE  INDEX `foo` ON `my_table` (`bar`, `baz`)"
+        ))
+    }
+
+    @Test
+    fun createUnique() {
+        val index = Index("foo", true, listOf(mockField("bar"), mockField("baz")))
+        MatcherAssert.assertThat(index.createQuery("my_table"), CoreMatchers.`is`(
+                "CREATE UNIQUE INDEX `foo` ON `my_table` (`bar`, `baz`)"
+        ))
+    }
+
+    private fun mockField(columnName : String): Field {
+        val (element, type) = mockElementAndType()
+        return Field(
+                element = element,
+                name = columnName + "_field",
+                affinity = SQLTypeAffinity.TEXT,
+                type = type,
+                columnName = columnName
+        )
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DaoWriterTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DaoWriterTest.kt
new file mode 100644
index 0000000..6d2bda3
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DaoWriterTest.kt
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import COMMON
+import android.arch.persistence.room.ext.RoomTypeNames
+import android.arch.persistence.room.processor.DaoProcessor
+import android.arch.persistence.room.testing.TestProcessor
+import com.google.auto.common.MoreElements
+import com.google.auto.common.MoreTypes
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import createVerifierFromEntities
+import loadJavaCode
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.tools.JavaFileObject
+
+@RunWith(JUnit4::class)
+class DaoWriterTest {
+    @Test
+    fun complexDao() {
+        singleDao(
+                loadJavaCode("databasewriter/input/ComplexDatabase.java",
+                        "foo.bar.ComplexDatabase"),
+                loadJavaCode("daoWriter/input/ComplexDao.java", "foo.bar.ComplexDao")
+        ).compilesWithoutError().and().generatesSources(
+                loadJavaCode("daoWriter/output/ComplexDao.java", "foo.bar.ComplexDao_Impl")
+        )
+    }
+
+    @Test
+    fun writerDao() {
+        singleDao(
+                loadJavaCode("daoWriter/input/WriterDao.java", "foo.bar.WriterDao")
+        ).compilesWithoutError().and().generatesSources(
+                loadJavaCode("daoWriter/output/WriterDao.java", "foo.bar.WriterDao_Impl")
+        )
+    }
+
+    @Test
+    fun deletionDao() {
+        singleDao(
+                loadJavaCode("daoWriter/input/DeletionDao.java", "foo.bar.DeletionDao")
+        ).compilesWithoutError().and().generatesSources(
+                loadJavaCode("daoWriter/output/DeletionDao.java", "foo.bar.DeletionDao_Impl")
+        )
+    }
+
+    @Test
+    fun updateDao() {
+        singleDao(
+                loadJavaCode("daoWriter/input/UpdateDao.java", "foo.bar.UpdateDao")
+        ).compilesWithoutError().and().generatesSources(
+                loadJavaCode("daoWriter/output/UpdateDao.java", "foo.bar.UpdateDao_Impl")
+        )
+    }
+
+    fun singleDao(vararg jfo : JavaFileObject): CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(jfo.toList() + COMMON.USER + COMMON.MULTI_PKEY_ENTITY + COMMON.BOOK +
+                        COMMON.LIVE_DATA + COMMON.COMPUTABLE_LIVE_DATA)
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Dao::class)
+                        .nextRunHandler { invocation ->
+                            val dao = invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Dao::class.java)
+                                    .first()
+                            val db = invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Database::class.java)
+                                    .firstOrNull()
+                            val dbType = MoreTypes.asDeclared(if (db != null) {
+                                db.asType()
+                            } else {
+                                invocation.context.processingEnv.elementUtils
+                                        .getTypeElement(RoomTypeNames.ROOM_DB.toString()).asType()
+                            })
+                            val parser = DaoProcessor(
+                                    baseContext = invocation.context,
+                                    element = MoreElements.asType(dao),
+                                    dbType = dbType,
+                                    dbVerifier = createVerifierFromEntities(invocation))
+                            val parsedDao = parser.process()
+                            DaoWriter(parsedDao, invocation.processingEnv)
+                                    .write(invocation.processingEnv)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DatabaseWriterTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DatabaseWriterTest.kt
new file mode 100644
index 0000000..9a3252f
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/DatabaseWriterTest.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import COMMON
+import android.arch.persistence.room.RoomProcessor
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import loadJavaCode
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.tools.JavaFileObject
+
+@RunWith(JUnit4::class)
+class DatabaseWriterTest {
+    @Test
+    fun simpleDb() {
+        singleDb(
+                loadJavaCode("databasewriter/input/ComplexDatabase.java",
+                        "foo.bar.ComplexDatabase"),
+                loadJavaCode("daoWriter/input/ComplexDao.java",
+                        "foo.bar.ComplexDao")
+        ).compilesWithoutError().and().generatesSources(
+                loadJavaCode("databasewriter/output/ComplexDatabase.java",
+                        "foo.bar.ComplexDatabase_Impl")
+        )
+    }
+
+    private fun singleDb(vararg jfo : JavaFileObject): CompileTester {
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(jfo.toList() + COMMON.USER +  COMMON.LIVE_DATA + COMMON.COMPUTABLE_LIVE_DATA)
+                .processedWith(RoomProcessor())
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriterTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriterTest.kt
new file mode 100644
index 0000000..aaa6b2e
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/EntityCursorConverterWriterTest.kt
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.processor.BaseEntityParserTest
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.squareup.javapoet.ClassName
+import com.squareup.javapoet.TypeSpec
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import javax.lang.model.element.Modifier
+
+@RunWith(JUnit4::class)
+class EntityCursorConverterWriterTest : BaseEntityParserTest() {
+    companion object {
+        val OUT_PREFIX = """
+            package foo.bar;
+            import android.database.Cursor;
+            public class MyContainerClass {
+            """.trimIndent()
+        const val OUT_SUFFIX = "}"
+    }
+
+    @Test
+    fun generateSimple() {
+        generateAndMatch(
+                """
+                @PrimaryKey
+                private int id;
+                String name;
+                String lastName;
+                int age;
+                public int getId() { return id; }
+                public void setId(int id) { this.id = id; }
+                """,
+                """
+                private MyEntity __entityCursorConverter_fooBarMyEntity(Cursor cursor) {
+                  final MyEntity _entity;
+                  final int _cursorIndexOfId = cursor.getColumnIndex("id");
+                  final int _cursorIndexOfName = cursor.getColumnIndex("name");
+                  final int _cursorIndexOfLastName = cursor.getColumnIndex("lastName");
+                  final int _cursorIndexOfAge = cursor.getColumnIndex("age");
+                  _entity = new MyEntity();
+                  if (_cursorIndexOfId != -1) {
+                    final int _tmpId;
+                    _tmpId = cursor.getInt(_cursorIndexOfId);
+                    _entity.setId(_tmpId);
+                  }
+                  if (_cursorIndexOfName != -1) {
+                    _entity.name = cursor.getString(_cursorIndexOfName);
+                  }
+                  if (_cursorIndexOfLastName != -1) {
+                    _entity.lastName = cursor.getString(_cursorIndexOfLastName);
+                  }
+                  if (_cursorIndexOfAge != -1) {
+                    _entity.age = cursor.getInt(_cursorIndexOfAge);
+                  }
+                  return _entity;
+                }
+                """.trimIndent())
+    }
+
+    fun generateAndMatch(input: String, output : String,
+                         attributes: Map<String, String> = mapOf()) {
+        generate(input, attributes)
+                .compilesWithoutError()
+                .and()
+                .generatesSources(JavaFileObjects.forSourceString(
+                        "foo.bar.MyEntity_CursorConverter",
+                        listOf(OUT_PREFIX,output,OUT_SUFFIX).joinToString("\n")))
+    }
+
+    fun generate(input: String, attributes: Map<String, String> = mapOf()) : CompileTester {
+        return singleEntity(input, attributes) { entity, invocation ->
+            val className = ClassName.get("foo.bar","MyContainerClass")
+            val writer = object : ClassWriter(className){
+                override fun createTypeSpecBuilder(): TypeSpec.Builder {
+                    getOrCreateMethod(EntityCursorConverterWriter(entity))
+                    return TypeSpec.classBuilder(className).apply {
+                        addModifiers(Modifier.PUBLIC)
+                    }
+                }
+            }
+            writer.write(invocation.processingEnv)
+        }
+    }
+}
diff --git a/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriterTest.kt b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriterTest.kt
new file mode 100644
index 0000000..26efb4b
--- /dev/null
+++ b/room/compiler/src/test/kotlin/android/arch/persistence/room/writer/SQLiteOpenHelperWriterTest.kt
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.writer
+
+import android.arch.persistence.room.processor.DatabaseProcessor
+import android.arch.persistence.room.testing.TestInvocation
+import android.arch.persistence.room.testing.TestProcessor
+import android.arch.persistence.room.vo.Database
+import com.google.auto.common.MoreElements
+import com.google.common.truth.Truth
+import com.google.testing.compile.CompileTester
+import com.google.testing.compile.JavaFileObjects
+import com.google.testing.compile.JavaSourcesSubjectFactory
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class SQLiteOpenHelperWriterTest {
+    companion object {
+        const val ENTITY_PREFIX = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            @Entity%s
+            public class MyEntity {
+            """
+        const val ENTITY_SUFFIX = "}"
+        const val DATABASE_CODE = """
+            package foo.bar;
+            import android.arch.persistence.room.*;
+            @Database(entities = {MyEntity.class}, version = 3)
+            abstract public class MyDatabase extends RoomDatabase {
+            }
+            """
+    }
+
+    @Test
+    fun createSimpleEntity() {
+        singleEntity(
+                """
+                @PrimaryKey
+                String uuid;
+                String name;
+                int age;
+                """.trimIndent()
+        ) { database, invocation ->
+            val query = SQLiteOpenHelperWriter(database)
+                    .createQuery(database.entities.first())
+            assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +
+                    " `MyEntity` (`uuid` TEXT, `name` TEXT, `age` INTEGER NOT NULL," +
+                    " PRIMARY KEY(`uuid`))"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun multiplePrimaryKeys() {
+        singleEntity(
+                """
+                String uuid;
+                String name;
+                int age;
+                """.trimIndent(), attributes = mapOf("primaryKeys" to "{\"uuid\", \"name\"}")
+        ) { database, invocation ->
+            val query = SQLiteOpenHelperWriter(database)
+                    .createQuery(database.entities.first())
+            assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +
+                    " `MyEntity` (`uuid` TEXT, `name` TEXT, `age` INTEGER NOT NULL," +
+                    " PRIMARY KEY(`uuid`, `name`))"))
+        }.compilesWithoutError()
+    }
+
+    @Test
+    fun autoIncrement() {
+        singleEntity(
+                """
+                @PrimaryKey(autoGenerate = true)
+                int uuid;
+                String name;
+                int age;
+                """.trimIndent()
+        ) { database, invocation ->
+            val query = SQLiteOpenHelperWriter(database)
+                    .createQuery(database.entities.first())
+            assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +
+                    " `MyEntity` (`uuid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
+                    " `name` TEXT, `age` INTEGER NOT NULL)"))
+        }.compilesWithoutError()
+    }
+
+    fun singleEntity(input: String, attributes: Map<String, String> = mapOf(),
+                     handler: (Database, TestInvocation) -> Unit): CompileTester {
+        val attributesReplacement : String
+        if (attributes.isEmpty()) {
+            attributesReplacement = ""
+        } else {
+            attributesReplacement = "(" +
+                    attributes.entries.map { "${it.key} = ${it.value}" }.joinToString(",") +
+                    ")".trimIndent()
+        }
+        return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
+                .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyEntity",
+                        ENTITY_PREFIX.format(attributesReplacement) + input + ENTITY_SUFFIX
+                ), JavaFileObjects.forSourceString("foo.bar.MyDatabase",
+                        DATABASE_CODE)))
+                .processedWith(TestProcessor.builder()
+                        .forAnnotations(android.arch.persistence.room.Database::class)
+                        .nextRunHandler { invocation ->
+                            val db = MoreElements.asType(invocation.roundEnv
+                                    .getElementsAnnotatedWith(
+                                            android.arch.persistence.room.Database::class.java)
+                                    .first())
+                            handler(DatabaseProcessor(invocation.context, db).process(), invocation)
+                            true
+                        }
+                        .build())
+    }
+}
diff --git a/room/db-impl/.gitignore b/room/db-impl/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/room/db-impl/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/room/db-impl/build.gradle b/room/db-impl/build.gradle
new file mode 100644
index 0000000..978681d
--- /dev/null
+++ b/room/db-impl/build.gradle
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+archivesBaseName = "support-db-impl"
+
+dependencies {
+    compile libs.support.annotations
+    compile project(":room:db")
+}
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    def jarTask = project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/room/db-impl/proguard-rules.pro b/room/db-impl/proguard-rules.pro
new file mode 100644
index 0000000..b7210d1
--- /dev/null
+++ b/room/db-impl/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/yboyar/android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
diff --git a/room/db-impl/src/main/AndroidManifest.xml b/room/db-impl/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..9350b90
--- /dev/null
+++ b/room/db-impl/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.db.framework">
+</manifest>
diff --git a/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteDatabase.java b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteDatabase.java
new file mode 100644
index 0000000..92a5820
--- /dev/null
+++ b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteDatabase.java
@@ -0,0 +1,320 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db.framework;
+
+import android.arch.persistence.db.SimpleSQLiteQuery;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteQuery;
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.SQLException;
+import android.database.sqlite.SQLiteCursor;
+import android.database.sqlite.SQLiteCursorDriver;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteQuery;
+import android.database.sqlite.SQLiteTransactionListener;
+import android.os.Build;
+import android.os.CancellationSignal;
+import android.support.annotation.RequiresApi;
+import android.util.Pair;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Delegates all calls to an implementation of {@link SQLiteDatabase}.
+ */
+@SuppressWarnings("unused")
+class FrameworkSQLiteDatabase implements SupportSQLiteDatabase {
+    private static final String[] CONFLICT_VALUES = new String[]
+            {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
+    private static final String[] EMPTY_STRING_ARRAY = new String[0];
+
+    private final SQLiteDatabase mDelegate;
+
+    /**
+     * Creates a wrapper around {@link SQLiteDatabase}.
+     *
+     * @param delegate The delegate to receive all calls.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public FrameworkSQLiteDatabase(SQLiteDatabase delegate) {
+        mDelegate = delegate;
+    }
+
+    @Override
+    public SupportSQLiteStatement compileStatement(String sql) {
+        return new FrameworkSQLiteStatement(mDelegate.compileStatement(sql));
+    }
+
+    @Override
+    public void beginTransaction() {
+        mDelegate.beginTransaction();
+    }
+
+    @Override
+    public void beginTransactionNonExclusive() {
+        mDelegate.beginTransactionNonExclusive();
+    }
+
+    @Override
+    public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
+        mDelegate.beginTransactionWithListener(transactionListener);
+    }
+
+    @Override
+    public void beginTransactionWithListenerNonExclusive(
+            SQLiteTransactionListener transactionListener) {
+        mDelegate.beginTransactionWithListenerNonExclusive(transactionListener);
+    }
+
+    @Override
+    public void endTransaction() {
+        mDelegate.endTransaction();
+    }
+
+    @Override
+    public void setTransactionSuccessful() {
+        mDelegate.setTransactionSuccessful();
+    }
+
+    @Override
+    public boolean inTransaction() {
+        return mDelegate.inTransaction();
+    }
+
+    @Override
+    public boolean isDbLockedByCurrentThread() {
+        return mDelegate.isDbLockedByCurrentThread();
+    }
+
+    @Override
+    public boolean yieldIfContendedSafely() {
+        return mDelegate.yieldIfContendedSafely();
+    }
+
+    @Override
+    public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
+        return mDelegate.yieldIfContendedSafely(sleepAfterYieldDelay);
+    }
+
+    @Override
+    public int getVersion() {
+        return mDelegate.getVersion();
+    }
+
+    @Override
+    public void setVersion(int version) {
+        mDelegate.setVersion(version);
+    }
+
+    @Override
+    public long getMaximumSize() {
+        return mDelegate.getMaximumSize();
+    }
+
+    @Override
+    public long setMaximumSize(long numBytes) {
+        return mDelegate.setMaximumSize(numBytes);
+    }
+
+    @Override
+    public long getPageSize() {
+        return mDelegate.getPageSize();
+    }
+
+    @Override
+    public void setPageSize(long numBytes) {
+        mDelegate.setPageSize(numBytes);
+    }
+
+    @Override
+    public Cursor query(String query) {
+        return query(new SimpleSQLiteQuery(query));
+    }
+
+    @Override
+    public Cursor query(String query, Object[] bindArgs) {
+        return query(new SimpleSQLiteQuery(query, bindArgs));
+    }
+
+
+    @Override
+    public Cursor query(final SupportSQLiteQuery supportQuery) {
+        return mDelegate.rawQueryWithFactory(new SQLiteDatabase.CursorFactory() {
+            @Override
+            public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
+                    String editTable, SQLiteQuery query) {
+                supportQuery.bindTo(new FrameworkSQLiteProgram(query));
+                return new SQLiteCursor(masterQuery, editTable, query);
+            }
+        }, supportQuery.getSql(), EMPTY_STRING_ARRAY, null);
+    }
+
+    @Override
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    public Cursor query(final SupportSQLiteQuery supportQuery,
+            CancellationSignal cancellationSignal) {
+        return mDelegate.rawQueryWithFactory(new SQLiteDatabase.CursorFactory() {
+            @Override
+            public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
+                    String editTable, SQLiteQuery query) {
+                supportQuery.bindTo(new FrameworkSQLiteProgram(query));
+                return new SQLiteCursor(masterQuery, editTable, query);
+            }
+        }, supportQuery.getSql(), EMPTY_STRING_ARRAY, null, cancellationSignal);
+    }
+
+    @Override
+    public long insert(String table, int conflictAlgorithm, ContentValues values)
+            throws SQLException {
+        return mDelegate.insertWithOnConflict(table, null, values,
+                conflictAlgorithm);
+    }
+
+    @Override
+    public int delete(String table, String whereClause, Object[] whereArgs) {
+        String query = "DELETE FROM " + table
+                + (isEmpty(whereClause) ? "" : " WHERE " + whereClause);
+        SupportSQLiteStatement statement = compileStatement(query);
+        SimpleSQLiteQuery.bind(statement, whereArgs);
+        return statement.executeUpdateDelete();
+    }
+
+
+    @Override
+    public int update(String table, int conflictAlgorithm, ContentValues values, String whereClause,
+            Object[] whereArgs) {
+        // taken from SQLiteDatabase class.
+        if (values == null || values.size() == 0) {
+            throw new IllegalArgumentException("Empty values");
+        }
+        StringBuilder sql = new StringBuilder(120);
+        sql.append("UPDATE ");
+        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
+        sql.append(table);
+        sql.append(" SET ");
+
+        // move all bind args to one array
+        int setValuesSize = values.size();
+        int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
+        Object[] bindArgs = new Object[bindArgsSize];
+        int i = 0;
+        for (String colName : values.keySet()) {
+            sql.append((i > 0) ? "," : "");
+            sql.append(colName);
+            bindArgs[i++] = values.get(colName);
+            sql.append("=?");
+        }
+        if (whereArgs != null) {
+            for (i = setValuesSize; i < bindArgsSize; i++) {
+                bindArgs[i] = whereArgs[i - setValuesSize];
+            }
+        }
+        if (!isEmpty(whereClause)) {
+            sql.append(" WHERE ");
+            sql.append(whereClause);
+        }
+        SupportSQLiteStatement stmt = compileStatement(sql.toString());
+        SimpleSQLiteQuery.bind(stmt, bindArgs);
+        return stmt.executeUpdateDelete();
+    }
+
+    @Override
+    public void execSQL(String sql) throws SQLException {
+        mDelegate.execSQL(sql);
+    }
+
+    @Override
+    public void execSQL(String sql, Object[] bindArgs) throws SQLException {
+        mDelegate.execSQL(sql, bindArgs);
+    }
+
+    @Override
+    public boolean isReadOnly() {
+        return mDelegate.isReadOnly();
+    }
+
+    @Override
+    public boolean isOpen() {
+        return mDelegate.isOpen();
+    }
+
+    @Override
+    public boolean needUpgrade(int newVersion) {
+        return mDelegate.needUpgrade(newVersion);
+    }
+
+    @Override
+    public String getPath() {
+        return mDelegate.getPath();
+    }
+
+    @Override
+    public void setLocale(Locale locale) {
+        mDelegate.setLocale(locale);
+    }
+
+    @Override
+    public void setMaxSqlCacheSize(int cacheSize) {
+        mDelegate.setMaxSqlCacheSize(cacheSize);
+    }
+
+    @Override
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    public void setForeignKeyConstraintsEnabled(boolean enable) {
+        mDelegate.setForeignKeyConstraintsEnabled(enable);
+    }
+
+    @Override
+    public boolean enableWriteAheadLogging() {
+        return mDelegate.enableWriteAheadLogging();
+    }
+
+    @Override
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    public void disableWriteAheadLogging() {
+        mDelegate.disableWriteAheadLogging();
+    }
+
+    @Override
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    public boolean isWriteAheadLoggingEnabled() {
+        return mDelegate.isWriteAheadLoggingEnabled();
+    }
+
+    @Override
+    public List<Pair<String, String>> getAttachedDbs() {
+        return mDelegate.getAttachedDbs();
+    }
+
+    @Override
+    public boolean isDatabaseIntegrityOk() {
+        return mDelegate.isDatabaseIntegrityOk();
+    }
+
+    @Override
+    public void close() throws IOException {
+        mDelegate.close();
+    }
+
+    private static boolean isEmpty(String input) {
+        return input == null || input.length() == 0;
+    }
+}
diff --git a/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelper.java b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelper.java
new file mode 100644
index 0000000..aa08fa4
--- /dev/null
+++ b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelper.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db.framework;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.content.Context;
+import android.database.DatabaseErrorHandler;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.os.Build;
+import android.support.annotation.RequiresApi;
+
+class FrameworkSQLiteOpenHelper implements SupportSQLiteOpenHelper {
+    private final OpenHelper mDelegate;
+
+    FrameworkSQLiteOpenHelper(Context context, String name, int version,
+            DatabaseErrorHandler errorHandler,
+            SupportSQLiteOpenHelper.Callback callback) {
+        mDelegate = createDelegate(context, name, version, errorHandler, callback);
+    }
+
+    private OpenHelper createDelegate(Context context, String name,
+            int version, DatabaseErrorHandler errorHandler,
+            final Callback callback) {
+        return new OpenHelper(context, name, null, version, errorHandler) {
+            @Override
+            public void onCreate(SQLiteDatabase sqLiteDatabase) {
+                mWrappedDb = new FrameworkSQLiteDatabase(sqLiteDatabase);
+                callback.onCreate(mWrappedDb);
+            }
+
+            @Override
+            public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
+                callback.onUpgrade(getWrappedDb(sqLiteDatabase), oldVersion, newVersion);
+            }
+
+            @Override
+            public void onConfigure(SQLiteDatabase db) {
+                callback.onConfigure(getWrappedDb(db));
+            }
+
+            @Override
+            public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+                callback.onDowngrade(getWrappedDb(db), oldVersion, newVersion);
+            }
+
+            @Override
+            public void onOpen(SQLiteDatabase db) {
+                callback.onOpen(getWrappedDb(db));
+            }
+        };
+    }
+
+    @Override
+    public String getDatabaseName() {
+        return mDelegate.getDatabaseName();
+    }
+
+    @Override
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    public void setWriteAheadLoggingEnabled(boolean enabled) {
+        mDelegate.setWriteAheadLoggingEnabled(enabled);
+    }
+
+    @Override
+    public SupportSQLiteDatabase getWritableDatabase() {
+        return mDelegate.getWritableSupportDatabase();
+    }
+
+    @Override
+    public SupportSQLiteDatabase getReadableDatabase() {
+        return mDelegate.getReadableSupportDatabase();
+    }
+
+    @Override
+    public void close() {
+        mDelegate.close();
+    }
+
+    abstract static class OpenHelper extends SQLiteOpenHelper {
+
+        FrameworkSQLiteDatabase mWrappedDb;
+
+        OpenHelper(Context context, String name,
+                SQLiteDatabase.CursorFactory factory, int version,
+                DatabaseErrorHandler errorHandler) {
+            super(context, name, factory, version, errorHandler);
+        }
+
+        SupportSQLiteDatabase getWritableSupportDatabase() {
+            SQLiteDatabase db = super.getWritableDatabase();
+            return getWrappedDb(db);
+        }
+
+        SupportSQLiteDatabase getReadableSupportDatabase() {
+            SQLiteDatabase db = super.getReadableDatabase();
+            return getWrappedDb(db);
+        }
+
+        FrameworkSQLiteDatabase getWrappedDb(SQLiteDatabase sqLiteDatabase) {
+            if (mWrappedDb == null) {
+                mWrappedDb = new FrameworkSQLiteDatabase(sqLiteDatabase);
+            }
+            return mWrappedDb;
+        }
+
+        @Override
+        public synchronized void close() {
+            super.close();
+            mWrappedDb = null;
+        }
+    }
+}
diff --git a/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelperFactory.java b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelperFactory.java
new file mode 100644
index 0000000..7b4245b
--- /dev/null
+++ b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteOpenHelperFactory.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db.framework;
+
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+
+/**
+ * Implements {@link SupportSQLiteOpenHelper.Factory} using the SQLite implementation in the
+ * framework.
+ */
+@SuppressWarnings("unused")
+public class FrameworkSQLiteOpenHelperFactory implements SupportSQLiteOpenHelper.Factory {
+    @Override
+    public SupportSQLiteOpenHelper create(SupportSQLiteOpenHelper.Configuration configuration) {
+        return new FrameworkSQLiteOpenHelper(
+                configuration.context, configuration.name,
+                configuration.version, configuration.errorHandler, configuration.callback
+        );
+    }
+}
diff --git a/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteProgram.java b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteProgram.java
new file mode 100644
index 0000000..6c2bb72
--- /dev/null
+++ b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteProgram.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.db.framework;
+
+import android.arch.persistence.db.SupportSQLiteProgram;
+import android.database.sqlite.SQLiteProgram;
+
+/**
+ * An wrapper around {@link SQLiteProgram} to implement {@link SupportSQLiteProgram} API.
+ */
+class FrameworkSQLiteProgram implements SupportSQLiteProgram {
+    private final SQLiteProgram mDelegate;
+
+    FrameworkSQLiteProgram(SQLiteProgram delegate) {
+        mDelegate = delegate;
+    }
+
+    @Override
+    public void bindNull(int index) {
+        mDelegate.bindNull(index);
+    }
+
+    @Override
+    public void bindLong(int index, long value) {
+        mDelegate.bindLong(index, value);
+    }
+
+    @Override
+    public void bindDouble(int index, double value) {
+        mDelegate.bindDouble(index, value);
+    }
+
+    @Override
+    public void bindString(int index, String value) {
+        mDelegate.bindString(index, value);
+    }
+
+    @Override
+    public void bindBlob(int index, byte[] value) {
+        mDelegate.bindBlob(index, value);
+    }
+
+    @Override
+    public void clearBindings() {
+        mDelegate.clearBindings();
+    }
+
+    @Override
+    public void close() throws Exception {
+        mDelegate.close();
+    }
+}
diff --git a/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteStatement.java b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteStatement.java
new file mode 100644
index 0000000..a2daf12
--- /dev/null
+++ b/room/db-impl/src/main/java/android/arch/persistence/db/framework/FrameworkSQLiteStatement.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db.framework;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.database.sqlite.SQLiteStatement;
+
+/**
+ * Delegates all calls to a {@link SQLiteStatement}.
+ */
+class FrameworkSQLiteStatement implements SupportSQLiteStatement {
+    private final SQLiteStatement mDelegate;
+
+    /**
+     * Creates a wrapper around a framework {@link SQLiteStatement}.
+     *
+     * @param delegate The SQLiteStatement to delegate calls to.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public FrameworkSQLiteStatement(SQLiteStatement delegate) {
+        mDelegate = delegate;
+    }
+
+    @Override
+    public void bindNull(int index) {
+        mDelegate.bindNull(index);
+    }
+
+    @Override
+    public void bindLong(int index, long value) {
+        mDelegate.bindLong(index, value);
+    }
+
+    @Override
+    public void bindDouble(int index, double value) {
+        mDelegate.bindDouble(index, value);
+    }
+
+    @Override
+    public void bindString(int index, String value) {
+        mDelegate.bindString(index, value);
+    }
+
+    @Override
+    public void bindBlob(int index, byte[] value) {
+        mDelegate.bindBlob(index, value);
+    }
+
+    @Override
+    public void clearBindings() {
+        mDelegate.clearBindings();
+    }
+
+    @Override
+    public void execute() {
+        mDelegate.execute();
+    }
+
+    @Override
+    public int executeUpdateDelete() {
+        return mDelegate.executeUpdateDelete();
+    }
+
+    @Override
+    public long executeInsert() {
+        return mDelegate.executeInsert();
+    }
+
+    @Override
+    public long simpleQueryForLong() {
+        return mDelegate.simpleQueryForLong();
+    }
+
+    @Override
+    public String simpleQueryForString() {
+        return mDelegate.simpleQueryForString();
+    }
+
+    @Override
+    public void close() throws Exception {
+        mDelegate.close();
+    }
+}
diff --git a/room/db/build.gradle b/room/db/build.gradle
new file mode 100644
index 0000000..d495bb8
--- /dev/null
+++ b/room/db/build.gradle
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+archivesBaseName = "support-db"
+
+dependencies {
+    compile libs.support.annotations
+}
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    def jarTask = project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/room/db/src/main/AndroidManifest.xml b/room/db/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..8a27324
--- /dev/null
+++ b/room/db/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.db">
+</manifest>
diff --git a/room/db/src/main/java/android/arch/persistence/db/SimpleSQLiteQuery.java b/room/db/src/main/java/android/arch/persistence/db/SimpleSQLiteQuery.java
new file mode 100644
index 0000000..b821176
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SimpleSQLiteQuery.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.db;
+
+/**
+ * A basic implemtation of {@link SupportSQLiteQuery} which receives a query and its args and binds
+ * args based on the passed in Object type.
+ */
+public class SimpleSQLiteQuery implements SupportSQLiteQuery {
+    private final String mQuery;
+    private final Object[] mBindArgs;
+
+    /**
+     * Creates an SQL query with the sql string and the bind arguments.
+     *
+     * @param query    The query string, can include bind arguments (.e.g ?).
+     * @param bindArgs The bind argument value that will replace the placeholders in the query.
+     */
+    public SimpleSQLiteQuery(String query, Object[] bindArgs) {
+        mQuery = query;
+        mBindArgs = bindArgs;
+    }
+
+    /**
+     * Creates an SQL query without any bind arguments.
+     *
+     * @param query The SQL query to execute. Cannot include bind parameters.
+     */
+    public SimpleSQLiteQuery(String query) {
+        this(query, null);
+    }
+
+    @Override
+    public String getSql() {
+        return mQuery;
+    }
+
+    @Override
+    public void bindTo(SupportSQLiteProgram statement) {
+        bind(statement, mBindArgs);
+    }
+
+    /**
+     * Binds the given arguments into the given sqlite statement.
+     *
+     * @param statement The sqlite statement
+     * @param bindArgs  The list of bind arguments
+     */
+    public static void bind(SupportSQLiteProgram statement, Object[] bindArgs) {
+        if (bindArgs == null) {
+            return;
+        }
+        final int limit = bindArgs.length;
+        for (int i = 0; i < limit; i++) {
+            final Object arg = bindArgs[i];
+            bind(statement, i + 1, arg);
+        }
+    }
+
+    private static void bind(SupportSQLiteProgram statement, int index, Object arg) {
+        // extracted from android.database.sqlite.SQLiteConnection
+        if (arg == null) {
+            statement.bindNull(index);
+        } else if (arg instanceof byte[]) {
+            statement.bindBlob(index, (byte[]) arg);
+        } else if (arg instanceof Float) {
+            statement.bindDouble(index, (Float) arg);
+        } else if (arg instanceof Double) {
+            statement.bindDouble(index, (Double) arg);
+        } else if (arg instanceof Long) {
+            statement.bindLong(index, (Long) arg);
+        } else if (arg instanceof Integer) {
+            statement.bindLong(index, (Integer) arg);
+        } else if (arg instanceof Short) {
+            statement.bindLong(index, (Short) arg);
+        } else if (arg instanceof Byte) {
+            statement.bindLong(index, (Byte) arg);
+        } else if (arg instanceof String) {
+            statement.bindString(index, (String) arg);
+        } else {
+            throw new IllegalArgumentException("Cannot bind " + arg + " at index " + index
+                    + " Supported types: null, byte[], float, double, long, int, short, byte,"
+                    + " string");
+        }
+    }
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteDatabase.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteDatabase.java
new file mode 100644
index 0000000..5f71baf
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteDatabase.java
@@ -0,0 +1,605 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db;
+
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.SQLException;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteTransactionListener;
+import android.os.Build;
+import android.os.CancellationSignal;
+import android.os.OperationCanceledException;
+import android.support.annotation.RequiresApi;
+import android.util.Pair;
+
+import java.io.Closeable;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * A database abstraction which removes the framework dependency and allows swapping underlying
+ * sql versions. It mimics the behavior of {@link android.database.sqlite.SQLiteDatabase}
+ */
+@SuppressWarnings("unused")
+public interface SupportSQLiteDatabase extends Closeable {
+    /**
+     * Compiles the given SQL statement.
+     *
+     * @param sql The sql query.
+     * @return Compiled statement.
+     */
+    SupportSQLiteStatement compileStatement(String sql);
+
+    /**
+     * Begins a transaction in EXCLUSIVE mode.
+     * <p>
+     * Transactions can be nested.
+     * When the outer transaction is ended all of
+     * the work done in that transaction and all of the nested transactions will be committed or
+     * rolled back. The changes will be rolled back if any transaction is ended without being
+     * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
+     * </p>
+     * <p>Here is the standard idiom for transactions:
+     *
+     * <pre>
+     *   db.beginTransaction();
+     *   try {
+     *     ...
+     *     db.setTransactionSuccessful();
+     *   } finally {
+     *     db.endTransaction();
+     *   }
+     * </pre>
+     */
+    void beginTransaction();
+
+    /**
+     * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
+     * the outer transaction is ended all of the work done in that transaction
+     * and all of the nested transactions will be committed or rolled back. The
+     * changes will be rolled back if any transaction is ended without being
+     * marked as clean (by calling setTransactionSuccessful). Otherwise they
+     * will be committed.
+     * <p>
+     * Here is the standard idiom for transactions:
+     *
+     * <pre>
+     *   db.beginTransactionNonExclusive();
+     *   try {
+     *     ...
+     *     db.setTransactionSuccessful();
+     *   } finally {
+     *     db.endTransaction();
+     *   }
+     * </pre>
+     */
+    void beginTransactionNonExclusive();
+
+    /**
+     * Begins a transaction in EXCLUSIVE mode.
+     * <p>
+     * Transactions can be nested.
+     * When the outer transaction is ended all of
+     * the work done in that transaction and all of the nested transactions will be committed or
+     * rolled back. The changes will be rolled back if any transaction is ended without being
+     * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
+     * </p>
+     * <p>Here is the standard idiom for transactions:
+     *
+     * <pre>
+     *   db.beginTransactionWithListener(listener);
+     *   try {
+     *     ...
+     *     db.setTransactionSuccessful();
+     *   } finally {
+     *     db.endTransaction();
+     *   }
+     * </pre>
+     *
+     * @param transactionListener listener that should be notified when the transaction begins,
+     *                            commits, or is rolled back, either explicitly or by a call to
+     *                            {@link #yieldIfContendedSafely}.
+     */
+    void beginTransactionWithListener(SQLiteTransactionListener transactionListener);
+
+    /**
+     * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
+     * the outer transaction is ended all of the work done in that transaction
+     * and all of the nested transactions will be committed or rolled back. The
+     * changes will be rolled back if any transaction is ended without being
+     * marked as clean (by calling setTransactionSuccessful). Otherwise they
+     * will be committed.
+     * <p>
+     * Here is the standard idiom for transactions:
+     *
+     * <pre>
+     *   db.beginTransactionWithListenerNonExclusive(listener);
+     *   try {
+     *     ...
+     *     db.setTransactionSuccessful();
+     *   } finally {
+     *     db.endTransaction();
+     *   }
+     * </pre>
+     *
+     * @param transactionListener listener that should be notified when the
+     *                            transaction begins, commits, or is rolled back, either
+     *                            explicitly or by a call to {@link #yieldIfContendedSafely}.
+     */
+    void beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener);
+
+    /**
+     * End a transaction. See beginTransaction for notes about how to use this and when transactions
+     * are committed and rolled back.
+     */
+    void endTransaction();
+
+    /**
+     * Marks the current transaction as successful. Do not do any more database work between
+     * calling this and calling endTransaction. Do as little non-database work as possible in that
+     * situation too. If any errors are encountered between this and endTransaction the transaction
+     * will still be committed.
+     *
+     * @throws IllegalStateException if the current thread is not in a transaction or the
+     *                               transaction is already marked as successful.
+     */
+    void setTransactionSuccessful();
+
+    /**
+     * Returns true if the current thread has a transaction pending.
+     *
+     * @return True if the current thread is in a transaction.
+     */
+    boolean inTransaction();
+
+    /**
+     * Returns true if the current thread is holding an active connection to the database.
+     * <p>
+     * The name of this method comes from a time when having an active connection
+     * to the database meant that the thread was holding an actual lock on the
+     * database.  Nowadays, there is no longer a true "database lock" although threads
+     * may block if they cannot acquire a database connection to perform a
+     * particular operation.
+     * </p>
+     *
+     * @return True if the current thread is holding an active connection to the database.
+     */
+    boolean isDbLockedByCurrentThread();
+
+    /**
+     * Temporarily end the transaction to let other threads run. The transaction is assumed to be
+     * successful so far. Do not call setTransactionSuccessful before calling this. When this
+     * returns a new transaction will have been created but not marked as successful. This assumes
+     * that there are no nested transactions (beginTransaction has only been called once) and will
+     * throw an exception if that is not the case.
+     *
+     * @return true if the transaction was yielded
+     */
+    boolean yieldIfContendedSafely();
+
+    /**
+     * Temporarily end the transaction to let other threads run. The transaction is assumed to be
+     * successful so far. Do not call setTransactionSuccessful before calling this. When this
+     * returns a new transaction will have been created but not marked as successful. This assumes
+     * that there are no nested transactions (beginTransaction has only been called once) and will
+     * throw an exception if that is not the case.
+     *
+     * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
+     *                             the lock was actually yielded. This will allow other background
+     *                             threads to make some
+     *                             more progress than they would if we started the transaction
+     *                             immediately.
+     * @return true if the transaction was yielded
+     */
+    boolean yieldIfContendedSafely(long sleepAfterYieldDelay);
+
+    /**
+     * Gets the database version.
+     *
+     * @return the database version
+     */
+    int getVersion();
+
+    /**
+     * Sets the database version.
+     *
+     * @param version the new database version
+     */
+    void setVersion(int version);
+
+    /**
+     * Returns the maximum size the database may grow to.
+     *
+     * @return the new maximum database size
+     */
+    long getMaximumSize();
+
+    /**
+     * Sets the maximum size the database will grow to. The maximum size cannot
+     * be set below the current size.
+     *
+     * @param numBytes the maximum database size, in bytes
+     * @return the new maximum database size
+     */
+    long setMaximumSize(long numBytes);
+
+    /**
+     * Returns the current database page size, in bytes.
+     *
+     * @return the database page size, in bytes
+     */
+    long getPageSize();
+
+    /**
+     * Sets the database page size. The page size must be a power of two. This
+     * method does not work if any data has been written to the database file,
+     * and must be called right after the database has been created.
+     *
+     * @param numBytes the database page size, in bytes
+     */
+    void setPageSize(long numBytes);
+
+    /**
+     * Runs the given query on the database. If you would like to have typed bind arguments,
+     * use {@link #query(SupportSQLiteQuery)}.
+     *
+     * @param query The SQL query that includes the query and can bind into a given compiled
+     *              program.
+     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
+     * {@link Cursor}s are not synchronized, see the documentation for more details.
+     * @see #query(SupportSQLiteQuery)
+     */
+    Cursor query(String query);
+
+    /**
+     * Runs the given query on the database. If you would like to have bind arguments,
+     * use {@link #query(SupportSQLiteQuery)}.
+     *
+     * @param query The SQL query that includes the query and can bind into a given compiled
+     *              program.
+     * @param bindArgs The query arguments to bind.
+     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
+     * {@link Cursor}s are not synchronized, see the documentation for more details.
+     * @see #query(SupportSQLiteQuery)
+     */
+    Cursor query(String query, Object[] bindArgs);
+
+    /**
+     * Runs the given query on the database.
+     * <p>
+     * This class allows using type safe sql program bindings while running queries.
+     *
+     * @param query The SQL query that includes the query and can bind into a given compiled
+     *              program.
+     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
+     * {@link Cursor}s are not synchronized, see the documentation for more details.
+     * @see SimpleSQLiteQuery
+     */
+    Cursor query(SupportSQLiteQuery query);
+
+    /**
+     * Runs the given query on the database.
+     * <p>
+     * This class allows using type safe sql program bindings while running queries.
+     *
+     * @param query The SQL query that includes the query and can bind into a given compiled
+     *              program.
+     * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
+     * If the operation is canceled, then {@link OperationCanceledException} will be thrown
+     * when the query is executed.
+     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
+     * {@link Cursor}s are not synchronized, see the documentation for more details.
+     */
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    Cursor query(SupportSQLiteQuery query, CancellationSignal cancellationSignal);
+
+    /**
+     * Convenience method for inserting a row into the database.
+     *
+     * @param table          the table to insert the row into
+     * @param values         this map contains the initial column values for the
+     *                       row. The keys should be the column names and the values the
+     *                       column values
+     * @param conflictAlgorithm for insert conflict resolver. One of
+     * {@link SQLiteDatabase#CONFLICT_NONE}, {@link SQLiteDatabase#CONFLICT_ROLLBACK},
+     * {@link SQLiteDatabase#CONFLICT_ABORT}, {@link SQLiteDatabase#CONFLICT_FAIL},
+     * {@link SQLiteDatabase#CONFLICT_IGNORE}, {@link SQLiteDatabase#CONFLICT_REPLACE}.
+     * @return the row ID of the newly inserted row, or -1 if an error occurred
+     * @throws SQLException If the insert fails
+     */
+    long insert(String table, int conflictAlgorithm, ContentValues values) throws SQLException;
+
+    /**
+     * Convenience method for deleting rows in the database.
+     *
+     * @param table       the table to delete from
+     * @param whereClause the optional WHERE clause to apply when deleting.
+     *                    Passing null will delete all rows.
+     * @param whereArgs   You may include ?s in the where clause, which
+     *                    will be replaced by the values from whereArgs. The values
+     *                    will be bound as Strings.
+     * @return the number of rows affected if a whereClause is passed in, 0
+     * otherwise. To remove all rows and get a count pass "1" as the
+     * whereClause.
+     */
+    int delete(String table, String whereClause, Object[] whereArgs);
+
+    /**
+     * Convenience method for updating rows in the database.
+     *
+     * @param table       the table to update in
+     * @param conflictAlgorithm for update conflict resolver. One of
+     * {@link SQLiteDatabase#CONFLICT_NONE}, {@link SQLiteDatabase#CONFLICT_ROLLBACK},
+     * {@link SQLiteDatabase#CONFLICT_ABORT}, {@link SQLiteDatabase#CONFLICT_FAIL},
+     * {@link SQLiteDatabase#CONFLICT_IGNORE}, {@link SQLiteDatabase#CONFLICT_REPLACE}.
+     * @param values      a map from column names to new column values. null is a
+     *                    valid value that will be translated to NULL.
+     * @param whereClause the optional WHERE clause to apply when updating.
+     *                    Passing null will update all rows.
+     * @param whereArgs   You may include ?s in the where clause, which
+     *                    will be replaced by the values from whereArgs. The values
+     *                    will be bound as Strings.
+     * @return the number of rows affected
+     */
+    int update(String table, int conflictAlgorithm,
+            ContentValues values, String whereClause, Object[] whereArgs);
+
+    /**
+     * Execute a single SQL statement that does not return any data.
+     * <p>
+     * When using {@link #enableWriteAheadLogging()}, journal_mode is
+     * automatically managed by this class. So, do not set journal_mode
+     * using "PRAGMA journal_mode'<value>" statement if your app is using
+     * {@link #enableWriteAheadLogging()}
+     * </p>
+     *
+     * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
+     *            not supported.
+     * @throws SQLException if the SQL string is invalid
+     * @see #query(SupportSQLiteQuery)
+     */
+    void execSQL(String sql) throws SQLException;
+
+    /**
+     * Execute a single SQL statement that does not return any data.
+     * <p>
+     * When using {@link #enableWriteAheadLogging()}, journal_mode is
+     * automatically managed by this class. So, do not set journal_mode
+     * using "PRAGMA journal_mode'<value>" statement if your app is using
+     * {@link #enableWriteAheadLogging()}
+     * </p>
+     *
+     * @param sql      the SQL statement to be executed. Multiple statements separated by semicolons
+     *                 are
+     *                 not supported.
+     * @param bindArgs only byte[], String, Long and Double are supported in selectionArgs.
+     * @throws SQLException if the SQL string is invalid
+     * @see #query(SupportSQLiteQuery)
+     */
+    void execSQL(String sql, Object[] bindArgs) throws SQLException;
+
+    /**
+     * Returns true if the database is opened as read only.
+     *
+     * @return True if database is opened as read only.
+     */
+    boolean isReadOnly();
+
+    /**
+     * Returns true if the database is currently open.
+     *
+     * @return True if the database is currently open (has not been closed).
+     */
+    boolean isOpen();
+
+    /**
+     * Returns true if the new version code is greater than the current database version.
+     *
+     * @param newVersion The new version code.
+     * @return True if the new version code is greater than the current database version.
+     */
+    boolean needUpgrade(int newVersion);
+
+    /**
+     * Gets the path to the database file.
+     *
+     * @return The path to the database file.
+     */
+    String getPath();
+
+    /**
+     * Sets the locale for this database.  Does nothing if this database has
+     * the {@link SQLiteDatabase#NO_LOCALIZED_COLLATORS} flag set or was opened read only.
+     *
+     * @param locale The new locale.
+     * @throws SQLException if the locale could not be set.  The most common reason
+     *                      for this is that there is no collator available for the locale you
+     *                      requested.
+     *                      In this case the database remains unchanged.
+     */
+    void setLocale(Locale locale);
+
+    /**
+     * Sets the maximum size of the prepared-statement cache for this database.
+     * (size of the cache = number of compiled-sql-statements stored in the cache).
+     * <p>
+     * Maximum cache size can ONLY be increased from its current size (default = 10).
+     * If this method is called with smaller size than the current maximum value,
+     * then IllegalStateException is thrown.
+     * <p>
+     * This method is thread-safe.
+     *
+     * @param cacheSize the size of the cache. can be (0 to
+     *                  {@link SQLiteDatabase#MAX_SQL_CACHE_SIZE})
+     * @throws IllegalStateException if input cacheSize gt;
+     *                               {@link SQLiteDatabase#MAX_SQL_CACHE_SIZE}.
+     */
+    void setMaxSqlCacheSize(int cacheSize);
+
+    /**
+     * Sets whether foreign key constraints are enabled for the database.
+     * <p>
+     * By default, foreign key constraints are not enforced by the database.
+     * This method allows an application to enable foreign key constraints.
+     * It must be called each time the database is opened to ensure that foreign
+     * key constraints are enabled for the session.
+     * </p><p>
+     * A good time to call this method is right after calling {@code #openOrCreateDatabase}
+     * or in the {@link SupportSQLiteOpenHelper.Callback#onConfigure} callback.
+     * </p><p>
+     * When foreign key constraints are disabled, the database does not check whether
+     * changes to the database will violate foreign key constraints.  Likewise, when
+     * foreign key constraints are disabled, the database will not execute cascade
+     * delete or update triggers.  As a result, it is possible for the database
+     * state to become inconsistent.  To perform a database integrity check,
+     * call {@link #isDatabaseIntegrityOk}.
+     * </p><p>
+     * This method must not be called while a transaction is in progress.
+     * </p><p>
+     * See also <a href="http://sqlite.org/foreignkeys.html">SQLite Foreign Key Constraints</a>
+     * for more details about foreign key constraint support.
+     * </p>
+     *
+     * @param enable True to enable foreign key constraints, false to disable them.
+     * @throws IllegalStateException if the are transactions is in progress
+     *                               when this method is called.
+     */
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    void setForeignKeyConstraintsEnabled(boolean enable);
+
+    /**
+     * This method enables parallel execution of queries from multiple threads on the
+     * same database.  It does this by opening multiple connections to the database
+     * and using a different database connection for each query.  The database
+     * journal mode is also changed to enable writes to proceed concurrently with reads.
+     * <p>
+     * When write-ahead logging is not enabled (the default), it is not possible for
+     * reads and writes to occur on the database at the same time.  Before modifying the
+     * database, the writer implicitly acquires an exclusive lock on the database which
+     * prevents readers from accessing the database until the write is completed.
+     * </p><p>
+     * In contrast, when write-ahead logging is enabled (by calling this method), write
+     * operations occur in a separate log file which allows reads to proceed concurrently.
+     * While a write is in progress, readers on other threads will perceive the state
+     * of the database as it was before the write began.  When the write completes, readers
+     * on other threads will then perceive the new state of the database.
+     * </p><p>
+     * It is a good idea to enable write-ahead logging whenever a database will be
+     * concurrently accessed and modified by multiple threads at the same time.
+     * However, write-ahead logging uses significantly more memory than ordinary
+     * journaling because there are multiple connections to the same database.
+     * So if a database will only be used by a single thread, or if optimizing
+     * concurrency is not very important, then write-ahead logging should be disabled.
+     * </p><p>
+     * After calling this method, execution of queries in parallel is enabled as long as
+     * the database remains open.  To disable execution of queries in parallel, either
+     * call {@link #disableWriteAheadLogging} or close the database and reopen it.
+     * </p><p>
+     * The maximum number of connections used to execute queries in parallel is
+     * dependent upon the device memory and possibly other properties.
+     * </p><p>
+     * If a query is part of a transaction, then it is executed on the same database handle the
+     * transaction was begun.
+     * </p><p>
+     * Writers should use {@link #beginTransactionNonExclusive()} or
+     * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
+     * to start a transaction.  Non-exclusive mode allows database file to be in readable
+     * by other threads executing queries.
+     * </p><p>
+     * If the database has any attached databases, then execution of queries in parallel is NOT
+     * possible.  Likewise, write-ahead logging is not supported for read-only databases
+     * or memory databases.  In such cases, {@code enableWriteAheadLogging} returns false.
+     * </p><p>
+     * The best way to enable write-ahead logging is to pass the
+     * {@link SQLiteDatabase#ENABLE_WRITE_AHEAD_LOGGING} flag to
+     * {@link SQLiteDatabase#openDatabase}.  This is more efficient than calling
+     * <code><pre>
+     *     SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
+     *             SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
+     *             myDatabaseErrorHandler);
+     *     db.enableWriteAheadLogging();
+     * </pre></code>
+     * </p><p>
+     * Another way to enable write-ahead logging is to call {@code enableWriteAheadLogging}
+     * after opening the database.
+     * <code><pre>
+     *     SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
+     *             SQLiteDatabase.CREATE_IF_NECESSARY, myDatabaseErrorHandler);
+     *     db.enableWriteAheadLogging();
+     * </pre></code>
+     * </p><p>
+     * See also <a href="http://sqlite.org/wal.html">SQLite Write-Ahead Logging</a> for
+     * more details about how write-ahead logging works.
+     * </p>
+     *
+     * @return True if write-ahead logging is enabled.
+     * @throws IllegalStateException if there are transactions in progress at the
+     *                               time this method is called.  WAL mode can only be changed when
+     *                               there are no
+     *                               transactions in progress.
+     * @see SQLiteDatabase#ENABLE_WRITE_AHEAD_LOGGING
+     * @see #disableWriteAheadLogging
+     */
+    boolean enableWriteAheadLogging();
+
+    /**
+     * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
+     *
+     * @throws IllegalStateException if there are transactions in progress at the
+     *                               time this method is called.  WAL mode can only be changed when
+     *                               there are no
+     *                               transactions in progress.
+     * @see #enableWriteAheadLogging
+     */
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    void disableWriteAheadLogging();
+
+    /**
+     * Returns true if write-ahead logging has been enabled for this database.
+     *
+     * @return True if write-ahead logging has been enabled for this database.
+     * @see #enableWriteAheadLogging
+     * @see SQLiteDatabase#ENABLE_WRITE_AHEAD_LOGGING
+     */
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    boolean isWriteAheadLoggingEnabled();
+
+    /**
+     * Returns list of full path names of all attached databases including the main database
+     * by executing 'pragma database_list' on the database.
+     *
+     * @return ArrayList of pairs of (database name, database file path) or null if the database
+     * is not open.
+     */
+    List<Pair<String, String>> getAttachedDbs();
+
+    /**
+     * Runs 'pragma integrity_check' on the given database (and all the attached databases)
+     * and returns true if the given database (and all its attached databases) pass integrity_check,
+     * false otherwise.
+     * <p>
+     * If the result is false, then this method logs the errors reported by the integrity_check
+     * command execution.
+     * <p>
+     * Note that 'pragma integrity_check' on a database can take a long time.
+     *
+     * @return true if the given database (and all its attached databases) pass integrity_check,
+     * false otherwise.
+     */
+    boolean isDatabaseIntegrityOk();
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteOpenHelper.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteOpenHelper.java
new file mode 100644
index 0000000..5a96e5a
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteOpenHelper.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db;
+
+import android.content.Context;
+import android.database.DatabaseErrorHandler;
+import android.database.DefaultDatabaseErrorHandler;
+import android.database.sqlite.SQLiteException;
+import android.os.Build;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
+
+/**
+ * An interface to map the behavior of {@link android.database.sqlite.SQLiteOpenHelper}.
+ * Note that since that class requires overriding certain methods, support implementation
+ * uses {@link Factory#create(Configuration)} to create this and {@link Callback} to implement
+ * the methods that should be overridden.
+ */
+@SuppressWarnings("unused")
+public interface SupportSQLiteOpenHelper {
+    /**
+     * Return the name of the SQLite database being opened, as given to
+     * the constructor.
+     */
+    String getDatabaseName();
+
+    /**
+     * Enables or disables the use of write-ahead logging for the database.
+     *
+     * Write-ahead logging cannot be used with read-only databases so the value of
+     * this flag is ignored if the database is opened read-only.
+     *
+     * @param enabled True if write-ahead logging should be enabled, false if it
+     *                should be disabled.
+     * @see SupportSQLiteDatabase#enableWriteAheadLogging()
+     */
+    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
+    void setWriteAheadLoggingEnabled(boolean enabled);
+
+    /**
+     * Create and/or open a database that will be used for reading and writing.
+     * The first time this is called, the database will be opened and
+     * {@link Callback#onCreate}, {@link Callback#onUpgrade} and/or {@link Callback#onOpen} will be
+     * called.
+     *
+     * <p>Once opened successfully, the database is cached, so you can
+     * call this method every time you need to write to the database.
+     * (Make sure to call {@link #close} when you no longer need the database.)
+     * Errors such as bad permissions or a full disk may cause this method
+     * to fail, but future attempts may succeed if the problem is fixed.</p>
+     *
+     * <p class="caution">Database upgrade may take a long time, you
+     * should not call this method from the application main thread, including
+     * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
+     *
+     * @return a read/write database object valid until {@link #close} is called
+     * @throws SQLiteException if the database cannot be opened for writing
+     */
+    SupportSQLiteDatabase getWritableDatabase();
+
+    /**
+     * Create and/or open a database.  This will be the same object returned by
+     * {@link #getWritableDatabase} unless some problem, such as a full disk,
+     * requires the database to be opened read-only.  In that case, a read-only
+     * database object will be returned.  If the problem is fixed, a future call
+     * to {@link #getWritableDatabase} may succeed, in which case the read-only
+     * database object will be closed and the read/write object will be returned
+     * in the future.
+     *
+     * <p class="caution">Like {@link #getWritableDatabase}, this method may
+     * take a long time to return, so you should not call it from the
+     * application main thread, including from
+     * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
+     *
+     * @return a database object valid until {@link #getWritableDatabase}
+     * or {@link #close} is called.
+     * @throws SQLiteException if the database cannot be opened
+     */
+    SupportSQLiteDatabase getReadableDatabase();
+
+    /**
+     * Close any open database object.
+     */
+    void close();
+
+    /**
+     * Matching callback methods from {@link android.database.sqlite.SQLiteOpenHelper}.
+     */
+    @SuppressWarnings({"unused", "WeakerAccess"})
+    abstract class Callback {
+        /**
+         * Called when the database connection is being configured, to enable features such as
+         * write-ahead logging or foreign key support.
+         * <p>
+         * This method is called before {@link #onCreate}, {@link #onUpgrade}, {@link #onDowngrade},
+         * or {@link #onOpen} are called. It should not modify the database except to configure the
+         * database connection as required.
+         * </p>
+         * <p>
+         * This method should only call methods that configure the parameters of the database
+         * connection, such as {@link SupportSQLiteDatabase#enableWriteAheadLogging}
+         * {@link SupportSQLiteDatabase#setForeignKeyConstraintsEnabled},
+         * {@link SupportSQLiteDatabase#setLocale},
+         * {@link SupportSQLiteDatabase#setMaximumSize}, or executing PRAGMA statements.
+         * </p>
+         *
+         * @param db The database.
+         */
+        public void onConfigure(SupportSQLiteDatabase db) {
+
+        }
+
+        /**
+         * Called when the database is created for the first time. This is where the
+         * creation of tables and the initial population of the tables should happen.
+         *
+         * @param db The database.
+         */
+        public abstract void onCreate(SupportSQLiteDatabase db);
+
+        /**
+         * Called when the database needs to be upgraded. The implementation
+         * should use this method to drop tables, add tables, or do anything else it
+         * needs to upgrade to the new schema version.
+         *
+         * <p>
+         * The SQLite ALTER TABLE documentation can be found
+         * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
+         * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
+         * you can use ALTER TABLE to rename the old table, then create the new table and then
+         * populate the new table with the contents of the old table.
+         * </p><p>
+         * This method executes within a transaction.  If an exception is thrown, all changes
+         * will automatically be rolled back.
+         * </p>
+         *
+         * @param db         The database.
+         * @param oldVersion The old database version.
+         * @param newVersion The new database version.
+         */
+        public abstract void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion);
+
+        /**
+         * Called when the database needs to be downgraded. This is strictly similar to
+         * {@link #onUpgrade} method, but is called whenever current version is newer than requested
+         * one.
+         * However, this method is not abstract, so it is not mandatory for a customer to
+         * implement it. If not overridden, default implementation will reject downgrade and
+         * throws SQLiteException
+         *
+         * <p>
+         * This method executes within a transaction.  If an exception is thrown, all changes
+         * will automatically be rolled back.
+         * </p>
+         *
+         * @param db         The database.
+         * @param oldVersion The old database version.
+         * @param newVersion The new database version.
+         */
+        public void onDowngrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) {
+            throw new SQLiteException("Can't downgrade database from version "
+                    + oldVersion + " to " + newVersion);
+        }
+
+        /**
+         * Called when the database has been opened.  The implementation
+         * should check {@link SupportSQLiteDatabase#isReadOnly} before updating the
+         * database.
+         * <p>
+         * This method is called after the database connection has been configured
+         * and after the database schema has been created, upgraded or downgraded as necessary.
+         * If the database connection must be configured in some way before the schema
+         * is created, upgraded, or downgraded, do it in {@link #onConfigure} instead.
+         * </p>
+         *
+         * @param db The database.
+         */
+        public void onOpen(SupportSQLiteDatabase db) {
+
+        }
+    }
+
+    /**
+     * The configuration to create an SQLite open helper object using {@link Factory}.
+     */
+    @SuppressWarnings("WeakerAccess")
+    class Configuration {
+        /**
+         * Context to use to open or create the database.
+         */
+        @NonNull
+        public final Context context;
+        /**
+         * Name of the database file, or null for an in-memory database.
+         */
+        @Nullable
+        public final String name;
+        /**
+         * Version number of the database (starting at 1); if the database is older,
+         * {@link SupportSQLiteOpenHelper.Callback#onUpgrade(SupportSQLiteDatabase, int, int)}
+         * will be used to upgrade the database; if the database is newer,
+         * {@link SupportSQLiteOpenHelper.Callback#onDowngrade(SupportSQLiteDatabase, int, int)}
+         * will be used to downgrade the database.
+         */
+        public final int version;
+        /**
+         * The callback class to handle creation, upgrade and downgrade.
+         */
+        @NonNull
+        public final SupportSQLiteOpenHelper.Callback callback;
+        /**
+         * The {@link DatabaseErrorHandler} to be used when sqlite reports database
+         * corruption, or null to use the default error handler.
+         */
+        @Nullable
+        public final DatabaseErrorHandler errorHandler;
+
+        Configuration(@NonNull Context context, @Nullable String name,
+                int version, @Nullable DatabaseErrorHandler errorHandler,
+                @NonNull Callback callback) {
+            this.context = context;
+            this.name = name;
+            this.version = version;
+            this.callback = callback;
+            this.errorHandler = errorHandler;
+        }
+
+        /**
+         * Creates a new Configuration.Builder to create an instance of Configuration.
+         *
+         * @param context to use to open or create the database.
+         */
+        public static Builder builder(Context context) {
+            return new Builder(context);
+        }
+
+        /**
+         * Builder class for {@link Configuration}.
+         */
+        public static class Builder {
+            Context mContext;
+            String mName;
+            int mVersion = 1;
+            SupportSQLiteOpenHelper.Callback mCallback;
+            DatabaseErrorHandler mErrorHandler;
+
+            public Configuration build() {
+                if (mCallback == null) {
+                    throw new IllegalArgumentException("Must set a callback to create the"
+                            + " configuration.");
+                }
+                if (mContext == null) {
+                    throw new IllegalArgumentException("Must set a non-null context to create"
+                            + " the configuration.");
+                }
+                if (mErrorHandler == null) {
+                    mErrorHandler = new DefaultDatabaseErrorHandler();
+                }
+                return new Configuration(mContext, mName, mVersion, mErrorHandler,
+                        mCallback);
+            }
+
+            Builder(@NonNull Context context) {
+                mContext = context;
+            }
+
+            /**
+             * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite
+             *                     reports database corruption, or null to use the default error
+             *                     handler.
+             * @return This
+             */
+            public Builder errorHandler(@Nullable DatabaseErrorHandler errorHandler) {
+                mErrorHandler = errorHandler;
+                return this;
+            }
+
+            /**
+             * @param name Name of the database file, or null for an in-memory database.
+             * @return This
+             */
+            public Builder name(@Nullable String name) {
+                mName = name;
+                return this;
+            }
+
+            /**
+             * @param callback The callback class to handle creation, upgrade and downgrade.
+             * @return this
+             */
+            public Builder callback(@NonNull Callback callback) {
+                mCallback = callback;
+                return this;
+            }
+
+            /**
+             * @param version Version number of the database (starting at 1); if the database is
+             * older,
+             * {@link SupportSQLiteOpenHelper.Callback#onUpgrade(SupportSQLiteDatabase, int, int)}
+             * will be used to upgrade the database; if the database is newer,
+             * {@link SupportSQLiteOpenHelper.Callback#onDowngrade(SupportSQLiteDatabase, int, int)}
+             * will be used to downgrade the database.
+             * @return this
+             */
+            public Builder version(int version) {
+                mVersion = version;
+                return this;
+            }
+        }
+    }
+
+    /**
+     * Factory class to create instances of {@link SupportSQLiteOpenHelper} using
+     * {@link Configuration}.
+     */
+    interface Factory {
+        /**
+         * Creates an instance of {@link SupportSQLiteOpenHelper} using the given configuration.
+         *
+         * @param configuration The configuration to use while creating the open helper.
+         *
+         * @return A SupportSQLiteOpenHelper which can be used to open a database.
+         */
+        SupportSQLiteOpenHelper create(Configuration configuration);
+    }
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteProgram.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteProgram.java
new file mode 100644
index 0000000..c6d43cc
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteProgram.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db;
+
+import android.annotation.TargetApi;
+import android.os.Build;
+
+/**
+ * An interface to map the behavior of {@link android.database.sqlite.SQLiteProgram}.
+ */
+
+@TargetApi(Build.VERSION_CODES.KITKAT)
+@SuppressWarnings("unused")
+public interface SupportSQLiteProgram extends AutoCloseable {
+    /**
+     * Bind a NULL value to this statement. The value remains bound until
+     * {@link #clearBindings} is called.
+     *
+     * @param index The 1-based index to the parameter to bind null to
+     */
+    void bindNull(int index);
+
+    /**
+     * Bind a long value to this statement. The value remains bound until
+     * {@link #clearBindings} is called.
+     *addToBindArgs
+     * @param index The 1-based index to the parameter to bind
+     * @param value The value to bind
+     */
+    void bindLong(int index, long value);
+
+    /**
+     * Bind a double value to this statement. The value remains bound until
+     * {@link #clearBindings} is called.
+     *
+     * @param index The 1-based index to the parameter to bind
+     * @param value The value to bind
+     */
+    void bindDouble(int index, double value);
+
+    /**
+     * Bind a String value to this statement. The value remains bound until
+     * {@link #clearBindings} is called.
+     *
+     * @param index The 1-based index to the parameter to bind
+     * @param value The value to bind, must not be null
+     */
+    void bindString(int index, String value);
+
+    /**
+     * Bind a byte array value to this statement. The value remains bound until
+     * {@link #clearBindings} is called.
+     *
+     * @param index The 1-based index to the parameter to bind
+     * @param value The value to bind, must not be null
+     */
+    void bindBlob(int index, byte[] value);
+
+    /**
+     * Clears all existing bindings. Unset bindings are treated as NULL.
+     */
+    void clearBindings();
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQuery.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQuery.java
new file mode 100644
index 0000000..2007634
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQuery.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.db;
+
+/**
+ * A query with typed bindings. It is better to use this API instead of
+ * {@link android.database.sqlite.SQLiteDatabase#rawQuery(String, String[])} because it allows
+ * binding type safe parameters.
+ */
+public interface SupportSQLiteQuery {
+    /**
+     * The SQL query. This query can have placeholders(?) for bind arguments.
+     *
+     * @return The SQL query to compile
+     */
+    String getSql();
+
+    /**
+     * Callback to bind the query parameters to the compiled statement.
+     *
+     * @param statement The compiled statement
+     */
+    void bindTo(SupportSQLiteProgram statement);
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQueryBuilder.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQueryBuilder.java
new file mode 100644
index 0000000..183fb0a
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteQueryBuilder.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.db;
+
+import java.util.regex.Pattern;
+
+/**
+ * A simple query builder to create SQL SELECT queries.
+ */
+@SuppressWarnings("unused")
+public class SupportSQLiteQueryBuilder {
+    private static final Pattern sLimitPattern =
+            Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");
+
+    private boolean mDistinct = false;
+    private final String mTable;
+    private String[] mColumns = null;
+    private String mSelection;
+    private Object[] mBindArgs;
+    private String mGroupBy = null;
+    private String mHaving = null;
+    private String mOrderBy = null;
+    private String mLimit = null;
+
+    /**
+     * Creates a query for the given table name.
+     *
+     * @param tableName The table name(s) to query.
+     *
+     * @return A builder to create a query.
+     */
+    public static SupportSQLiteQueryBuilder builder(String tableName) {
+        return new SupportSQLiteQueryBuilder(tableName);
+    }
+
+    private SupportSQLiteQueryBuilder(String table) {
+        mTable = table;
+    }
+
+    /**
+     * Adds DISTINCT keyword to the query.
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder distinct() {
+        mDistinct = true;
+        return this;
+    }
+
+    /**
+     * Sets the given list of columns as the columns that will be returned.
+     *
+     * @param columns The list of column names that should be returned.
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder columns(String[] columns) {
+        mColumns = columns;
+        return this;
+    }
+
+    /**
+     * Sets the arguments for the WHERE clause.
+     *
+     * @param selection The list of selection columns
+     * @param bindArgs The list of bind arguments to match against these columns
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder selection(String selection, Object[] bindArgs) {
+        mSelection = selection;
+        mBindArgs = bindArgs;
+        return this;
+    }
+
+    /**
+     * Adds a GROUP BY statement.
+     *
+     * @param groupBy The value of the GROUP BY statement.
+     *
+     * @return this
+     */
+    @SuppressWarnings("WeakerAccess")
+    public SupportSQLiteQueryBuilder groupBy(String groupBy) {
+        mGroupBy = groupBy;
+        return this;
+    }
+
+    /**
+     * Adds a HAVING statement. You must also provide {@link #groupBy(String)} for this to work.
+     *
+     * @param having The having clause.
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder having(String having) {
+        mHaving = having;
+        return this;
+    }
+
+    /**
+     * Adds an ORDER BY statement.
+     *
+     * @param orderBy The order clause.
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder orderBy(String orderBy) {
+        mOrderBy = orderBy;
+        return this;
+    }
+
+    /**
+     * Adds a LIMIT statement.
+     *
+     * @param limit The limit value.
+     *
+     * @return this
+     */
+    public SupportSQLiteQueryBuilder limit(String limit) {
+        if (!isEmpty(limit) && !sLimitPattern.matcher(limit).matches()) {
+            throw new IllegalArgumentException("invalid LIMIT clauses:" + limit);
+        }
+        mLimit = limit;
+        return this;
+    }
+
+    /**
+     * Creates the {@link SupportSQLiteQuery} that can be passed into
+     * {@link SupportSQLiteDatabase#query(SupportSQLiteQuery)}.
+     *
+     * @return a new query
+     */
+    public SupportSQLiteQuery create() {
+        if (isEmpty(mGroupBy) && !isEmpty(mHaving)) {
+            throw new IllegalArgumentException(
+                    "HAVING clauses are only permitted when using a groupBy clause");
+        }
+        StringBuilder query = new StringBuilder(120);
+
+        query.append("SELECT ");
+        if (mDistinct) {
+            query.append("DISTINCT ");
+        }
+        if (mColumns != null && mColumns.length != 0) {
+            appendColumns(query, mColumns);
+        } else {
+            query.append(" * ");
+        }
+        query.append(" FROM ");
+        query.append(mTable);
+        appendClause(query, " WHERE ", mSelection);
+        appendClause(query, " GROUP BY ", mGroupBy);
+        appendClause(query, " HAVING ", mHaving);
+        appendClause(query, " ORDER BY ", mOrderBy);
+        appendClause(query, " LIMIT ", mLimit);
+
+        return new SimpleSQLiteQuery(query.toString(), mBindArgs);
+    }
+
+    private static void appendClause(StringBuilder s, String name, String clause) {
+        if (!isEmpty(clause)) {
+            s.append(name);
+            s.append(clause);
+        }
+    }
+
+    /**
+     * Add the names that are non-null in columns to s, separating
+     * them with commas.
+     */
+    private static void appendColumns(StringBuilder s, String[] columns) {
+        int n = columns.length;
+
+        for (int i = 0; i < n; i++) {
+            String column = columns[i];
+            if (i > 0) {
+                s.append(", ");
+            }
+            s.append(column);
+        }
+        s.append(' ');
+    }
+
+    private static boolean isEmpty(String input) {
+        return input == null || input.length() == 0;
+    }
+}
diff --git a/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteStatement.java b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteStatement.java
new file mode 100644
index 0000000..5a329d7
--- /dev/null
+++ b/room/db/src/main/java/android/arch/persistence/db/SupportSQLiteStatement.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.db;
+
+/**
+ * An interface to map the behavior of {@link android.database.sqlite.SQLiteStatement}.
+ */
+@SuppressWarnings("unused")
+public interface SupportSQLiteStatement extends SupportSQLiteProgram {
+    /**
+     * Execute this SQL statement, if it is not a SELECT / INSERT / DELETE / UPDATE, for example
+     * CREATE / DROP table, view, trigger, index etc.
+     *
+     * @throws android.database.SQLException If the SQL string is invalid for
+     *         some reason
+     */
+    void execute();
+
+    /**
+     * Execute this SQL statement, if the the number of rows affected by execution of this SQL
+     * statement is of any importance to the caller - for example, UPDATE / DELETE SQL statements.
+     *
+     * @return the number of rows affected by this SQL statement execution.
+     * @throws android.database.SQLException If the SQL string is invalid for
+     *         some reason
+     */
+    int executeUpdateDelete();
+
+    /**
+     * Execute this SQL statement and return the ID of the row inserted due to this call.
+     * The SQL statement should be an INSERT for this to be a useful call.
+     *
+     * @return the row ID of the last row inserted, if this insert is successful. -1 otherwise.
+     *
+     * @throws android.database.SQLException If the SQL string is invalid for
+     *         some reason
+     */
+    long executeInsert();
+
+    /**
+     * Execute a statement that returns a 1 by 1 table with a numeric value.
+     * For example, SELECT COUNT(*) FROM table;
+     *
+     * @return The result of the query.
+     *
+     * @throws android.database.sqlite.SQLiteDoneException if the query returns zero rows
+     */
+    long simpleQueryForLong();
+    /**
+     * Execute a statement that returns a 1 by 1 table with a text value.
+     * For example, SELECT COUNT(*) FROM table;
+     *
+     * @return The result of the query.
+     *
+     * @throws android.database.sqlite.SQLiteDoneException if the query returns zero rows
+     */
+    String simpleQueryForString();
+}
diff --git a/room/gradle/wrapper/gradle-wrapper.jar b/room/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..d6e2637
--- /dev/null
+++ b/room/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/room/gradle/wrapper/gradle-wrapper.properties b/room/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..a5292b0
--- /dev/null
+++ b/room/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Fri Dec 09 13:07:04 PST 2016
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-bin.zip
diff --git a/room/gradlew b/room/gradlew
new file mode 100755
index 0000000..4ef3a87
--- /dev/null
+++ b/room/gradlew
@@ -0,0 +1,171 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+  NONSTOP* )
+    nonstop=true
+    ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Escape application args
+for s in "${@}" ; do
+    s=\"$s\"
+    APP_ARGS=$APP_ARGS" "$s
+done
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- "$DEFAULT_JVM_OPTS" "$JAVA_OPTS" "$GRADLE_OPTS" "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+  cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/room/gradlew.bat b/room/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/room/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windows variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/room/integration-tests/kotlintestapp/.gitignore b/room/integration-tests/kotlintestapp/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/room/integration-tests/kotlintestapp/build.gradle b/room/integration-tests/kotlintestapp/build.gradle
new file mode 100644
index 0000000..0d70666
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/build.gradle
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+apply plugin: 'com.android.application'
+apply plugin: 'kotlin-kapt'
+apply plugin: 'kotlin-android'
+
+project.ext.noDocs = true
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+        javaCompileOptions {
+            annotationProcessorOptions {
+                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
+            }
+        }
+    }
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+    sourceSets {
+        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
+    }
+}
+
+dependencies {
+    implementation project(":room:common")
+    implementation project(":room:db")
+    implementation project(":room:db-impl")
+    implementation project(':room:runtime')
+    implementation project(':arch:runtime')
+
+    implementation libs.support.app_compat
+    kapt project(":room:compiler")
+    kaptAndroidTest project(":room:compiler")
+
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+        exclude module: 'hamcrest-core'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+        exclude module: "hamcrest-core"
+    })
+    // IJ's gradle integration just cannot figure this out ...
+    androidTestImplementation project(':lifecycle:extensions')
+    androidTestImplementation project(':lifecycle:common')
+    androidTestImplementation project(':lifecycle:runtime')
+    androidTestImplementation project(':room:testing')
+    androidTestImplementation project(':room:rxjava2')
+    androidTestImplementation project(':arch:core-testing')
+    androidTestImplementation libs.rx_java
+    testImplementation libs.mockito_core
+}
+
+createAndroidCheckstyle(project)
+createKotlinCheckstyle(project)
+tasks['check'].dependsOn(tasks['connectedCheck'])
+
+uploadArchives.enabled = false
diff --git a/room/integration-tests/kotlintestapp/proguard-rules.pro b/room/integration-tests/kotlintestapp/proguard-rules.pro
new file mode 100644
index 0000000..d50f27e
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/proguard-rules.pro
@@ -0,0 +1,25 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/florinam/Work/Coding/support/ub-supportlib-26.0/prebuilts/fullsdk-darwin/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.BooksDatabase/1.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.BooksDatabase/1.json
new file mode 100644
index 0000000..dd056e2
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.BooksDatabase/1.json
@@ -0,0 +1,159 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 1,
+    "identityHash": "64fa560604c57044726b190dadbd8258",
+    "entities": [
+      {
+        "tableName": "Book",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`bookId` TEXT NOT NULL, `title` TEXT NOT NULL, `bookPublisherId` TEXT NOT NULL, PRIMARY KEY(`bookId`), FOREIGN KEY(`bookPublisherId`) REFERENCES `Publisher`(`publisherId`) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)",
+        "fields": [
+          {
+            "fieldPath": "bookId",
+            "columnName": "bookId",
+            "affinity": "TEXT",
+            "notNull": true
+          },
+          {
+            "fieldPath": "title",
+            "columnName": "title",
+            "affinity": "TEXT",
+            "notNull": true
+          },
+          {
+            "fieldPath": "bookPublisherId",
+            "columnName": "bookPublisherId",
+            "affinity": "TEXT",
+            "notNull": true
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "bookId"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": [
+          {
+            "table": "Publisher",
+            "onDelete": "NO ACTION",
+            "onUpdate": "NO ACTION",
+            "columns": [
+              "bookPublisherId"
+            ],
+            "referencedColumns": [
+              "publisherId"
+            ]
+          }
+        ]
+      },
+      {
+        "tableName": "Author",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`authorId` TEXT NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`authorId`))",
+        "fields": [
+          {
+            "fieldPath": "authorId",
+            "columnName": "authorId",
+            "affinity": "TEXT",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": true
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "authorId"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Publisher",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publisherId` TEXT NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`publisherId`))",
+        "fields": [
+          {
+            "fieldPath": "publisherId",
+            "columnName": "publisherId",
+            "affinity": "TEXT",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": true
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "publisherId"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "BookAuthor",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`bookId` TEXT NOT NULL, `authorId` TEXT NOT NULL, PRIMARY KEY(`bookId`, `authorId`), FOREIGN KEY(`bookId`) REFERENCES `Book`(`bookId`) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, FOREIGN KEY(`authorId`) REFERENCES `Author`(`authorId`) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED)",
+        "fields": [
+          {
+            "fieldPath": "bookId",
+            "columnName": "bookId",
+            "affinity": "TEXT",
+            "notNull": true
+          },
+          {
+            "fieldPath": "authorId",
+            "columnName": "authorId",
+            "affinity": "TEXT",
+            "notNull": true
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "bookId",
+            "authorId"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": [
+          {
+            "table": "Book",
+            "onDelete": "CASCADE",
+            "onUpdate": "CASCADE",
+            "columns": [
+              "bookId"
+            ],
+            "referencedColumns": [
+              "bookId"
+            ]
+          },
+          {
+            "table": "Author",
+            "onDelete": "CASCADE",
+            "onUpdate": "CASCADE",
+            "columns": [
+              "authorId"
+            ],
+            "referencedColumns": [
+              "authorId"
+            ]
+          }
+        ]
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"64fa560604c57044726b190dadbd8258\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/1.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/1.json
new file mode 100644
index 0000000..e05f095
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/1.json
@@ -0,0 +1,38 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 1,
+    "identityHash": "2f3557e56d7f665363f3e20d14787a59",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"2f3557e56d7f665363f3e20d14787a59\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/2.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/2.json
new file mode 100644
index 0000000..8982d4f
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/2.json
@@ -0,0 +1,63 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 2,
+    "identityHash": "aee9a6eed720c059df0f2ee0d6e96d89",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"aee9a6eed720c059df0f2ee0d6e96d89\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/3.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/3.json
new file mode 100644
index 0000000..3bf0f03
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/3.json
@@ -0,0 +1,69 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 3,
+    "identityHash": "3f2a99b6d768af0184e077808f7348fe",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `addedInV3` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"3f2a99b6d768af0184e077808f7348fe\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/4.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/4.json
new file mode 100644
index 0000000..e899a02
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/4.json
@@ -0,0 +1,100 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 4,
+    "identityHash": "abbae5f17d94ff7c2c7e05ca217ccc31",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `addedInV3` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity3",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER, `removedInV5` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "removedInV5",
+            "columnName": "removedInV5",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"abbae5f17d94ff7c2c7e05ca217ccc31\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/5.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/5.json
new file mode 100644
index 0000000..801fdb5
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/5.json
@@ -0,0 +1,94 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 5,
+    "identityHash": "5543c44fe679f4cf8f03093d66838068",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `addedInV3` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity3",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"5543c44fe679f4cf8f03093d66838068\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/6.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/6.json
new file mode 100644
index 0000000..a6fdf5b
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/6.json
@@ -0,0 +1,69 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 6,
+    "identityHash": "3f2a99b6d768af0184e077808f7348fe",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `addedInV3` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"3f2a99b6d768af0184e077808f7348fe\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/7.json b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/7.json
new file mode 100644
index 0000000..78ce189
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/schemas/android.arch.persistence.room.integration.kotlintestapp.migration.MigrationDbKotlin/7.json
@@ -0,0 +1,118 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 7,
+    "identityHash": "5653c29453937d8e34dc031af1ab4c7d",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [
+          {
+            "name": "index_Entity1_name",
+            "unique": true,
+            "columnNames": [
+              "name"
+            ],
+            "createSql": "CREATE UNIQUE INDEX `index_Entity1_name` ON `${TABLE_NAME}` (`name`)"
+          }
+        ],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `addedInV3` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity4",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`), FOREIGN KEY(`name`) REFERENCES `Entity1`(`name`) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": [
+          {
+            "table": "Entity1",
+            "onDelete": "NO ACTION",
+            "onUpdate": "NO ACTION",
+            "columns": [
+              "name"
+            ],
+            "referencedColumns": [
+              "name"
+            ]
+          }
+        ]
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"5653c29453937d8e34dc031af1ab4c7d\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDao.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDao.kt
new file mode 100644
index 0000000..6dc0276
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDao.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp
+
+import android.arch.lifecycle.LiveData
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.integration.kotlintestapp.vo.*
+import io.reactivex.Flowable
+
+@Dao
+interface BooksDao {
+
+    @Insert
+    fun addPublishers(vararg publishers: Publisher)
+
+    @Insert
+    fun addAuthors(vararg authors: Author)
+
+    @Insert
+    fun addBooks(vararg books: Book)
+
+    @Insert
+    fun addBookAuthors(vararg bookAuthors: BookAuthor)
+
+    @Query("SELECT * FROM book WHERE bookId = :bookId")
+    fun getBook(bookId: String): Book
+
+    @Query("SELECT * FROM book WHERE bookId = :bookId")
+    fun getBookLiveData(bookId: String): LiveData<Book>
+
+    @Query("SELECT * FROM book WHERE bookId = :bookId")
+    fun getBookFlowable(bookId: String): Flowable<Book>
+
+    @Query("SELECT * FROM book INNER JOIN publisher " +
+            "ON book.bookPublisherId = publisher.publisherId ")
+    fun getBooksWithPublisher(): List<BookWithPublisher>
+
+    @Query("SELECT * FROM book INNER JOIN publisher " +
+            "ON book.bookPublisherId = publisher.publisherId ")
+    fun getBooksWithPublisherLiveData(): LiveData<List<BookWithPublisher>>
+
+    @Query("SELECT * FROM book INNER JOIN publisher " +
+            "ON book.bookPublisherId = publisher.publisherId ")
+    fun getBooksWithPublisherFlowable(): Flowable<List<BookWithPublisher>>
+
+    @Query("SELECT * FROM publisher WHERE publisherId = :publisherId")
+    fun getPublisherWithBooks(publisherId: String): PublisherWithBooks
+
+    @Query("SELECT * FROM publisher WHERE publisherId = :publisherId")
+    fun getPublisherWithBooksLiveData(publisherId: String): LiveData<PublisherWithBooks>
+
+    @Query("SELECT * FROM publisher WHERE publisherId = :publisherId")
+    fun getPublisherWithBooksFlowable(publisherId: String): Flowable<PublisherWithBooks>
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDatabase.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDatabase.kt
new file mode 100644
index 0000000..b5b6f26
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/BooksDatabase.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp
+
+import android.arch.persistence.room.Database
+import android.arch.persistence.room.RoomDatabase
+import android.arch.persistence.room.integration.kotlintestapp.vo.Author
+import android.arch.persistence.room.integration.kotlintestapp.vo.Book
+import android.arch.persistence.room.integration.kotlintestapp.vo.BookAuthor
+import android.arch.persistence.room.integration.kotlintestapp.vo.Publisher
+
+@Database(entities = arrayOf(Book::class, Author::class, Publisher::class, BookAuthor::class),
+        version = 1)
+abstract class BooksDatabase : RoomDatabase() {
+
+    abstract fun booksDao(): BooksDao
+
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationDbKotlin.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationDbKotlin.kt
new file mode 100644
index 0000000..67374a5
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationDbKotlin.kt
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.migration
+
+import android.arch.persistence.db.SupportSQLiteDatabase
+import android.arch.persistence.room.Dao
+import android.arch.persistence.room.Database
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ForeignKey
+import android.arch.persistence.room.Ignore
+import android.arch.persistence.room.Index
+import android.arch.persistence.room.Insert
+import android.arch.persistence.room.PrimaryKey
+import android.arch.persistence.room.Query
+import android.arch.persistence.room.RoomDatabase
+import android.content.ContentValues
+import android.database.sqlite.SQLiteDatabase
+
+@Database(version = MigrationDbKotlin.LATEST_VERSION,
+        entities = arrayOf(MigrationDbKotlin.Entity1::class, MigrationDbKotlin.Entity2::class,
+                MigrationDbKotlin.Entity4::class))
+abstract class MigrationDbKotlin : RoomDatabase() {
+
+    internal abstract fun dao(): MigrationDao
+
+    @Entity(indices = arrayOf(Index(value = "name", unique = true)))
+    data class Entity1(@PrimaryKey var id: Int = 0, var name: String?) {
+
+        companion object {
+            val TABLE_NAME = "Entity1"
+        }
+    }
+
+    @Entity
+    open class Entity2(@PrimaryKey var id: Int = 0, var addedInV3: String?, var name: String?) {
+        companion object {
+            val TABLE_NAME = "Entity2"
+        }
+    }
+
+    @Entity
+    data class Entity3(@PrimaryKey var id: Int = 0, @Ignore var removedInV5: String?,
+                       var name: String?) { // added in version 4, removed at 6
+        companion object {
+            val TABLE_NAME = "Entity3"
+        }
+    }
+
+    @Entity(foreignKeys = arrayOf(ForeignKey(entity = Entity1::class,
+            parentColumns = arrayOf("name"),
+            childColumns = arrayOf("name"),
+            deferred = true)))
+    data class Entity4(@PrimaryKey var id: Int = 0, var name: String?) {
+        companion object {
+            val TABLE_NAME = "Entity4"
+        }
+    }
+
+    @Dao
+    internal interface MigrationDao {
+        @Query("SELECT * from Entity1 ORDER BY id ASC")
+        fun loadAllEntity1s(): List<Entity1>
+
+        @Query("SELECT * from Entity2 ORDER BY id ASC")
+        fun loadAllEntity2s(): List<Entity2>
+
+        @Query("SELECT * from Entity2 ORDER BY id ASC")
+        fun loadAllEntity2sAsPojo(): List<Entity2Pojo>
+
+        @Insert
+        fun insert(vararg entity2: Entity2)
+    }
+
+    internal class Entity2Pojo(id: Int, addedInV3: String?, name: String?)
+        : Entity2(id, addedInV3, name)
+
+    /**
+     * not a real dao because database will change.
+     */
+    internal class Dao_V1(val mDb: SupportSQLiteDatabase) {
+
+        fun insertIntoEntity1(id: Int, name: String) {
+            val values = ContentValues()
+            values.put("id", id)
+            values.put("name", name)
+            val insertionId = mDb.insert(Entity1.TABLE_NAME,
+                    SQLiteDatabase.CONFLICT_REPLACE, values)
+            if (insertionId == -1L) {
+                throw RuntimeException("test sanity failure")
+            }
+        }
+    }
+
+    /**
+     * not a real dao because database will change.
+     */
+    internal class Dao_V2(val mDb: SupportSQLiteDatabase) {
+
+        fun insertIntoEntity2(id: Int, name: String) {
+            val values = ContentValues()
+            values.put("id", id)
+            values.put("name", name)
+            val insertionId = mDb.insert(Entity2.TABLE_NAME,
+                    SQLiteDatabase.CONFLICT_REPLACE, values)
+            if (insertionId == -1L) {
+                throw RuntimeException("test sanity failure")
+            }
+        }
+    }
+
+    companion object {
+        const val LATEST_VERSION = 7
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationKotlinTest.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationKotlinTest.kt
new file mode 100644
index 0000000..eb1a9b8
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/migration/MigrationKotlinTest.kt
@@ -0,0 +1,306 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.migration
+
+import android.arch.persistence.db.SupportSQLiteDatabase
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory
+import android.arch.persistence.room.Room
+import android.arch.persistence.room.migration.Migration
+import android.arch.persistence.room.testing.MigrationTestHelper
+import android.arch.persistence.room.util.TableInfo
+import android.support.test.InstrumentationRegistry
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.CoreMatchers.containsString
+import org.hamcrest.CoreMatchers.instanceOf
+import org.hamcrest.CoreMatchers.nullValue
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Rule
+import org.junit.Test
+import java.io.FileNotFoundException
+import java.io.IOException
+
+
+class MigrationKotlinTest {
+
+    @get:Rule
+    var helper: MigrationTestHelper = MigrationTestHelper(
+            InstrumentationRegistry.getInstrumentation(),
+            MigrationDbKotlin::class.java.canonicalName,
+            FrameworkSQLiteOpenHelperFactory())
+
+    companion object {
+        val TEST_DB = "migration-test"
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun giveBadResource() {
+        val helper = MigrationTestHelper(
+                InstrumentationRegistry.getInstrumentation(),
+                "foo", FrameworkSQLiteOpenHelperFactory())
+        try {
+            helper.createDatabase(TEST_DB, 1)
+            throw AssertionError("must have failed with missing file exception")
+        } catch (exception: FileNotFoundException) {
+            assertThat<String>(exception.message, containsString("Cannot find"))
+        }
+
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun startInCurrentVersion() {
+        val db = helper.createDatabase(TEST_DB,
+                MigrationDbKotlin.LATEST_VERSION)
+        val dao = MigrationDbKotlin.Dao_V1(db)
+        dao.insertIntoEntity1(2, "x")
+        db.close()
+        val migrationDb = getLatestDb()
+        val items = migrationDb.dao().loadAllEntity1s()
+        helper.closeWhenFinished(migrationDb)
+        assertThat<Int>(items.size, `is`<Int>(1))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun addTable() {
+        var db = helper.createDatabase(TEST_DB, 1)
+        val dao = MigrationDbKotlin.Dao_V1(db)
+        dao.insertIntoEntity1(2, "foo")
+        dao.insertIntoEntity1(3, "bar")
+        db.close()
+        db = helper.runMigrationsAndValidate(TEST_DB, 2, true,
+                MIGRATION_1_2)
+        MigrationDbKotlin.Dao_V2(db).insertIntoEntity2(3, "blah")
+        db.close()
+        val migrationDb = getLatestDb()
+        val entity1s = migrationDb.dao().loadAllEntity1s()
+
+        assertThat(entity1s.size, `is`(2))
+        val entity2 = MigrationDbKotlin.Entity2(2, null, "bar")
+        // assert no error happens
+        migrationDb.dao().insert(entity2)
+        val entity2s = migrationDb.dao().loadAllEntity2s()
+        assertThat(entity2s.size, `is`(2))
+    }
+
+    private fun getLatestDb(): MigrationDbKotlin {
+        val db = Room.databaseBuilder(
+                InstrumentationRegistry.getInstrumentation().targetContext,
+                MigrationDbKotlin::class.java, TEST_DB).addMigrations(*ALL_MIGRATIONS).build()
+        // trigger open
+        db.beginTransaction()
+        db.endTransaction()
+        helper.closeWhenFinished(db)
+        return db
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun addTableFailure() {
+        testFailure(1, 2)
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun addColumnFailure() {
+        val db = helper.createDatabase(TEST_DB, 2)
+        db.close()
+        var caught: IllegalStateException? = null
+        try {
+            helper.runMigrationsAndValidate(TEST_DB, 3, true,
+                    EmptyMigration(2, 3))
+        } catch (ex: IllegalStateException) {
+            caught = ex
+        }
+
+        assertThat<IllegalStateException>(caught,
+                instanceOf<IllegalStateException>(IllegalStateException::class.java))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun addColumn() {
+        val db = helper.createDatabase(TEST_DB, 2)
+        val v2Dao = MigrationDbKotlin.Dao_V2(db)
+        v2Dao.insertIntoEntity2(7, "blah")
+        db.close()
+        helper.runMigrationsAndValidate(TEST_DB, 3, true, MIGRATION_2_3)
+        // trigger open.
+        val migrationDb = getLatestDb()
+        val entity2s = migrationDb.dao().loadAllEntity2s()
+        assertThat(entity2s.size, `is`(1))
+        assertThat<String>(entity2s[0].name, `is`("blah"))
+        assertThat<String>(entity2s[0].addedInV3, `is`<Any>(nullValue()))
+
+        val entity2Pojos = migrationDb.dao().loadAllEntity2sAsPojo()
+        assertThat(entity2Pojos.size, `is`(1))
+        assertThat<String>(entity2Pojos[0].name, `is`("blah"))
+        assertThat<String>(entity2Pojos[0].addedInV3, `is`<Any>(nullValue()))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun failedToRemoveColumn() {
+        testFailure(4, 5)
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun removeColumn() {
+        helper.createDatabase(TEST_DB, 4)
+        val db = helper.runMigrationsAndValidate(TEST_DB,
+                5, true, MIGRATION_4_5)
+        val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME)
+        assertThat(info.columns.size, `is`(2))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun dropTable() {
+        helper.createDatabase(TEST_DB, 5)
+        val db = helper.runMigrationsAndValidate(TEST_DB,
+                6, true, MIGRATION_5_6)
+        val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME)
+        assertThat(info.columns.size, `is`(0))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun failedToDropTable() {
+        testFailure(5, 6)
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun failedToDropTableDontVerify() {
+        helper.createDatabase(TEST_DB, 5)
+        val db = helper.runMigrationsAndValidate(TEST_DB,
+                6, false, EmptyMigration(5, 6))
+        val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME)
+        assertThat(info.columns.size, `is`(2))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun failedForeignKey() {
+        val db = helper.createDatabase(TEST_DB, 6)
+        db.close()
+        var throwable: Throwable? = null
+        try {
+            helper.runMigrationsAndValidate(TEST_DB,
+                    7, false, object : Migration(6, 7) {
+                override fun migrate(database: SupportSQLiteDatabase) {
+                    database.execSQL("CREATE TABLE Entity4 (`id` INTEGER, `name` TEXT,"
+                            + " PRIMARY KEY(`id`))")
+                }
+            })
+        } catch (t: Throwable) {
+            throwable = t
+        }
+
+        assertThat<Throwable>(throwable, instanceOf<Throwable>(IllegalStateException::class.java))
+
+        assertThat<String>(throwable!!.message, containsString("Migration failed"))
+    }
+
+    @Test
+    @Throws(IOException::class)
+    fun newTableWithForeignKey() {
+        helper.createDatabase(TEST_DB, 6)
+        val db = helper.runMigrationsAndValidate(TEST_DB,
+                7, false, MIGRATION_6_7)
+        val info = TableInfo.read(db, MigrationDbKotlin.Entity4.TABLE_NAME)
+        assertThat(info.foreignKeys.size, `is`(1))
+    }
+
+    @Throws(IOException::class)
+    private fun testFailure(startVersion: Int, endVersion: Int) {
+        val db = helper.createDatabase(TEST_DB, startVersion)
+        db.close()
+        var throwable: Throwable? = null
+        try {
+            helper.runMigrationsAndValidate(TEST_DB, endVersion, true,
+                    EmptyMigration(startVersion, endVersion))
+        } catch (t: Throwable) {
+            throwable = t
+        }
+
+        assertThat<Throwable>(throwable, instanceOf<Throwable>(IllegalStateException::class.java))
+        assertThat<String>(throwable!!.message, containsString("Migration failed"))
+    }
+
+
+    internal val MIGRATION_1_2: Migration = object : Migration(1, 2) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity2` (`id` INTEGER NOT NULL,"
+                    + " `name` TEXT, PRIMARY KEY(`id`))")
+        }
+    }
+
+    internal val MIGRATION_2_3: Migration = object : Migration(2, 3) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("ALTER TABLE " + MigrationDbKotlin.Entity2.TABLE_NAME
+                    + " ADD COLUMN addedInV3 TEXT")
+        }
+    }
+
+    internal val MIGRATION_3_4: Migration = object : Migration(3, 4) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3` (`id` INTEGER NOT NULL,"
+                    + " `removedInV5` TEXT, `name` TEXT, PRIMARY KEY(`id`))")
+        }
+    }
+
+    internal val MIGRATION_4_5: Migration = object : Migration(4, 5) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3_New` (`id` INTEGER NOT NULL,"
+                    + " `name` TEXT, PRIMARY KEY(`id`))")
+            database.execSQL("INSERT INTO Entity3_New(`id`, `name`) "
+                    + "SELECT `id`, `name` FROM Entity3")
+            database.execSQL("DROP TABLE Entity3")
+            database.execSQL("ALTER TABLE Entity3_New RENAME TO Entity3")
+        }
+    }
+
+    internal val MIGRATION_5_6: Migration = object : Migration(5, 6) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("DROP TABLE " + MigrationDbKotlin.Entity3.TABLE_NAME)
+        }
+    }
+
+    internal val MIGRATION_6_7: Migration = object : Migration(6, 7) {
+        override fun migrate(database: SupportSQLiteDatabase) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS "
+                    + MigrationDbKotlin.Entity4.TABLE_NAME
+                    + " (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`),"
+                    + " FOREIGN KEY(`name`) REFERENCES `Entity1`(`name`)"
+                    + " ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)")
+        }
+    }
+
+    private val ALL_MIGRATIONS = arrayOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5,
+            MIGRATION_5_6, MIGRATION_6_7)
+
+    internal class EmptyMigration(startVersion: Int, endVersion: Int)
+        : Migration(startVersion, endVersion) {
+
+        override fun migrate(database: SupportSQLiteDatabase) {
+            // do nothing
+        }
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/BooksDaoTest.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/BooksDaoTest.kt
new file mode 100644
index 0000000..31344d6
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/BooksDaoTest.kt
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.persistence.room.integration.kotlintestapp.vo.Book
+import android.arch.persistence.room.integration.kotlintestapp.vo.BookWithPublisher
+import android.arch.persistence.room.integration.kotlintestapp.vo.Publisher
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+
+class BooksDaoTest : TestDatabaseTest() {
+
+    @Test
+    fun bookById() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1)
+
+        assertThat(booksDao.getBook(TestUtil.BOOK_1.bookId), `is`<Book>(TestUtil.BOOK_1))
+    }
+
+    @Test
+    fun bookWithPublisher() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1)
+
+        var expected = BookWithPublisher(TestUtil.BOOK_1.bookId, TestUtil.BOOK_1.title,
+                TestUtil.PUBLISHER)
+        var expectedList = ArrayList<BookWithPublisher>()
+        expectedList.add(expected)
+
+        assertThat(database.booksDao().getBooksWithPublisher(),
+                `is`<List<BookWithPublisher>>(expectedList))
+    }
+
+    @Test
+    fun publisherWithBooks() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
+
+        var actualPublisherWithBooks = booksDao.getPublisherWithBooks(
+                TestUtil.PUBLISHER.publisherId)
+
+        assertThat(actualPublisherWithBooks.publisher, `is`<Publisher>(TestUtil.PUBLISHER))
+        assertThat(actualPublisherWithBooks.books?.size, `is`(2))
+        assertThat(actualPublisherWithBooks.books?.get(0), `is`<Book>(TestUtil.BOOK_1))
+        assertThat(actualPublisherWithBooks.books?.get(1), `is`<Book>(TestUtil.BOOK_2))
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataQueryTest.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataQueryTest.kt
new file mode 100644
index 0000000..41fcf82
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataQueryTest.kt
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.persistence.room.integration.kotlintestapp.vo.Book
+import android.arch.persistence.room.integration.kotlintestapp.vo.BookWithPublisher
+import android.arch.persistence.room.integration.kotlintestapp.vo.Publisher
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.junit.Test
+
+
+class LiveDataQueryTest : TestDatabaseTest() {
+
+    @Test
+    fun observeBooksById() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1)
+
+        val book = LiveDataTestUtil.getValue(booksDao.getBookLiveData(TestUtil.BOOK_1.bookId))
+
+        assertThat(book, `is`<Book>(TestUtil.BOOK_1))
+    }
+
+    @Test
+    fun observeBooksWithPublisher() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1)
+
+        var expected = BookWithPublisher(TestUtil.BOOK_1.bookId, TestUtil.BOOK_1.title,
+                TestUtil.PUBLISHER)
+        var expectedList = ArrayList<BookWithPublisher>()
+        expectedList.add(expected)
+
+        val actual = LiveDataTestUtil.getValue(booksDao.getBooksWithPublisherLiveData())
+        assertThat(actual, `is`<List<BookWithPublisher>>(expectedList))
+    }
+
+    @Test
+    fun publisherWithBooks() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
+
+        var actualPublisherWithBooks = LiveDataTestUtil.getValue(
+                booksDao.getPublisherWithBooksLiveData(TestUtil.PUBLISHER.publisherId))
+
+        assertThat(actualPublisherWithBooks.publisher, `is`<Publisher>(TestUtil.PUBLISHER))
+        assertThat(actualPublisherWithBooks.books?.size, `is`(2))
+        assertThat(actualPublisherWithBooks.books?.get(0), `is`<Book>(TestUtil.BOOK_1))
+        assertThat(actualPublisherWithBooks.books?.get(1), `is`<Book>(TestUtil.BOOK_2))
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataTestUtil.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataTestUtil.kt
new file mode 100644
index 0000000..5533f11
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/LiveDataTestUtil.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.lifecycle.LiveData
+import android.arch.lifecycle.Observer
+
+object LiveDataTestUtil {
+
+    @Throws(InterruptedException::class)
+    fun <T> getValue(liveData: LiveData<T>): T {
+        val data = arrayOfNulls<Any>(1)
+        val observer = object : Observer<T> {
+            override fun onChanged(o: T?) {
+                data[0] = o
+                liveData.removeObserver(this)
+            }
+        }
+        liveData.observeForever(observer)
+
+        return data[0] as T
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/RxJava2QueryTest.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/RxJava2QueryTest.kt
new file mode 100644
index 0000000..a3d0a68
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/RxJava2QueryTest.kt
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.persistence.room.integration.kotlintestapp.vo.BookWithPublisher
+import org.junit.Test
+
+class RxJava2QueryTest : TestDatabaseTest() {
+
+    @Test
+    fun observeBooksById() {
+        database.booksDao().addAuthors(TestUtil.AUTHOR_1)
+        database.booksDao().addPublishers(TestUtil.PUBLISHER)
+        database.booksDao().addBooks(TestUtil.BOOK_1)
+
+        database.booksDao().getBookFlowable(TestUtil.BOOK_1.bookId)
+                .test()
+                .assertValue { book -> book == TestUtil.BOOK_1 }
+    }
+
+    @Test
+    fun observeBooksWithPublisher() {
+        database.booksDao().addAuthors(TestUtil.AUTHOR_1)
+        database.booksDao().addPublishers(TestUtil.PUBLISHER)
+        database.booksDao().addBooks(TestUtil.BOOK_1)
+
+        var expected = BookWithPublisher(TestUtil.BOOK_1.bookId, TestUtil.BOOK_1.title,
+                TestUtil.PUBLISHER)
+        var expectedList = ArrayList<BookWithPublisher>()
+        expectedList.add(expected)
+
+        database.booksDao().getBooksWithPublisherFlowable()
+                .test()
+                .assertValue(expectedList)
+    }
+
+    @Test
+    fun publisherWithBooks() {
+        booksDao.addAuthors(TestUtil.AUTHOR_1)
+        booksDao.addPublishers(TestUtil.PUBLISHER)
+        booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
+
+        booksDao.getPublisherWithBooksFlowable(TestUtil.PUBLISHER.publisherId)
+                .test()
+                .assertValue {
+                    it.publisher == TestUtil.PUBLISHER
+                            && it.books?.size == 2
+                            && it.books?.get(0) == TestUtil.BOOK_1
+                            && it.books?.get(1) == TestUtil.BOOK_2
+                }
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestDatabaseTest.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestDatabaseTest.kt
new file mode 100644
index 0000000..42815b2
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestDatabaseTest.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.core.executor.testing.InstantTaskExecutorRule
+import android.arch.persistence.room.Room
+import android.arch.persistence.room.integration.kotlintestapp.BooksDao
+import android.arch.persistence.room.integration.kotlintestapp.BooksDatabase
+import android.support.test.InstrumentationRegistry
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+
+abstract class TestDatabaseTest {
+
+    @get:Rule
+    var instantTaskExecutorRule = InstantTaskExecutorRule()
+
+    protected lateinit var database: BooksDatabase
+    protected lateinit var booksDao: BooksDao
+
+    @Before
+    @Throws(Exception::class)
+    fun setUp() {
+        database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
+                BooksDatabase::class.java)
+                // allowing main thread queries, just for testing
+                .allowMainThreadQueries()
+                .build()
+
+        booksDao = database.booksDao()
+    }
+
+    @After
+    @Throws(Exception::class)
+    fun tearDown() {
+        database.close()
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestUtil.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestUtil.kt
new file mode 100644
index 0000000..c4d406c
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/test/TestUtil.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.test
+
+import android.arch.persistence.room.integration.kotlintestapp.vo.Author
+import android.arch.persistence.room.integration.kotlintestapp.vo.Book
+import android.arch.persistence.room.integration.kotlintestapp.vo.BookAuthor
+import android.arch.persistence.room.integration.kotlintestapp.vo.Publisher
+
+class TestUtil {
+
+    companion object {
+
+        val PUBLISHER = Publisher("ph1", "publisher 1")
+        val PUBLISHER2 = Publisher("ph2", "publisher 2")
+
+        val AUTHOR_1 = Author("a1", "author 1")
+        val AUTHOR_2 = Author("a2", "author 2")
+
+        val BOOK_1 = Book("b1", "book title 1", "ph1")
+        val BOOK_2 = Book("b2", "book title 2", "ph1")
+
+        val BOOK_AUTHOR_1_1 = BookAuthor(BOOK_1.bookId, AUTHOR_1.authorId)
+        val BOOK_AUTHOR_1_2 = BookAuthor(BOOK_1.bookId, AUTHOR_2.authorId)
+        val BOOK_AUTHOR_2_2 = BookAuthor(BOOK_2.bookId, AUTHOR_2.authorId)
+    }
+}
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Author.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Author.kt
new file mode 100644
index 0000000..a51c256
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Author.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.PrimaryKey
+
+@Entity
+data class Author(@PrimaryKey val authorId: String, val name: String)
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Book.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Book.kt
new file mode 100644
index 0000000..794e60b
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Book.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ForeignKey
+import android.arch.persistence.room.PrimaryKey
+
+@Entity(foreignKeys = arrayOf(
+        ForeignKey(entity = Publisher::class,
+                parentColumns = arrayOf("publisherId"),
+                childColumns = arrayOf("bookPublisherId"),
+                deferred = true)))
+data class Book(@PrimaryKey val bookId: String, val title: String, val bookPublisherId: String)
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookAuthor.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookAuthor.kt
new file mode 100644
index 0000000..4fc661c
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookAuthor.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.ForeignKey
+
+
+@Entity(foreignKeys = arrayOf(
+        ForeignKey(entity = Book::class,
+                parentColumns = arrayOf("bookId"),
+                childColumns = arrayOf("bookId"),
+                onUpdate = ForeignKey.CASCADE,
+                onDelete = ForeignKey.CASCADE,
+                deferred = true),
+        ForeignKey(entity = Author::class,
+                parentColumns = arrayOf("authorId"),
+                childColumns = arrayOf("authorId"),
+                onUpdate = ForeignKey.CASCADE,
+                onDelete = ForeignKey.CASCADE,
+                deferred = true)),
+        primaryKeys = arrayOf("bookId", "authorId"))
+data class BookAuthor(val bookId: String, val authorId: String)
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookWithPublisher.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookWithPublisher.kt
new file mode 100644
index 0000000..6516c23
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/BookWithPublisher.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Embedded
+
+
+data class BookWithPublisher(val bookId: String, val title: String,
+                             @Embedded val publisher: Publisher)
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Publisher.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Publisher.kt
new file mode 100644
index 0000000..ea1550a
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/Publisher.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Entity
+import android.arch.persistence.room.PrimaryKey
+
+@Entity
+data class Publisher(@PrimaryKey val publisherId: String, val name: String)
diff --git a/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/PublisherWithBooks.kt b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/PublisherWithBooks.kt
new file mode 100644
index 0000000..fe482b1
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/androidTest/java/android/arch/persistence/room/integration/kotlintestapp/vo/PublisherWithBooks.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.kotlintestapp.vo
+
+import android.arch.persistence.room.Embedded
+import android.arch.persistence.room.Relation
+
+class PublisherWithBooks {
+    @Embedded var publisher: Publisher? = null
+    @Relation(parentColumn = "publisherId", // publisher.publisherId
+            entityColumn = "bookPublisherId", // book.bookPublisherId
+            entity = Book::class)
+    var books: List<Book>? = null
+}
diff --git a/room/integration-tests/kotlintestapp/src/main/AndroidManifest.xml b/room/integration-tests/kotlintestapp/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..d079891
--- /dev/null
+++ b/room/integration-tests/kotlintestapp/src/main/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.arch.persistence.room.integration.kotlintestapp"/>
diff --git a/room/integration-tests/testapp/.gitignore b/room/integration-tests/testapp/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/room/integration-tests/testapp/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/room/integration-tests/testapp/build.gradle b/room/integration-tests/testapp/build.gradle
new file mode 100644
index 0000000..9873138
--- /dev/null
+++ b/room/integration-tests/testapp/build.gradle
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+apply plugin: 'com.android.application'
+
+project.ext.noDocs = true
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+        javaCompileOptions {
+            annotationProcessorOptions {
+                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
+            }
+        }
+    }
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+    sourceSets {
+        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
+    }
+}
+
+dependencies {
+    compile project(":room:common")
+    compile project(":room:db")
+    compile project(":room:db-impl")
+    compile project(':room:runtime')
+    compile project(':arch:runtime')
+    compile project(':arch:common')
+    compile project(':paging:common')
+    compile project(':lifecycle:extensions')
+    compile project(':lifecycle:runtime')
+    compile project(':lifecycle:common')
+    compile project(':room:rxjava2')
+    compile project(':paging:runtime')
+
+    compile libs.support.recyclerview
+    compile libs.support.app_compat
+    annotationProcessor project(":room:compiler")
+    androidTestAnnotationProcessor project(":room:compiler")
+
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+        exclude module: 'hamcrest-core'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+        exclude module: "hamcrest-core"
+    })
+    // IJ's gradle integration just cannot figure this out ...
+    androidTestCompile project(':lifecycle:extensions')
+    androidTestCompile project(':lifecycle:common')
+    androidTestCompile project(':lifecycle:runtime')
+    androidTestCompile project(':room:testing')
+    androidTestCompile project(':room:rxjava2')
+    androidTestCompile project(':arch:core-testing')
+    androidTestCompile libs.rx_java
+    androidTestCompile libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+}
+
+createAndroidCheckstyle(project)
+tasks['check'].dependsOn(tasks['connectedCheck'])
+
+uploadArchives.enabled = false
diff --git a/room/integration-tests/testapp/proguard-rules.pro b/room/integration-tests/testapp/proguard-rules.pro
new file mode 100644
index 0000000..b7210d1
--- /dev/null
+++ b/room/integration-tests/testapp/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/yboyar/android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/1.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/1.json
new file mode 100644
index 0000000..e05f095
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/1.json
@@ -0,0 +1,38 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 1,
+    "identityHash": "2f3557e56d7f665363f3e20d14787a59",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"2f3557e56d7f665363f3e20d14787a59\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/2.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/2.json
new file mode 100644
index 0000000..fc5a1b6
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/2.json
@@ -0,0 +1,64 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 2,
+    "identityHash": "aee9a6eed720c059df0f2ee0d6e96d89",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"aee9a6eed720c059df0f2ee0d6e96d89\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/3.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/3.json
new file mode 100644
index 0000000..f4629da
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/3.json
@@ -0,0 +1,70 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 3,
+    "identityHash": "3f2a99b6d768af0184e077808f7348fe",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `addedInV3` TEXT, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"3f2a99b6d768af0184e077808f7348fe\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/4.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/4.json
new file mode 100644
index 0000000..b5a0794
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/4.json
@@ -0,0 +1,101 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 4,
+    "identityHash": "abbae5f17d94ff7c2c7e05ca217ccc31",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `addedInV3` TEXT, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity3",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `removedInV5` TEXT, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "removedInV5",
+            "columnName": "removedInV5",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"abbae5f17d94ff7c2c7e05ca217ccc31\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/5.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/5.json
new file mode 100644
index 0000000..367b1f2
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/5.json
@@ -0,0 +1,95 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 5,
+    "identityHash": "5543c44fe679f4cf8f03093d66838068",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `addedInV3` TEXT, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity3",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"5543c44fe679f4cf8f03093d66838068\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/6.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/6.json
new file mode 100644
index 0000000..3468f5b
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/6.json
@@ -0,0 +1,70 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 6,
+    "identityHash": "3f2a99b6d768af0184e077808f7348fe",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `addedInV3` TEXT, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"3f2a99b6d768af0184e077808f7348fe\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/7.json b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/7.json
new file mode 100644
index 0000000..93a9682
--- /dev/null
+++ b/room/integration-tests/testapp/schemas/android.arch.persistence.room.integration.testapp.migration.MigrationDb/7.json
@@ -0,0 +1,118 @@
+{
+  "formatVersion": 1,
+  "database": {
+    "version": 7,
+    "identityHash": "03ff272b825e27b5c15545c85fe1b845",
+    "entities": [
+      {
+        "tableName": "Entity1",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [
+          {
+            "name": "index_Entity1_name",
+            "unique": true,
+            "columnNames": [
+              "name"
+            ],
+            "createSql": "CREATE UNIQUE INDEX `index_Entity1_name` ON `${TABLE_NAME}` (`name`)"
+          }
+        ],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity2",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `addedInV3` TEXT, `name` TEXT)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "addedInV3",
+            "columnName": "addedInV3",
+            "affinity": "TEXT",
+            "notNull": false
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": true
+        },
+        "indices": [],
+        "foreignKeys": []
+      },
+      {
+        "tableName": "Entity4",
+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`), FOREIGN KEY(`name`) REFERENCES `Entity1`(`name`) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)",
+        "fields": [
+          {
+            "fieldPath": "id",
+            "columnName": "id",
+            "affinity": "INTEGER",
+            "notNull": true
+          },
+          {
+            "fieldPath": "name",
+            "columnName": "name",
+            "affinity": "TEXT",
+            "notNull": false
+          }
+        ],
+        "primaryKey": {
+          "columnNames": [
+            "id"
+          ],
+          "autoGenerate": false
+        },
+        "indices": [],
+        "foreignKeys": [
+          {
+            "table": "Entity1",
+            "onDelete": "NO ACTION",
+            "onUpdate": "NO ACTION",
+            "columns": [
+              "name"
+            ],
+            "referencedColumns": [
+              "name"
+            ]
+          }
+        ]
+      }
+    ],
+    "setupQueries": [
+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"03ff272b825e27b5c15545c85fe1b845\")"
+    ]
+  }
+}
\ No newline at end of file
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/InvalidationTrackerTrojan.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/InvalidationTrackerTrojan.java
new file mode 100644
index 0000000..5fa15ac
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/InvalidationTrackerTrojan.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+/**
+ * Trojan class to be able to assert internal state.
+ */
+public class InvalidationTrackerTrojan {
+    public static int countObservers(InvalidationTracker tracker) {
+        return tracker.mObserverMap.size();
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/PKeyTestDatabase.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/PKeyTestDatabase.java
new file mode 100644
index 0000000..e61d808
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/PKeyTestDatabase.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.integration.testapp.vo.IntAutoIncPKeyEntity;
+import android.arch.persistence.room.integration.testapp.vo.IntegerAutoIncPKeyEntity;
+
+import java.util.List;
+
+@Database(entities = {IntAutoIncPKeyEntity.class, IntegerAutoIncPKeyEntity.class}, version = 1,
+        exportSchema = false)
+public abstract class PKeyTestDatabase extends RoomDatabase {
+    public abstract IntPKeyDao intPKeyDao();
+    public abstract IntegerPKeyDao integerPKeyDao();
+
+    @Dao
+    public interface IntPKeyDao {
+        @Insert
+        void insertMe(IntAutoIncPKeyEntity... items);
+        @Insert
+        long insertAndGetId(IntAutoIncPKeyEntity item);
+
+        @Insert
+        long[] insertAndGetIds(IntAutoIncPKeyEntity... item);
+
+        @Query("select * from IntAutoIncPKeyEntity WHERE pKey = :key")
+        IntAutoIncPKeyEntity getMe(int key);
+
+        @Query("select data from IntAutoIncPKeyEntity WHERE pKey IN(:ids)")
+        List<String> loadDataById(long... ids);
+    }
+
+    @Dao
+    public interface IntegerPKeyDao {
+        @Insert
+        void insertMe(IntegerAutoIncPKeyEntity items);
+        @Query("select * from IntegerAutoIncPKeyEntity WHERE pKey = :key")
+        IntegerAutoIncPKeyEntity getMe(int key);
+
+        @Insert
+        long insertAndGetId(IntegerAutoIncPKeyEntity item);
+
+        @Insert
+        long[] insertAndGetIds(IntegerAutoIncPKeyEntity... item);
+
+        @Query("select data from IntegerAutoIncPKeyEntity WHERE pKey IN(:ids)")
+        List<String> loadDataById(long... ids);
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/TestDatabase.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/TestDatabase.java
new file mode 100644
index 0000000..e573de1
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/TestDatabase.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp;
+
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.TypeConverter;
+import android.arch.persistence.room.TypeConverters;
+import android.arch.persistence.room.integration.testapp.dao.BlobEntityDao;
+import android.arch.persistence.room.integration.testapp.dao.PetCoupleDao;
+import android.arch.persistence.room.integration.testapp.dao.PetDao;
+import android.arch.persistence.room.integration.testapp.dao.ProductDao;
+import android.arch.persistence.room.integration.testapp.dao.SchoolDao;
+import android.arch.persistence.room.integration.testapp.dao.ToyDao;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.dao.UserPetDao;
+import android.arch.persistence.room.integration.testapp.vo.BlobEntity;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.PetCouple;
+import android.arch.persistence.room.integration.testapp.vo.Product;
+import android.arch.persistence.room.integration.testapp.vo.School;
+import android.arch.persistence.room.integration.testapp.vo.Toy;
+import android.arch.persistence.room.integration.testapp.vo.User;
+
+import java.util.Date;
+
+@Database(entities = {User.class, Pet.class, School.class, PetCouple.class, Toy.class,
+        BlobEntity.class, Product.class},
+        version = 1, exportSchema = false)
+@TypeConverters(TestDatabase.Converters.class)
+public abstract class TestDatabase extends RoomDatabase {
+    public abstract UserDao getUserDao();
+    public abstract PetDao getPetDao();
+    public abstract UserPetDao getUserPetDao();
+    public abstract SchoolDao getSchoolDao();
+    public abstract PetCoupleDao getPetCoupleDao();
+    public abstract ToyDao getToyDao();
+    public abstract BlobEntityDao getBlobEntityDao();
+    public abstract ProductDao getProductDao();
+
+    @SuppressWarnings("unused")
+    public static class Converters {
+        @TypeConverter
+        public Date fromTimestamp(Long value) {
+            return value == null ? null : new Date(value);
+        }
+
+        @TypeConverter
+        public Long dateToTimestamp(Date date) {
+            if (date == null) {
+                return null;
+            } else {
+                return date.getTime();
+            }
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/BlobEntityDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/BlobEntityDao.java
new file mode 100644
index 0000000..212eba7
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/BlobEntityDao.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.integration.testapp.vo.BlobEntity;
+
+import java.util.List;
+
+@Dao
+public interface BlobEntityDao {
+
+    @Insert
+    void insert(BlobEntity item);
+
+    @Query("SELECT * FROM BlobEntity")
+    List<BlobEntity> selectAll();
+
+    @Query("SELECT content FROM BlobEntity WHERE id = :id")
+    byte[] getContent(long id);
+
+    @Query("UPDATE BlobEntity SET content = :content WHERE id = :id")
+    void updateContent(long id, byte[] content);
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetCoupleDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetCoupleDao.java
new file mode 100644
index 0000000..4f7c4e2
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetCoupleDao.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.integration.testapp.vo.PetCouple;
+
+import java.util.List;
+
+@Dao
+public interface PetCoupleDao {
+    @Insert
+    void insert(PetCouple couple);
+
+    @Query("SELECT * FROM PetCouple")
+    List<PetCouple> loadAll();
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetDao.java
new file mode 100644
index 0000000..5179655
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/PetDao.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.OnConflictStrategy;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+
+@Dao
+public interface PetDao {
+    @Insert(onConflict = OnConflictStrategy.REPLACE)
+    void insertOrReplace(Pet... pets);
+
+    @Insert
+    void insertAll(Pet[] pets);
+
+    @Query("SELECT COUNT(*) FROM Pet")
+    int count();
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ProductDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ProductDao.java
new file mode 100644
index 0000000..417fb72
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ProductDao.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.integration.testapp.vo.Product;
+import android.support.annotation.NonNull;
+
+@Dao
+public interface ProductDao {
+
+    @Insert
+    long insert(@NonNull Product product);
+
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/SchoolDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/SchoolDao.java
new file mode 100644
index 0000000..7bb137f
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/SchoolDao.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.OnConflictStrategy;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.RoomWarnings;
+import android.arch.persistence.room.integration.testapp.vo.Coordinates;
+import android.arch.persistence.room.integration.testapp.vo.School;
+import android.arch.persistence.room.integration.testapp.vo.SchoolRef;
+
+import java.util.List;
+
+@Dao
+public abstract class SchoolDao {
+    @Insert(onConflict = OnConflictStrategy.REPLACE)
+    public abstract void insert(School... schools);
+
+    @Query("SELECT * from School WHERE address_street LIKE '%' || :street || '%'")
+    public abstract List<School> findByStreet(String street);
+
+    @Query("SELECT mName, manager_mName FROM School")
+    public abstract List<School> schoolAndManagerNames();
+
+    @Query("SELECT mName, manager_mName FROM School")
+    @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
+    public abstract List<SchoolRef> schoolAndManagerNamesAsPojo();
+
+    @Query("SELECT address_lat as lat, address_lng as lng FROM School WHERE mId = :schoolId")
+    public abstract Coordinates loadCoordinates(int schoolId);
+
+    @Query("SELECT address_lat, address_lng FROM School WHERE mId = :schoolId")
+    public abstract School loadCoordinatesAsSchool(int schoolId);
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ToyDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ToyDao.java
new file mode 100644
index 0000000..5d50a62
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/ToyDao.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.integration.testapp.vo.Toy;
+
+@Dao
+public interface ToyDao {
+    @Insert
+    void insert(Toy... toys);
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java
new file mode 100644
index 0000000..97461c0
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Delete;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.OnConflictStrategy;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Update;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.vo.AvgWeightByAge;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.util.paging.CountedDataSource;
+import android.arch.util.paging.LiveLazyListProvider;
+import android.database.Cursor;
+
+import org.reactivestreams.Publisher;
+
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import io.reactivex.Flowable;
+import io.reactivex.Maybe;
+import io.reactivex.Single;
+
+@SuppressWarnings("SameParameterValue")
+@Dao
+public abstract class UserDao {
+
+    private final TestDatabase mDatabase;
+
+    public UserDao(TestDatabase database) {
+        mDatabase = database;
+    }
+
+    @Query("select * from user where mName like :name")
+    public abstract List<User> findUsersByName(String name);
+
+    @Query("select * from user where mId = :id")
+    public abstract User load(int id);
+
+    @Query("select * from user where mId IN(:ids)")
+    public abstract User[] loadByIds(int... ids);
+
+    @Insert
+    public abstract void insert(User user);
+
+    @Insert(onConflict = OnConflictStrategy.REPLACE)
+    public abstract void insertOrReplace(User user);
+
+    @Delete
+    public abstract int delete(User user);
+
+    @Delete
+    public abstract int deleteAll(User[] users);
+
+    @Query("delete from user")
+    public abstract int deleteEverything();
+
+    @Update
+    public abstract int update(User user);
+
+    @Update
+    public abstract int updateAll(List<User> users);
+
+    @Insert
+    public abstract void insertAll(User[] users);
+
+    @Query("select * from user where mAdmin = :isAdmin")
+    public abstract List<User> findByAdmin(boolean isAdmin);
+
+    @Query("delete from user where mAge > :age")
+    public abstract int deleteAgeGreaterThan(int age);
+
+    @Query("delete from user where mId IN(:uids)")
+    public abstract int deleteByUids(int... uids);
+
+    @Query("delete from user where mAge >= :min AND mAge <= :max")
+    public abstract int deleteByAgeRange(int min, int max);
+
+    @Query("update user set mName = :name where mId = :id")
+    public abstract int updateById(int id, String name);
+
+    @Query("update user set mId = mId + :amount")
+    public abstract void incrementIds(int amount);
+
+    @Query("update user set mAge = mAge + 1")
+    public abstract void incrementAgeOfAll();
+
+    @Query("select mId from user order by mId ASC")
+    public abstract List<Integer> loadIds();
+
+    @Query("select * from user where mId = :id")
+    public abstract LiveData<User> liveUserById(int id);
+
+    @Query("select * from user where mName LIKE '%' || :name || '%' ORDER BY mId DESC")
+    public abstract LiveData<List<User>> liveUsersListByName(String name);
+
+    @Query("select * from user where length(mName) = :length")
+    public abstract List<User> findByNameLength(int length);
+
+    @Query("select * from user where mAge = :age")
+    public abstract List<User> findByAge(int age);
+
+    @Query("select mAge, AVG(mWeight) from user GROUP BY mAge ORDER BY 2 DESC")
+    public abstract List<AvgWeightByAge> weightByAge();
+
+    @Query("select mAge, AVG(mWeight) from user GROUP BY mAge ORDER BY 2 DESC LIMIT 1")
+    public abstract LiveData<AvgWeightByAge> maxWeightByAgeGroup();
+
+    @Query("select * from user where mBirthday > :from AND mBirthday < :to")
+    public abstract List<User> findByBirthdayRange(Date from, Date to);
+
+    @Query("select mId from user where mId IN (:ids)")
+    public abstract Cursor findUsersAsCursor(int... ids);
+
+    @Query("select * from user where mId = :id")
+    public abstract Flowable<User> flowableUserById(int id);
+
+    @Query("select * from user where mId = :id")
+    public abstract Maybe<User> maybeUserById(int id);
+
+    @Query("select * from user where mId IN (:ids)")
+    public abstract Maybe<List<User>> maybeUsersByIds(int... ids);
+
+    @Query("select * from user where mId = :id")
+    public abstract Single<User> singleUserById(int id);
+
+    @Query("select * from user where mId IN (:ids)")
+    public abstract Single<List<User>> singleUsersByIds(int... ids);
+
+    @Query("select COUNT(*) from user")
+    public abstract Flowable<Integer> flowableCountUsers();
+
+    @Query("select COUNT(*) from user")
+    public abstract Publisher<Integer> publisherCountUsers();
+
+    @Query("SELECT mBirthday from User where mId = :id")
+
+    public abstract Date getBirthday(int id);
+
+    @Query("SELECT COUNT(*) from user")
+    public abstract int count();
+
+    public void insertBothByRunnable(final User a, final User b) {
+        mDatabase.runInTransaction(new Runnable() {
+            @Override
+            public void run() {
+                insert(a);
+                insert(b);
+            }
+        });
+    }
+
+    public int insertBothByCallable(final User a, final User b) {
+        return mDatabase.runInTransaction(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                insert(a);
+                insert(b);
+                return 2;
+            }
+        });
+    }
+
+    @Query("SELECT * FROM user where mAge > :age")
+    public abstract LiveLazyListProvider<User> loadPagedByAge(int age);
+
+    @Query("SELECT * FROM user ORDER BY mAge DESC")
+    public abstract CountedDataSource<User> loadUsersByAgeDesc();
+
+    @Query("DELETE FROM User WHERE mId IN (:ids) AND mAge == :age")
+    public abstract int deleteByAgeAndIds(int age, List<Integer> ids);
+
+    @Query("UPDATE User set mWeight = :weight WHERE mId IN (:ids) AND mAge == :age")
+    public abstract int updateByAgeAndIds(float weight, int age, List<Integer> ids);
+
+    // QueryLoader
+
+    @Query("SELECT COUNT(*) from user")
+    public abstract Integer getUserCount();
+
+    //   name desc
+    @Query("SELECT * from user ORDER BY mName DESC LIMIT :limit OFFSET :offset")
+    public abstract List<User> userNameLimitOffset(int limit, int offset);
+
+    @Query("SELECT * from user WHERE mName < :key ORDER BY mName DESC LIMIT :limit")
+    public abstract List<User> userNameLoadAfter(String key, int limit);
+
+    @Query("SELECT * from user WHERE mName > :key ORDER BY mName ASC LIMIT :limit")
+    public abstract List<User> userNameLoadBefore(String key, int limit);
+
+    //    last asc, first desc, id asc
+    @Query("SELECT * from user"
+            + " ORDER BY mLastName DESC, mName ASC, mId DESC"
+            + " LIMIT :limit OFFSET :offset")
+    public abstract List<User> userComplexLimitOffset(int limit, int offset);
+
+    @Query("SELECT * from user"
+            + " WHERE mLastName < :lastName or (mLastName = :lastName and (mName > :name or (mName = :name and mId < :id)))"
+            + " ORDER BY mLastName DESC, mName ASC, mId DESC"
+            + " LIMIT :limit")
+    public abstract List<User> userComplexLoadAfter(String lastName, String name, int id, int limit);
+
+    @Query("SELECT * from user"
+            + " WHERE mLastName > :lastName or (mLastName = :lastName and (mName < :name or (mName = :name and mId > :id)))"
+            + " ORDER BY mLastName ASC, mName DESC, mId ASC"
+            + " LIMIT :limit")
+    public abstract List<User> userComplexLoadBefore(String lastName, String name, int id, int limit);
+
+
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserPetDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserPetDao.java
new file mode 100644
index 0000000..3507aee
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserPetDao.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.dao;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Delete;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Update;
+import android.arch.persistence.room.integration.testapp.vo.EmbeddedUserAndAllPets;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.persistence.room.integration.testapp.vo.UserAndAllPets;
+import android.arch.persistence.room.integration.testapp.vo.UserAndPet;
+import android.arch.persistence.room.integration.testapp.vo.UserAndPetNonNull;
+import android.arch.persistence.room.integration.testapp.vo.UserIdAndPetNames;
+import android.arch.persistence.room.integration.testapp.vo.UserWithPetsAndToys;
+
+import java.util.List;
+
+@Dao
+public interface UserPetDao {
+    @Query("SELECT * FROM User u, Pet p WHERE u.mId = p.mUserId")
+    List<UserAndPet> loadAll();
+
+    @Query("SELECT * FROM User u LEFT OUTER JOIN Pet p ON u.mId = p.mUserId")
+    List<UserAndPet> loadUsers();
+
+    @Query("SELECT * FROM User u LEFT OUTER JOIN Pet p ON u.mId = p.mUserId")
+    List<UserAndPetNonNull> loadUsersWithNonNullPet();
+
+    @Query("SELECT * FROM Pet p LEFT OUTER JOIN User u ON u.mId = p.mUserId")
+    List<UserAndPet> loadPets();
+
+    @Query("SELECT * FROM User u")
+    List<UserAndAllPets> loadAllUsersWithTheirPets();
+
+    @Query("SELECT * FROM User u")
+    List<UserIdAndPetNames> loadUserAndPetNames();
+
+    @Query("SELECT * FROM User u")
+    List<UserWithPetsAndToys> loadUserWithPetsAndToys();
+
+    @Query("SELECT * FROM User UNION ALL SELECT * FROM USER")
+    List<UserAndAllPets> unionByItself();
+
+    @Query("SELECT * FROM User u where u.mId = :userId")
+    LiveData<UserAndAllPets> liveUserWithPets(int userId);
+
+    @Query("SELECT * FROM User u where u.mId = :uid")
+    EmbeddedUserAndAllPets loadUserAndPetsAsEmbedded(int uid);
+
+    @Insert
+    void insertUserAndPet(User user, Pet pet);
+
+    @Update
+    void updateUsersAndPets(User[] users, Pet[] pets);
+
+    @Delete
+    void delete2UsersAndPets(User user1, User user2, Pet[] pets);
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationDb.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationDb.java
new file mode 100644
index 0000000..4a95ad8
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationDb.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.migration;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.ForeignKey;
+import android.arch.persistence.room.Ignore;
+import android.arch.persistence.room.Index;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.RoomDatabase;
+import android.content.ContentValues;
+import android.database.sqlite.SQLiteDatabase;
+
+import java.util.List;
+
+@SuppressWarnings("WeakerAccess")
+@Database(version = MigrationDb.LATEST_VERSION,
+        entities = {MigrationDb.Entity1.class, MigrationDb.Entity2.class,
+                MigrationDb.Entity4.class})
+public abstract class MigrationDb extends RoomDatabase {
+    static final int LATEST_VERSION = 7;
+    abstract MigrationDao dao();
+    @Entity(indices = {@Index(value = "name", unique = true)})
+    static class Entity1 {
+        public static final String TABLE_NAME = "Entity1";
+        @PrimaryKey
+        public int id;
+        public String name;
+    }
+
+    @Entity
+    static class Entity2 {
+        public static final String TABLE_NAME = "Entity2";
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String addedInV3;
+        public String name;
+    }
+
+    @Entity
+    static class Entity3 { // added in version 4, removed at 6
+        public static final String TABLE_NAME = "Entity3";
+        @PrimaryKey
+        public int id;
+        @Ignore //removed at 5
+        public String removedInV5;
+        public String name;
+    }
+
+    @Entity(foreignKeys = {
+            @ForeignKey(entity = Entity1.class,
+            parentColumns = "name",
+            childColumns = "name",
+            deferred = true)})
+    static class Entity4 {
+        public static final String TABLE_NAME = "Entity4";
+        @PrimaryKey
+        public int id;
+        public String name;
+    }
+
+    @Dao
+    interface MigrationDao {
+        @Query("SELECT * from Entity1 ORDER BY id ASC")
+        List<Entity1> loadAllEntity1s();
+        @Query("SELECT * from Entity2 ORDER BY id ASC")
+        List<Entity2> loadAllEntity2s();
+        @Query("SELECT * from Entity2 ORDER BY id ASC")
+        List<Entity2Pojo> loadAllEntity2sAsPojo();
+        @Insert
+        void insert(Entity2... entity2);
+    }
+
+    static class Entity2Pojo extends Entity2 {
+    }
+
+    /**
+     * not a real dao because database will change.
+     */
+    static class Dao_V1 {
+        final SupportSQLiteDatabase mDb;
+
+        Dao_V1(SupportSQLiteDatabase db) {
+            mDb = db;
+        }
+
+        public void insertIntoEntity1(int id, String name) {
+            ContentValues values = new ContentValues();
+            values.put("id", id);
+            values.put("name", name);
+            long insertionId = mDb.insert(Entity1.TABLE_NAME,
+                    SQLiteDatabase.CONFLICT_REPLACE, values);
+            if (insertionId == -1) {
+                throw new RuntimeException("test sanity failure");
+            }
+        }
+    }
+
+    /**
+     * not a real dao because database will change.
+     */
+    static class Dao_V2 {
+        final SupportSQLiteDatabase mDb;
+
+        Dao_V2(SupportSQLiteDatabase db) {
+            mDb = db;
+        }
+
+        public void insertIntoEntity2(int id, String name) {
+            ContentValues values = new ContentValues();
+            values.put("id", id);
+            values.put("name", name);
+            long insertionId = mDb.insert(Entity2.TABLE_NAME,
+                    SQLiteDatabase.CONFLICT_REPLACE, values);
+            if (insertionId == -1) {
+                throw new RuntimeException("test sanity failure");
+            }
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationTest.java
new file mode 100644
index 0000000..aa297ed
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/migration/MigrationTest.java
@@ -0,0 +1,337 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.migration;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.migration.Migration;
+import android.arch.persistence.room.testing.MigrationTestHelper;
+import android.arch.persistence.room.util.TableInfo;
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Test custom database migrations.
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class MigrationTest {
+    private static final String TEST_DB = "migration-test";
+    @Rule
+    public MigrationTestHelper helper;
+
+    public MigrationTest() {
+        helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
+                MigrationDb.class.getCanonicalName());
+    }
+
+    @Test
+    public void giveBadResource() throws IOException {
+        MigrationTestHelper helper = new MigrationTestHelper(
+                InstrumentationRegistry.getInstrumentation(),
+                "foo", new FrameworkSQLiteOpenHelperFactory());
+        try {
+            helper.createDatabase(TEST_DB, 1);
+            throw new AssertionError("must have failed with missing file exception");
+        } catch (FileNotFoundException exception) {
+            assertThat(exception.getMessage(), containsString("Cannot find"));
+        }
+    }
+
+    @Test
+    public void startInCurrentVersion() throws IOException {
+        SupportSQLiteDatabase db = helper.createDatabase(TEST_DB,
+                MigrationDb.LATEST_VERSION);
+        final MigrationDb.Dao_V1 dao = new MigrationDb.Dao_V1(db);
+        dao.insertIntoEntity1(2, "x");
+        db.close();
+        MigrationDb migrationDb = getLatestDb();
+        List<MigrationDb.Entity1> items = migrationDb.dao().loadAllEntity1s();
+        helper.closeWhenFinished(migrationDb);
+        assertThat(items.size(), is(1));
+    }
+
+    @Test
+    public void addTable() throws IOException {
+        SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
+        final MigrationDb.Dao_V1 dao = new MigrationDb.Dao_V1(db);
+        dao.insertIntoEntity1(2, "foo");
+        dao.insertIntoEntity1(3, "bar");
+        db.close();
+        db = helper.runMigrationsAndValidate(TEST_DB, 2, true, MIGRATION_1_2);
+        new MigrationDb.Dao_V2(db).insertIntoEntity2(3, "blah");
+        db.close();
+        MigrationDb migrationDb = getLatestDb();
+        List<MigrationDb.Entity1> entity1s = migrationDb.dao().loadAllEntity1s();
+
+        assertThat(entity1s.size(), is(2));
+        MigrationDb.Entity2 entity2 = new MigrationDb.Entity2();
+        entity2.id = 2;
+        entity2.name = "bar";
+        // assert no error happens
+        migrationDb.dao().insert(entity2);
+        List<MigrationDb.Entity2> entity2s = migrationDb.dao().loadAllEntity2s();
+        assertThat(entity2s.size(), is(2));
+    }
+
+    private MigrationDb getLatestDb() {
+        MigrationDb db = Room.databaseBuilder(
+                InstrumentationRegistry.getInstrumentation().getTargetContext(),
+                MigrationDb.class, TEST_DB).addMigrations(ALL_MIGRATIONS).build();
+        // trigger open
+        db.beginTransaction();
+        db.endTransaction();
+        helper.closeWhenFinished(db);
+        return db;
+    }
+
+    @Test
+    public void addTableFailure() throws IOException {
+        testFailure(1, 2);
+    }
+
+    @Test
+    public void addColumnFailure() throws IOException {
+        SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 2);
+        db.close();
+        IllegalStateException caught = null;
+        try {
+            helper.runMigrationsAndValidate(TEST_DB, 3, true, new EmptyMigration(2, 3));
+        } catch (IllegalStateException ex) {
+            caught = ex;
+        }
+        assertThat(caught, instanceOf(IllegalStateException.class));
+    }
+
+    @Test
+    public void addColumn() throws IOException {
+        SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 2);
+        MigrationDb.Dao_V2 v2Dao = new MigrationDb.Dao_V2(db);
+        v2Dao.insertIntoEntity2(7, "blah");
+        db.close();
+        helper.runMigrationsAndValidate(TEST_DB, 3, true, MIGRATION_2_3);
+        // trigger open.
+        MigrationDb migrationDb = getLatestDb();
+        List<MigrationDb.Entity2> entity2s = migrationDb.dao().loadAllEntity2s();
+        assertThat(entity2s.size(), is(1));
+        assertThat(entity2s.get(0).name, is("blah"));
+        assertThat(entity2s.get(0).addedInV3, is(nullValue()));
+
+        List<MigrationDb.Entity2Pojo> entity2Pojos = migrationDb.dao().loadAllEntity2sAsPojo();
+        assertThat(entity2Pojos.size(), is(1));
+        assertThat(entity2Pojos.get(0).name, is("blah"));
+        assertThat(entity2Pojos.get(0).addedInV3, is(nullValue()));
+    }
+
+    @Test
+    public void failedToRemoveColumn() throws IOException {
+        testFailure(4, 5);
+    }
+
+    @Test
+    public void removeColumn() throws IOException {
+        helper.createDatabase(TEST_DB, 4);
+        final SupportSQLiteDatabase db = helper.runMigrationsAndValidate(TEST_DB,
+                5, true, MIGRATION_4_5);
+        final TableInfo info = TableInfo.read(db, MigrationDb.Entity3.TABLE_NAME);
+        assertThat(info.columns.size(), is(2));
+    }
+
+    @Test
+    public void dropTable() throws IOException {
+        helper.createDatabase(TEST_DB, 5);
+        final SupportSQLiteDatabase db = helper.runMigrationsAndValidate(TEST_DB,
+                6, true, MIGRATION_5_6);
+        final TableInfo info = TableInfo.read(db, MigrationDb.Entity3.TABLE_NAME);
+        assertThat(info.columns.size(), is(0));
+    }
+
+    @Test
+    public void failedToDropTable() throws IOException {
+        testFailure(5, 6);
+    }
+
+    @Test
+    public void failedToDropTableDontVerify() throws IOException {
+        helper.createDatabase(TEST_DB, 5);
+        final SupportSQLiteDatabase db = helper.runMigrationsAndValidate(TEST_DB,
+                6, false, new EmptyMigration(5, 6));
+        final TableInfo info = TableInfo.read(db, MigrationDb.Entity3.TABLE_NAME);
+        assertThat(info.columns.size(), is(2));
+    }
+
+    @Test
+    public void failedForeignKey() throws IOException {
+        final SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 6);
+        db.close();
+        Throwable throwable = null;
+        try {
+            helper.runMigrationsAndValidate(TEST_DB,
+                    7, false, new Migration(6, 7) {
+                        @Override
+                        public void migrate(SupportSQLiteDatabase database) {
+                            database.execSQL("CREATE TABLE Entity4 (`id` INTEGER NOT NULL,"
+                                    + " `name` TEXT, PRIMARY KEY(`id`))");
+                        }
+                    });
+        } catch (Throwable t) {
+            throwable = t;
+        }
+        assertThat(throwable, instanceOf(IllegalStateException.class));
+        //noinspection ConstantConditions
+        assertThat(throwable.getMessage(), containsString("Migration failed"));
+    }
+
+    @Test
+    public void newTableWithForeignKey() throws IOException {
+        helper.createDatabase(TEST_DB, 6);
+        final SupportSQLiteDatabase db = helper.runMigrationsAndValidate(TEST_DB,
+                7, false, MIGRATION_6_7);
+        final TableInfo info = TableInfo.read(db, MigrationDb.Entity4.TABLE_NAME);
+        assertThat(info.foreignKeys.size(), is(1));
+    }
+
+    @Test
+    public void missingMigration() throws IOException {
+        SupportSQLiteDatabase database = helper.createDatabase(TEST_DB, 1);
+        database.close();
+        try {
+            Context targetContext = InstrumentationRegistry.getTargetContext();
+            MigrationDb db = Room.databaseBuilder(targetContext, MigrationDb.class, TEST_DB)
+                    .build();
+            db.dao().loadAllEntity1s();
+            throw new AssertionError("Should've failed :/");
+        } catch (IllegalStateException ignored) {
+        }
+    }
+
+    @Test
+    public void missingMigrationNuke() throws IOException {
+        SupportSQLiteDatabase database = helper.createDatabase(TEST_DB, 1);
+        final MigrationDb.Dao_V1 dao = new MigrationDb.Dao_V1(database);
+        dao.insertIntoEntity1(2, "foo");
+        dao.insertIntoEntity1(3, "bar");
+        database.close();
+
+        Context targetContext = InstrumentationRegistry.getTargetContext();
+        MigrationDb db = Room.databaseBuilder(targetContext, MigrationDb.class, TEST_DB)
+                .fallbackToDestructiveMigration()
+                .build();
+        assertThat(db.dao().loadAllEntity1s().size(), is(0));
+        db.close();
+    }
+
+    private void testFailure(int startVersion, int endVersion) throws IOException {
+        final SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, startVersion);
+        db.close();
+        Throwable throwable = null;
+        try {
+            helper.runMigrationsAndValidate(TEST_DB, endVersion, true,
+                    new EmptyMigration(startVersion, endVersion));
+        } catch (Throwable t) {
+            throwable = t;
+        }
+        assertThat(throwable, instanceOf(IllegalStateException.class));
+        //noinspection ConstantConditions
+        assertThat(throwable.getMessage(), containsString("Migration failed"));
+    }
+
+    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity2` ("
+                    + "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+                    + " `name` TEXT)");
+        }
+    };
+
+    private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("ALTER TABLE " + MigrationDb.Entity2.TABLE_NAME
+                    + " ADD COLUMN addedInV3 TEXT");
+        }
+    };
+
+    private static final Migration MIGRATION_3_4 = new Migration(3, 4) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3` (`id` INTEGER NOT NULL,"
+                    + " `removedInV5` TEXT, `name` TEXT, PRIMARY KEY(`id`))");
+        }
+    };
+
+    private static final Migration MIGRATION_4_5 = new Migration(4, 5) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3_New` (`id` INTEGER NOT NULL,"
+                    + " `name` TEXT, PRIMARY KEY(`id`))");
+            database.execSQL("INSERT INTO Entity3_New(`id`, `name`) "
+                    + "SELECT `id`, `name` FROM Entity3");
+            database.execSQL("DROP TABLE Entity3");
+            database.execSQL("ALTER TABLE Entity3_New RENAME TO Entity3");
+        }
+    };
+
+    private static final Migration MIGRATION_5_6 = new Migration(5, 6) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("DROP TABLE " + MigrationDb.Entity3.TABLE_NAME);
+        }
+    };
+
+    private static final Migration MIGRATION_6_7 = new Migration(6, 7) {
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            database.execSQL("CREATE TABLE IF NOT EXISTS " + MigrationDb.Entity4.TABLE_NAME
+                    + " (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`),"
+                    + " FOREIGN KEY(`name`) REFERENCES `Entity1`(`name`)"
+                    + " ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)");
+        }
+    };
+
+    private static final Migration[] ALL_MIGRATIONS = new Migration[]{MIGRATION_1_2,
+            MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7};
+
+    static final class EmptyMigration extends Migration {
+        EmptyMigration(int startVersion, int endVersion) {
+            super(startVersion, endVersion);
+        }
+
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+            // do nothing
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java
new file mode 100644
index 0000000..961a07e
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.paging;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.persistence.room.integration.testapp.test.TestDatabaseTest;
+import android.arch.persistence.room.integration.testapp.test.TestUtil;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.util.paging.CountedDataSource;
+import android.support.annotation.NonNull;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class LimitOffsetDataSourceTest extends TestDatabaseTest {
+    @Test
+    public void emptyPage() {
+        CountedDataSource<User> dataSource = mUserDao.loadUsersByAgeDesc();
+        assertThat(dataSource.loadCount(), is(0));
+    }
+
+    @Test
+    public void initial() {
+        List<User> users = createTestData();
+        CountedDataSource<User> dataSource = mUserDao.loadUsersByAgeDesc();
+        assertThat(dataSource.loadCount(), is(10));
+        List<User> initial = dataSource.loadAfterInitial(-1, 1);
+        assertThat(initial.get(0), is(users.get(0)));
+        List<User> second = dataSource.loadAfterInitial(0, 1);
+        assertThat(second.get(0), is(users.get(1)));
+    }
+
+    @Test
+    public void loadAll() {
+        List<User> users = createTestData();
+
+        CountedDataSource<User> dataSource = mUserDao.loadUsersByAgeDesc();
+        List<User> all = dataSource.loadAfterInitial(-1, 10);
+        assertThat(users, is(all));
+    }
+
+    @Test
+    public void loadAfter() {
+        List<User> users = createTestData();
+        CountedDataSource<User> dataSource = mUserDao.loadUsersByAgeDesc();
+        List<User> result = dataSource.loadAfter(3, users.get(3), 2);
+        assertThat(result, is(users.subList(4, 6)));
+    }
+
+    @Test
+    public void loadBefore() {
+        List<User> users = createTestData();
+        CountedDataSource<User> dataSource = mUserDao.loadUsersByAgeDesc();
+        List<User> result = dataSource.loadBefore(5, users.get(5), 3);
+        List<User> expected = new ArrayList<>(users.subList(2, 5));
+        Collections.reverse(expected);
+        assertThat(result, is(expected));
+    }
+
+    @NonNull
+    private List<User> createTestData() {
+        List<User> users = new ArrayList<>();
+        for (int i = 0; i < 10; i++) {
+            User user = TestUtil.createUser(i);
+            user.setAge(1);
+            mUserDao.insert(user);
+            users.add(user);
+        }
+        return users;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LiveLazyListProviderTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LiveLazyListProviderTest.java
new file mode 100644
index 0000000..d9472c1
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LiveLazyListProviderTest.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.paging;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.testing.CountingTaskExecutorRule;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.Observer;
+import android.arch.persistence.room.integration.testapp.test.TestDatabaseTest;
+import android.arch.persistence.room.integration.testapp.test.TestUtil;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.util.paging.LazyList;
+import android.arch.util.paging.ListConfig;
+import android.support.annotation.Nullable;
+import android.support.test.filters.LargeTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+@RunWith(AndroidJUnit4.class)
+public class LiveLazyListProviderTest extends TestDatabaseTest {
+    @Rule
+    public CountingTaskExecutorRule mExecutorRule = new CountingTaskExecutorRule();
+    @Test
+    @LargeTest
+    public void getUsersAsLazyList()
+            throws InterruptedException, ExecutionException, TimeoutException {
+        mDatabase.beginTransaction();
+        try {
+            for (int i = 0; i < 100; i++) {
+                final User user = TestUtil.createUser(i + 1);
+                user.setAge(i);
+                mUserDao.insert(user);
+            }
+            mDatabase.setTransactionSuccessful();
+        } finally {
+            mDatabase.endTransaction();
+        }
+        assertThat(mUserDao.count(), is(100));
+        final LiveData<LazyList<User>> livePagedUsers = mUserDao.loadPagedByAge(3).create(
+                ListConfig.builder().pageSize(10).prefetchDistance(1).create());
+
+        final TestLifecycleOwner testOwner = new TestLifecycleOwner();
+        testOwner.handleEvent(Lifecycle.Event.ON_CREATE);
+        drain();
+        LazyListObserver<User> observer = new LazyListObserver<>();
+
+        observe(livePagedUsers, testOwner, observer);
+        assertThat(observer.get(), nullValue());
+        observer.reset();
+
+        testOwner.handleEvent(Lifecycle.Event.ON_START);
+        drain();
+
+        LazyList<User> lazyList1 = observer.get();
+        assertThat(lazyList1, is(notNullValue()));
+
+        assertThat(lazyList1.size(), is(96));
+        assertThat(lazyList1.get(20), is(nullValue()));
+        drain();
+        assertThat(lazyList1.get(31), nullValue());
+        assertThat(lazyList1.get(20), notNullValue());
+        assertThat(lazyList1.get(16), notNullValue());
+
+        drain();
+        assertThat(lazyList1.get(31), notNullValue());
+        assertThat(lazyList1.get(50), nullValue());
+        drain();
+        assertThat(lazyList1.get(50), notNullValue());
+        observer.reset();
+        // now invalidate the database but don't get the new paged list
+        mUserDao.updateById(50, "foo");
+        assertThat(lazyList1.get(70), nullValue());
+        drain();
+        assertThat(lazyList1.get(70), nullValue());
+        LazyList<User> lazyList = observer.get();
+        assertThat(lazyList.get(70), notNullValue());
+    }
+
+    private void drain() throws InterruptedException, TimeoutException {
+        mExecutorRule.drainTasks(60, TimeUnit.SECONDS);
+    }
+
+    private void observe(final LiveData liveData, final LifecycleOwner provider,
+            final Observer observer) throws ExecutionException, InterruptedException {
+        FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                //noinspection unchecked
+                liveData.observe(provider, observer);
+                return null;
+            }
+        });
+        AppToolkitTaskExecutor.getInstance().executeOnMainThread(futureTask);
+        futureTask.get();
+    }
+
+    static class TestLifecycleOwner implements LifecycleOwner {
+
+        private LifecycleRegistry mLifecycle;
+
+        TestLifecycleOwner() {
+            mLifecycle = new LifecycleRegistry(this);
+        }
+
+        @Override
+        public Lifecycle getLifecycle() {
+            return mLifecycle;
+        }
+
+        void handleEvent(Lifecycle.Event event) {
+            mLifecycle.handleLifecycleEvent(event);
+        }
+    }
+
+    private static class LazyListObserver<T> implements Observer<LazyList<T>> {
+        private LazyList<T> mList;
+        public void reset() {
+            mList = null;
+        }
+
+        public LazyList<T> get() {
+            return mList;
+        }
+
+        @Override
+        public void onChanged(@Nullable LazyList<T> lazyList) {
+            mList = lazyList;
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ComplexQueryDataSourceTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ComplexQueryDataSourceTest.java
new file mode 100644
index 0000000..5b44c08
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ComplexQueryDataSourceTest.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.util.paging.CountedDataSource;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class ComplexQueryDataSourceTest extends TestDatabaseTest {
+    /**
+     * Proper, keyed implementation.
+     */
+    public class KeyedUserQueryDataSource extends CountedDataSource<User> {
+        @Override
+        public int loadCount() {
+            return mUserDao.getUserCount();
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfterInitial(int position, int pageSize) {
+            return mUserDao.userComplexLimitOffset(pageSize, position + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfter(int currentEndIndex, @NonNull User currentEndItem,
+                int pageSize) {
+            return mUserDao.userComplexLoadAfter(
+                    currentEndItem.getLastName(),
+                    currentEndItem.getName(),
+                    currentEndItem.getId(),
+                    pageSize);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadBefore(int currentBeginIndex, @NonNull User currentBeginItem,
+                int pageSize) {
+            return mUserDao.userComplexLoadBefore(
+                    currentBeginItem.getLastName(),
+                    currentBeginItem.getName(),
+                    currentBeginItem.getId(),
+                    pageSize);
+        }
+    }
+
+    /**
+     * Lazy, LIMIT/OFFSET implementation.
+     */
+    public class OffsetUserQueryDataSource extends CountedDataSource<User> {
+
+        @Override
+        public int loadCount() {
+            return mUserDao.getUserCount();
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfterInitial(int position, int pageSize) {
+            return mUserDao.userComplexLimitOffset(pageSize, position + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfter(int currentEndIndex, @NonNull User currentEndItem,
+                int pageSize) {
+            return mUserDao.userComplexLimitOffset(pageSize, currentEndIndex + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadBefore(int currentBeginIndex, @NonNull User currentBeginItem,
+                int pageSize) {
+            int targetOffset = currentBeginIndex - pageSize;
+            int offset = Math.max(0, targetOffset);
+            int limit = Math.min(pageSize, pageSize + targetOffset);
+
+            List<User> users = mUserDao.userComplexLimitOffset(limit, offset);
+            Collections.reverse(users); // :P
+            return users;
+        }
+    }
+
+    private static final User[] USERS_BY_LAST_FIRST_ID = new User[100];
+
+    @BeforeClass
+    public static void setupClass() {
+        String[] lastNames = new String[10];
+
+        String[] firstNames = new String[10];
+        for (int i = 0; i < 10; i++) {
+            lastNames[i] = "f" + (char) ('a' + i);
+            firstNames[i] = "l" + (char) ('a' + i);
+        }
+
+        for (int i = 0; i < USERS_BY_LAST_FIRST_ID.length; i++) {
+            User user = new User();
+            user.setId(i);
+            user.setName(firstNames[i % 10]);
+            user.setLastName(lastNames[(i / 10) % 10]);
+            user.setAge((int) (10 + Math.random() * 50));
+            user.setCustomField(UUID.randomUUID().toString());
+            user.setBirthday(new Date());
+            USERS_BY_LAST_FIRST_ID[i] = user;
+        }
+    }
+
+    @Before
+    public void setup() {
+        mUserDao.insertAll(USERS_BY_LAST_FIRST_ID);
+
+        Arrays.sort(USERS_BY_LAST_FIRST_ID, new Comparator<User>() {
+            @Override
+            public int compare(User o1, User o2) {
+                int diff = o2.getLastName().compareTo(o1.getLastName());
+                if (diff != 0) {
+                    return diff;
+                }
+                diff = o2.getName().compareTo(o1.getName());
+                if (diff != 0) {
+                    return -diff; // Note: 'mName' is ASC, therefore diff reversed
+                }
+
+                return o2.getId() - o1.getId();
+            }
+        });
+    }
+
+    @Test
+    public void testKeyedQueryDataSource() {
+        QueryDataSourceTest.verifyUserDataSource(USERS_BY_LAST_FIRST_ID,
+                new KeyedUserQueryDataSource());
+    }
+
+    @Test
+    public void testIndexedQueryDataSourceFull() {
+        QueryDataSourceTest.verifyUserDataSource(USERS_BY_LAST_FIRST_ID,
+                new OffsetUserQueryDataSource());
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ConstructorTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ConstructorTest.java
new file mode 100644
index 0000000..4e8fa97
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ConstructorTest.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SuppressWarnings("SqlNoDataSourceInspection")
+@SmallTest
+public class ConstructorTest {
+    @Database(version = 1, entities = {FullConstructor.class, PartialConstructor.class},
+            exportSchema = false)
+    abstract static class MyDb extends RoomDatabase {
+        abstract MyDao dao();
+    }
+
+    @Dao
+    interface MyDao {
+        @Insert
+        void insertFull(FullConstructor... full);
+
+        @Query("SELECT * FROM fc WHERE a = :a")
+        FullConstructor loadFull(int a);
+
+        @Insert
+        void insertPartial(PartialConstructor... partial);
+
+        @Query("SELECT * FROM pc WHERE a = :a")
+        PartialConstructor loadPartial(int a);
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(tableName = "fc")
+    static class FullConstructor {
+        @PrimaryKey
+        public final int a;
+        public final int b;
+        @Embedded
+        public final MyEmbedded embedded;
+
+        FullConstructor(int a, int b, MyEmbedded embedded) {
+            this.a = a;
+            this.b = b;
+            this.embedded = embedded;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            FullConstructor that = (FullConstructor) o;
+
+            if (a != that.a) return false;
+            //noinspection SimplifiableIfStatement
+            if (b != that.b) return false;
+            return embedded != null ? embedded.equals(that.embedded)
+                    : that.embedded == null;
+        }
+
+        @Override
+        public int hashCode() {
+            int result = a;
+            result = 31 * result + b;
+            result = 31 * result + (embedded != null ? embedded.hashCode() : 0);
+            return result;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(tableName = "pc")
+    static class PartialConstructor {
+        @PrimaryKey
+        public final int a;
+        public int b;
+        @Embedded
+        private MyEmbedded mEmbedded;
+
+        PartialConstructor(int a) {
+            this.a = a;
+        }
+
+        public MyEmbedded getEmbedded() {
+            return mEmbedded;
+        }
+
+        public void setEmbedded(MyEmbedded embedded) {
+            mEmbedded = embedded;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            PartialConstructor that = (PartialConstructor) o;
+
+            if (a != that.a) return false;
+            //noinspection SimplifiableIfStatement
+            if (b != that.b) return false;
+            return mEmbedded != null ? mEmbedded.equals(that.mEmbedded)
+                    : that.mEmbedded == null;
+        }
+
+        @Override
+        public int hashCode() {
+            int result = a;
+            result = 31 * result + b;
+            result = 31 * result + (mEmbedded != null ? mEmbedded.hashCode() : 0);
+            return result;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    static class MyEmbedded {
+        public final String text;
+
+        MyEmbedded(String text) {
+            this.text = text;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            MyEmbedded that = (MyEmbedded) o;
+
+            return text != null ? text.equals(that.text) : that.text == null;
+        }
+
+        @Override
+        public int hashCode() {
+            return text != null ? text.hashCode() : 0;
+        }
+    }
+
+    private MyDb mDb;
+    private MyDao mDao;
+
+    @Before
+    public void init() {
+        mDb = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), MyDb.class)
+                .build();
+        mDao = mDb.dao();
+    }
+
+    @Test
+    public void insertAndReadFullConstructor() {
+        FullConstructor inserted = new FullConstructor(1, 2, null);
+        mDao.insertFull(inserted);
+        final FullConstructor load = mDao.loadFull(1);
+        assertThat(load, is(inserted));
+    }
+
+    @Test
+    public void insertAndReadPartial() {
+        PartialConstructor item = new PartialConstructor(3);
+        item.b = 7;
+        mDao.insertPartial(item);
+        PartialConstructor load = mDao.loadPartial(3);
+        assertThat(load, is(item));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/CustomDatabaseTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/CustomDatabaseTest.java
new file mode 100644
index 0000000..353c2e3
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/CustomDatabaseTest.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.mockito.AdditionalAnswers.delegatesTo;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.SupportSQLiteQuery;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.integration.testapp.database.Customer;
+import android.arch.persistence.room.integration.testapp.database.SampleDatabase;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteException;
+import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.LargeTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class CustomDatabaseTest {
+
+    @Test
+    public void invalidationTrackerAfterClose() {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        RoomDatabase.Builder<SampleDatabase> builder =
+                Room.databaseBuilder(context, SampleDatabase.class, "db")
+                        .openHelperFactory(new RethrowExceptionFactory());
+        Customer customer = new Customer();
+        for (int i = 0; i < 100; i++) {
+            SampleDatabase db = builder.build();
+            customer.setId(i);
+            db.getCustomerDao().insert(customer);
+            // Give InvalidationTracker enough time to start #mRefreshRunnable and pass the
+            // initialization check.
+            SystemClock.sleep(1);
+            // InvalidationTracker#mRefreshRunnable will cause race condition if its database query
+            // happens after close.
+            db.close();
+        }
+    }
+
+    /**
+     * This is mostly {@link FrameworkSQLiteOpenHelperFactory}, but the returned {@link
+     * SupportSQLiteDatabase} fails with {@link RuntimeException} instead of {@link
+     * IllegalStateException} or {@link SQLiteException}. This way, we can simulate custom database
+     * implementation that throws its own exception types.
+     */
+    private static class RethrowExceptionFactory implements SupportSQLiteOpenHelper.Factory {
+
+        @Override
+        public SupportSQLiteOpenHelper create(SupportSQLiteOpenHelper.Configuration configuration) {
+            final FrameworkSQLiteOpenHelperFactory factory = new FrameworkSQLiteOpenHelperFactory();
+            final SupportSQLiteOpenHelper helper = factory.create(configuration);
+            SupportSQLiteOpenHelper helperMock = mock(SupportSQLiteOpenHelper.class,
+                    delegatesTo(helper));
+            // Inject mocks to the object hierarchy.
+            doAnswer(new Answer() {
+                @Override
+                public SupportSQLiteDatabase answer(InvocationOnMock invocation)
+                        throws Throwable {
+                    final SupportSQLiteDatabase db = helper.getWritableDatabase();
+                    SupportSQLiteDatabase dbMock = mock(SupportSQLiteDatabase.class,
+                            delegatesTo(db));
+                    doAnswer(new Answer() {
+                        @Override
+                        public Cursor answer(InvocationOnMock invocation) throws Throwable {
+                            SupportSQLiteQuery query = invocation.getArgument(0);
+                            try {
+                                return db.query(query);
+                            } catch (IllegalStateException | SQLiteException e) {
+                                // Rethrow the exception in order to simulate the way custom
+                                // database implementation throws its own exception types.
+                                throw new RuntimeException("closed", e);
+                            }
+                        }
+                    }).when(dbMock).query(any(SupportSQLiteQuery.class));
+                    return dbMock;
+                }
+            }).when(helperMock).getWritableDatabase();
+            return helperMock;
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/DatabaseCallbackTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/DatabaseCallbackTest.java
new file mode 100644
index 0000000..579b3e4
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/DatabaseCallbackTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.core.IsCollectionContaining.hasItem;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.content.Context;
+import android.database.Cursor;
+import android.support.annotation.NonNull;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+public class DatabaseCallbackTest {
+
+    @Test
+    @MediumTest
+    public void createAndOpen() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        TestDatabaseCallback callback1 = new TestDatabaseCallback();
+        TestDatabase db1 = Room.databaseBuilder(context, TestDatabase.class, "test")
+                .addCallback(callback1)
+                .build();
+        assertFalse(callback1.mCreated);
+        assertFalse(callback1.mOpened);
+        User user1 = TestUtil.createUser(3);
+        user1.setName("george");
+        db1.getUserDao().insert(user1);
+        assertTrue(callback1.mCreated);
+        assertTrue(callback1.mOpened);
+        TestDatabaseCallback callback2 = new TestDatabaseCallback();
+        TestDatabase db2 = Room.databaseBuilder(context, TestDatabase.class, "test")
+                .addCallback(callback2)
+                .build();
+        assertFalse(callback2.mCreated);
+        assertFalse(callback2.mOpened);
+        User user2 = db2.getUserDao().load(3);
+        assertThat(user2.getName(), is("george"));
+        assertFalse(callback2.mCreated); // Not called; already created by db1
+        assertTrue(callback2.mOpened);
+    }
+
+    @Test
+    @SmallTest
+    public void writeOnCreate() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class)
+                .addCallback(new RoomDatabase.Callback() {
+                    @Override
+                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
+                        Cursor cursor = null;
+                        try {
+                            cursor = db.query(
+                                    "SELECT name FROM sqlite_master WHERE type = 'table'");
+                            ArrayList<String> names = new ArrayList<>();
+                            while (cursor.moveToNext()) {
+                                names.add(cursor.getString(0));
+                            }
+                            assertThat(names, hasItem("User"));
+                        } finally {
+                            if (cursor != null) {
+                                cursor.close();
+                            }
+                        }
+                    }
+                })
+                .build();
+        List<Integer> ids = db.getUserDao().loadIds();
+        assertThat(ids, is(empty()));
+    }
+
+    public static class TestDatabaseCallback extends RoomDatabase.Callback {
+
+        boolean mCreated;
+        boolean mOpened;
+
+        @Override
+        public void onCreate(@NonNull SupportSQLiteDatabase db) {
+            mCreated = true;
+        }
+
+        @Override
+        public void onOpen(@NonNull SupportSQLiteDatabase db) {
+            mOpened = true;
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/EmbeddedTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/EmbeddedTest.java
new file mode 100644
index 0000000..d680f3d
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/EmbeddedTest.java
@@ -0,0 +1,246 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.dao.PetCoupleDao;
+import android.arch.persistence.room.integration.testapp.dao.PetDao;
+import android.arch.persistence.room.integration.testapp.dao.SchoolDao;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.dao.UserPetDao;
+import android.arch.persistence.room.integration.testapp.vo.Coordinates;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.PetCouple;
+import android.arch.persistence.room.integration.testapp.vo.School;
+import android.arch.persistence.room.integration.testapp.vo.SchoolRef;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.persistence.room.integration.testapp.vo.UserAndPet;
+import android.arch.persistence.room.integration.testapp.vo.UserAndPetNonNull;
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class EmbeddedTest {
+    private UserDao mUserDao;
+    private PetDao mPetDao;
+    private UserPetDao mUserPetDao;
+    private SchoolDao mSchoolDao;
+    private PetCoupleDao mPetCoupleDao;
+
+    @Before
+    public void createDb() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        mUserDao = db.getUserDao();
+        mPetDao = db.getPetDao();
+        mUserPetDao = db.getUserPetDao();
+        mSchoolDao = db.getSchoolDao();
+        mPetCoupleDao = db.getPetCoupleDao();
+    }
+
+    @Test
+    public void loadAll() {
+        Pet pet = TestUtil.createPet(1);
+        User user = TestUtil.createUser(2);
+        pet.setUserId(user.getId());
+        mUserDao.insert(user);
+        mPetDao.insertOrReplace(pet);
+        List<UserAndPet> all = mUserPetDao.loadAll();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(user));
+        assertThat(all.get(0).getPet(), is(pet));
+    }
+
+    @Test
+    public void loadFromUsers() {
+        Pet pet = TestUtil.createPet(1);
+        User user = TestUtil.createUser(2);
+        pet.setUserId(user.getId());
+        mUserDao.insert(user);
+        mPetDao.insertOrReplace(pet);
+        List<UserAndPet> all = mUserPetDao.loadUsers();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(user));
+        assertThat(all.get(0).getPet(), is(pet));
+    }
+
+    @Test
+    public void loadFromUsersWithNullPet() {
+        User user = TestUtil.createUser(2);
+        mUserDao.insert(user);
+        List<UserAndPet> all = mUserPetDao.loadUsers();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(user));
+        assertThat(all.get(0).getPet(), is(nullValue()));
+    }
+
+    @Test
+    public void loadFromUsersWithNonNullPet() {
+        User user = TestUtil.createUser(2);
+        mUserDao.insert(user);
+        List<UserAndPetNonNull> all = mUserPetDao.loadUsersWithNonNullPet();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(user));
+        assertThat(all.get(0).getPet(), is(new Pet()));
+    }
+
+    @Test
+    public void loadFromPets() {
+        Pet pet = TestUtil.createPet(1);
+        User user = TestUtil.createUser(2);
+        pet.setUserId(user.getId());
+        mUserDao.insert(user);
+        mPetDao.insertOrReplace(pet);
+        List<UserAndPet> all = mUserPetDao.loadPets();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(user));
+        assertThat(all.get(0).getPet(), is(pet));
+    }
+
+    @Test
+    public void loadFromPetsWithNullUser() {
+        Pet pet = TestUtil.createPet(1);
+        mPetDao.insertOrReplace(pet);
+        List<UserAndPet> all = mUserPetDao.loadPets();
+        assertThat(all.size(), is(1));
+        assertThat(all.get(0).getUser(), is(nullValue()));
+        assertThat(all.get(0).getPet(), is(pet));
+    }
+
+    @Test
+    public void findSchoolByStreet() {
+        School school = TestUtil.createSchool(3, 5);
+        school.getAddress().setStreet("foo");
+        mSchoolDao.insert(school);
+        List<School> result = mSchoolDao.findByStreet("foo");
+        assertThat(result.size(), is(1));
+        assertThat(result.get(0), is(school));
+    }
+
+    @Test
+    public void loadSubFieldsAsPojo() throws Exception {
+        loadSubFieldsTest(new Callable<List<School>>() {
+            @Override
+            public List<School> call() throws Exception {
+                List<School> result = new ArrayList<>();
+                for (SchoolRef ref : mSchoolDao.schoolAndManagerNamesAsPojo()) {
+                    result.add(ref);
+                }
+                return result;
+            }
+        });
+    }
+
+    @Test
+    public void loadSubFieldsAsEntity() throws Exception {
+        loadSubFieldsTest(new Callable<List<School>>() {
+            @Override
+            public List<School> call() throws Exception {
+                return mSchoolDao.schoolAndManagerNames();
+            }
+        });
+    }
+
+    public void loadSubFieldsTest(Callable<List<School>> loader) throws Exception {
+        School school = TestUtil.createSchool(3, 5);
+        school.setName("MTV High");
+        school.getManager().setName("chet");
+        mSchoolDao.insert(school);
+
+        School school2 = TestUtil.createSchool(4, 6);
+        school2.setName("MTV Low");
+        school2.setManager(null);
+        mSchoolDao.insert(school2);
+
+        List<School> schools = loader.call();
+        assertThat(schools.size(), is(2));
+        assertThat(schools.get(0).getName(), is("MTV High"));
+        assertThat(schools.get(1).getName(), is("MTV Low"));
+        assertThat(schools.get(0).address, nullValue());
+        assertThat(schools.get(1).address, nullValue());
+        assertThat(schools.get(0).getManager(), notNullValue());
+        assertThat(schools.get(1).getManager(), nullValue());
+        assertThat(schools.get(0).getManager().getName(), is("chet"));
+    }
+
+    @Test
+    public void loadNestedSub() {
+        School school = TestUtil.createSchool(3, 5);
+        school.getAddress().getCoordinates().lat = 3.;
+        school.getAddress().getCoordinates().lng = 4.;
+        mSchoolDao.insert(school);
+        Coordinates coordinates = mSchoolDao.loadCoordinates(3);
+        assertThat(coordinates.lat, is(3.));
+        assertThat(coordinates.lng, is(4.));
+
+        School asSchool = mSchoolDao.loadCoordinatesAsSchool(3);
+        assertThat(asSchool.address.getCoordinates().lat, is(3.));
+        assertThat(asSchool.address.getCoordinates().lng, is(4.));
+        // didn't as for it so don't load
+        assertThat(asSchool.getManager(), nullValue());
+        assertThat(asSchool.address.getStreet(), nullValue());
+    }
+
+    @Test
+    public void sameFieldType() {
+        Pet male = TestUtil.createPet(3);
+        Pet female = TestUtil.createPet(5);
+        PetCouple petCouple = new PetCouple();
+        petCouple.id = "foo";
+        petCouple.male = male;
+        petCouple.setFemale(female);
+        mPetCoupleDao.insert(petCouple);
+        List<PetCouple> petCouples = mPetCoupleDao.loadAll();
+        assertThat(petCouples.size(), is(1));
+        PetCouple loaded = petCouples.get(0);
+        assertThat(loaded.id, is("foo"));
+        assertThat(loaded.male, is(male));
+        assertThat(loaded.getFemale(), is(female));
+    }
+
+    @Test
+    public void sameFieldOneNull() {
+        Pet loneWolf = TestUtil.createPet(3);
+        PetCouple petCouple = new PetCouple();
+        petCouple.id = "foo";
+        petCouple.male = loneWolf;
+        mPetCoupleDao.insert(petCouple);
+        List<PetCouple> petCouples = mPetCoupleDao.loadAll();
+        assertThat(petCouples.size(), is(1));
+        PetCouple loaded = petCouples.get(0);
+        assertThat(loaded.id, is("foo"));
+        assertThat(loaded.male, is(loneWolf));
+        assertThat(loaded.getFemale(), is(nullValue()));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ForeignKeyTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ForeignKeyTest.java
new file mode 100644
index 0000000..502d1f8
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/ForeignKeyTest.java
@@ -0,0 +1,425 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.both;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.either;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.Delete;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.ForeignKey;
+import android.arch.persistence.room.Ignore;
+import android.arch.persistence.room.Index;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.database.sqlite.SQLiteException;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.hamcrest.Matcher;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Locale;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ForeignKeyTest {
+    @Database(version = 1, entities = {A.class, B.class, C.class, D.class, E.class},
+            exportSchema = false)
+    abstract static class ForeignKeyDb extends RoomDatabase {
+        abstract FkDao dao();
+    }
+
+    @SuppressWarnings({"SqlNoDataSourceInspection", "SameParameterValue"})
+    @Dao
+    interface FkDao {
+        @Insert
+        void insert(A... a);
+
+        @Insert
+        void insert(B... b);
+
+        @Insert
+        void insert(C... c);
+
+        @Insert
+        void insert(D... d);
+
+        @Query("SELECT * FROM A WHERE id = :id")
+        A loadA(int id);
+
+        @Query("SELECT * FROM B WHERE id = :id")
+        B loadB(int id);
+
+        @Query("SELECT * FROM C WHERE id = :id")
+        C loadC(int id);
+
+        @Query("SELECT * FROM D WHERE id = :id")
+        D loadD(int id);
+
+        @Query("SELECT * FROM E WHERE id = :id")
+        E loadE(int id);
+
+        @Delete
+        void delete(A... a);
+
+        @Delete
+        void delete(B... b);
+
+        @Delete
+        void delete(C... c);
+
+        @Query("UPDATE A SET name = :newName WHERE id = :id")
+        void changeNameA(int id, String newName);
+
+        @Insert
+        void insert(E... e);
+
+
+    }
+
+    @Entity(indices = {@Index(value = "name", unique = true),
+            @Index(value = {"name", "lastName"}, unique = true)})
+    static class A {
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String name;
+        public String lastName;
+
+        A(String name) {
+            this.name = name;
+        }
+
+        @Ignore
+        A(String name, String lastName) {
+            this.name = name;
+            this.lastName = lastName;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(foreignKeys = {
+            @ForeignKey(entity = A.class,
+                    parentColumns = "name",
+                    childColumns = "aName")})
+
+    static class B {
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String aName;
+
+        B(String aName) {
+            this.aName = aName;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(foreignKeys = {
+            @ForeignKey(entity = A.class,
+                    parentColumns = "name",
+                    childColumns = "aName",
+                    deferred = true)})
+    static class C {
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String aName;
+
+        C(String aName) {
+            this.aName = aName;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(foreignKeys = {
+            @ForeignKey(entity = A.class,
+                    parentColumns = "name",
+                    childColumns = "aName",
+                    onDelete = ForeignKey.CASCADE,
+                    onUpdate = ForeignKey.CASCADE)})
+    static class D {
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String aName;
+
+        D(String aName) {
+            this.aName = aName;
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    @Entity(foreignKeys = {
+            @ForeignKey(entity = A.class,
+                    parentColumns = {"name", "lastName"},
+                    childColumns = {"aName", "aLastName"},
+                    onDelete = ForeignKey.SET_NULL,
+                    onUpdate = ForeignKey.CASCADE)})
+    static class E {
+        @PrimaryKey(autoGenerate = true)
+        public int id;
+        public String aName;
+        public String aLastName;
+
+        E() {
+        }
+
+        @Ignore
+        E(String aName, String aLastName) {
+            this.aName = aName;
+            this.aLastName = aLastName;
+        }
+    }
+
+
+    private ForeignKeyDb mDb;
+    private FkDao mDao;
+
+    @Before
+    public void openDb() {
+        mDb = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
+                ForeignKeyDb.class).build();
+        mDao = mDb.dao();
+    }
+
+    @Test
+    public void simpleForeignKeyFailure() {
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                mDao.insert(new B("foo"));
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void simpleForeignKeyDeferredFailure() {
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                mDao.insert(new C("foo"));
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void immediateForeignKeyFailure() {
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                try {
+                    mDb.beginTransaction();
+                    mDao.insert(new B("foo"));
+                    mDao.insert(new A("foo"));
+                    mDb.setTransactionSuccessful();
+                } finally {
+                    mDb.endTransaction();
+                }
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+    }
+
+    @Test
+    public void deferredForeignKeySuccess() {
+        try {
+            mDb.beginTransaction();
+            mDao.insert(new C("foo"));
+            mDao.insert(new A("foo"));
+            mDb.setTransactionSuccessful();
+        } finally {
+            mDb.endTransaction();
+        }
+        assertThat(mDao.loadA(1), notNullValue());
+        assertThat(mDao.loadC(1), notNullValue());
+    }
+
+    @Test
+    public void onDelete_noAction() {
+        mDao.insert(new A("a1"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new B("a1"));
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                mDao.delete(a);
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void onDelete_noAction_withTransaction() {
+        mDao.insert(new A("a1"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new B("a1"));
+        final B b = mDao.loadB(1);
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                deleteInTransaction(a, b);
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void onDelete_noAction_deferred() {
+        mDao.insert(new A("a1"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new C("a1"));
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                mDao.delete(a);
+            }
+        });
+        assertThat(t, instanceOf(SQLiteException.class));
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void onDelete_noAction__deferredWithTransaction() {
+        mDao.insert(new A("a1"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new C("a1"));
+        final C c = mDao.loadC(1);
+        deleteInTransaction(a, c);
+    }
+
+    @Test
+    public void onDelete_cascade() {
+        mDao.insert(new A("a1"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new D("a1"));
+        final D d = mDao.loadD(1);
+        assertThat("test sanity", d, notNullValue());
+        mDao.delete(a);
+        assertThat(mDao.loadD(1), nullValue());
+    }
+
+    @Test
+    public void onUpdate_cascade() {
+        mDao.insert(new A("a1"));
+        mDao.insert(new D("a1"));
+        final D d = mDao.loadD(1);
+        assertThat("test sanity", d, notNullValue());
+        mDao.changeNameA(1, "bla");
+        assertThat(mDao.loadD(1).aName, equalTo("bla"));
+        assertThat(mDao.loadA(1).name, equalTo("bla"));
+    }
+
+    @Test
+    public void multipleReferences() {
+        mDao.insert(new A("a1", "a2"));
+        final A a = mDao.loadA(1);
+        assertThat("test sanity", a, notNullValue());
+        Throwable t = catchException(new ThrowingRunnable() {
+            @Override
+            public void run() throws Exception {
+                mDao.insert(new E("a1", "dsa"));
+            }
+        });
+        assertThat(t.getMessage().toUpperCase(Locale.US), is(foreignKeyErrorMessage()));
+    }
+
+    @Test
+    public void onDelete_setNull_multipleReferences() {
+        mDao.insert(new A("a1", "a2"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new E("a1", "a2"));
+        assertThat(mDao.loadE(1), notNullValue());
+        mDao.delete(a);
+        E e = mDao.loadE(1);
+        assertThat(e, notNullValue());
+        assertThat(e.aName, nullValue());
+        assertThat(e.aLastName, nullValue());
+    }
+
+    @Test
+    public void onUpdate_cascade_multipleReferences() {
+        mDao.insert(new A("a1", "a2"));
+        final A a = mDao.loadA(1);
+        mDao.insert(new E("a1", "a2"));
+        assertThat(mDao.loadE(1), notNullValue());
+        mDao.changeNameA(1, "foo");
+        assertThat(mDao.loadE(1), notNullValue());
+        assertThat(mDao.loadE(1).aName, equalTo("foo"));
+        assertThat(mDao.loadE(1).aLastName, equalTo("a2"));
+    }
+
+    private static Matcher<String> foreignKeyErrorMessage() {
+        return either(containsString("FOREIGN KEY"))
+                .or(both(containsString("CODE 19")).and(containsString("CONSTRAINT FAILED")));
+    }
+
+    @SuppressWarnings("Duplicates")
+    private void deleteInTransaction(A a, B b) {
+        mDb.beginTransaction();
+        try {
+            mDao.delete(a);
+            mDao.delete(b);
+            mDb.setTransactionSuccessful();
+        } finally {
+            mDb.endTransaction();
+        }
+    }
+
+    @SuppressWarnings("Duplicates")
+    private void deleteInTransaction(A a, C c) {
+        mDb.beginTransaction();
+        try {
+            mDao.delete(a);
+            mDao.delete(c);
+            mDb.setTransactionSuccessful();
+        } finally {
+            mDb.endTransaction();
+        }
+    }
+
+    private static Throwable catchException(ThrowingRunnable throwingRunnable) {
+        try {
+            throwingRunnable.run();
+        } catch (Throwable t) {
+            return t;
+        }
+        throw new RuntimeException("didn't throw an exception");
+    }
+
+    private interface ThrowingRunnable {
+        void run() throws Exception;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IdentityDetectionTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IdentityDetectionTest.java
new file mode 100644
index 0000000..1c1b503
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IdentityDetectionTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.Log;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.vo.User;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class IdentityDetectionTest {
+    static final String TAG = "IdentityDetectionTest";
+    static final String DB_FILE_NAME = "identity_test_db";
+    TestDatabase mTestDatabase;
+    @Before
+    public void createTestDatabase() {
+        deleteDbFile();
+    }
+
+    @Test
+    public void reOpenWithoutIssues() {
+        openDb();
+        mTestDatabase.getUserDao().insert(TestUtil.createUser(3));
+        closeDb();
+        openDb();
+        User[] users = mTestDatabase.getUserDao().loadByIds(3);
+        assertThat(users.length, is(1));
+    }
+
+    @Test
+    public void reOpenChangedHash() {
+        openDb();
+        mTestDatabase.getUserDao().insert(TestUtil.createUser(3));
+        // change the hash
+        SupportSQLiteDatabase db = mTestDatabase.getOpenHelper().getWritableDatabase();
+        db.execSQL("UPDATE " + Room.MASTER_TABLE_NAME + " SET `identity_hash` = ?"
+                + " WHERE id = 42", new String[]{"bad hash"});
+        closeDb();
+        Throwable[] exceptions = new Throwable[1];
+        try {
+            openDb();
+            mTestDatabase.getUserDao().loadByIds(3);
+        } catch (Throwable t) {
+            exceptions[0] = t;
+            mTestDatabase = null;
+        }
+        assertThat(exceptions[0], instanceOf(IllegalStateException.class));
+    }
+
+    private void closeDb() {
+        mTestDatabase.getOpenHelper().close();
+    }
+
+    private void openDb() {
+        mTestDatabase = Room.databaseBuilder(InstrumentationRegistry.getTargetContext(),
+                TestDatabase.class, DB_FILE_NAME).build();
+    }
+
+    @After
+    public void clear() {
+        try {
+            if (mTestDatabase != null) {
+                closeDb();
+            }
+            deleteDbFile();
+        } finally {
+            Log.e(TAG, "could not close test database");
+        }
+    }
+
+    private void deleteDbFile() {
+        File testDb = InstrumentationRegistry.getTargetContext().getDatabasePath(DB_FILE_NAME);
+        testDb.delete();
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IndexingTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IndexingTest.java
new file mode 100644
index 0000000..16f916b
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/IndexingTest.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.Index;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class IndexingTest {
+    @Entity(
+            tableName = "foo_table",
+            indices = {
+                    @Index({"field1", "field2"}),
+                    @Index(value = {"field2", "mId"}, unique = true),
+                    @Index(value = {"field2"}, unique = true, name = "customIndex"),
+            })
+    static class Entity1 {
+        @PrimaryKey
+        public int mId;
+        public String field1;
+        public String field2;
+        @ColumnInfo(index = true, name = "my_field")
+        public String field3;
+    }
+
+    static class IndexInfo {
+        public String name;
+        @ColumnInfo(name = "tbl_name")
+        public String tableName;
+        public String sql;
+    }
+
+    @Dao
+    public interface SqlMasterDao {
+        @Query("SELECT * FROM sqlite_master WHERE type = 'index'")
+        List<IndexInfo> loadIndices();
+    }
+
+    @Database(entities = {Entity1.class}, version = 1, exportSchema = false)
+    abstract static class IndexingDb extends RoomDatabase {
+        abstract SqlMasterDao sqlMasterDao();
+    }
+
+    @Test
+    public void verifyIndices() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        IndexingDb db = Room.inMemoryDatabaseBuilder(context, IndexingDb.class).build();
+        List<IndexInfo> indices = db.sqlMasterDao().loadIndices();
+        assertThat(indices.size(), is(4));
+        for (IndexInfo info : indices) {
+            assertThat(info.tableName, is("foo_table"));
+        }
+        assertThat(indices.get(0).sql, is("CREATE INDEX `index_foo_table_field1_field2`"
+                + " ON `foo_table` (`field1`, `field2`)"));
+        assertThat(indices.get(1).sql, is("CREATE UNIQUE INDEX `index_foo_table_field2_mId`"
+                + " ON `foo_table` (`field2`, `mId`)"));
+        assertThat(indices.get(2).sql, is("CREATE UNIQUE INDEX `customIndex`"
+                + " ON `foo_table` (`field2`)"));
+        assertThat(indices.get(3).sql, is("CREATE INDEX `index_foo_table_my_field`"
+                + " ON `foo_table` (`my_field`)"));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/InvalidationTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/InvalidationTest.java
new file mode 100644
index 0000000..b6efe69
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/InvalidationTest.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.TaskExecutor;
+import android.arch.persistence.room.InvalidationTracker;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.support.annotation.NonNull;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Tests invalidation tracking.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class InvalidationTest {
+    private UserDao mUserDao;
+    private TestDatabase mDb;
+
+    @Before
+    public void createDb() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        mDb = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        mUserDao = mDb.getUserDao();
+    }
+
+    @Before
+    public void setSingleThreadedIO() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(new TaskExecutor() {
+            ExecutorService mIOExecutor = Executors.newSingleThreadExecutor();
+            Handler mHandler = new Handler(Looper.getMainLooper());
+
+            @Override
+            public void executeOnDiskIO(Runnable runnable) {
+                mIOExecutor.execute(runnable);
+            }
+
+            @Override
+            public void postToMainThread(Runnable runnable) {
+                mHandler.post(runnable);
+            }
+
+            @Override
+            public boolean isMainThread() {
+                return Thread.currentThread() == Looper.getMainLooper().getThread();
+            }
+        });
+    }
+
+    @After
+    public void clearExecutor() {
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    private void waitUntilIOThreadIsIdle() {
+        FutureTask<Void> future = new FutureTask<>(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                return null;
+            }
+        });
+        AppToolkitTaskExecutor.getInstance().executeOnDiskIO(future);
+        //noinspection TryWithIdenticalCatches
+        try {
+            future.get();
+        } catch (InterruptedException e) {
+            throw new RuntimeException(e);
+        } catch (ExecutionException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Test
+    public void testInvalidationOnUpdate() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        LatchObserver observer = new LatchObserver(1, "User");
+        mDb.getInvalidationTracker().addObserver(observer);
+        mUserDao.updateById(3, "foo2");
+        waitUntilIOThreadIsIdle();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables(), hasSize(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("User"));
+    }
+
+    @Test
+    public void testInvalidationOnDelete() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        LatchObserver observer = new LatchObserver(1, "User");
+        mDb.getInvalidationTracker().addObserver(observer);
+        mUserDao.delete(user);
+        waitUntilIOThreadIsIdle();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables(), hasSize(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("User"));
+    }
+
+    @Test
+    public void testInvalidationOnInsert() throws InterruptedException {
+        LatchObserver observer = new LatchObserver(1, "User");
+        mDb.getInvalidationTracker().addObserver(observer);
+        mUserDao.insert(TestUtil.createUser(3));
+        waitUntilIOThreadIsIdle();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables(), hasSize(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("User"));
+    }
+
+    @Test
+    public void testDontInvalidateOnLateInsert() throws InterruptedException {
+        LatchObserver observer = new LatchObserver(1, "User");
+        mUserDao.insert(TestUtil.createUser(3));
+        waitUntilIOThreadIsIdle();
+        mDb.getInvalidationTracker().addObserver(observer);
+        waitUntilIOThreadIsIdle();
+        assertThat(observer.await(), is(false));
+    }
+
+    private static class LatchObserver extends InvalidationTracker.Observer {
+        CountDownLatch mLatch;
+
+        private Set<String> mInvalidatedTables;
+
+        LatchObserver(int permits, String... tables) {
+            super(tables);
+            mLatch = new CountDownLatch(permits);
+        }
+
+        boolean await() throws InterruptedException {
+            return mLatch.await(5, TimeUnit.SECONDS);
+        }
+
+        @Override
+        public void onInvalidated(@NonNull Set<String> tables) {
+            mInvalidatedTables = tables;
+            mLatch.countDown();
+        }
+
+        Set<String> getInvalidatedTables() {
+            return mInvalidatedTables;
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/LiveDataQueryTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/LiveDataQueryTest.java
new file mode 100644
index 0000000..927f0f4
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/LiveDataQueryTest.java
@@ -0,0 +1,315 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.testing.CountingTaskExecutorRule;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleOwner;
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.Observer;
+import android.arch.persistence.room.InvalidationTrackerTrojan;
+import android.arch.persistence.room.integration.testapp.vo.AvgWeightByAge;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.persistence.room.integration.testapp.vo.UserAndAllPets;
+import android.support.annotation.Nullable;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.ref.WeakReference;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Tests invalidation tracking.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class LiveDataQueryTest extends TestDatabaseTest {
+    @Rule
+    public CountingTaskExecutorRule mExecutorRule = new CountingTaskExecutorRule();
+
+    @Test
+    public void observeById() throws InterruptedException, ExecutionException, TimeoutException {
+        final LiveData<User> userLiveData = mUserDao.liveUserById(5);
+        final TestLifecycleOwner testOwner = new TestLifecycleOwner();
+        testOwner.handleEvent(Lifecycle.Event.ON_CREATE);
+        final TestObserver<User> observer = new TestObserver<>();
+        observe(userLiveData, testOwner, observer);
+        assertThat(observer.hasValue(), is(false));
+        observer.reset();
+
+        testOwner.handleEvent(Lifecycle.Event.ON_START);
+        assertThat(observer.get(), is(nullValue()));
+
+        // another id
+        observer.reset();
+        mUserDao.insert(TestUtil.createUser(7));
+        assertThat(observer.get(), is(nullValue()));
+
+        observer.reset();
+        final User u5 = TestUtil.createUser(5);
+        mUserDao.insert(u5);
+        assertThat(observer.get(), is(notNullValue()));
+
+        u5.setName("foo-foo-foo");
+        observer.reset();
+        mUserDao.insertOrReplace(u5);
+        final User updated = observer.get();
+        assertThat(updated, is(notNullValue()));
+        assertThat(updated.getName(), is("foo-foo-foo"));
+
+        testOwner.handleEvent(Lifecycle.Event.ON_STOP);
+        observer.reset();
+        u5.setName("baba");
+        mUserDao.insertOrReplace(u5);
+        assertThat(observer.hasValue(), is(false));
+    }
+
+    @Test
+    public void observeListQuery() throws InterruptedException, ExecutionException,
+            TimeoutException {
+        final LiveData<List<User>> userLiveData = mUserDao.liveUsersListByName("frida");
+        final TestLifecycleOwner lifecycleOwner = new TestLifecycleOwner();
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        final TestObserver<List<User>> observer = new TestObserver<>();
+        observe(userLiveData, lifecycleOwner, observer);
+        assertThat(observer.get(), is(Collections.<User>emptyList()));
+
+        observer.reset();
+        final User user1 = TestUtil.createUser(3);
+        user1.setName("dog frida");
+        mUserDao.insert(user1);
+        assertThat(observer.get(), is(Collections.singletonList(user1)));
+
+        observer.reset();
+        final User user2 = TestUtil.createUser(5);
+        user2.setName("does not match");
+        mUserDao.insert(user2);
+        assertThat(observer.get(), is(Collections.singletonList(user1)));
+
+        observer.reset();
+        user1.setName("i don't match either");
+        mUserDao.insertOrReplace(user1);
+        assertThat(observer.get(), is(Collections.<User>emptyList()));
+
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_STOP);
+
+        observer.reset();
+        final User user3 = TestUtil.createUser(9);
+        user3.setName("painter frida");
+        mUserDao.insertOrReplace(user3);
+        assertThat(observer.hasValue(), is(false));
+
+        observer.reset();
+        final User user4 = TestUtil.createUser(11);
+        user4.setName("friday");
+        mUserDao.insertOrReplace(user4);
+        assertThat(observer.hasValue(), is(false));
+
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        assertThat(observer.get(), is(Arrays.asList(user4, user3)));
+    }
+
+    @Test
+    public void liveDataWithPojo() throws ExecutionException, InterruptedException,
+            TimeoutException {
+        User[] users = TestUtil.createUsersArray(3, 5, 7, 9);
+        users[0].setAge(10);
+        users[0].setWeight(15);
+
+        users[1].setAge(20);
+        users[1].setWeight(25);
+
+        users[2].setAge(20);
+        users[2].setWeight(26);
+
+        users[3].setAge(10);
+        users[3].setWeight(21);
+
+        final TestLifecycleOwner lifecycleOwner = new TestLifecycleOwner();
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+
+        final TestObserver<AvgWeightByAge> observer = new TestObserver<>();
+        LiveData<AvgWeightByAge> liveData = mUserDao.maxWeightByAgeGroup();
+
+        observe(liveData, lifecycleOwner, observer);
+        assertThat(observer.get(), is(nullValue()));
+
+        observer.reset();
+        mUserDao.insertAll(users);
+        assertThat(observer.get(), is(new AvgWeightByAge(20, 25.5f)));
+
+        observer.reset();
+        User user3 = mUserDao.load(3);
+        user3.setWeight(79);
+        mUserDao.insertOrReplace(user3);
+
+        assertThat(observer.get(), is(new AvgWeightByAge(10, 50)));
+    }
+
+    @Test
+    public void withRelation() throws ExecutionException, InterruptedException, TimeoutException {
+        final LiveData<UserAndAllPets> liveData = mUserPetDao.liveUserWithPets(3);
+        final TestObserver<UserAndAllPets> observer = new TestObserver<>();
+        final TestLifecycleOwner lifecycleOwner = new TestLifecycleOwner();
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        observe(liveData, lifecycleOwner, observer);
+        assertThat(observer.get(), is(nullValue()));
+
+        observer.reset();
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        final UserAndAllPets noPets = observer.get();
+        assertThat(noPets.user, is(user));
+
+        observer.reset();
+        Pet[] pets = TestUtil.createPetsForUser(3, 1, 2);
+        mPetDao.insertAll(pets);
+
+        final UserAndAllPets withPets = observer.get();
+        assertThat(withPets.user, is(user));
+        assertThat(withPets.pets, is(Arrays.asList(pets)));
+    }
+
+    @MediumTest
+    @Test
+    public void handleGc() throws ExecutionException, InterruptedException, TimeoutException {
+        LiveData<User> liveData = mUserDao.liveUserById(3);
+        final TestObserver<User> observer = new TestObserver<>();
+        final TestLifecycleOwner lifecycleOwner = new TestLifecycleOwner();
+        lifecycleOwner.handleEvent(Lifecycle.Event.ON_START);
+        observe(liveData, lifecycleOwner, observer);
+        assertThat(observer.get(), is(nullValue()));
+        observer.reset();
+        final User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        assertThat(observer.get(), is(notNullValue()));
+        observer.reset();
+        forceGc();
+        String name = UUID.randomUUID().toString();
+        mUserDao.updateById(3, name);
+        assertThat(observer.get().getName(), is(name));
+
+        // release references
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                lifecycleOwner.handleEvent(Lifecycle.Event.ON_DESTROY);
+            }
+        });
+        WeakReference<LiveData> weakLiveData = new WeakReference<LiveData>(liveData);
+        //noinspection UnusedAssignment
+        liveData = null;
+        forceGc();
+        mUserDao.updateById(3, "Bar");
+        forceGc();
+        assertThat(InvalidationTrackerTrojan.countObservers(mDatabase.getInvalidationTracker()),
+                is(0));
+        assertThat(weakLiveData.get(), nullValue());
+    }
+
+    private void observe(final LiveData liveData, final LifecycleOwner provider,
+            final Observer observer) throws ExecutionException, InterruptedException {
+        FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                //noinspection unchecked
+                liveData.observe(provider, observer);
+                return null;
+            }
+        });
+        AppToolkitTaskExecutor.getInstance().executeOnMainThread(futureTask);
+        futureTask.get();
+    }
+
+    private void drain() throws TimeoutException, InterruptedException {
+        mExecutorRule.drainTasks(1, TimeUnit.MINUTES);
+    }
+
+    private static void forceGc() {
+        Runtime.getRuntime().gc();
+        Runtime.getRuntime().runFinalization();
+        Runtime.getRuntime().gc();
+        Runtime.getRuntime().runFinalization();
+    }
+
+    static class TestLifecycleOwner implements LifecycleOwner {
+
+        private LifecycleRegistry mLifecycle;
+
+        TestLifecycleOwner() {
+            mLifecycle = new LifecycleRegistry(this);
+        }
+
+        @Override
+        public Lifecycle getLifecycle() {
+            return mLifecycle;
+        }
+
+        void handleEvent(Lifecycle.Event event) {
+            mLifecycle.handleLifecycleEvent(event);
+        }
+    }
+
+    private class TestObserver<T> implements Observer<T> {
+        private T mLastData;
+        private boolean mHasValue = false;
+
+        void reset() {
+            mHasValue = false;
+            mLastData = null;
+        }
+
+        @Override
+        public void onChanged(@Nullable T o) {
+            mLastData = o;
+            mHasValue = true;
+        }
+
+        boolean hasValue() throws TimeoutException, InterruptedException {
+            drain();
+            return mHasValue;
+        }
+
+        T get() throws InterruptedException, TimeoutException {
+            drain();
+            assertThat(hasValue(), is(true));
+            return mLastData;
+        }
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/MainThreadCheckTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/MainThreadCheckTest.java
new file mode 100644
index 0000000..f4ed5dd
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/MainThreadCheckTest.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.util.Function;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class MainThreadCheckTest {
+
+    @Test
+    public void testMainThread() {
+        final Throwable error = test(false, new Function<TestDatabase, Void>() {
+            @Override
+            public Void apply(TestDatabase db) {
+                db.getUserDao().load(3);
+                return null;
+            }
+        });
+        assertThat(error, notNullValue());
+        assertThat(error, instanceOf(IllegalStateException.class));
+    }
+
+    @Test
+    public void testFlowableOnMainThread() {
+        final Throwable error = test(false, new Function<TestDatabase, Void>() {
+            @Override
+            public Void apply(TestDatabase db) {
+                db.getUserDao().flowableUserById(3);
+                return null;
+            }
+        });
+        assertThat(error, nullValue());
+    }
+
+    @Test
+    public void testLiveDataOnMainThread() {
+        final Throwable error = test(false, new Function<TestDatabase, Void>() {
+            @Override
+            public Void apply(TestDatabase db) {
+                db.getUserDao().liveUserById(3);
+                return null;
+            }
+        });
+        assertThat(error, nullValue());
+    }
+
+    @Test
+    public void testAllowMainThread() {
+        final Throwable error = test(true, new Function<TestDatabase, Void>() {
+            @Override
+            public Void apply(TestDatabase db) {
+                db.getUserDao().load(3);
+                return null;
+            }
+        });
+        assertThat(error, nullValue());
+    }
+
+    private Throwable test(boolean allowMainThread, final Function<TestDatabase, Void> fun) {
+        Context context = InstrumentationRegistry.getTargetContext();
+        final RoomDatabase.Builder<TestDatabase> builder = Room.inMemoryDatabaseBuilder(
+                context, TestDatabase.class);
+        if (allowMainThread) {
+            builder.allowMainThreadQueries();
+        }
+        final TestDatabase db = builder.build();
+        final AtomicReference<Throwable> error = new AtomicReference<>();
+        try {
+            InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        fun.apply(db);
+                    } catch (Throwable t) {
+                        error.set(t);
+                    }
+                }
+            });
+        } finally {
+            db.close();
+        }
+        return error.get();
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoTest.java
new file mode 100644
index 0000000..b43e274
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.vo.AvgWeightByAge;
+import android.arch.persistence.room.integration.testapp.vo.User;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+
+@RunWith(AndroidJUnit4.class)
+public class PojoTest {
+    private UserDao mUserDao;
+
+    @Before
+    public void createDb() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        mUserDao = db.getUserDao();
+    }
+
+    @Test
+    public void weightsByAge() {
+        User[] users = TestUtil.createUsersArray(3, 5, 7, 10);
+        users[0].setAge(10);
+        users[0].setWeight(20);
+
+        users[1].setAge(10);
+        users[1].setWeight(30);
+
+        users[2].setAge(15);
+        users[2].setWeight(12);
+
+        users[3].setAge(35);
+        users[3].setWeight(55);
+
+        mUserDao.insertAll(users);
+        assertThat(mUserDao.weightByAge(), is(
+                Arrays.asList(
+                        new AvgWeightByAge(35, 55),
+                        new AvgWeightByAge(10, 25),
+                        new AvgWeightByAge(15, 12)
+                )
+        ));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoWithRelationTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoWithRelationTest.java
new file mode 100644
index 0000000..45233f3
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PojoWithRelationTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.persistence.room.integration.testapp.vo.EmbeddedUserAndAllPets;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.Toy;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.persistence.room.integration.testapp.vo.UserAndAllPets;
+import android.arch.persistence.room.integration.testapp.vo.UserIdAndPetNames;
+import android.arch.persistence.room.integration.testapp.vo.UserWithPetsAndToys;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class PojoWithRelationTest extends TestDatabaseTest {
+    @Test
+    public void fetchAll() {
+        User[] users = TestUtil.createUsersArray(1, 2, 3);
+        Pet[][] userPets = new Pet[3][];
+        mUserDao.insertAll(users);
+        for (User user : users) {
+            Pet[] pets = TestUtil.createPetsForUser(user.getId(), user.getId() * 10,
+                    user.getId() - 1);
+            mPetDao.insertAll(pets);
+            userPets[user.getId() - 1] = pets;
+        }
+        List<UserAndAllPets> usersAndPets = mUserPetDao.loadAllUsersWithTheirPets();
+        assertThat(usersAndPets.size(), is(3));
+        assertThat(usersAndPets.get(0).user, is(users[0]));
+        assertThat(usersAndPets.get(0).pets, is(Collections.<Pet>emptyList()));
+
+        assertThat(usersAndPets.get(1).user, is(users[1]));
+        assertThat(usersAndPets.get(1).pets, is(Arrays.asList(userPets[1])));
+
+        assertThat(usersAndPets.get(2).user, is(users[2]));
+        assertThat(usersAndPets.get(2).pets, is(Arrays.asList(userPets[2])));
+    }
+
+    private void createData() {
+        User[] users = TestUtil.createUsersArray(1, 2);
+        mUserDao.insertAll(users);
+        Pet user1_pet1 = TestUtil.createPet(1);
+        user1_pet1.setUserId(1);
+        user1_pet1.setName("pet1");
+        mPetDao.insertOrReplace(user1_pet1);
+
+        Pet user1_pet2 = TestUtil.createPet(2);
+        user1_pet2.setUserId(1);
+        user1_pet2.setName("pet2");
+        mPetDao.insertOrReplace(user1_pet2);
+
+        Pet user2_pet1 = TestUtil.createPet(3);
+        user2_pet1.setUserId(2);
+        user2_pet1.setName("pet3");
+        mPetDao.insertOrReplace(user2_pet1);
+    }
+
+    @Test
+    public void fetchWithNames() {
+        createData();
+
+        List<UserIdAndPetNames> usersAndPets = mUserPetDao.loadUserAndPetNames();
+        assertThat(usersAndPets.size(), is(2));
+        assertThat(usersAndPets.get(0).userId, is(1));
+        assertThat(usersAndPets.get(1).userId, is(2));
+        assertThat(usersAndPets.get(0).names, is(Arrays.asList("pet1", "pet2")));
+        assertThat(usersAndPets.get(1).names, is(Collections.singletonList("pet3")));
+    }
+
+    @Test
+    public void nested() {
+        createData();
+        Toy pet1_toy1 = new Toy();
+        pet1_toy1.setName("toy1");
+        pet1_toy1.setPetId(1);
+        Toy pet1_toy2 = new Toy();
+        pet1_toy2.setName("toy2");
+        pet1_toy2.setPetId(1);
+        mToyDao.insert(pet1_toy1, pet1_toy2);
+        List<UserWithPetsAndToys> userWithPetsAndToys = mUserPetDao.loadUserWithPetsAndToys();
+        assertThat(userWithPetsAndToys.size(), is(2));
+        UserWithPetsAndToys first = userWithPetsAndToys.get(0);
+        List<Toy> toys = first.pets.get(0).toys;
+        assertThat(toys.get(0).getName(), is("toy1"));
+        assertThat(toys.get(1).getName(), is("toy2"));
+        assertThat(userWithPetsAndToys.get(1).pets.get(0).toys, is(Collections.<Toy>emptyList()));
+    }
+
+    @Test
+    public void duplicateParentField() {
+        User[] users = TestUtil.createUsersArray(1, 2);
+        Pet[] pets_1 = TestUtil.createPetsForUser(1, 1, 2);
+        Pet[] pets_2 = TestUtil.createPetsForUser(2, 10, 1);
+        mUserDao.insertAll(users);
+        mPetDao.insertAll(pets_1);
+        mPetDao.insertAll(pets_2);
+        List<UserAndAllPets> userAndAllPets = mUserPetDao.unionByItself();
+        assertThat(userAndAllPets.size(), is(4));
+        for (int i = 0; i < 4; i++) {
+            assertThat("user at " + i, userAndAllPets.get(i).user, is(users[i % 2]));
+        }
+        assertThat(userAndAllPets.get(0).pets, is(Arrays.asList(pets_1)));
+        assertThat(userAndAllPets.get(2).pets, is(Arrays.asList(pets_1)));
+
+        assertThat(userAndAllPets.get(1).pets, is(Arrays.asList(pets_2)));
+        assertThat(userAndAllPets.get(3).pets, is(Arrays.asList(pets_2)));
+    }
+
+    @Test
+    public void embeddedRelation() {
+        createData();
+        EmbeddedUserAndAllPets relationContainer = mUserPetDao.loadUserAndPetsAsEmbedded(1);
+        assertThat(relationContainer.getUserAndAllPets(), notNullValue());
+        assertThat(relationContainer.getUserAndAllPets().user.getId(), is(1));
+        assertThat(relationContainer.getUserAndAllPets().pets.size(), is(2));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PrimaryKeyTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PrimaryKeyTest.java
new file mode 100644
index 0000000..97ce10c
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/PrimaryKeyTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.PKeyTestDatabase;
+import android.arch.persistence.room.integration.testapp.vo.IntAutoIncPKeyEntity;
+import android.arch.persistence.room.integration.testapp.vo.IntegerAutoIncPKeyEntity;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class PrimaryKeyTest {
+    private PKeyTestDatabase mDatabase;
+    @Before
+    public void setup() {
+        mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getTargetContext(),
+                PKeyTestDatabase.class).build();
+    }
+
+    @Test
+    public void integerTest() {
+        IntegerAutoIncPKeyEntity entity = new IntegerAutoIncPKeyEntity();
+        entity.data = "foo";
+        mDatabase.integerPKeyDao().insertMe(entity);
+        IntegerAutoIncPKeyEntity loaded = mDatabase.integerPKeyDao().getMe(1);
+        assertThat(loaded, notNullValue());
+        assertThat(loaded.data, is(entity.data));
+    }
+
+    @Test
+    public void dontOverrideNullable0() {
+        IntegerAutoIncPKeyEntity entity = new IntegerAutoIncPKeyEntity();
+        entity.pKey = 0;
+        entity.data = "foo";
+        mDatabase.integerPKeyDao().insertMe(entity);
+        IntegerAutoIncPKeyEntity loaded = mDatabase.integerPKeyDao().getMe(0);
+        assertThat(loaded, notNullValue());
+        assertThat(loaded.data, is(entity.data));
+    }
+
+    @Test
+    public void intTest() {
+        IntAutoIncPKeyEntity entity = new IntAutoIncPKeyEntity();
+        entity.data = "foo";
+        mDatabase.intPKeyDao().insertMe(entity);
+        IntAutoIncPKeyEntity loaded = mDatabase.intPKeyDao().getMe(1);
+        assertThat(loaded, notNullValue());
+        assertThat(loaded.data, is(entity.data));
+    }
+
+    @Test
+    public void getInsertedId() {
+        IntAutoIncPKeyEntity entity = new IntAutoIncPKeyEntity();
+        entity.data = "foo";
+        final long id = mDatabase.intPKeyDao().insertAndGetId(entity);
+        assertThat(mDatabase.intPKeyDao().getMe((int) id).data, is("foo"));
+    }
+
+    @Test
+    public void getInsertedIds() {
+        IntAutoIncPKeyEntity entity = new IntAutoIncPKeyEntity();
+        entity.data = "foo";
+        IntAutoIncPKeyEntity entity2 = new IntAutoIncPKeyEntity();
+        entity2.data = "foo2";
+        final long[] ids = mDatabase.intPKeyDao().insertAndGetIds(entity, entity2);
+        assertThat(mDatabase.intPKeyDao().loadDataById(ids), is(Arrays.asList("foo", "foo2")));
+    }
+
+    @Test
+    public void getInsertedIdFromInteger() {
+        IntegerAutoIncPKeyEntity entity = new IntegerAutoIncPKeyEntity();
+        entity.data = "foo";
+        final long id = mDatabase.integerPKeyDao().insertAndGetId(entity);
+        assertThat(mDatabase.integerPKeyDao().getMe((int) id).data, is("foo"));
+    }
+
+    @Test
+    public void getInsertedIdsFromInteger() {
+        IntegerAutoIncPKeyEntity entity = new IntegerAutoIncPKeyEntity();
+        entity.data = "foo";
+        IntegerAutoIncPKeyEntity entity2 = new IntegerAutoIncPKeyEntity();
+        entity2.data = "foo2";
+        final long[] ids = mDatabase.integerPKeyDao().insertAndGetIds(entity, entity2);
+        assertThat(mDatabase.integerPKeyDao().loadDataById(ids), is(Arrays.asList("foo", "foo2")));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryDataSourceTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryDataSourceTest.java
new file mode 100644
index 0000000..eadb8db
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryDataSourceTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertNotNull;
+
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.util.paging.CountedDataSource;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class QueryDataSourceTest extends TestDatabaseTest {
+    /**
+     * Proper, keyed implementation.
+     */
+    public class KeyedUserQueryDataSource extends CountedDataSource<User> {
+        @Override
+        public int loadCount() {
+            return mUserDao.getUserCount();
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfterInitial(int position, int pageSize) {
+            return mUserDao.userNameLimitOffset(pageSize, position + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfter(int currentEndIndex, @NonNull User currentEndItem,
+                int pageSize) {
+            return mUserDao.userNameLoadAfter(currentEndItem.getName(), pageSize);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadBefore(int currentBeginIndex, @NonNull User currentBeginItem,
+                int pageSize) {
+            return mUserDao.userNameLoadBefore(currentBeginItem.getName(), pageSize);
+        }
+    }
+
+    /**
+     * Lazy, LIMIT/OFFSET implementation.
+     */
+    public class OffsetUserQueryDataSource extends CountedDataSource<User> {
+
+        @Override
+        public int loadCount() {
+            return mUserDao.getUserCount();
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfterInitial(int position, int pageSize) {
+            return mUserDao.userNameLimitOffset(pageSize, position + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadAfter(int currentEndIndex, @NonNull User currentEndItem,
+                int pageSize) {
+            return mUserDao.userNameLimitOffset(pageSize, currentEndIndex + 1);
+        }
+
+        @Nullable
+        @Override
+        public List<User> loadBefore(int currentBeginIndex, @NonNull User currentBeginItem,
+                int pageSize) {
+            int targetOffset = currentBeginIndex - pageSize;
+            int offset = Math.max(0, targetOffset);
+            int limit = Math.min(pageSize, pageSize + targetOffset);
+
+            List<User> users = mUserDao.userNameLimitOffset(limit, offset);
+            Collections.reverse(users); // :P
+            return users;
+        }
+    }
+
+    private static final User[] USERS_BY_NAME = new User[50];
+
+    @BeforeClass
+    public static void setupClass() {
+        for (int i = 0; i < USERS_BY_NAME.length; i++) {
+            USERS_BY_NAME[i] = TestUtil.createUser(i);
+        }
+    }
+
+    @Before
+    public void setup() {
+        mUserDao.insertAll(USERS_BY_NAME);
+
+        Arrays.sort(USERS_BY_NAME, new Comparator<User>() {
+            @Override
+            public int compare(User o1, User o2) {
+                return o2.getName().compareTo(o1.getName());
+            }
+        });
+    }
+
+    @Test
+    public void testKeyedQueryDataSource() {
+        verifyUserDataSource(USERS_BY_NAME, new KeyedUserQueryDataSource());
+    }
+
+    @Test
+    public void testIndexedQueryDataSourceFull() {
+        verifyUserDataSource(USERS_BY_NAME, new OffsetUserQueryDataSource());
+    }
+
+
+    public static void verifyUserDataSource(User[] expected, CountedDataSource<User> dataSource) {
+        List<User> list = new ArrayList<>();
+        List<User> p = dataSource.loadAfterInitial(14, 10);
+        assertNotNull(p);
+        list.addAll(p);
+
+        assertArrayEquals(Arrays.copyOfRange(expected, 15, 25), list.toArray());
+        p = dataSource.loadAfter(24, list.get(list.size() - 1), 10);
+        assertNotNull(p);
+        list.addAll(p);
+
+        assertArrayEquals(Arrays.copyOfRange(expected, 15, 35), list.toArray());
+
+        p = dataSource.loadBefore(15, list.get(0), 10);
+        assertNotNull(p);
+        for (User u : p) {
+            list.add(0, u);
+        }
+
+        assertArrayEquals(Arrays.copyOfRange(expected, 5, 35), list.toArray());
+
+        p = dataSource.loadBefore(5, list.get(0), 10);
+        assertNotNull(p);
+        for (User u : p) {
+            list.add(0, u);
+        }
+
+        assertArrayEquals(Arrays.copyOfRange(expected, 0, 35), list.toArray());
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/RxJava2Test.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/RxJava2Test.java
new file mode 100644
index 0000000..1bbc140
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/RxJava2Test.java
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.executor.TaskExecutor;
+import android.arch.persistence.room.EmptyResultSetException;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.support.test.filters.MediumTest;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import io.reactivex.disposables.Disposable;
+import io.reactivex.observers.TestObserver;
+import io.reactivex.schedulers.TestScheduler;
+import io.reactivex.subscribers.TestSubscriber;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class RxJava2Test extends TestDatabaseTest {
+
+    private TestScheduler mTestScheduler;
+
+    @Before
+    public void setupSchedulers() {
+        mTestScheduler = new TestScheduler();
+        mTestScheduler.start();
+        AppToolkitTaskExecutor.getInstance().setDelegate(new TaskExecutor() {
+            @Override
+            public void executeOnDiskIO(Runnable runnable) {
+                mTestScheduler.scheduleDirect(runnable);
+            }
+
+            @Override
+            public void postToMainThread(Runnable runnable) {
+                Assert.fail("no main thread in this test");
+            }
+
+            @Override
+            public boolean isMainThread() {
+                return false;
+            }
+        });
+    }
+
+    @After
+    public void clearSchedulers() {
+        mTestScheduler.shutdown();
+        AppToolkitTaskExecutor.getInstance().setDelegate(null);
+    }
+
+    private void drain() throws InterruptedException {
+        mTestScheduler.triggerActions();
+    }
+
+    @Test
+    public void maybeUser_Empty() throws InterruptedException {
+        TestObserver<User> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.maybeUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        testObserver.assertNoValues();
+        disposable.dispose();
+    }
+
+    @Test
+    public void maybeUser_WithData() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        TestObserver<User> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.maybeUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        testObserver.assertValue(user);
+
+        disposable.dispose();
+    }
+
+    @Test
+    public void maybeUsers_EmptyList() throws InterruptedException {
+        TestObserver<List<User>> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.maybeUsersByIds(3, 5, 7).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        testObserver.assertValue(Collections.<User>emptyList());
+        disposable.dispose();
+    }
+
+    @Test
+    public void maybeUsers_WithValue() throws InterruptedException {
+        User[] users = TestUtil.createUsersArray(3, 5);
+        mUserDao.insertAll(users);
+        TestObserver<List<User>> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.maybeUsersByIds(3, 5, 7).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        // since this is a clean db, it is ok to rely on the order for the test.
+        testObserver.assertValue(Arrays.asList(users));
+        disposable.dispose();
+    }
+
+    @Test
+    public void singleUser_Empty() throws InterruptedException {
+        TestObserver<User> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.singleUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        // figure out which error we should dispatch
+        testObserver.assertError(EmptyResultSetException.class);
+        testObserver.assertNoValues();
+        disposable.dispose();
+    }
+
+    @Test
+    public void singleUser_WithData() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        TestObserver<User> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.singleUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        testObserver.assertValue(user);
+
+        disposable.dispose();
+    }
+
+    @Test
+    public void singleUsers_EmptyList() throws InterruptedException {
+        TestObserver<List<User>> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.singleUsersByIds(3, 5, 7).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        testObserver.assertValue(Collections.<User>emptyList());
+        disposable.dispose();
+    }
+
+    @Test
+    public void singleUsers_WithValue() throws InterruptedException {
+        User[] users = TestUtil.createUsersArray(3, 5);
+        mUserDao.insertAll(users);
+        TestObserver<List<User>> testObserver = new TestObserver<>();
+        Disposable disposable = mUserDao.singleUsersByIds(3, 5, 7).observeOn(mTestScheduler)
+                .subscribeWith(testObserver);
+        drain();
+        testObserver.assertComplete();
+        // since this is a clean db, it is ok to rely on the order for the test.
+        testObserver.assertValue(Arrays.asList(users));
+        disposable.dispose();
+    }
+
+    @Test
+    public void observeOnce() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        drain();
+        TestSubscriber<User> consumer = new TestSubscriber<>();
+        Disposable disposable = mUserDao.flowableUserById(3).subscribeWith(consumer);
+        drain();
+        consumer.assertValue(user);
+        disposable.dispose();
+    }
+
+    @Test
+    public void observeChangeAndDispose() throws InterruptedException {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        drain();
+        TestSubscriber<User> consumer = new TestSubscriber<>();
+        Disposable disposable = mUserDao.flowableUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(consumer);
+        drain();
+        assertThat(consumer.values().get(0), is(user));
+        user.setName("rxy");
+        mUserDao.insertOrReplace(user);
+        drain();
+        User next = consumer.values().get(1);
+        assertThat(next, is(user));
+        disposable.dispose();
+        user.setName("foo");
+        mUserDao.insertOrReplace(user);
+        drain();
+        assertThat(consumer.valueCount(), is(2));
+    }
+
+    @Test
+    @MediumTest
+    public void observeEmpty() throws InterruptedException {
+        TestSubscriber<User> consumer = new TestSubscriber<>();
+        Disposable disposable = mUserDao.flowableUserById(3).observeOn(mTestScheduler)
+                .subscribeWith(consumer);
+        drain();
+        consumer.assertNoValues();
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        drain();
+        assertThat(consumer.values().get(0), is(user));
+        disposable.dispose();
+        user.setAge(88);
+        mUserDao.insertOrReplace(user);
+        drain();
+        assertThat(consumer.valueCount(), is(1));
+    }
+
+    @Test
+    public void flowableCountUsers() throws InterruptedException {
+        TestSubscriber<Integer> consumer = new TestSubscriber<>();
+        mUserDao.flowableCountUsers()
+                .observeOn(mTestScheduler)
+                .subscribe(consumer);
+        drain();
+        assertThat(consumer.values().get(0), is(0));
+        mUserDao.insertAll(TestUtil.createUsersArray(1, 3, 4, 6));
+        drain();
+        assertThat(consumer.values().get(1), is(4));
+        mUserDao.deleteByUids(3, 7);
+        drain();
+        assertThat(consumer.values().get(2), is(3));
+        mUserDao.deleteByUids(101);
+        drain();
+        assertThat(consumer.valueCount(), is(3));
+    }
+
+    @Test
+    @MediumTest
+    public void publisherCountUsers() throws InterruptedException {
+        TestSubscriber<Integer> subscriber = new TestSubscriber<>();
+        mUserDao.publisherCountUsers().subscribe(subscriber);
+        drain();
+        subscriber.assertSubscribed();
+        subscriber.request(2);
+        drain();
+        subscriber.assertValue(0);
+        mUserDao.insert(TestUtil.createUser(2));
+        drain();
+        subscriber.assertValues(0, 1);
+        subscriber.cancel();
+        subscriber.assertNoErrors();
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/SimpleEntityReadWriteTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/SimpleEntityReadWriteTest.java
new file mode 100644
index 0000000..2b4a0e9
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/SimpleEntityReadWriteTest.java
@@ -0,0 +1,495 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasSize;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.dao.BlobEntityDao;
+import android.arch.persistence.room.integration.testapp.dao.PetDao;
+import android.arch.persistence.room.integration.testapp.dao.ProductDao;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.dao.UserPetDao;
+import android.arch.persistence.room.integration.testapp.vo.BlobEntity;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.Product;
+import android.arch.persistence.room.integration.testapp.vo.User;
+import android.arch.persistence.room.integration.testapp.vo.UserAndAllPets;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteConstraintException;
+import android.database.sqlite.SQLiteException;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import junit.framework.AssertionFailedError;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class SimpleEntityReadWriteTest {
+    private UserDao mUserDao;
+    private BlobEntityDao mBlobEntityDao;
+    private PetDao mPetDao;
+    private UserPetDao mUserPetDao;
+    private ProductDao mProductDao;
+
+    @Before
+    public void createDb() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        mUserDao = db.getUserDao();
+        mPetDao = db.getPetDao();
+        mUserPetDao = db.getUserPetDao();
+        mBlobEntityDao = db.getBlobEntityDao();
+        mProductDao = db.getProductDao();
+    }
+
+    @Test
+    public void writeUserAndReadInList() throws Exception {
+        User user = TestUtil.createUser(3);
+        user.setName("george");
+        mUserDao.insert(user);
+        List<User> byName = mUserDao.findUsersByName("george");
+        assertThat(byName.get(0), equalTo(user));
+    }
+
+    @Test
+    public void insertNull() throws Exception {
+        @SuppressWarnings("ConstantConditions")
+        Product product = new Product(1, null);
+        Throwable throwable = null;
+        try {
+            mProductDao.insert(product);
+        } catch (Throwable t) {
+            throwable = t;
+        }
+        assertNotNull("Was expecting an exception", throwable);
+        assertThat(throwable, instanceOf(SQLiteConstraintException.class));
+    }
+
+    @Test
+    public void insertDifferentEntities() throws Exception {
+        User user1 = TestUtil.createUser(3);
+        user1.setName("george");
+        Pet pet = TestUtil.createPet(1);
+        pet.setUserId(3);
+        pet.setName("a");
+        mUserPetDao.insertUserAndPet(user1, pet);
+        assertThat(mUserDao.count(), is(1));
+        List<UserAndAllPets> inserted = mUserPetDao.loadAllUsersWithTheirPets();
+        assertThat(inserted, hasSize(1));
+        assertThat(inserted.get(0).user.getId(), is(3));
+        assertThat(inserted.get(0).user.getName(), is(equalTo("george")));
+        assertThat(inserted.get(0).pets, hasSize(1));
+        assertThat(inserted.get(0).pets.get(0).getPetId(), is(1));
+        assertThat(inserted.get(0).pets.get(0).getName(), is("a"));
+        assertThat(inserted.get(0).pets.get(0).getUserId(), is(3));
+        pet.setName("b");
+        mUserPetDao.updateUsersAndPets(new User[]{user1}, new Pet[]{pet});
+        List<UserAndAllPets> updated = mUserPetDao.loadAllUsersWithTheirPets();
+        assertThat(updated, hasSize(1));
+        assertThat(updated.get(0).pets, hasSize(1));
+        assertThat(updated.get(0).pets.get(0).getName(), is("b"));
+        User user2 = TestUtil.createUser(5);
+        user2.setName("chet");
+        mUserDao.insert(user2);
+        assertThat(mUserDao.count(), is(2));
+        mUserPetDao.delete2UsersAndPets(user1, user2, new Pet[]{pet});
+        List<UserAndAllPets> deleted = mUserPetDao.loadAllUsersWithTheirPets();
+        assertThat(deleted, hasSize(0));
+    }
+
+    @Test
+    public void insertDifferentEntities_transaction() throws Exception {
+        Pet pet = TestUtil.createPet(1);
+        mPetDao.insertOrReplace(pet);
+        assertThat(mPetDao.count(), is(1));
+        User user = TestUtil.createUser(3);
+        try {
+            mUserPetDao.insertUserAndPet(user, pet);
+            fail("Exception expected");
+        } catch (SQLiteConstraintException ignored) {
+        }
+        assertThat(mUserDao.count(), is(0));
+        assertThat(mPetDao.count(), is(1));
+    }
+
+    @Test
+    public void throwExceptionOnConflict() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+
+        User user2 = TestUtil.createUser(3);
+        try {
+            mUserDao.insert(user2);
+            throw new AssertionFailedError("didn't throw in conflicting insertion");
+        } catch (SQLiteException ignored) {
+        }
+    }
+
+    @Test
+    public void replaceOnConflict() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+
+        User user2 = TestUtil.createUser(3);
+        mUserDao.insertOrReplace(user2);
+
+        assertThat(mUserDao.load(3), equalTo(user2));
+        assertThat(mUserDao.load(3), not(equalTo(user)));
+    }
+
+    @Test
+    public void updateSimple() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        user.setName("i am an updated name");
+        assertThat(mUserDao.update(user), is(1));
+        assertThat(mUserDao.load(user.getId()), equalTo(user));
+    }
+
+    @Test
+    public void updateNonExisting() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        User user2 = TestUtil.createUser(4);
+        assertThat(mUserDao.update(user2), is(0));
+    }
+
+    @Test
+    public void updateList() {
+        List<User> users = TestUtil.createUsersList(3, 4, 5);
+        mUserDao.insertAll(users.toArray(new User[3]));
+        for (User user : users) {
+            user.setName("name " + user.getId());
+        }
+        assertThat(mUserDao.updateAll(users), is(3));
+        for (User user : users) {
+            assertThat(mUserDao.load(user.getId()).getName(), is("name " + user.getId()));
+        }
+    }
+
+    @Test
+    public void updateListPartial() {
+        List<User> existingUsers = TestUtil.createUsersList(3, 4, 5);
+        mUserDao.insertAll(existingUsers.toArray(new User[3]));
+        for (User user : existingUsers) {
+            user.setName("name " + user.getId());
+        }
+        List<User> allUsers = TestUtil.createUsersList(7, 8, 9);
+        allUsers.addAll(existingUsers);
+        assertThat(mUserDao.updateAll(allUsers), is(3));
+        for (User user : existingUsers) {
+            assertThat(mUserDao.load(user.getId()).getName(), is("name " + user.getId()));
+        }
+    }
+
+    @Test
+    public void delete() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        assertThat(mUserDao.delete(user), is(1));
+        assertThat(mUserDao.delete(user), is(0));
+        assertThat(mUserDao.load(3), is(nullValue()));
+    }
+
+    @Test
+    public void deleteAll() {
+        User[] users = TestUtil.createUsersArray(3, 5, 7, 9);
+        mUserDao.insertAll(users);
+        // there is actually no guarantee for this order by works fine since they are ordered for
+        // the test and it is a new database (no pages to recycle etc)
+        assertThat(mUserDao.loadByIds(3, 5, 7, 9), is(users));
+        int deleteCount = mUserDao.deleteAll(new User[]{users[0], users[3],
+                TestUtil.createUser(9)});
+        assertThat(deleteCount, is(2));
+        assertThat(mUserDao.loadByIds(3, 5, 7, 9), is(new User[]{users[1], users[2]}));
+    }
+
+    @Test
+    public void deleteEverything() {
+        User user = TestUtil.createUser(3);
+        mUserDao.insert(user);
+        assertThat(mUserDao.count(), is(1));
+        int count = mUserDao.deleteEverything();
+        assertThat(count, is(1));
+        assertThat(mUserDao.count(), is(0));
+    }
+
+    @Test
+    public void findByBoolean() {
+        User user1 = TestUtil.createUser(3);
+        user1.setAdmin(true);
+        User user2 = TestUtil.createUser(5);
+        user2.setAdmin(false);
+        mUserDao.insert(user1);
+        mUserDao.insert(user2);
+        assertThat(mUserDao.findByAdmin(true), is(Arrays.asList(user1)));
+        assertThat(mUserDao.findByAdmin(false), is(Arrays.asList(user2)));
+    }
+
+    @Test
+    public void deleteByAge() {
+        User user1 = TestUtil.createUser(3);
+        user1.setAge(30);
+        User user2 = TestUtil.createUser(5);
+        user2.setAge(45);
+        mUserDao.insert(user1);
+        mUserDao.insert(user2);
+        assertThat(mUserDao.deleteAgeGreaterThan(60), is(0));
+        assertThat(mUserDao.deleteAgeGreaterThan(45), is(0));
+        assertThat(mUserDao.deleteAgeGreaterThan(35), is(1));
+        assertThat(mUserDao.loadByIds(3, 5), is(new User[]{user1}));
+    }
+
+    @Test
+    public void deleteByAgeRange() {
+        User user1 = TestUtil.createUser(3);
+        user1.setAge(30);
+        User user2 = TestUtil.createUser(5);
+        user2.setAge(45);
+        mUserDao.insert(user1);
+        mUserDao.insert(user2);
+        assertThat(mUserDao.deleteByAgeRange(35, 40), is(0));
+        assertThat(mUserDao.deleteByAgeRange(25, 30), is(1));
+        assertThat(mUserDao.loadByIds(3, 5), is(new User[]{user2}));
+    }
+
+    @Test
+    public void deleteByUIds() {
+        User[] users = TestUtil.createUsersArray(3, 5, 7, 9, 11);
+        mUserDao.insertAll(users);
+        assertThat(mUserDao.deleteByUids(2, 4, 6), is(0));
+        assertThat(mUserDao.deleteByUids(3, 11), is(2));
+        assertThat(mUserDao.loadByIds(3, 5, 7, 9, 11), is(new User[]{
+                users[1], users[2], users[3]
+        }));
+    }
+
+    @Test
+    public void updateNameById() {
+        User[] usersArray = TestUtil.createUsersArray(3, 5, 7);
+        mUserDao.insertAll(usersArray);
+        assertThat("test sanity", usersArray[1].getName(), not(equalTo("updated name")));
+        int changed = mUserDao.updateById(5, "updated name");
+        assertThat(changed, is(1));
+        assertThat(mUserDao.load(5).getName(), is("updated name"));
+    }
+
+    @Test
+    public void incrementIds() {
+        User[] usersArr = TestUtil.createUsersArray(2, 4, 6);
+        mUserDao.insertAll(usersArr);
+        mUserDao.incrementIds(1);
+        assertThat(mUserDao.loadIds(), is(Arrays.asList(3, 5, 7)));
+    }
+
+    @Test
+    public void incrementAgeOfAll() {
+        User[] users = TestUtil.createUsersArray(3, 5, 7);
+        users[0].setAge(3);
+        users[1].setAge(5);
+        users[2].setAge(7);
+        mUserDao.insertAll(users);
+        assertThat(mUserDao.count(), is(3));
+        mUserDao.incrementAgeOfAll();
+        for (User user : mUserDao.loadByIds(3, 5, 7)) {
+            assertThat(user.getAge(), is(user.getId() + 1));
+        }
+    }
+
+    @Test
+    public void findByIntQueryParameter() {
+        User user = TestUtil.createUser(1);
+        final String name = "my name";
+        user.setName(name);
+        mUserDao.insert(user);
+        assertThat(mUserDao.findByNameLength(name.length()), is(Collections.singletonList(user)));
+    }
+
+    @Test
+    public void findByIntFieldMatch() {
+        User user = TestUtil.createUser(1);
+        user.setAge(19);
+        mUserDao.insert(user);
+        assertThat(mUserDao.findByAge(19), is(Collections.singletonList(user)));
+    }
+
+    @Test
+    public void customConverterField() {
+        User user = TestUtil.createUser(20);
+        Date theDate = new Date(System.currentTimeMillis() - 200);
+        user.setBirthday(theDate);
+        mUserDao.insert(user);
+        assertThat(mUserDao.findByBirthdayRange(new Date(theDate.getTime() - 100),
+                new Date(theDate.getTime() + 1)).get(0), is(user));
+        assertThat(mUserDao.findByBirthdayRange(new Date(theDate.getTime()),
+                new Date(theDate.getTime() + 1)).size(), is(0));
+    }
+
+    @Test
+    public void renamedField() {
+        User user = TestUtil.createUser(3);
+        user.setCustomField("foo laaa");
+        mUserDao.insertOrReplace(user);
+        User loaded = mUserDao.load(3);
+        assertThat(loaded.getCustomField(), is("foo laaa"));
+        assertThat(loaded, is(user));
+    }
+
+    @Test
+    public void readViaCursor() {
+        User[] users = TestUtil.createUsersArray(3, 5, 7, 9);
+        mUserDao.insertAll(users);
+        Cursor cursor = mUserDao.findUsersAsCursor(3, 5, 9);
+        try {
+            assertThat(cursor.getCount(), is(3));
+            assertThat(cursor.moveToNext(), is(true));
+            assertThat(cursor.getInt(0), is(3));
+            assertThat(cursor.moveToNext(), is(true));
+            assertThat(cursor.getInt(0), is(5));
+            assertThat(cursor.moveToNext(), is(true));
+            assertThat(cursor.getInt(0), is(9));
+            assertThat(cursor.moveToNext(), is(false));
+        } finally {
+            cursor.close();
+        }
+    }
+
+    @Test
+    public void readDirectWithTypeAdapter() {
+        User user = TestUtil.createUser(3);
+        user.setBirthday(null);
+        mUserDao.insert(user);
+        assertThat(mUserDao.getBirthday(3), is(nullValue()));
+        Calendar calendar = Calendar.getInstance();
+        calendar.add(Calendar.YEAR, 3);
+        Date birthday = calendar.getTime();
+        user.setBirthday(birthday);
+
+        mUserDao.update(user);
+        assertThat(mUserDao.getBirthday(3), is(birthday));
+    }
+
+    @Test
+    public void emptyInQuery() {
+        User[] users = mUserDao.loadByIds();
+        assertThat(users, is(new User[0]));
+    }
+
+    @Test
+    public void blob() {
+        BlobEntity a = new BlobEntity(1, "abc".getBytes());
+        BlobEntity b = new BlobEntity(2, "def".getBytes());
+        mBlobEntityDao.insert(a);
+        mBlobEntityDao.insert(b);
+        List<BlobEntity> list = mBlobEntityDao.selectAll();
+        assertThat(list, hasSize(2));
+        mBlobEntityDao.updateContent(2, "ghi".getBytes());
+        assertThat(mBlobEntityDao.getContent(2), is(equalTo("ghi".getBytes())));
+    }
+
+    @Test
+    public void transactionByRunnable() {
+        User a = TestUtil.createUser(3);
+        User b = TestUtil.createUser(5);
+        mUserDao.insertBothByRunnable(a, b);
+        assertThat(mUserDao.count(), is(2));
+    }
+
+    @Test
+    public void transactionByRunnable_failure() {
+        User a = TestUtil.createUser(3);
+        User b = TestUtil.createUser(3);
+        boolean caught = false;
+        try {
+            mUserDao.insertBothByRunnable(a, b);
+        } catch (SQLiteConstraintException e) {
+            caught = true;
+        }
+        assertTrue("SQLiteConstraintException expected", caught);
+        assertThat(mUserDao.count(), is(0));
+    }
+
+    @Test
+    public void transactionByCallable() {
+        User a = TestUtil.createUser(3);
+        User b = TestUtil.createUser(5);
+        int count = mUserDao.insertBothByCallable(a, b);
+        assertThat(mUserDao.count(), is(2));
+        assertThat(count, is(2));
+    }
+
+    @Test
+    public void transactionByCallable_failure() {
+        User a = TestUtil.createUser(3);
+        User b = TestUtil.createUser(3);
+        boolean caught = false;
+        try {
+            mUserDao.insertBothByCallable(a, b);
+        } catch (SQLiteConstraintException e) {
+            caught = true;
+        }
+        assertTrue("SQLiteConstraintException expected", caught);
+        assertThat(mUserDao.count(), is(0));
+    }
+
+    @Test
+    public void multipleInParamsFollowedByASingleParam_delete() {
+        User user = TestUtil.createUser(3);
+        user.setAge(30);
+        mUserDao.insert(user);
+        assertThat(mUserDao.deleteByAgeAndIds(20, Arrays.asList(3, 5)), is(0));
+        assertThat(mUserDao.count(), is(1));
+        assertThat(mUserDao.deleteByAgeAndIds(30, Arrays.asList(3, 5)), is(1));
+        assertThat(mUserDao.count(), is(0));
+    }
+
+    @Test
+    public void multipleInParamsFollowedByASingleParam_update() {
+        User user = TestUtil.createUser(3);
+        user.setAge(30);
+        user.setWeight(10f);
+        mUserDao.insert(user);
+        assertThat(mUserDao.updateByAgeAndIds(3f, 20, Arrays.asList(3, 5)), is(0));
+        assertThat(mUserDao.loadByIds(3)[0].getWeight(), is(10f));
+        assertThat(mUserDao.updateByAgeAndIds(3f, 30, Arrays.asList(3, 5)), is(1));
+        assertThat(mUserDao.loadByIds(3)[0].getWeight(), is(3f));
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestDatabaseTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestDatabaseTest.java
new file mode 100644
index 0000000..02499a7
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestDatabaseTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.test;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+import android.arch.persistence.room.integration.testapp.dao.PetCoupleDao;
+import android.arch.persistence.room.integration.testapp.dao.PetDao;
+import android.arch.persistence.room.integration.testapp.dao.SchoolDao;
+import android.arch.persistence.room.integration.testapp.dao.ToyDao;
+import android.arch.persistence.room.integration.testapp.dao.UserDao;
+import android.arch.persistence.room.integration.testapp.dao.UserPetDao;
+
+import org.junit.Before;
+
+@SuppressWarnings("WeakerAccess")
+public abstract class TestDatabaseTest {
+    protected TestDatabase mDatabase;
+    protected UserDao mUserDao;
+    protected PetDao mPetDao;
+    protected UserPetDao mUserPetDao;
+    protected SchoolDao mSchoolDao;
+    protected PetCoupleDao mPetCoupleDao;
+    protected ToyDao mToyDao;
+
+    @Before
+    public void createDb() {
+        Context context = InstrumentationRegistry.getTargetContext();
+        mDatabase = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        mUserDao = mDatabase.getUserDao();
+        mPetDao = mDatabase.getPetDao();
+        mUserPetDao = mDatabase.getUserPetDao();
+        mSchoolDao = mDatabase.getSchoolDao();
+        mPetCoupleDao = mDatabase.getPetCoupleDao();
+        mToyDao = mDatabase.getToyDao();
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestUtil.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestUtil.java
new file mode 100644
index 0000000..0a35b2f
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/TestUtil.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.test;
+
+import android.arch.persistence.room.integration.testapp.vo.Address;
+import android.arch.persistence.room.integration.testapp.vo.Coordinates;
+import android.arch.persistence.room.integration.testapp.vo.Pet;
+import android.arch.persistence.room.integration.testapp.vo.School;
+import android.arch.persistence.room.integration.testapp.vo.User;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+
+public class TestUtil {
+    public static User[] createUsersArray(int... ids) {
+        User[] result = new User[ids.length];
+        for (int i = 0; i < ids.length; i++) {
+            result[i] = createUser(ids[i]);
+        }
+        return result;
+    }
+
+    public static List<User> createUsersList(int... ids) {
+        List<User> result = new ArrayList<>();
+        for (int id : ids) {
+            result.add(createUser(id));
+        }
+        return result;
+    }
+
+    public static User createUser(int id) {
+        User user = new User();
+        user.setId(id);
+        user.setName(UUID.randomUUID().toString());
+        user.setLastName(UUID.randomUUID().toString());
+        user.setAge((int) (10 + Math.random() * 50));
+        user.setCustomField(UUID.randomUUID().toString());
+        user.setBirthday(new Date());
+        return user;
+    }
+
+    public static Pet createPet(int id) {
+        Pet pet = new Pet();
+        pet.setPetId(id);
+        pet.setName(UUID.randomUUID().toString());
+        return pet;
+    }
+
+    public static Pet[] createPetsForUser(int uid, int petStartId, int count) {
+        Pet[] pets = new Pet[count];
+        for (int i = 0; i < count; i++) {
+            Pet pet = createPet(petStartId++);
+            pet.setUserId(uid);
+            pets[i] = pet;
+        }
+        return pets;
+    }
+
+    public static School createSchool(int id, int managerId) {
+        School school = new School();
+        school.setId(id);
+        school.setName(UUID.randomUUID().toString());
+        school.setManager(createUser(managerId));
+        school.setAddress(createAddress());
+        return school;
+    }
+
+    private static Address createAddress() {
+        Address address = new Address();
+        address.setCoordinates(createCoordinates());
+        address.setPostCode((int) (Math.random() * 1000 + 1000));
+        address.setState(UUID.randomUUID().toString().substring(0, 2));
+        address.setStreet(UUID.randomUUID().toString());
+        return address;
+    }
+
+    private static Coordinates createCoordinates() {
+        Coordinates coordinates = new Coordinates();
+        coordinates.lat = Math.random();
+        coordinates.lng = Math.random();
+        return coordinates;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Address.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Address.java
new file mode 100644
index 0000000..46f3bb6
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Address.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Embedded;
+
+public class Address {
+    @ColumnInfo(name = "street")
+    private String mStreet;
+    @ColumnInfo(name = "state")
+    private String mState;
+    @ColumnInfo(name = "post_code")
+    private int mPostCode;
+    @Embedded
+    private Coordinates mCoordinates;
+
+    public String getStreet() {
+        return mStreet;
+    }
+
+    public void setStreet(String street) {
+        mStreet = street;
+    }
+
+    public String getState() {
+        return mState;
+    }
+
+    public void setState(String state) {
+        mState = state;
+    }
+
+    public int getPostCode() {
+        return mPostCode;
+    }
+
+    public void setPostCode(int postCode) {
+        mPostCode = postCode;
+    }
+
+    public Coordinates getCoordinates() {
+        return mCoordinates;
+    }
+
+    public void setCoordinates(Coordinates coordinates) {
+        mCoordinates = coordinates;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Address address = (Address) o;
+
+        if (mPostCode != address.mPostCode) return false;
+        if (mStreet != null ? !mStreet.equals(address.mStreet) : address.mStreet != null) {
+            return false;
+        }
+        if (mState != null ? !mState.equals(address.mState) : address.mState != null) {
+            return false;
+        }
+        return mCoordinates != null ? mCoordinates.equals(address.mCoordinates)
+                : address.mCoordinates == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mStreet != null ? mStreet.hashCode() : 0;
+        result = 31 * result + (mState != null ? mState.hashCode() : 0);
+        result = 31 * result + mPostCode;
+        result = 31 * result + (mCoordinates != null ? mCoordinates.hashCode() : 0);
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/AvgWeightByAge.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/AvgWeightByAge.java
new file mode 100644
index 0000000..4d22f13
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/AvgWeightByAge.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Ignore;
+
+@SuppressWarnings("unused")
+public class AvgWeightByAge {
+
+    private int mAge;
+
+    @ColumnInfo(name = "AVG(mWeight)")
+    private float mWeight;
+
+    public AvgWeightByAge() {
+    }
+
+    @Ignore
+    public AvgWeightByAge(int age, float weight) {
+        mAge = age;
+        mWeight = weight;
+    }
+
+    public int getAge() {
+        return mAge;
+    }
+
+    public void setAge(int age) {
+        mAge = age;
+    }
+
+    public float getWeight() {
+        return mWeight;
+    }
+
+    public void setWeight(float weight) {
+        mWeight = weight;
+    }
+
+    @Override
+    public String toString() {
+        return "AvgWeightByAge{"
+                + "mAge=" + mAge
+                + ", mWeight=" + mWeight
+                + '}';
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        AvgWeightByAge that = (AvgWeightByAge) o;
+
+        //noinspection SimplifiableIfStatement
+        if (mAge != that.mAge) {
+            return false;
+        }
+        return Float.compare(that.mWeight, mWeight) == 0;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mAge;
+        result = 31 * result + (mWeight != +0.0f ? Float.floatToIntBits(mWeight) : 0);
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/BlobEntity.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/BlobEntity.java
new file mode 100644
index 0000000..134afc7
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/BlobEntity.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+@Entity
+public class BlobEntity {
+    @PrimaryKey
+    public long id;
+    public byte[] content;
+
+    public BlobEntity(long id, byte[] content) {
+        this.id = id;
+        this.content = content;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Coordinates.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Coordinates.java
new file mode 100644
index 0000000..e8cfd06
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Coordinates.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+public class Coordinates {
+    public double lat;
+    public double lng;
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Coordinates that = (Coordinates) o;
+
+        if (Double.compare(that.lat, lat) != 0) return false;
+        return Double.compare(that.lng, lng) == 0;
+    }
+
+    @Override
+    public int hashCode() {
+        int result;
+        long temp;
+        temp = Double.doubleToLongBits(lat);
+        result = (int) (temp ^ (temp >>> 32));
+        temp = Double.doubleToLongBits(lng);
+        result = 31 * result + (int) (temp ^ (temp >>> 32));
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/EmbeddedUserAndAllPets.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/EmbeddedUserAndAllPets.java
new file mode 100644
index 0000000..ca82bfe
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/EmbeddedUserAndAllPets.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+
+public class EmbeddedUserAndAllPets {
+    @Embedded
+    UserAndAllPets mUserAndAllPets;
+
+    public UserAndAllPets getUserAndAllPets() {
+        return mUserAndAllPets;
+    }
+
+    public void setUserAndAllPets(UserAndAllPets userAndAllPets) {
+        this.mUserAndAllPets = userAndAllPets;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntAutoIncPKeyEntity.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntAutoIncPKeyEntity.java
new file mode 100644
index 0000000..3392649
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntAutoIncPKeyEntity.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+@Entity
+public class IntAutoIncPKeyEntity {
+    @PrimaryKey(autoGenerate = true)
+    public int pKey;
+    public String data;
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntegerAutoIncPKeyEntity.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntegerAutoIncPKeyEntity.java
new file mode 100644
index 0000000..636ffd9
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/IntegerAutoIncPKeyEntity.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+@Entity
+public class IntegerAutoIncPKeyEntity {
+    @PrimaryKey(autoGenerate = true)
+    public Integer pKey;
+    public String data;
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Pet.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Pet.java
new file mode 100644
index 0000000..8806e10
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Pet.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+@Entity
+public class Pet {
+    @PrimaryKey
+    private int mPetId;
+    private int mUserId;
+    @ColumnInfo(name = "mPetName")
+    private String mName;
+
+    public int getPetId() {
+        return mPetId;
+    }
+
+    public void setPetId(int petId) {
+        mPetId = petId;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public void setName(String name) {
+        mName = name;
+    }
+
+    public int getUserId() {
+        return mUserId;
+    }
+
+    public void setUserId(int userId) {
+        mUserId = userId;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Pet pet = (Pet) o;
+
+        if (mPetId != pet.mPetId) return false;
+        if (mUserId != pet.mUserId) return false;
+        return mName != null ? mName.equals(pet.mName) : pet.mName == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mPetId;
+        result = 31 * result + mUserId;
+        result = 31 * result + (mName != null ? mName.hashCode() : 0);
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetAndToys.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetAndToys.java
new file mode 100644
index 0000000..69fb591
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetAndToys.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Relation;
+
+import java.util.List;
+
+public class PetAndToys {
+    @Embedded
+    public Pet pet;
+    @Relation(parentColumn = "mPetId", entityColumn = "mPetId")
+    public List<Toy> toys;
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetCouple.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetCouple.java
new file mode 100644
index 0000000..f27b131
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/PetCouple.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.RoomWarnings;
+
+@Entity
+@SuppressWarnings(RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED)
+public class PetCouple {
+    @PrimaryKey
+    public String id;
+    @Embedded(prefix = "male_")
+    public Pet male;
+    @Embedded(prefix = "female_")
+    private Pet mFemale;
+
+    public Pet getFemale() {
+        return mFemale;
+    }
+
+    public void setFemale(Pet female) {
+        mFemale = female;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        PetCouple petCouple = (PetCouple) o;
+
+        if (male != null ? !male.equals(petCouple.male) : petCouple.male != null) return false;
+        return mFemale != null ? mFemale.equals(petCouple.mFemale) : petCouple.mFemale == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = male != null ? male.hashCode() : 0;
+        result = 31 * result + (mFemale != null ? mFemale.hashCode() : 0);
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Product.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Product.java
new file mode 100644
index 0000000..a395aea
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Product.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.support.annotation.NonNull;
+
+@Entity(tableName = "products")
+public class Product {
+
+    @PrimaryKey(autoGenerate = true)
+    public final int id;
+
+    @NonNull
+    public final String name;
+
+    public Product(int id, @NonNull String name) {
+        this.id = id;
+        this.name = name;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/School.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/School.java
new file mode 100644
index 0000000..f0426f1
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/School.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+@Entity
+public class School {
+    @PrimaryKey
+    private int mId;
+    private String mName;
+    @Embedded(prefix = "address_")
+    public Address address;
+
+    @Embedded(prefix = "manager_")
+    private User mManager;
+
+    public int getId() {
+        return mId;
+    }
+
+    public void setId(int id) {
+        mId = id;
+    }
+
+    public Address getAddress() {
+        return address;
+    }
+
+    public void setAddress(Address address) {
+        this.address = address;
+    }
+
+    public User getManager() {
+        return mManager;
+    }
+
+    public void setManager(User manager) {
+        mManager = manager;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public void setName(String name) {
+        mName = name;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        School school = (School) o;
+
+        if (mId != school.mId) {
+            return false;
+        }
+        if (mName != null ? !mName.equals(school.mName) : school.mName != null) {
+            return false;
+        }
+        if (address != null ? !address.equals(school.address) : school.address != null) {
+            return false;
+        }
+        return mManager != null ? mManager.equals(school.mManager) : school.mManager == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mId;
+        result = 31 * result + (mName != null ? mName.hashCode() : 0);
+        result = 31 * result + (address != null ? address.hashCode() : 0);
+        result = 31 * result + (mManager != null ? mManager.hashCode() : 0);
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/SchoolRef.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/SchoolRef.java
new file mode 100644
index 0000000..bbf0cb4
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/SchoolRef.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+public class SchoolRef extends School {
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Toy.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Toy.java
new file mode 100644
index 0000000..5198c2d
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/Toy.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
+/**
+ * The toys of a pet.
+ */
+@Entity
+public class Toy {
+    @PrimaryKey(autoGenerate = true)
+    private int mId;
+    private String mName;
+    private int mPetId;
+
+    public int getId() {
+        return mId;
+    }
+
+    public void setId(int id) {
+        mId = id;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public void setName(String name) {
+        mName = name;
+    }
+
+    public int getPetId() {
+        return mPetId;
+    }
+
+    public void setPetId(int petId) {
+        mPetId = petId;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Toy toy = (Toy) o;
+
+        if (mId != toy.mId) return false;
+        if (mPetId != toy.mPetId) return false;
+        return mName != null ? mName.equals(toy.mName) : toy.mName == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mId;
+        result = 31 * result + (mName != null ? mName.hashCode() : 0);
+        result = 31 * result + mPetId;
+        return result;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/User.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/User.java
new file mode 100644
index 0000000..57cf585
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/User.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.TypeConverters;
+import android.arch.persistence.room.integration.testapp.TestDatabase;
+
+import java.util.Date;
+
+@Entity
+@TypeConverters({TestDatabase.Converters.class})
+public class User {
+
+    @PrimaryKey
+    private int mId;
+
+    private String mName;
+
+    private String mLastName;
+
+    private int mAge;
+
+    private boolean mAdmin;
+
+    private float mWeight;
+
+    private Date mBirthday;
+
+    @ColumnInfo(name = "custommm")
+    private String mCustomField;
+
+    public int getId() {
+        return mId;
+    }
+
+    public void setId(int id) {
+        this.mId = id;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public void setName(String name) {
+        this.mName = name;
+    }
+
+    public String getLastName() {
+        return mLastName;
+    }
+
+    public void setLastName(String lastName) {
+        this.mLastName = lastName;
+    }
+
+    public int getAge() {
+        return mAge;
+    }
+
+    public void setAge(int age) {
+        this.mAge = age;
+    }
+
+    public boolean isAdmin() {
+        return mAdmin;
+    }
+
+    public void setAdmin(boolean admin) {
+        mAdmin = admin;
+    }
+
+    public float getWeight() {
+        return mWeight;
+    }
+
+    public void setWeight(float weight) {
+        mWeight = weight;
+    }
+
+    public Date getBirthday() {
+        return mBirthday;
+    }
+
+    public void setBirthday(Date birthday) {
+        mBirthday = birthday;
+    }
+
+    public String getCustomField() {
+        return mCustomField;
+    }
+
+    public void setCustomField(String customField) {
+        mCustomField = customField;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        User user = (User) o;
+
+        if (mId != user.mId) return false;
+        if (mAge != user.mAge) return false;
+        if (mAdmin != user.mAdmin) return false;
+        if (Float.compare(user.mWeight, mWeight) != 0) return false;
+        if (mName != null ? !mName.equals(user.mName) : user.mName != null) return false;
+        if (mLastName != null ? !mLastName.equals(user.mLastName) : user.mLastName != null) {
+            return false;
+        }
+        if (mBirthday != null ? !mBirthday.equals(user.mBirthday) : user.mBirthday != null) {
+            return false;
+        }
+        return mCustomField != null ? mCustomField.equals(user.mCustomField)
+                : user.mCustomField == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mId;
+        result = 31 * result + (mName != null ? mName.hashCode() : 0);
+        result = 31 * result + (mLastName != null ? mLastName.hashCode() : 0);
+        result = 31 * result + mAge;
+        result = 31 * result + (mAdmin ? 1 : 0);
+        result = 31 * result + (mWeight != +0.0f ? Float.floatToIntBits(mWeight) : 0);
+        result = 31 * result + (mBirthday != null ? mBirthday.hashCode() : 0);
+        result = 31 * result + (mCustomField != null ? mCustomField.hashCode() : 0);
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "User{"
+                + "mId=" + mId
+                + ", mName='" + mName + '\''
+                + ", mLastName='" + mLastName + '\''
+                + ", mAge=" + mAge
+                + ", mAdmin=" + mAdmin
+                + ", mWeight=" + mWeight
+                + ", mBirthday=" + mBirthday
+                + ", mCustom=" + mCustomField
+                + '}';
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndAllPets.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndAllPets.java
new file mode 100644
index 0000000..24a0710
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndAllPets.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Relation;
+
+import java.util.List;
+
+public class UserAndAllPets {
+    @Embedded
+    public User user;
+    @Relation(parentColumn = "mId", entityColumn = "mUserId")
+    public List<Pet> pets;
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPet.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPet.java
new file mode 100644
index 0000000..628e9bf
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPet.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+import android.arch.persistence.room.Embedded;
+
+public class UserAndPet {
+    @Embedded
+    private User mUser;
+    @Embedded
+    private Pet mPet;
+
+    public User getUser() {
+        return mUser;
+    }
+
+    public void setUser(User user) {
+        mUser = user;
+    }
+
+    public Pet getPet() {
+        return mPet;
+    }
+
+    public void setPet(Pet pet) {
+        mPet = pet;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPetNonNull.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPetNonNull.java
new file mode 100644
index 0000000..8739bd0
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserAndPetNonNull.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.support.annotation.NonNull;
+
+public class UserAndPetNonNull {
+    @Embedded
+    private User mUser;
+    @Embedded
+    @NonNull
+    private Pet mPet;
+
+    public User getUser() {
+        return mUser;
+    }
+
+    public void setUser(User user) {
+        mUser = user;
+    }
+
+    public Pet getPet() {
+        return mPet;
+    }
+
+    public void setPet(Pet pet) {
+        mPet = pet;
+    }
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserIdAndPetNames.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserIdAndPetNames.java
new file mode 100644
index 0000000..444431e
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserIdAndPetNames.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.ColumnInfo;
+import android.arch.persistence.room.Relation;
+
+import java.util.List;
+
+/**
+ * Same as Pet class but only keeps name and user id
+ */
+public class UserIdAndPetNames {
+    @ColumnInfo(name = "mId")
+    public int userId;
+    @Relation(entity = Pet.class, parentColumn = "mId", entityColumn = "mUserId",
+            projection = "mPetName")
+    public List<String> names;
+}
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserWithPetsAndToys.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserWithPetsAndToys.java
new file mode 100644
index 0000000..01c9bed
--- /dev/null
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/vo/UserWithPetsAndToys.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.vo;
+
+import android.arch.persistence.room.Embedded;
+import android.arch.persistence.room.Relation;
+
+import java.util.List;
+
+public class UserWithPetsAndToys {
+    @Embedded
+    public User user;
+    @Relation(entity = Pet.class, parentColumn = "mId", entityColumn = "mUserId")
+    public List<PetAndToys> pets;
+}
diff --git a/room/integration-tests/testapp/src/main/AndroidManifest.xml b/room/integration-tests/testapp/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..27fabd4
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/AndroidManifest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.room.integration.testapp">
+    <application
+        android:allowBackup="true"
+        android:supportsRtl="true">
+        <activity
+            android:name=".LazyListActivity"
+            android:label="Room LazyList"
+            android:theme="@style/Theme.AppCompat">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+  </manifest>
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java
new file mode 100644
index 0000000..2d8391c
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp;
+
+import android.app.Application;
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.lifecycle.AndroidViewModel;
+import android.arch.lifecycle.LiveData;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.integration.testapp.database.Customer;
+import android.arch.persistence.room.integration.testapp.database.SampleDatabase;
+import android.arch.util.paging.LazyList;
+import android.arch.util.paging.ListConfig;
+
+import java.util.UUID;
+
+/**
+ * Sample database-backed view model of Customers
+ */
+public class CustomerViewModel extends AndroidViewModel {
+    private SampleDatabase mDatabase;
+    private LiveData<LazyList<Customer>> mLiveCustomerList;
+    private static int sCustomerId = 0;
+
+    public CustomerViewModel(Application application) {
+        super(application);
+        createDb();
+        mLiveCustomerList = mDatabase.getCustomerDao().loadPagedAgeOrder().create(
+                ListConfig.builder()
+                        .pageSize(10)
+                        .prefetchDistance(10)
+                        .create());
+    }
+
+    private void createDb() {
+        mDatabase = Room.inMemoryDatabaseBuilder(this.getApplication(),
+                SampleDatabase.class).build();
+    }
+
+    public void setDatabase(SampleDatabase database) {
+        mDatabase = database;
+
+    }
+
+    void insertCustomer() {
+        AppToolkitTaskExecutor.getInstance().executeOnDiskIO(new Runnable() {
+            @Override
+            public void run() {
+                Customer customer = new Customer();
+                customer.setId(sCustomerId++);
+                customer.setName(UUID.randomUUID().toString());
+                customer.setLastName(UUID.randomUUID().toString());
+                mDatabase.getCustomerDao().insert(customer);
+            }
+        });
+    }
+
+    LiveData<LazyList<Customer>> getLazyList() {
+        return mLiveCustomerList;
+    }
+}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListActivity.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListActivity.java
new file mode 100644
index 0000000..983a52f
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListActivity.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp;
+
+import android.arch.lifecycle.LifecycleRegistry;
+import android.arch.lifecycle.LifecycleRegistryOwner;
+import android.arch.lifecycle.ViewModelProviders;
+import android.arch.persistence.room.integration.testapp.database.Customer;
+import android.arch.util.paging.LazyListAdapterHelper;
+import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
+import android.support.v7.widget.RecyclerView;
+import android.view.View;
+import android.widget.Button;
+
+/**
+ * Sample LazyList activity which uses Room.
+ */
+public class LazyListActivity extends AppCompatActivity implements LifecycleRegistryOwner {
+
+    @Override
+    protected void onCreate(final Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final CustomerViewModel viewModel = ViewModelProviders.of(this)
+                .get(CustomerViewModel.class);
+        setContentView(R.layout.activity_recycler_view);
+        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
+        final LazyListCustomerAdapter adapter = new LazyListCustomerAdapter(
+                LazyListAdapterHelper
+                        .<Customer>builder()
+                        .lifecycle(this)
+                        .diffCallback(Customer.DIFF_CALLBACK)
+                        .source(viewModel.getLazyList()));
+        recyclerView.setAdapter(adapter);
+        final Button button = (Button) findViewById(R.id.button);
+        button.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                viewModel.insertCustomer();
+            }
+        });
+    }
+
+    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
+
+    @Override
+    public LifecycleRegistry getLifecycle() {
+        return mLifecycleRegistry;
+    }
+}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListCustomerAdapter.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListCustomerAdapter.java
new file mode 100644
index 0000000..2fc7e71
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/LazyListCustomerAdapter.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp;
+
+import android.arch.persistence.room.integration.testapp.database.Customer;
+import android.arch.util.paging.LazyListAdapterHelper;
+import android.support.v7.widget.RecyclerView;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import io.reactivex.annotations.NonNull;
+
+/**
+ * Sample adapter which uses a LazyListAdapterHelper.
+ */
+public class LazyListCustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
+    private final LazyListAdapterHelper<Customer> mHelper;
+
+    public LazyListCustomerAdapter(@NonNull LazyListAdapterHelper.Builder<Customer> builder) {
+        this.mHelper = builder.adapter(this).create();
+    }
+
+    @Override
+    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+        return new RecyclerView.ViewHolder(new TextView(parent.getContext())) {
+        };
+    }
+
+    @Override
+    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
+        Customer customer = mHelper.get(position);
+        ((TextView) (holder.itemView)).setText(customer == null ? "loading" : customer.getLastName());
+        holder.itemView.setMinimumHeight(400);
+    }
+
+    @Override
+    public int getItemCount() {
+        return mHelper.getItemCount();
+    }
+}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/Customer.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/Customer.java
new file mode 100644
index 0000000..eb928da
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/Customer.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.database;
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.TypeConverters;
+import android.arch.util.paging.DiffCallback;
+import android.support.annotation.NonNull;
+
+/**
+ * Sample entity
+ */
+@Entity
+public class Customer {
+
+    @PrimaryKey
+    private int mId;
+
+    private String mName;
+
+    private String mLastName;
+
+    public int getId() {
+        return mId;
+    }
+
+    public void setId(int id) {
+        this.mId = id;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public void setName(String name) {
+        this.mName = name;
+    }
+
+    public String getLastName() {
+        return mLastName;
+    }
+
+    public void setLastName(String lastName) {
+        this.mLastName = lastName;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Customer customer = (Customer) o;
+
+        if (mId != customer.mId) {
+            return false;
+        }
+        if (mName != null ? !mName.equals(customer.mName) : customer.mName != null) {
+            return false;
+        }
+        return mLastName != null ? mLastName.equals(customer.mLastName)
+                : customer.mLastName == null;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mId;
+        result = 31 * result + (mName != null ? mName.hashCode() : 0);
+        result = 31 * result + (mLastName != null ? mLastName.hashCode() : 0);
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "Customer{"
+                + "mId=" + mId
+                + ", mName='" + mName + '\''
+                + ", mLastName='" + mLastName + '\''
+                + '}';
+    }
+
+    public static final DiffCallback<Customer> DIFF_CALLBACK = new DiffCallback<Customer>() {
+        @Override
+        public boolean areContentsTheSame(@NonNull Customer oldItem, @NonNull Customer newItem) {
+            return oldItem.equals(newItem);
+        }
+
+        @Override
+        public boolean areItemsTheSame(@NonNull Customer oldItem, @NonNull Customer newItem) {
+            return oldItem.getId() == newItem.getId();
+        }
+    };
+}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/CustomerDao.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/CustomerDao.java
new file mode 100644
index 0000000..d82701b
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/CustomerDao.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.integration.testapp.database;
+
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.util.paging.ListConfig;
+import android.arch.util.paging.LiveLazyListProvider;
+
+/**
+ * Simple Customer DAO for Room Customer list sample.
+ */
+@Dao
+public interface CustomerDao {
+
+    /**
+     * Insert a customer
+     * @param customer Customer.
+     */
+    @Insert
+    void insert(Customer customer);
+
+    /**
+     * Insert multiple customers.
+     * @param customers Customers.
+     */
+    @Insert
+    void insertAll(Customer[] customers);
+
+    /**
+     * @return LiveLazyListProvider of customers, ordered by last name. Call
+     * {@link LiveLazyListProvider#create(ListConfig)} to get a LiveData of LazyLists.
+     */
+    @Query("SELECT * FROM customer ORDER BY mLastName ASC")
+    LiveLazyListProvider<Customer> loadPagedAgeOrder();
+}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/SampleDatabase.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/SampleDatabase.java
new file mode 100644
index 0000000..eec59f6
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/SampleDatabase.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.database;
+
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.TypeConverter;
+import android.arch.persistence.room.TypeConverters;
+
+import java.util.Date;
+
+/**
+ * Sample database of customers.
+ */
+@Database(entities = {Customer.class},
+        version = 1, exportSchema = false)
+public abstract class SampleDatabase extends RoomDatabase {
+    /**
+     * @return customer dao.
+     */
+    public abstract CustomerDao getCustomerDao();
+}
diff --git a/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml b/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
new file mode 100644
index 0000000..7e2367b
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/activity_recycler_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="android.arch.persistence.room.integration.testapp.LazyListActivity">
+    <android.support.v7.widget.RecyclerView
+        android:id="@+id/recyclerview"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        app:layoutManager="LinearLayoutManager"
+        android:clipToPadding="false"
+        android:paddingBottom="@dimen/activity_vertical_margin"
+        android:paddingLeft="@dimen/activity_horizontal_margin"
+        android:paddingRight="@dimen/activity_horizontal_margin"
+        android:paddingTop="@dimen/activity_vertical_margin"
+    />
+    <Button
+        android:id="@+id/button"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true"
+        android:text="@string/insert"/>
+</RelativeLayout>
diff --git a/room/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml b/room/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml
new file mode 100644
index 0000000..edff918
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/res/values-w820dp/dimens.xml
@@ -0,0 +1,23 @@
+
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>
diff --git a/room/integration-tests/testapp/src/main/res/values/dimens.xml b/room/integration-tests/testapp/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..3358489
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/res/values/dimens.xml
@@ -0,0 +1,21 @@
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>
diff --git a/room/integration-tests/testapp/src/main/res/values/strings.xml b/room/integration-tests/testapp/src/main/res/values/strings.xml
new file mode 100644
index 0000000..5f55cc3
--- /dev/null
+++ b/room/integration-tests/testapp/src/main/res/values/strings.xml
@@ -0,0 +1,19 @@
+<!--
+~ Copyright (C) 2017 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.
+-->
+
+<resources>
+    <string name="insert">Insert</string>
+</resources>
diff --git a/room/integration-tests/testapp/src/test/java/android/arch/persistence/room/integration/testapp/db/JDBCOpenHelper.java b/room/integration-tests/testapp/src/test/java/android/arch/persistence/room/integration/testapp/db/JDBCOpenHelper.java
new file mode 100644
index 0000000..3cbffc8
--- /dev/null
+++ b/room/integration-tests/testapp/src/test/java/android/arch/persistence/room/integration/testapp/db/JDBCOpenHelper.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.integration.testapp.db;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+
+public class JDBCOpenHelper implements SupportSQLiteOpenHelper {
+    @Override
+    public String getDatabaseName() {
+        return null;
+    }
+
+    @Override
+    public void setWriteAheadLoggingEnabled(boolean enabled) {
+
+    }
+
+    @Override
+    public SupportSQLiteDatabase getWritableDatabase() {
+        return null;
+    }
+
+    @Override
+    public SupportSQLiteDatabase getReadableDatabase() {
+        return null;
+    }
+
+    @Override
+    public void close() {
+
+    }
+}
diff --git a/room/migration/build.gradle b/room/migration/build.gradle
new file mode 100644
index 0000000..7e3794b
--- /dev/null
+++ b/room/migration/build.gradle
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+apply plugin: 'maven'
+apply plugin: 'java'
+
+sourceCompatibility = 1.7
+
+sourceSets {
+    test.java.srcDirs += 'src/tests/kotlin'
+}
+project.ext.noDocs = true
+dependencies {
+    compile project(":room:common")
+    compile libs.kotlin.stdlib
+    compile libs.gson
+    testCompile libs.junit
+    testCompile libs.ij_annotations
+    testCompile libs.mockito_core
+}
+
+archivesBaseName = "migration"
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/BundleUtil.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/BundleUtil.java
new file mode 100644
index 0000000..4356e69
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/BundleUtil.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+/**
+ * Utility functions for bundling.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class BundleUtil {
+    /**
+     * Placeholder for table names in queries.
+     */
+    public static final String TABLE_NAME_PLACEHOLDER = "${TABLE_NAME}";
+
+    static String replaceTableName(String contents, String tableName) {
+        return contents.replace(TABLE_NAME_PLACEHOLDER, tableName);
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/DatabaseBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/DatabaseBundle.java
new file mode 100644
index 0000000..4ac9029
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/DatabaseBundle.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Data class that holds the schema information for a
+ * {@link android.arch.persistence.room.Database Database}.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class DatabaseBundle {
+    @SerializedName("version")
+    private int mVersion;
+    @SerializedName("identityHash")
+    private String mIdentityHash;
+    @SerializedName("entities")
+    private List<EntityBundle> mEntities;
+    // then entity where we keep room information
+    @SerializedName("setupQueries")
+    private List<String> mSetupQueries;
+    private transient Map<String, EntityBundle> mEntitiesByTableName;
+
+    /**
+     * Creates a new database
+     * @param version Version
+     * @param identityHash Identity hash
+     * @param entities List of entities
+     */
+    public DatabaseBundle(int version, String identityHash, List<EntityBundle> entities,
+            List<String> setupQueries) {
+        mVersion = version;
+        mIdentityHash = identityHash;
+        mEntities = entities;
+        mSetupQueries = setupQueries;
+    }
+
+    /**
+     * @return The identity has of the Database.
+     */
+    public String getIdentityHash() {
+        return mIdentityHash;
+    }
+
+    /**
+     * @return The database version.
+     */
+    public int getVersion() {
+        return mVersion;
+    }
+
+    /**
+     * @return List of entities.
+     */
+    public List<EntityBundle> getEntities() {
+        return mEntities;
+    }
+
+    /**
+     * @return Map of entities, keyed by table name.
+     */
+    @SuppressWarnings("unused")
+    public Map<String, EntityBundle> getEntitiesByTableName() {
+        if (mEntitiesByTableName == null) {
+            mEntitiesByTableName = new HashMap<>();
+            for (EntityBundle bundle : mEntities) {
+                mEntitiesByTableName.put(bundle.getTableName(), bundle);
+            }
+        }
+        return mEntitiesByTableName;
+    }
+
+    /**
+     * @return List of SQL queries to build this database from scratch.
+     */
+    public List<String> buildCreateQueries() {
+        List<String> result = new ArrayList<>();
+        for (EntityBundle entityBundle : mEntities) {
+            result.addAll(entityBundle.buildCreateQueries());
+        }
+        result.addAll(mSetupQueries);
+        return result;
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/EntityBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/EntityBundle.java
new file mode 100644
index 0000000..8980a3b
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/EntityBundle.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.annotations.SerializedName;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Data class that holds the schema information about an
+ * {@link android.arch.persistence.room.Entity Entity}.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class EntityBundle {
+
+    static final String NEW_TABLE_PREFIX = "_new_";
+
+    @SerializedName("tableName")
+    private String mTableName;
+    @SerializedName("createSql")
+    private String mCreateSql;
+    @SerializedName("fields")
+    private List<FieldBundle> mFields;
+    @SerializedName("primaryKey")
+    private PrimaryKeyBundle mPrimaryKey;
+    @SerializedName("indices")
+    private List<IndexBundle> mIndices;
+    @SerializedName("foreignKeys")
+    private List<ForeignKeyBundle> mForeignKeys;
+
+    private transient String mNewTableName;
+    private transient Map<String, FieldBundle> mFieldsByColumnName;
+
+    /**
+     * Creates a new bundle.
+     *
+     * @param tableName The table name.
+     * @param createSql Create query with the table name placeholder.
+     * @param fields The list of fields.
+     * @param primaryKey The primary key.
+     * @param indices The list of indices
+     * @param foreignKeys The list of foreign keys
+     */
+    public EntityBundle(String tableName, String createSql,
+            List<FieldBundle> fields,
+            PrimaryKeyBundle primaryKey,
+            List<IndexBundle> indices,
+            List<ForeignKeyBundle> foreignKeys) {
+        mTableName = tableName;
+        mCreateSql = createSql;
+        mFields = fields;
+        mPrimaryKey = primaryKey;
+        mIndices = indices;
+        mForeignKeys = foreignKeys;
+    }
+
+    /**
+     * @return The table name if it is created during a table schema modification.
+     */
+    public String getNewTableName() {
+        if (mNewTableName == null) {
+            mNewTableName = NEW_TABLE_PREFIX + mTableName;
+        }
+        return mNewTableName;
+    }
+
+    /**
+     * @return Map of fields keyed by their column names.
+     */
+    public Map<String, FieldBundle> getFieldsByColumnName() {
+        if (mFieldsByColumnName == null) {
+            mFieldsByColumnName = new HashMap<>();
+            for (FieldBundle bundle : mFields) {
+                mFieldsByColumnName.put(bundle.getColumnName(), bundle);
+            }
+        }
+        return mFieldsByColumnName;
+    }
+
+    /**
+     * @return The table name.
+     */
+    public String getTableName() {
+        return mTableName;
+    }
+
+    /**
+     * @return The create query with table name placeholder.
+     */
+    public String getCreateSql() {
+        return mCreateSql;
+    }
+
+    /**
+     * @return List of fields.
+     */
+    public List<FieldBundle> getFields() {
+        return mFields;
+    }
+
+    /**
+     * @return The primary key description.
+     */
+    public PrimaryKeyBundle getPrimaryKey() {
+        return mPrimaryKey;
+    }
+
+    /**
+     * @return List of indices.
+     */
+    public List<IndexBundle> getIndices() {
+        return mIndices;
+    }
+
+    /**
+     * @return List of foreign keys.
+     */
+    public List<ForeignKeyBundle> getForeignKeys() {
+        return mForeignKeys;
+    }
+
+    /**
+     * @return Create table SQL query that uses the actual table name.
+     */
+    public String createTable() {
+        return BundleUtil.replaceTableName(mCreateSql, getTableName());
+    }
+
+    /**
+     * @return Create table SQL query that uses the table name with "new" prefix.
+     */
+    public String createNewTable() {
+        return BundleUtil.replaceTableName(mCreateSql, getNewTableName());
+    }
+
+    /**
+     * @return Renames the table with {@link #getNewTableName()} to {@link #getTableName()}.
+     */
+    @NotNull
+    public String renameToOriginal() {
+        return "ALTER TABLE " + getNewTableName() + " RENAME TO " + getTableName();
+    }
+
+    /**
+     * @return Creates the list of SQL queries that are necessary to create this entity.
+     */
+    public Collection<String> buildCreateQueries() {
+        List<String> result = new ArrayList<>();
+        result.add(createTable());
+        for (IndexBundle indexBundle : mIndices) {
+            result.add(indexBundle.create(getTableName()));
+        }
+        return result;
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/FieldBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/FieldBundle.java
new file mode 100644
index 0000000..eb73d81
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/FieldBundle.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * Data class that holds the schema information for an
+ * {@link android.arch.persistence.room.Entity Entity} field.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class FieldBundle {
+    @SerializedName("fieldPath")
+    private String mFieldPath;
+    @SerializedName("columnName")
+    private String mColumnName;
+    @SerializedName("affinity")
+    private String mAffinity;
+    @SerializedName("notNull")
+    private boolean mNonNull;
+
+    public FieldBundle(String fieldPath, String columnName, String affinity, boolean nonNull) {
+        mFieldPath = fieldPath;
+        mColumnName = columnName;
+        mAffinity = affinity;
+        mNonNull = nonNull;
+    }
+
+    public String getFieldPath() {
+        return mFieldPath;
+    }
+
+    public String getColumnName() {
+        return mColumnName;
+    }
+
+    public String getAffinity() {
+        return mAffinity;
+    }
+
+    public boolean isNonNull() {
+        return mNonNull;
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/ForeignKeyBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/ForeignKeyBundle.java
new file mode 100644
index 0000000..1467a4f
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/ForeignKeyBundle.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.List;
+
+/**
+ * Holds the information about a foreign key reference.
+ */
+public class ForeignKeyBundle {
+    @SerializedName("table")
+    private String mTable;
+    @SerializedName("onDelete")
+    private String mOnDelete;
+    @SerializedName("onUpdate")
+    private String mOnUpdate;
+    @SerializedName("columns")
+    private List<String> mColumns;
+    @SerializedName("referencedColumns")
+    private List<String> mReferencedColumns;
+
+    /**
+     * Creates a foreign key bundle with the given parameters.
+     *
+     * @param table The target table
+     * @param onDelete OnDelete action
+     * @param onUpdate OnUpdate action
+     * @param columns The list of columns in the current table
+     * @param referencedColumns The list of columns in the referenced table
+     */
+    public ForeignKeyBundle(String table, String onDelete, String onUpdate,
+            List<String> columns, List<String> referencedColumns) {
+        mTable = table;
+        mOnDelete = onDelete;
+        mOnUpdate = onUpdate;
+        mColumns = columns;
+        mReferencedColumns = referencedColumns;
+    }
+
+    /**
+     * Returns the table name
+     *
+     * @return Returns the table name
+     */
+    public String getTable() {
+        return mTable;
+    }
+
+    /**
+     * Returns the SQLite foreign key action that will be performed when referenced row is deleted.
+     *
+     * @return The SQLite on delete action
+     */
+    public String getOnDelete() {
+        return mOnDelete;
+    }
+
+    /**
+     * Returns the SQLite foreign key action that will be performed when referenced row is updated.
+     *
+     * @return The SQLite on update action
+     */
+    public String getOnUpdate() {
+        return mOnUpdate;
+    }
+
+    /**
+     * Returns the ordered list of columns in the current table.
+     *
+     * @return The list of columns in the current entity.
+     */
+    public List<String> getColumns() {
+        return mColumns;
+    }
+
+    /**
+     * Returns the ordered list of columns in the referenced table.
+     *
+     * @return The list of columns in the referenced entity.
+     */
+    public List<String> getReferencedColumns() {
+        return mReferencedColumns;
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/IndexBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/IndexBundle.java
new file mode 100644
index 0000000..ba40618
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/IndexBundle.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.List;
+
+/**
+ * Data class that holds the schema information about a table Index.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class IndexBundle {
+    @SerializedName("name")
+    private String mName;
+    @SerializedName("unique")
+    private boolean mUnique;
+    @SerializedName("columnNames")
+    private List<String> mColumnNames;
+    @SerializedName("createSql")
+    private String mCreateSql;
+
+    public IndexBundle(String name, boolean unique, List<String> columnNames,
+            String createSql) {
+        mName = name;
+        mUnique = unique;
+        mColumnNames = columnNames;
+        mCreateSql = createSql;
+    }
+
+    public String getName() {
+        return mName;
+    }
+
+    public boolean isUnique() {
+        return mUnique;
+    }
+
+    public List<String> getColumnNames() {
+        return mColumnNames;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public String create(String tableName) {
+        return BundleUtil.replaceTableName(mCreateSql, tableName);
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/PrimaryKeyBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/PrimaryKeyBundle.java
new file mode 100644
index 0000000..c16f967
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/PrimaryKeyBundle.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.List;
+
+/**
+ * Data class that holds the schema information about a primary key.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class PrimaryKeyBundle {
+    @SerializedName("columnNames")
+    private List<String> mColumnNames;
+    @SerializedName("autoGenerate")
+    private boolean mAutoGenerate;
+
+    public PrimaryKeyBundle(boolean autoGenerate, List<String> columnNames) {
+        mColumnNames = columnNames;
+        mAutoGenerate = autoGenerate;
+    }
+
+    public List<String> getColumnNames() {
+        return mColumnNames;
+    }
+
+    public boolean isAutoGenerate() {
+        return mAutoGenerate;
+    }
+}
diff --git a/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/SchemaBundle.java b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/SchemaBundle.java
new file mode 100644
index 0000000..d6171aa
--- /dev/null
+++ b/room/migration/src/main/java/android/arch/persistence/room/migration/bundle/SchemaBundle.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration.bundle;
+
+import android.support.annotation.RestrictTo;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.annotations.SerializedName;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * Data class that holds the information about a database schema export.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class SchemaBundle {
+
+    @SerializedName("formatVersion")
+    private int mFormatVersion;
+    @SerializedName("database")
+    private DatabaseBundle mDatabase;
+
+    private static final Gson GSON;
+    private static final String CHARSET = "UTF-8";
+    public static final int LATEST_FORMAT = 1;
+    static {
+        GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
+    }
+
+    public SchemaBundle(int formatVersion, DatabaseBundle database) {
+        mFormatVersion = formatVersion;
+        mDatabase = database;
+    }
+
+    @SuppressWarnings("unused")
+    public int getFormatVersion() {
+        return mFormatVersion;
+    }
+
+    public DatabaseBundle getDatabase() {
+        return mDatabase;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static SchemaBundle deserialize(InputStream fis)
+            throws UnsupportedEncodingException {
+        InputStreamReader is = new InputStreamReader(fis, CHARSET);
+        try {
+            return GSON.fromJson(is, SchemaBundle.class);
+        } finally {
+            safeClose(is);
+            safeClose(fis);
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static void serialize(SchemaBundle bundle, File file) throws IOException {
+        FileOutputStream fos = new FileOutputStream(file, false);
+        OutputStreamWriter osw = new OutputStreamWriter(fos, CHARSET);
+        try {
+            GSON.toJson(bundle, osw);
+        } finally {
+            safeClose(osw);
+            safeClose(fos);
+        }
+    }
+
+    private static void safeClose(Closeable closeable) {
+        if (closeable != null) {
+            try {
+                closeable.close();
+            } catch (Throwable ignored) {
+            }
+        }
+    }
+
+}
diff --git a/room/runtime/build.gradle b/room/runtime/build.gradle
new file mode 100644
index 0000000..e44a021
--- /dev/null
+++ b/room/runtime/build.gradle
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+
+    buildTypes.all {
+        consumerProguardFiles 'proguard-rules.pro'
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    api project(":room:common")
+    api project(":room:db")
+    api project(":room:db-impl")
+    api project(":arch:runtime")
+    provided project(":paging:common")
+
+    provided project(":lifecycle:runtime")
+    provided project(":lifecycle:extensions")
+    compile libs.support.core_utils
+
+
+    testCompile project(":arch:core-testing")
+    testCompile libs.junit
+    testCompile libs.mockito_core
+    testCompile libs.support.annotations
+
+    androidTestCompile libs.junit
+    androidTestCompile(libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestCompile(libs.espresso_core, {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+}
+
+archivesBaseName = "runtime"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/room/runtime/proguard-rules.pro b/room/runtime/proguard-rules.pro
new file mode 100644
index 0000000..6cdf91c
--- /dev/null
+++ b/room/runtime/proguard-rules.pro
@@ -0,0 +1 @@
+-keep public class * extends android.arch.persistence.room.RoomDatabase
diff --git a/room/runtime/src/androidTest/java/android/arch/persistence/room/migration/TableInfoTest.java b/room/runtime/src/androidTest/java/android/arch/persistence/room/migration/TableInfoTest.java
new file mode 100644
index 0000000..c6eade5
--- /dev/null
+++ b/room/runtime/src/androidTest/java/android/arch/persistence/room/migration/TableInfoTest.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration;
+
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.util.TableInfo;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class TableInfoTest {
+    private SupportSQLiteDatabase mDb;
+
+    @Test
+    public void readSimple() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT,"
+                        + "name TEXT)");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo("foo",
+                toMap(new TableInfo.Column("id", "INTEGER", false, 1),
+                        new TableInfo.Column("name", "TEXT", false, 0)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    @Test
+    public void multiplePrimaryKeys() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (id INTEGER,"
+                        + "name TEXT, PRIMARY KEY(name, id))");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo("foo",
+                toMap(new TableInfo.Column("id", "INTEGER", false, 2),
+                        new TableInfo.Column("name", "TEXT", false, 1)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    @Test
+    public void alteredTable() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (id INTEGER,"
+                        + "name TEXT, PRIMARY KEY(name))");
+        mDb.execSQL("ALTER TABLE foo ADD COLUMN added REAL;");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo("foo",
+                toMap(new TableInfo.Column("id", "INTEGER", false, 0),
+                        new TableInfo.Column("name", "TEXT", false, 1),
+                        new TableInfo.Column("added", "REAL", false, 0)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    @Test
+    public void nonNull() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (name TEXT NOT NULL)");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo("foo",
+                toMap(new TableInfo.Column("name", "TEXT", true, 0)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    @Test
+    public void defaultValue() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (name TEXT DEFAULT blah)");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo(
+                "foo",
+                toMap(new TableInfo.Column("name", "TEXT", false, 0)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    @Test
+    public void foreignKey() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (name TEXT)",
+                "CREATE TABLE bar(barName TEXT, FOREIGN KEY(barName) REFERENCES foo(name))"
+        );
+        TableInfo info = TableInfo.read(mDb, "bar");
+        assertThat(info.foreignKeys.size(), is(1));
+        final TableInfo.ForeignKey foreignKey = info.foreignKeys.iterator().next();
+        assertThat(foreignKey.columnNames, is(singletonList("barName")));
+        assertThat(foreignKey.referenceColumnNames, is(singletonList("name")));
+        assertThat(foreignKey.onDelete, is("NO ACTION"));
+        assertThat(foreignKey.onUpdate, is("NO ACTION"));
+        assertThat(foreignKey.referenceTable, is("foo"));
+    }
+
+    @Test
+    public void multipleForeignKeys() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (name TEXT, lastName TEXT)",
+                "CREATE TABLE foo2 (name TEXT, lastName TEXT)",
+                "CREATE TABLE bar(barName TEXT, barLastName TEXT, "
+                        + " FOREIGN KEY(barName) REFERENCES foo(name) ON UPDATE SET NULL,"
+                        + " FOREIGN KEY(barLastName) REFERENCES foo2(lastName) ON DELETE CASCADE)");
+        TableInfo info = TableInfo.read(mDb, "bar");
+        assertThat(info.foreignKeys.size(), is(2));
+        Set<TableInfo.ForeignKey> expected = new HashSet<>();
+        expected.add(new TableInfo.ForeignKey("foo2", // table
+                "CASCADE", // on delete
+                "NO ACTION", // on update
+                singletonList("barLastName"), // my
+                singletonList("lastName")) // ref
+        );
+        expected.add(new TableInfo.ForeignKey("foo", // table
+                "NO ACTION", // on delete
+                "SET NULL", // on update
+                singletonList("barName"), // mine
+                singletonList("name")/*ref*/));
+        assertThat(info.foreignKeys, equalTo(expected));
+    }
+
+    @Test
+    public void compositeForeignKey() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (name TEXT, lastName TEXT)",
+                "CREATE TABLE bar(barName TEXT, barLastName TEXT, "
+                        + " FOREIGN KEY(barName, barLastName) REFERENCES foo(name, lastName)"
+                        + " ON UPDATE cascade ON DELETE RESTRICT)");
+        TableInfo info = TableInfo.read(mDb, "bar");
+        assertThat(info.foreignKeys.size(), is(1));
+        TableInfo.ForeignKey expected = new TableInfo.ForeignKey(
+                "foo", // table
+                "RESTRICT", // on delete
+                "CASCADE", // on update
+                asList("barName", "barLastName"), // my columns
+                asList("name", "lastName") // ref columns
+        );
+        assertThat(info.foreignKeys.iterator().next(), is(expected));
+    }
+
+    @Test
+    public void caseInsensitiveTypeName() {
+        mDb = createDatabase(
+                "CREATE TABLE foo (n integer)");
+        TableInfo info = TableInfo.read(mDb, "foo");
+        assertThat(info, is(new TableInfo(
+                "foo",
+                toMap(new TableInfo.Column("n", "INTEGER", false, 0)),
+                Collections.<TableInfo.ForeignKey>emptySet())));
+    }
+
+    private static Map<String, TableInfo.Column> toMap(TableInfo.Column... columns) {
+        Map<String, TableInfo.Column> result = new HashMap<>();
+        for (TableInfo.Column column : columns) {
+            result.put(column.name, column);
+        }
+        return result;
+    }
+
+    @After
+    public void closeDb() throws IOException {
+        if (mDb != null && mDb.isOpen()) {
+            mDb.close();
+        }
+    }
+
+    private static SupportSQLiteDatabase createDatabase(final String... queries) {
+        return new FrameworkSQLiteOpenHelperFactory().create(
+                SupportSQLiteOpenHelper.Configuration
+                        .builder(InstrumentationRegistry.getTargetContext())
+                        .name(null)
+                        .version(1)
+                        .callback(new SupportSQLiteOpenHelper.Callback() {
+                            @Override
+                            public void onCreate(SupportSQLiteDatabase db) {
+                                for (String query : queries) {
+                                    db.execSQL(query);
+                                }
+                            }
+
+                            @Override
+                            public void onUpgrade(SupportSQLiteDatabase db, int oldVersion,
+                                    int newVersion) {
+                                throw new IllegalStateException("should not be upgrading");
+                            }
+                        }).build()
+        ).getWritableDatabase();
+    }
+}
diff --git a/room/runtime/src/main/AndroidManifest.xml b/room/runtime/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..54a5b36
--- /dev/null
+++ b/room/runtime/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2016 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.room">
+</manifest>
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/DatabaseConfiguration.java b/room/runtime/src/main/java/android/arch/persistence/room/DatabaseConfiguration.java
new file mode 100644
index 0000000..adf5d4d
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/DatabaseConfiguration.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.content.Context;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.List;
+
+/**
+ * Configuration class for a {@link RoomDatabase}.
+ */
+@SuppressWarnings("WeakerAccess")
+public class DatabaseConfiguration {
+    /**
+     * The factory to use to access the database.
+     */
+    @NonNull
+    public final SupportSQLiteOpenHelper.Factory sqliteOpenHelperFactory;
+    /**
+     * The context to use while connecting to the database.
+     */
+    @NonNull
+    public final Context context;
+    /**
+     * The name of the database file or null if it is an in-memory database.
+     */
+    @Nullable
+    public final String name;
+
+    /**
+     * Collection of available migrations.
+     */
+    @NonNull
+    public final RoomDatabase.MigrationContainer migrationContainer;
+
+    @Nullable
+    public final List<RoomDatabase.Callback> callbacks;
+
+    /**
+     * Whether Room should throw an exception for queries run on the main thread.
+     */
+    public final boolean allowMainThreadQueries;
+
+    /**
+     * If true, Room should crash if a migration is missing.
+     */
+    public final boolean requireMigration;
+
+    /**
+     * Creates a database configuration with the given values.
+     *
+     * @param context The application context.
+     * @param name Name of the database, can be null if it is in memory.
+     * @param sqliteOpenHelperFactory The open helper factory to use.
+     * @param migrationContainer The migration container for migrations.
+     * @param callbacks The list of callbacks for database events.
+     * @param allowMainThreadQueries Whether to allow main thread reads/writes or not.
+     * @param requireMigration True if Room should require a valid migration if version changes,
+     *                        instead of recreating the tables.
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public DatabaseConfiguration(@NonNull Context context, @Nullable String name,
+            @NonNull SupportSQLiteOpenHelper.Factory sqliteOpenHelperFactory,
+            @NonNull RoomDatabase.MigrationContainer migrationContainer,
+            @Nullable List<RoomDatabase.Callback> callbacks,
+            boolean allowMainThreadQueries,
+            boolean requireMigration) {
+        this.sqliteOpenHelperFactory = sqliteOpenHelperFactory;
+        this.context = context;
+        this.name = name;
+        this.migrationContainer = migrationContainer;
+        this.callbacks = callbacks;
+        this.allowMainThreadQueries = allowMainThreadQueries;
+        this.requireMigration = requireMigration;
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/EntityDeletionOrUpdateAdapter.java b/room/runtime/src/main/java/android/arch/persistence/room/EntityDeletionOrUpdateAdapter.java
new file mode 100644
index 0000000..6f4aa68
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/EntityDeletionOrUpdateAdapter.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.support.annotation.RestrictTo;
+
+/**
+ * Implementations of this class knows how to delete or update a particular entity.
+ * <p>
+ * This is an internal library class and all of its implementations are auto-generated.
+ *
+ * @param <T> The type parameter of the entity to be deleted
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+@SuppressWarnings({"WeakerAccess", "unused"})
+public abstract class EntityDeletionOrUpdateAdapter<T> extends SharedSQLiteStatement {
+    /**
+     * Creates a DeletionOrUpdateAdapter that can delete or update the entity type T on the given
+     * database.
+     *
+     * @param database The database to delete / update the item in.
+     */
+    public EntityDeletionOrUpdateAdapter(RoomDatabase database) {
+        super(database);
+    }
+
+    /**
+     * Create the deletion or update query
+     *
+     * @return An SQL query that can delete or update instances of T.
+     */
+    protected abstract String createQuery();
+
+    /**
+     * Binds the entity into the given statement.
+     *
+     * @param statement The SQLite statement that prepared for the query returned from
+     *                  createQuery.
+     * @param entity    The entity of type T.
+     */
+    protected abstract void bind(SupportSQLiteStatement statement, T entity);
+
+    /**
+     * Deletes or updates the given entities in the database and returns the affected row count.
+     *
+     * @param entity The entity to delete or update
+     * @return The number of affected rows
+     */
+    public final int handle(T entity) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            bind(stmt, entity);
+            return stmt.executeUpdateDelete();
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Deletes or updates the given entities in the database and returns the affected row count.
+     *
+     * @param entities Entities to delete or update
+     * @return The number of affected rows
+     */
+    public final int handleMultiple(Iterable<T> entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            int total = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                total += stmt.executeUpdateDelete();
+            }
+            return total;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Deletes or updates the given entities in the database and returns the affected row count.
+     *
+     * @param entities Entities to delete or update
+     * @return The number of affected rows
+     */
+    public final int handleMultiple(T[] entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            int total = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                total += stmt.executeUpdateDelete();
+            }
+            return total;
+        } finally {
+            release(stmt);
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/EntityInsertionAdapter.java b/room/runtime/src/main/java/android/arch/persistence/room/EntityInsertionAdapter.java
new file mode 100644
index 0000000..6cfa332
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/EntityInsertionAdapter.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.support.annotation.RestrictTo;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Implementations of this class knows how to insert a particular entity.
+ * <p>
+ * This is an internal library class and all of its implementations are auto-generated.
+ *
+ * @param <T> The type parameter of the entity to be inserted
+ * @hide
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class EntityInsertionAdapter<T> extends SharedSQLiteStatement {
+    /**
+     * Creates an InsertionAdapter that can insert the entity type T into the given database.
+     *
+     * @param database The database to insert into.
+     */
+    public EntityInsertionAdapter(RoomDatabase database) {
+        super(database);
+    }
+
+    /**
+     * Binds the entity into the given statement.
+     *
+     * @param statement The SQLite statement that prepared for the query returned from
+     *                  createInsertQuery.
+     * @param entity    The entity of type T.
+     */
+    protected abstract void bind(SupportSQLiteStatement statement, T entity);
+
+    /**
+     * Inserts the entity into the database.
+     *
+     * @param entity The entity to insert
+     */
+    public final void insert(T entity) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            bind(stmt, entity);
+            stmt.executeInsert();
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database.
+     *
+     * @param entities Entities to insert
+     */
+    public final void insert(T[] entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            for (T entity : entities) {
+                bind(stmt, entity);
+                stmt.executeInsert();
+            }
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database.
+     *
+     * @param entities Entities to insert
+     */
+    public final void insert(Iterable<T> entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            for (T entity : entities) {
+                bind(stmt, entity);
+                stmt.executeInsert();
+            }
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entity into the database and returns the row id.
+     *
+     * @param entity The entity to insert
+     * @return The SQLite row id
+     */
+    public final long insertAndReturnId(T entity) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            bind(stmt, entity);
+            return stmt.executeInsert();
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final long[] insertAndReturnIdsArray(Collection<T> entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final long[] result = new long[entities.size()];
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result[index] = stmt.executeInsert();
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final long[] insertAndReturnIdsArray(T[] entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final long[] result = new long[entities.length];
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result[index] = stmt.executeInsert();
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final Long[] insertAndReturnIdsArrayBox(Collection<T> entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final Long[] result = new Long[entities.size()];
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result[index] = stmt.executeInsert();
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final Long[] insertAndReturnIdsArrayBox(T[] entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final Long[] result = new Long[entities.length];
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result[index] = stmt.executeInsert();
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final List<Long> insertAndReturnIdsList(T[] entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final List<Long> result = new ArrayList<>(entities.length);
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result.add(index, stmt.executeInsert());
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+
+    /**
+     * Inserts the given entities into the database and returns the row ids.
+     *
+     * @param entities Entities to insert
+     * @return The SQLite row ids
+     */
+    public final List<Long> insertAndReturnIdsList(Collection<T> entities) {
+        final SupportSQLiteStatement stmt = acquire();
+        try {
+            final List<Long> result = new ArrayList<>(entities.size());
+            int index = 0;
+            for (T entity : entities) {
+                bind(stmt, entity);
+                result.add(index, stmt.executeInsert());
+                index++;
+            }
+            return result;
+        } finally {
+            release(stmt);
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/InvalidationTracker.java b/room/runtime/src/main/java/android/arch/persistence/room/InvalidationTracker.java
new file mode 100644
index 0000000..619c53d
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/InvalidationTracker.java
@@ -0,0 +1,659 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.core.internal.SafeIterableMap;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteException;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.VisibleForTesting;
+import android.support.annotation.WorkerThread;
+import android.support.v4.util.ArrayMap;
+import android.support.v4.util.ArraySet;
+import android.util.Log;
+
+import java.lang.ref.WeakReference;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+
+/**
+ * InvalidationTracker keeps a list of tables modified by queries and notifies its callbacks about
+ * these tables.
+ */
+// We create an in memory table with (version, table_id) where version is an auto-increment primary
+// key and a table_id (hardcoded int from initialization).
+// ObservedTableTracker tracks list of tables we should be watching (e.g. adding triggers for).
+// Before each beginTransaction, RoomDatabase invokes InvalidationTracker to sync trigger states.
+// After each endTransaction, RoomDatabase invokes InvalidationTracker to refresh invalidated
+// tables.
+// Each update on one of the observed tables triggers an insertion into this table, hence a
+// new version.
+// Unfortunately, we cannot override the previous row because sqlite uses the conflict resolution
+// of the outer query (the thing that triggered us) so we do a cleanup as we sync instead of letting
+// SQLite override the rows.
+// https://sqlite.org/lang_createtrigger.html:  An ON CONFLICT clause may be specified as part of an
+// UPDATE or INSERT action within the body of the trigger. However if an ON CONFLICT clause is
+// specified as part of the statement causing the trigger to fire, then conflict handling policy of
+// the outer statement is used instead.
+public class InvalidationTracker {
+
+    private static final String[] TRIGGERS = new String[]{"UPDATE", "DELETE", "INSERT"};
+
+    private static final String UPDATE_TABLE_NAME = "room_table_modification_log";
+
+    private static final String VERSION_COLUMN_NAME = "version";
+
+    private static final String TABLE_ID_COLUMN_NAME = "table_id";
+
+    private static final String CREATE_VERSION_TABLE_SQL = "CREATE TEMP TABLE " + UPDATE_TABLE_NAME
+            + "(" + VERSION_COLUMN_NAME
+            + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+            + TABLE_ID_COLUMN_NAME
+            + " INTEGER)";
+
+    @VisibleForTesting
+    static final String CLEANUP_SQL = "DELETE FROM " + UPDATE_TABLE_NAME
+            + " WHERE " + VERSION_COLUMN_NAME + " NOT IN( SELECT MAX("
+            + VERSION_COLUMN_NAME + ") FROM " + UPDATE_TABLE_NAME
+            + " GROUP BY " + TABLE_ID_COLUMN_NAME + ")";
+
+    @VisibleForTesting
+    // We always clean before selecting so it is unlikely to have the same row twice and if we
+    // do, it is not a big deal, just more data in the cursor.
+    static final String SELECT_UPDATED_TABLES_SQL = "SELECT * FROM " + UPDATE_TABLE_NAME
+            + " WHERE " + VERSION_COLUMN_NAME
+            + "  > ? ORDER BY " + VERSION_COLUMN_NAME + " ASC;";
+
+    @NonNull
+    @VisibleForTesting
+    ArrayMap<String, Integer> mTableIdLookup;
+    private String[] mTableNames;
+
+    @NonNull
+    @VisibleForTesting
+    long[] mTableVersions;
+
+    private Object[] mQueryArgs = new Object[1];
+
+    // max id in the last syc
+    private long mMaxVersion = -1;
+
+    private final RoomDatabase mDatabase;
+
+    AtomicBoolean mPendingRefresh = new AtomicBoolean(false);
+
+    private volatile boolean mInitialized = false;
+
+    private volatile SupportSQLiteStatement mCleanupStatement;
+
+    private ObservedTableTracker mObservedTableTracker;
+
+    // should be accessed with synchronization only.
+    @VisibleForTesting
+    final SafeIterableMap<Observer, ObserverWrapper> mObserverMap = new SafeIterableMap<>();
+
+    /**
+     * Used by the generated code.
+     *
+     * @hide
+     */
+    @SuppressWarnings("WeakerAccess")
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public InvalidationTracker(RoomDatabase database, String... tableNames) {
+        mDatabase = database;
+        mObservedTableTracker = new ObservedTableTracker(tableNames.length);
+        mTableIdLookup = new ArrayMap<>();
+        final int size = tableNames.length;
+        mTableNames = new String[size];
+        for (int id = 0; id < size; id++) {
+            final String tableName = tableNames[id].toLowerCase(Locale.US);
+            mTableIdLookup.put(tableName, id);
+            mTableNames[id] = tableName;
+        }
+        mTableVersions = new long[tableNames.length];
+        Arrays.fill(mTableVersions, 0);
+    }
+
+    /**
+     * Internal method to initialize table tracking.
+     * <p>
+     * You should never call this method, it is called by the generated code.
+     */
+    void internalInit(SupportSQLiteDatabase database) {
+        synchronized (this) {
+            if (mInitialized) {
+                Log.e(Room.LOG_TAG, "Invalidation tracker is initialized twice :/.");
+                return;
+            }
+
+            database.beginTransaction();
+            try {
+                database.execSQL("PRAGMA temp_store = MEMORY;");
+                database.execSQL("PRAGMA recursive_triggers='ON';");
+                database.execSQL(CREATE_VERSION_TABLE_SQL);
+                database.setTransactionSuccessful();
+            } finally {
+                database.endTransaction();
+            }
+            mCleanupStatement = database.compileStatement(CLEANUP_SQL);
+            mInitialized = true;
+        }
+    }
+
+    private static void appendTriggerName(StringBuilder builder, String tableName,
+            String triggerType) {
+        builder.append("room_table_modification_trigger_")
+                .append(tableName)
+                .append("_")
+                .append(triggerType);
+    }
+
+    private void stopTrackingTable(SupportSQLiteDatabase writableDb, int tableId) {
+        final String tableName = mTableNames[tableId];
+        StringBuilder stringBuilder = new StringBuilder();
+        for (String trigger : TRIGGERS) {
+            stringBuilder.setLength(0);
+            stringBuilder.append("DROP TRIGGER IF EXISTS ");
+            appendTriggerName(stringBuilder, tableName, trigger);
+            writableDb.execSQL(stringBuilder.toString());
+        }
+    }
+
+    private void startTrackingTable(SupportSQLiteDatabase writableDb, int tableId) {
+        final String tableName = mTableNames[tableId];
+        StringBuilder stringBuilder = new StringBuilder();
+        for (String trigger : TRIGGERS) {
+            stringBuilder.setLength(0);
+            stringBuilder.append("CREATE TEMP TRIGGER IF NOT EXISTS ");
+            appendTriggerName(stringBuilder, tableName, trigger);
+            stringBuilder.append(" AFTER ")
+                    .append(trigger)
+                    .append(" ON ")
+                    .append(tableName)
+                    .append(" BEGIN INSERT OR REPLACE INTO ")
+                    .append(UPDATE_TABLE_NAME)
+                    .append(" VALUES(null, ")
+                    .append(tableId)
+                    .append("); END");
+            writableDb.execSQL(stringBuilder.toString());
+        }
+    }
+
+    /**
+     * Adds the given observer to the observers list and it will be notified if any table it
+     * observes changes.
+     * <p>
+     * Database changes are pulled on another thread so in some race conditions, the observer might
+     * be invoked for changes that were done before it is added.
+     * <p>
+     * If the observer already exists, this is a no-op call.
+     * <p>
+     * If one of the tables in the Observer does not exist in the database, this method throws an
+     * {@link IllegalArgumentException}.
+     *
+     * @param observer The observer which listens the database for changes.
+     */
+    public void addObserver(Observer observer) {
+        final String[] tableNames = observer.mTables;
+        int[] tableIds = new int[tableNames.length];
+        final int size = tableNames.length;
+        long[] versions = new long[tableNames.length];
+
+        // TODO sync versions ?
+        for (int i = 0; i < size; i++) {
+            Integer tableId = mTableIdLookup.get(tableNames[i].toLowerCase(Locale.US));
+            if (tableId == null) {
+                throw new IllegalArgumentException("There is no table with name " + tableNames[i]);
+            }
+            tableIds[i] = tableId;
+            versions[i] = mMaxVersion;
+        }
+        ObserverWrapper wrapper = new ObserverWrapper(observer, tableIds, tableNames, versions);
+        ObserverWrapper currentObserver;
+        synchronized (mObserverMap) {
+            currentObserver = mObserverMap.putIfAbsent(observer, wrapper);
+        }
+        if (currentObserver == null && mObservedTableTracker.onAdded(tableIds)) {
+            AppToolkitTaskExecutor.getInstance().executeOnDiskIO(mSyncTriggers);
+        }
+    }
+
+    /**
+     * Adds an observer but keeps a weak reference back to it.
+     * <p>
+     * Note that you cannot remove this observer once added. It will be automatically removed
+     * when the observer is GC'ed.
+     *
+     * @param observer The observer to which InvalidationTracker will keep a weak reference.
+     * @hide
+     */
+    @SuppressWarnings("unused")
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public void addWeakObserver(Observer observer) {
+        addObserver(new WeakObserver(this, observer));
+    }
+
+    /**
+     * Removes the observer from the observers list.
+     *
+     * @param observer The observer to remove.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void removeObserver(final Observer observer) {
+        ObserverWrapper wrapper;
+        synchronized (mObserverMap) {
+            wrapper = mObserverMap.remove(observer);
+        }
+        if (wrapper != null && mObservedTableTracker.onRemoved(wrapper.mTableIds)) {
+            AppToolkitTaskExecutor.getInstance().executeOnDiskIO(mSyncTriggers);
+        }
+    }
+
+    private Runnable mSyncTriggers = new Runnable() {
+        @Override
+        public void run() {
+            if (mDatabase.inTransaction()) {
+                // we won't run this inside another transaction.
+                return;
+            }
+            if (!ensureInitialization()) {
+                return;
+            }
+            try {
+                // This method runs in a while loop because while changes are synced to db, another
+                // runnable may be skipped. If we cause it to skip, we need to do its work.
+                while (true) {
+                    // there is a potential race condition where another mSyncTriggers runnable
+                    // can start running right after we get the tables list to sync.
+                    final int[] tablesToSync = mObservedTableTracker.getTablesToSync();
+                    if (tablesToSync == null) {
+                        return;
+                    }
+                    final int limit = tablesToSync.length;
+                    final SupportSQLiteDatabase writableDatabase = mDatabase.getOpenHelper()
+                            .getWritableDatabase();
+                    try {
+                        writableDatabase.beginTransaction();
+                        for (int tableId = 0; tableId < limit; tableId++) {
+                            switch (tablesToSync[tableId]) {
+                                case ObservedTableTracker.ADD:
+                                    startTrackingTable(writableDatabase, tableId);
+                                    break;
+                                case ObservedTableTracker.REMOVE:
+                                    stopTrackingTable(writableDatabase, tableId);
+                                    break;
+                            }
+                        }
+                        writableDatabase.setTransactionSuccessful();
+                    } finally {
+                        writableDatabase.endTransaction();
+                    }
+                    mObservedTableTracker.onSyncCompleted();
+                }
+            } catch (IllegalStateException | SQLiteException exception) {
+                // may happen if db is closed. just log.
+                Log.e(Room.LOG_TAG, "Cannot run invalidation tracker. Is the db closed?",
+                        exception);
+            }
+        }
+    };
+
+    private boolean ensureInitialization() {
+        if (!mDatabase.isOpen()) {
+            return false;
+        }
+        if (!mInitialized) {
+            // trigger initialization
+            mDatabase.getOpenHelper().getWritableDatabase();
+        }
+        if (!mInitialized) {
+            Log.e(Room.LOG_TAG, "database is not initialized even though it is open");
+            return false;
+        }
+        return true;
+    }
+
+    @VisibleForTesting
+    Runnable mRefreshRunnable = new Runnable() {
+        @Override
+        public void run() {
+            final Lock closeLock = mDatabase.getCloseLock();
+            boolean hasUpdatedTable = false;
+            try {
+                closeLock.lock();
+
+                if (!ensureInitialization()) {
+                    return;
+                }
+
+                if (mDatabase.inTransaction()
+                        || !mPendingRefresh.compareAndSet(true, false)) {
+                    // no pending refresh
+                    return;
+                }
+                mCleanupStatement.executeUpdateDelete();
+                mQueryArgs[0] = mMaxVersion;
+                Cursor cursor = mDatabase.query(SELECT_UPDATED_TABLES_SQL, mQueryArgs);
+                //noinspection TryFinallyCanBeTryWithResources
+                try {
+                    while (cursor.moveToNext()) {
+                        final long version = cursor.getLong(0);
+                        final int tableId = cursor.getInt(1);
+
+                        mTableVersions[tableId] = version;
+                        hasUpdatedTable = true;
+                        // result is ordered so we can safely do this assignment
+                        mMaxVersion = version;
+                    }
+                } finally {
+                    cursor.close();
+                }
+            } catch (IllegalStateException | SQLiteException exception) {
+                // may happen if db is closed. just log.
+                Log.e(Room.LOG_TAG, "Cannot run invalidation tracker. Is the db closed?",
+                        exception);
+            } finally {
+                closeLock.unlock();
+            }
+            if (hasUpdatedTable) {
+                synchronized (mObserverMap) {
+                    for (Map.Entry<Observer, ObserverWrapper> entry : mObserverMap) {
+                        entry.getValue().checkForInvalidation(mTableVersions);
+                    }
+                }
+            }
+        }
+    };
+
+    /**
+     * Enqueues a task to refresh the list of updated tables.
+     * <p>
+     * This method is automatically called when {@link RoomDatabase#endTransaction()} is called but
+     * if you have another connection to the database or directly use {@link
+     * SupportSQLiteDatabase}, you may need to call this manually.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void refreshVersionsAsync() {
+        // TODO we should consider doing this sync instead of async.
+        if (mPendingRefresh.compareAndSet(false, true)) {
+            AppToolkitTaskExecutor.getInstance().executeOnDiskIO(mRefreshRunnable);
+        }
+    }
+
+    /**
+     * Check versions for tables, and run observers synchronously if tables have been updated.
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    @WorkerThread
+    public void refreshVersionsSync() {
+        syncTriggers();
+        mRefreshRunnable.run();
+    }
+
+    /**
+     * Called by RoomDatabase before each beginTransaction call.
+     * <p>
+     * It is important that pending trigger changes are applied to the database before any query
+     * runs. Otherwise, we may miss some changes.
+     * <p>
+     * This api should eventually be public.
+     */
+    void syncTriggers() {
+        mSyncTriggers.run();
+    }
+
+    /**
+     * Wraps an observer and keeps the table information.
+     * <p>
+     * Internally table ids are used which may change from database to database so the table
+     * related information is kept here rather than in the Observer.
+     */
+    @SuppressWarnings("WeakerAccess")
+    static class ObserverWrapper {
+        final int[] mTableIds;
+        private final String[] mTableNames;
+        private final long[] mVersions;
+        final Observer mObserver;
+        private final Set<String> mSingleTableSet;
+
+        ObserverWrapper(Observer observer, int[] tableIds, String[] tableNames, long[] versions) {
+            mObserver = observer;
+            mTableIds = tableIds;
+            mTableNames = tableNames;
+            mVersions = versions;
+            if (tableIds.length == 1) {
+                ArraySet<String> set = new ArraySet<>();
+                set.add(mTableNames[0]);
+                mSingleTableSet = Collections.unmodifiableSet(set);
+            } else {
+                mSingleTableSet = null;
+            }
+        }
+
+        void checkForInvalidation(long[] versions) {
+            Set<String> invalidatedTables = null;
+            final int size = mTableIds.length;
+            for (int index = 0; index < size; index++) {
+                final int tableId = mTableIds[index];
+                final long newVersion = versions[tableId];
+                final long currentVersion = mVersions[index];
+                if (currentVersion < newVersion) {
+                    mVersions[index] = newVersion;
+                    if (size == 1) {
+                        // Optimization for a single-table observer
+                        invalidatedTables = mSingleTableSet;
+                    } else {
+                        if (invalidatedTables == null) {
+                            invalidatedTables = new ArraySet<>(size);
+                        }
+                        invalidatedTables.add(mTableNames[index]);
+                    }
+                }
+            }
+            if (invalidatedTables != null) {
+                mObserver.onInvalidated(invalidatedTables);
+            }
+        }
+    }
+
+    /**
+     * An observer that can listen for changes in the database.
+     */
+    public abstract static class Observer {
+        final String[] mTables;
+
+        /**
+         * Observes the given list of tables.
+         *
+         * @param firstTable The table name
+         * @param rest       More table names
+         */
+        @SuppressWarnings("unused")
+        protected Observer(@NonNull String firstTable, String... rest) {
+            mTables = Arrays.copyOf(rest, rest.length + 1);
+            mTables[rest.length] = firstTable;
+        }
+
+        /**
+         * Observes the given list of tables.
+         *
+         * @param tables The list of tables to observe for changes.
+         */
+        public Observer(@NonNull String[] tables) {
+            // copy tables in case user modifies them afterwards
+            mTables = Arrays.copyOf(tables, tables.length);
+        }
+
+        /**
+         * Called when one of the observed tables is invalidated in the database.
+         *
+         * @param tables A set of invalidated tables. This is useful when the observer targets
+         *               multiple tables and want to know which table is invalidated.
+         */
+        public abstract void onInvalidated(@NonNull Set<String> tables);
+    }
+
+
+    /**
+     * Keeps a list of tables we should observe. Invalidation tracker lazily syncs this list w/
+     * triggers in the database.
+     * <p>
+     * This class is thread safe
+     */
+    static class ObservedTableTracker {
+        static final int NO_OP = 0; // don't change trigger state for this table
+        static final int ADD = 1; // add triggers for this table
+        static final int REMOVE = 2; // remove triggers for this table
+
+        // number of observers per table
+        final long[] mTableObservers;
+        // trigger state for each table at last sync
+        // this field is updated when syncAndGet is called.
+        final boolean[] mTriggerStates;
+        // when sync is called, this field is returned. It includes actions as ADD, REMOVE, NO_OP
+        final int[] mTriggerStateChanges;
+
+        boolean mNeedsSync;
+
+        /**
+         * After we return non-null value from getTablesToSync, we expect a onSyncCompleted before
+         * returning any non-null value from getTablesToSync.
+         * This allows us to workaround any multi-threaded state syncing issues.
+         */
+        boolean mPendingSync;
+
+        ObservedTableTracker(int tableCount) {
+            mTableObservers = new long[tableCount];
+            mTriggerStates = new boolean[tableCount];
+            mTriggerStateChanges = new int[tableCount];
+            Arrays.fill(mTableObservers, 0);
+            Arrays.fill(mTriggerStates, false);
+        }
+
+        /**
+         * @return true if # of triggers is affected.
+         */
+        boolean onAdded(int... tableIds) {
+            boolean needTriggerSync = false;
+            synchronized (this) {
+                for (int tableId : tableIds) {
+                    final long prevObserverCount = mTableObservers[tableId];
+                    mTableObservers[tableId] = prevObserverCount + 1;
+                    if (prevObserverCount == 0) {
+                        mNeedsSync = true;
+                        needTriggerSync = true;
+                    }
+                }
+            }
+            return needTriggerSync;
+        }
+
+        /**
+         * @return true if # of triggers is affected.
+         */
+        boolean onRemoved(int... tableIds) {
+            boolean needTriggerSync = false;
+            synchronized (this) {
+                for (int tableId : tableIds) {
+                    final long prevObserverCount = mTableObservers[tableId];
+                    mTableObservers[tableId] = prevObserverCount - 1;
+                    if (prevObserverCount == 1) {
+                        mNeedsSync = true;
+                        needTriggerSync = true;
+                    }
+                }
+            }
+            return needTriggerSync;
+        }
+
+        /**
+         * If this returns non-null, you must call onSyncCompleted.
+         *
+         * @return int[] An int array where the index for each tableId has the action for that
+         * table.
+         */
+        @Nullable
+        int[] getTablesToSync() {
+            synchronized (this) {
+                if (!mNeedsSync || mPendingSync) {
+                    return null;
+                }
+                final int tableCount = mTableObservers.length;
+                for (int i = 0; i < tableCount; i++) {
+                    final boolean newState = mTableObservers[i] > 0;
+                    if (newState != mTriggerStates[i]) {
+                        mTriggerStateChanges[i] = newState ? ADD : REMOVE;
+                    } else {
+                        mTriggerStateChanges[i] = NO_OP;
+                    }
+                    mTriggerStates[i] = newState;
+                }
+                mPendingSync = true;
+                mNeedsSync = false;
+                return mTriggerStateChanges;
+            }
+        }
+
+        /**
+         * if getTablesToSync returned non-null, the called should call onSyncCompleted once it
+         * is done.
+         */
+        void onSyncCompleted() {
+            synchronized (this) {
+                mPendingSync = false;
+            }
+        }
+    }
+
+    /**
+     * An Observer wrapper that keeps a weak reference to the given object.
+     * <p>
+     * This class with automatically unsubscribe when the wrapped observer goes out of memory.
+     */
+    static class WeakObserver extends Observer {
+        final InvalidationTracker mTracker;
+        final WeakReference<Observer> mDelegateRef;
+
+        WeakObserver(InvalidationTracker tracker, Observer delegate) {
+            super(delegate.mTables);
+            mTracker = tracker;
+            mDelegateRef = new WeakReference<>(delegate);
+        }
+
+        @Override
+        public void onInvalidated(@NonNull Set<String> tables) {
+            final Observer observer = mDelegateRef.get();
+            if (observer == null) {
+                mTracker.removeObserver(this);
+            } else {
+                observer.onInvalidated(tables);
+            }
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/Room.java b/room/runtime/src/main/java/android/arch/persistence/room/Room.java
new file mode 100644
index 0000000..80e95a7
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/Room.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.content.Context;
+import android.support.annotation.NonNull;
+
+/**
+ * Utility class for Room.
+ */
+@SuppressWarnings("unused")
+public class Room {
+    static final String LOG_TAG = "ROOM";
+    /**
+     * The master table where room keeps its metadata information.
+     */
+    public static final String MASTER_TABLE_NAME = RoomMasterTable.TABLE_NAME;
+    private static final String CURSOR_CONV_SUFFIX = "_CursorConverter";
+
+    /**
+     * Creates a RoomDatabase.Builder for a persistent database. Once a database is built, you
+     * should keep a reference to it and re-use it.
+     *
+     * @param context The context for the database. This is usually the Application context.
+     * @param klass   The abstract class which is annotated with {@link Database} and extends
+     *                {@link RoomDatabase}.
+     * @param name    The name of the database file.
+     * @param <T>     The type of the database class.
+     * @return A {@code RoomDatabaseBuilder<T>} which you can use to create the database.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public static <T extends RoomDatabase> RoomDatabase.Builder<T> databaseBuilder(
+            @NonNull Context context, @NonNull Class<T> klass, @NonNull String name) {
+        //noinspection ConstantConditions
+        if (name == null || name.trim().length() == 0) {
+            throw new IllegalArgumentException("Cannot create a database with null or empty name."
+                    + " If you are trying to create an in memory database, use Room"
+                    + ".inMemoryDatabaseBuilder");
+        }
+        return new RoomDatabase.Builder<>(context, klass, name);
+    }
+
+    /**
+     * Creates a RoomDatabase.Builder for an in memory database. Information stored in an in memory
+     * database disappears when the process is killed.
+     * Once a database is built, you should keep a reference to it and re-use it.
+     *
+     * @param context The context for the database. This is usually the Application context.
+     * @param klass   The abstract class which is annotated with {@link Database} and extends
+     *                {@link RoomDatabase}.
+     * @param <T>     The type of the database class.
+     * @return A {@code RoomDatabaseBuilder<T>} which you can use to create the database.
+     */
+    public static <T extends RoomDatabase> RoomDatabase.Builder<T> inMemoryDatabaseBuilder(
+            @NonNull Context context, @NonNull Class<T> klass) {
+        return new RoomDatabase.Builder<>(context, klass, null);
+    }
+
+    @NonNull
+    static <T, C> T getGeneratedImplementation(Class<C> klass, String suffix) {
+        final String fullPackage = klass.getPackage().getName();
+        String name = klass.getCanonicalName();
+        final String postPackageName = fullPackage.isEmpty()
+                ? name
+                : (name.substring(fullPackage.length() + 1));
+        final String implName = postPackageName.replace('.', '_') + suffix;
+        //noinspection TryWithIdenticalCatches
+        try {
+
+            @SuppressWarnings("unchecked")
+            final Class<T> aClass = (Class<T>) Class.forName(
+                    fullPackage.isEmpty() ? implName : fullPackage + "." + implName);
+            return aClass.newInstance();
+        } catch (ClassNotFoundException e) {
+            throw new RuntimeException("cannot find implementation for "
+                    + klass.getCanonicalName() + ". " + implName + " does not exist");
+        } catch (IllegalAccessException e) {
+            throw new RuntimeException("Cannot access the constructor"
+                    + klass.getCanonicalName());
+        } catch (InstantiationException e) {
+            throw new RuntimeException("Failed to create an instance of "
+                    + klass.getCanonicalName());
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/RoomDatabase.java b/room/runtime/src/main/java/android/arch/persistence/room/RoomDatabase.java
new file mode 100644
index 0000000..e64f2d6
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/RoomDatabase.java
@@ -0,0 +1,560 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.arch.persistence.db.SimpleSQLiteQuery;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.SupportSQLiteQuery;
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.migration.Migration;
+import android.content.Context;
+import android.database.Cursor;
+import android.support.annotation.CallSuper;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+import android.support.v4.util.SparseArrayCompat;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * Base class for all Room databases. All classes that are annotated with {@link Database} must
+ * extend this class.
+ * <p>
+ * RoomDatabase provides direct access to the underlying database implementation but you should
+ * prefer using {@link Dao} classes.
+ *
+ * @see Database
+ */
+@SuppressWarnings({"unused", "WeakerAccess"})
+public abstract class RoomDatabase {
+    private static final String DB_IMPL_SUFFIX = "_Impl";
+    // set by the generated open helper.
+    protected volatile SupportSQLiteDatabase mDatabase;
+    private SupportSQLiteOpenHelper mOpenHelper;
+    private final InvalidationTracker mInvalidationTracker;
+    private boolean mAllowMainThreadQueries;
+
+    @Nullable
+    protected List<Callback> mCallbacks;
+
+    private final ReentrantLock mCloseLock = new ReentrantLock();
+
+    /**
+     * {@link InvalidationTracker} uses this lock to prevent the database from closing while it is
+     * querying database updates.
+     *
+     * @return The lock for {@link #close()}.
+     */
+    Lock getCloseLock() {
+        return mCloseLock;
+    }
+
+    /**
+     * Creates a RoomDatabase.
+     * <p>
+     * You cannot create an instance of a database, instead, you should acquire it via
+     * {@link Room#databaseBuilder(Context, Class, String)} or
+     * {@link Room#inMemoryDatabaseBuilder(Context, Class)}.
+     */
+    public RoomDatabase() {
+        mInvalidationTracker = createInvalidationTracker();
+    }
+
+    /**
+     * Called by {@link Room} when it is initialized.
+     *
+     * @param configuration The database configuration.
+     */
+    @CallSuper
+    public void init(DatabaseConfiguration configuration) {
+        mOpenHelper = createOpenHelper(configuration);
+        mCallbacks = configuration.callbacks;
+        mAllowMainThreadQueries = configuration.allowMainThreadQueries;
+    }
+
+    /**
+     * Returns the SQLite open helper used by this database.
+     *
+     * @return The SQLite open helper used by this database.
+     */
+    public SupportSQLiteOpenHelper getOpenHelper() {
+        return mOpenHelper;
+    }
+
+    /**
+     * Creates the open helper to access the database. Generated class already implements this
+     * method.
+     * Note that this method is called when the RoomDatabase is initialized.
+     *
+     * @param config The configuration of the Room database.
+     * @return A new SupportSQLiteOpenHelper to be used while connecting to the database.
+     */
+    protected abstract SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config);
+
+    /**
+     * Called when the RoomDatabase is created.
+     * <p>
+     * This is already implemented by the generated code.
+     *
+     * @return Creates a new InvalidationTracker.
+     */
+    protected abstract InvalidationTracker createInvalidationTracker();
+
+    /**
+     * Returns true if database connection is open and initialized.
+     *
+     * @return true if the database connection is open, false otherwise.
+     */
+    public boolean isOpen() {
+        final SupportSQLiteDatabase db = mDatabase;
+        return db != null && db.isOpen();
+    }
+
+    /**
+     * Closes the database if it is already open.
+     */
+    public void close() {
+        if (isOpen()) {
+            try {
+                mCloseLock.lock();
+                mOpenHelper.close();
+            } finally {
+                mCloseLock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Asserts that we are not on the main thread.
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public void assertNotMainThread() {
+        if (mAllowMainThreadQueries) {
+            return;
+        }
+        if (AppToolkitTaskExecutor.getInstance().isMainThread()) {
+            throw new IllegalStateException("Cannot access database on the main thread since"
+                    + " it may potentially lock the UI for a long period of time.");
+        }
+    }
+
+    // Below, there are wrapper methods for SupportSQLiteDatabase. This helps us track which
+    // methods we are using and also helps unit tests to mock this class without mocking
+    // all SQLite database methods.
+
+    /**
+     * Convenience method to query the database with arguments.
+     *
+     * @param query The sql query
+     * @param args The bind arguments for the placeholders in the query
+     *
+     * @return A Cursor obtained by running the given query in the Room database.
+     */
+    public Cursor query(String query, @Nullable Object[] args) {
+        return mOpenHelper.getWritableDatabase().query(new SimpleSQLiteQuery(query, args));
+    }
+
+    /**
+     * Wrapper for {@link SupportSQLiteDatabase#query(SupportSQLiteQuery)}.
+     *
+     * @param query The Query which includes the SQL and a bind callback for bind arguments.
+     * @return Result of the query.
+     */
+    public Cursor query(SupportSQLiteQuery query) {
+        assertNotMainThread();
+        return mOpenHelper.getWritableDatabase().query(query);
+    }
+
+    /**
+     * Wrapper for {@link SupportSQLiteDatabase#compileStatement(String)}.
+     *
+     * @param sql The query to compile.
+     * @return The compiled query.
+     */
+    public SupportSQLiteStatement compileStatement(String sql) {
+        assertNotMainThread();
+        return mOpenHelper.getWritableDatabase().compileStatement(sql);
+    }
+
+    /**
+     * Wrapper for {@link SupportSQLiteDatabase#beginTransaction()}.
+     */
+    public void beginTransaction() {
+        assertNotMainThread();
+        mInvalidationTracker.syncTriggers();
+        mOpenHelper.getWritableDatabase().beginTransaction();
+    }
+
+    /**
+     * Wrapper for {@link SupportSQLiteDatabase#endTransaction()}.
+     */
+    public void endTransaction() {
+        mOpenHelper.getWritableDatabase().endTransaction();
+        mInvalidationTracker.refreshVersionsAsync();
+    }
+
+    /**
+     * Wrapper for {@link SupportSQLiteDatabase#setTransactionSuccessful()}.
+     */
+    public void setTransactionSuccessful() {
+        mOpenHelper.getWritableDatabase().setTransactionSuccessful();
+    }
+
+    /**
+     * Executes the specified {@link Runnable} in a database transaction. The transaction will be
+     * marked as successful unless an exception is thrown in the {@link Runnable}.
+     *
+     * @param body The piece of code to execute.
+     */
+    public void runInTransaction(Runnable body) {
+        beginTransaction();
+        try {
+            body.run();
+            setTransactionSuccessful();
+        } finally {
+            endTransaction();
+        }
+    }
+
+    /**
+     * Executes the specified {@link Callable} in a database transaction. The transaction will be
+     * marked as successful unless an exception is thrown in the {@link Callable}.
+     *
+     * @param body The piece of code to execute.
+     * @param <V>  The type of the return value.
+     * @return The value returned from the {@link Callable}.
+     */
+    public <V> V runInTransaction(Callable<V> body) {
+        beginTransaction();
+        try {
+            V result = body.call();
+            setTransactionSuccessful();
+            return result;
+        } catch (RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new RuntimeException("Exception in transaction", e);
+        } finally {
+            endTransaction();
+        }
+    }
+
+    /**
+     * Called by the generated code when database is open.
+     * <p>
+     * You should never call this method manually.
+     *
+     * @param db The database instance.
+     */
+    protected void internalInitInvalidationTracker(SupportSQLiteDatabase db) {
+        mInvalidationTracker.internalInit(db);
+    }
+
+    /**
+     * Returns the invalidation tracker for this database.
+     * <p>
+     * You can use the invalidation tracker to get notified when certain tables in the database
+     * are modified.
+     *
+     * @return The invalidation tracker for the database.
+     */
+    public InvalidationTracker getInvalidationTracker() {
+        return mInvalidationTracker;
+    }
+
+    /**
+     * Returns true if current thread is in a transaction.
+     *
+     * @return True if there is an active transaction in current thread, false otherwise.
+     * @see SupportSQLiteDatabase#inTransaction()
+     */
+    public boolean inTransaction() {
+        return mOpenHelper.getWritableDatabase().inTransaction();
+    }
+
+    /**
+     * Builder for RoomDatabase.
+     *
+     * @param <T> The type of the abstract database class.
+     */
+    @SuppressWarnings("unused")
+    public static class Builder<T extends RoomDatabase> {
+        private final Class<T> mDatabaseClass;
+        private final String mName;
+        private final Context mContext;
+        private ArrayList<Callback> mCallbacks;
+
+        private SupportSQLiteOpenHelper.Factory mFactory;
+        private boolean mInMemory;
+        private boolean mAllowMainThreadQueries;
+        private boolean mRequireMigration;
+        /**
+         * Migrations, mapped by from-to pairs.
+         */
+        private MigrationContainer mMigrationContainer;
+
+        Builder(@NonNull Context context, @NonNull Class<T> klass, @Nullable String name) {
+            mContext = context;
+            mDatabaseClass = klass;
+            mName = name;
+            mRequireMigration = true;
+            mMigrationContainer = new MigrationContainer();
+        }
+
+        /**
+         * Sets the database factory. If not set, it defaults to
+         * {@link FrameworkSQLiteOpenHelperFactory}.
+         *
+         * @param factory The factory to use to access the database.
+         * @return this
+         */
+        public Builder<T> openHelperFactory(SupportSQLiteOpenHelper.Factory factory) {
+            mFactory = factory;
+            return this;
+        }
+
+        /**
+         * Adds a migration to the builder.
+         * <p>
+         * Each Migration has a start and end versions and Room runs these migrations to bring the
+         * database to the latest version.
+         * <p>
+         * If a migration item is missing between current version and the latest version, Room
+         * will clear the database and recreate so even if you have no changes between 2 versions,
+         * you should still provide a Migration object to the builder.
+         * <p>
+         * A migration can handle more than 1 version (e.g. if you have a faster path to choose when
+         * going version 3 to 5 without going to version 4). If Room opens a database at version
+         * 3 and latest version is &gt;= 5, Room will use the migration object that can migrate from
+         * 3 to 5 instead of 3 to 4 and 4 to 5.
+         *
+         * @param migrations The migration object that can modify the database and to the necessary
+         *                   changes.
+         * @return this
+         */
+        public Builder<T> addMigrations(Migration... migrations) {
+            mMigrationContainer.addMigrations(migrations);
+            return this;
+        }
+
+        /**
+         * Disables the main thread query check for Room.
+         * <p>
+         * Room ensures that Database is never accessed on the main thread because it may lock the
+         * main thread and trigger an ANR. If you need to access the database from the main thread,
+         * you should always use async alternatives or manually move the call to a background
+         * thread.
+         * <p>
+         * You may want to turn this check off for testing.
+         *
+         * @return this
+         */
+        public Builder<T> allowMainThreadQueries() {
+            mAllowMainThreadQueries = true;
+            return this;
+        }
+
+        /**
+         * When the database version on the device does not match the latest schema version, Room
+         * runs necessary {@link Migration}s on the database.
+         * <p>
+         * If it cannot find the set of {@link Migration}s that will bring the database to the
+         * current version, it will throw an {@link IllegalStateException}.
+         * <p>
+         * You can call this method to change this behavior to re-create the database instead of
+         * crashing.
+         * <p>
+         * Note that this will delete all of the data in the database tables managed by Room.
+         *
+         * @return this
+         */
+        public Builder<T> fallbackToDestructiveMigration() {
+            mRequireMigration = false;
+            return this;
+        }
+
+        /**
+         * Adds a {@link Callback} to this database.
+         *
+         * @param callback The callback.
+         * @return this
+         */
+        public Builder<T> addCallback(@NonNull Callback callback) {
+            if (mCallbacks == null) {
+                mCallbacks = new ArrayList<>();
+            }
+            mCallbacks.add(callback);
+            return this;
+        }
+
+        /**
+         * Creates the databases and initializes it.
+         * <p>
+         * By default, all RoomDatabases use in memory storage for TEMP tables and enables recursive
+         * triggers.
+         *
+         * @return A new database instance.
+         */
+        public T build() {
+            //noinspection ConstantConditions
+            if (mContext == null) {
+                throw new IllegalArgumentException("Cannot provide null context for the database.");
+            }
+            //noinspection ConstantConditions
+            if (mDatabaseClass == null) {
+                throw new IllegalArgumentException("Must provide an abstract class that"
+                        + " extends RoomDatabase");
+            }
+            if (mFactory == null) {
+                mFactory = new FrameworkSQLiteOpenHelperFactory();
+            }
+            DatabaseConfiguration configuration =
+                    new DatabaseConfiguration(mContext, mName, mFactory, mMigrationContainer,
+                            mCallbacks, mAllowMainThreadQueries, mRequireMigration);
+            T db = Room.getGeneratedImplementation(mDatabaseClass, DB_IMPL_SUFFIX);
+            db.init(configuration);
+            return db;
+        }
+    }
+
+    /**
+     * A container to hold migrations. It also allows querying its contents to find migrations
+     * between two versions.
+     */
+    public static class MigrationContainer {
+        private SparseArrayCompat<SparseArrayCompat<Migration>> mMigrations =
+                new SparseArrayCompat<>();
+
+        /**
+         * Adds the given migrations to the list of available migrations. If 2 migrations have the
+         * same start-end versions, the latter migration overrides the previous one.
+         *
+         * @param migrations List of available migrations.
+         */
+        public void addMigrations(Migration... migrations) {
+            for (Migration migration : migrations) {
+                addMigration(migration);
+            }
+        }
+
+        private void addMigration(Migration migration) {
+            final int start = migration.startVersion;
+            final int end = migration.endVersion;
+            SparseArrayCompat<Migration> targetMap = mMigrations.get(start);
+            if (targetMap == null) {
+                targetMap = new SparseArrayCompat<>();
+                mMigrations.put(start, targetMap);
+            }
+            Migration existing = targetMap.get(end);
+            if (existing != null) {
+                Log.w(Room.LOG_TAG, "Overriding migration " + existing + " with " + migration);
+            }
+            targetMap.append(end, migration);
+        }
+
+        /**
+         * Finds the list of migrations that should be run to move from {@code start} version to
+         * {@code end} version.
+         *
+         * @param start The current database version
+         * @param end   The target database version
+         * @return An ordered list of {@link Migration} objects that should be run to migrate
+         * between the given versions. If a migration path cannot be found, returns {@code null}.
+         */
+        @Nullable
+        public List<Migration> findMigrationPath(int start, int end) {
+            if (start == end) {
+                return Collections.emptyList();
+            }
+            boolean migrateUp = end > start;
+            List<Migration> result = new ArrayList<>();
+            return findUpMigrationPath(result, migrateUp, start, end);
+        }
+
+        private List<Migration> findUpMigrationPath(List<Migration> result, boolean upgrade,
+                int start, int end) {
+            final int searchDirection = upgrade ? -1 : 1;
+            while (upgrade ? start < end : start > end) {
+                SparseArrayCompat<Migration> targetNodes = mMigrations.get(start);
+                if (targetNodes == null) {
+                    return null;
+                }
+                // keys are ordered so we can start searching from one end of them.
+                final int size = targetNodes.size();
+                final int firstIndex;
+                final int lastIndex;
+
+                if (upgrade) {
+                    firstIndex = size - 1;
+                    lastIndex = -1;
+                } else {
+                    firstIndex = 0;
+                    lastIndex = size;
+                }
+                boolean found = false;
+                for (int i = firstIndex; i != lastIndex; i += searchDirection) {
+                    int targetVersion = targetNodes.keyAt(i);
+                    if (targetVersion <= end && targetVersion > start) {
+                        result.add(targetNodes.valueAt(i));
+                        start = targetVersion;
+                        found = true;
+                        break;
+                    }
+                }
+                if (!found) {
+                    return null;
+                }
+            }
+            return result;
+        }
+    }
+
+    /**
+     * Callback for {@link RoomDatabase}.
+     */
+    public abstract static class Callback {
+
+        /**
+         * Called when the database is created for the first time. This is called after all the
+         * tables are created.
+         *
+         * @param db The database.
+         */
+        public void onCreate(@NonNull SupportSQLiteDatabase db) {
+        }
+
+        /**
+         * Called when the database has been opened.
+         *
+         * @param db The database.
+         */
+        public void onOpen(@NonNull SupportSQLiteDatabase db) {
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/RoomOpenHelper.java b/room/runtime/src/main/java/android/arch/persistence/room/RoomOpenHelper.java
new file mode 100644
index 0000000..8767f06
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/RoomOpenHelper.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SimpleSQLiteQuery;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.room.migration.Migration;
+import android.database.Cursor;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.List;
+
+/**
+ * An open helper that holds a reference to the configuration until the database is opened.
+ *
+ * @hide
+ */
+@SuppressWarnings("unused")
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class RoomOpenHelper extends SupportSQLiteOpenHelper.Callback {
+    @Nullable
+    private DatabaseConfiguration mConfiguration;
+    @NonNull
+    private final Delegate mDelegate;
+    @NonNull
+    private final String mIdentityHash;
+
+    public RoomOpenHelper(@NonNull DatabaseConfiguration configuration, @NonNull Delegate delegate,
+            @NonNull String identityHash) {
+        mConfiguration = configuration;
+        mDelegate = delegate;
+        mIdentityHash = identityHash;
+    }
+
+    @Override
+    public void onConfigure(SupportSQLiteDatabase db) {
+        super.onConfigure(db);
+    }
+
+    @Override
+    public void onCreate(SupportSQLiteDatabase db) {
+        updateIdentity(db);
+        mDelegate.createAllTables(db);
+        mDelegate.onCreate(db);
+    }
+
+    @Override
+    public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) {
+        boolean migrated = false;
+        if (mConfiguration != null) {
+            List<Migration> migrations = mConfiguration.migrationContainer.findMigrationPath(
+                    oldVersion, newVersion);
+            if (migrations != null) {
+                for (Migration migration : migrations) {
+                    migration.migrate(db);
+                }
+                mDelegate.validateMigration(db);
+                updateIdentity(db);
+                migrated = true;
+            }
+        }
+        if (!migrated) {
+            if (mConfiguration == null || mConfiguration.requireMigration) {
+                throw new IllegalStateException("A migration from " + oldVersion + " to "
+                + newVersion + " is necessary. Please provide a Migration in the builder or call"
+                        + " fallbackToDestructiveMigration in the builder in which case Room will"
+                        + " re-create all of the tables.");
+            }
+            mDelegate.dropAllTables(db);
+            mDelegate.createAllTables(db);
+        }
+    }
+
+    @Override
+    public void onDowngrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) {
+        onUpgrade(db, oldVersion, newVersion);
+    }
+
+    @Override
+    public void onOpen(SupportSQLiteDatabase db) {
+        super.onOpen(db);
+        checkIdentity(db);
+        mDelegate.onOpen(db);
+        // there might be too many configurations etc, just clear it.
+        mConfiguration = null;
+    }
+
+    private void checkIdentity(SupportSQLiteDatabase db) {
+        createMasterTableIfNotExists(db);
+        String identityHash = "";
+        Cursor cursor = db.query(new SimpleSQLiteQuery(RoomMasterTable.READ_QUERY));
+        //noinspection TryFinallyCanBeTryWithResources
+        try {
+            if (cursor.moveToFirst()) {
+                identityHash = cursor.getString(0);
+            }
+        } finally {
+            cursor.close();
+        }
+        if (!mIdentityHash.equals(identityHash)) {
+            throw new IllegalStateException("Room cannot verify the data integrity. Looks like"
+                    + " you've changed schema but forgot to update the version number. You can"
+                    + " simply fix this by increasing the version number.");
+        }
+    }
+
+    private void updateIdentity(SupportSQLiteDatabase db) {
+        createMasterTableIfNotExists(db);
+        db.execSQL(RoomMasterTable.createInsertQuery(mIdentityHash));
+    }
+
+    private void createMasterTableIfNotExists(SupportSQLiteDatabase db) {
+        db.execSQL(RoomMasterTable.CREATE_QUERY);
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public abstract static class Delegate {
+        protected abstract void dropAllTables(SupportSQLiteDatabase database);
+
+        protected abstract void createAllTables(SupportSQLiteDatabase database);
+
+        protected abstract void onOpen(SupportSQLiteDatabase database);
+
+        protected abstract void onCreate(SupportSQLiteDatabase database);
+
+        /**
+         * Called after a migration run to validate database integrity.
+         *
+         * @param db The SQLite database.
+         */
+        protected abstract void validateMigration(SupportSQLiteDatabase db);
+    }
+
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/RoomSQLiteQuery.java b/room/runtime/src/main/java/android/arch/persistence/room/RoomSQLiteQuery.java
new file mode 100644
index 0000000..a8defd4
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/RoomSQLiteQuery.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteProgram;
+import android.arch.persistence.db.SupportSQLiteQuery;
+import android.support.annotation.IntDef;
+import android.support.annotation.RestrictTo;
+import android.support.annotation.VisibleForTesting;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * This class is used as an intermediate place to keep binding arguments so that we can run
+ * Cursor queries with correct types rather than passing everything as a string.
+ * <p>
+ * Because it is relatively a big object, they are pooled and must be released after each use.
+ *
+ * @hide
+ */
+@SuppressWarnings("unused")
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public class RoomSQLiteQuery implements SupportSQLiteQuery, SupportSQLiteProgram {
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    // Maximum number of queries we'll keep cached.
+    static final int POOL_LIMIT = 15;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    // Once we hit POOL_LIMIT, we'll bring the pool size back to the desired number. We always
+    // clear the bigger queries (# of arguments).
+    static final int DESIRED_POOL_SIZE = 10;
+    private volatile String mQuery;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    final long[] mLongBindings;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    final double[] mDoubleBindings;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    final String[] mStringBindings;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    final byte[][] mBlobBindings;
+
+    @Binding
+    private final int[] mBindingTypes;
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    final int mCapacity;
+    // number of arguments in the query
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    int mArgCount;
+
+
+    @SuppressWarnings("WeakerAccess")
+    @VisibleForTesting
+    static final TreeMap<Integer, RoomSQLiteQuery> sQueryPool = new TreeMap<>();
+
+    /**
+     * Returns a new RoomSQLiteQuery that can accept the given number of arguments and holds the
+     * given query.
+     *
+     * @param query         The query to prepare
+     * @param argumentCount The number of query arguments
+     * @return A RoomSQLiteQuery that holds the given query and has space for the given number of
+     * arguments.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public static RoomSQLiteQuery acquire(String query, int argumentCount) {
+        synchronized (sQueryPool) {
+            final Map.Entry<Integer, RoomSQLiteQuery> entry =
+                    sQueryPool.ceilingEntry(argumentCount);
+            if (entry != null) {
+                sQueryPool.remove(entry.getKey());
+                final RoomSQLiteQuery sqliteQuery = entry.getValue();
+                sqliteQuery.init(query, argumentCount);
+                return sqliteQuery;
+            }
+        }
+        RoomSQLiteQuery sqLiteQuery = new RoomSQLiteQuery(argumentCount);
+        sqLiteQuery.init(query, argumentCount);
+        return sqLiteQuery;
+    }
+
+    private RoomSQLiteQuery(int capacity) {
+        mCapacity = capacity;
+        // because, 1 based indices... we don't want to offsets everything with 1 all the time.
+        int limit = capacity + 1;
+        //noinspection WrongConstant
+        mBindingTypes = new int[limit];
+        mLongBindings = new long[limit];
+        mDoubleBindings = new double[limit];
+        mStringBindings = new String[limit];
+        mBlobBindings = new byte[limit][];
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    void init(String query, int argCount) {
+        mQuery = query;
+        mArgCount = argCount;
+    }
+
+    /**
+     * Releases the query back to the pool.
+     * <p>
+     * After released, the statement might be returned when {@link #acquire(String, int)} is called
+     * so you should never re-use it after releasing.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public void release() {
+        synchronized (sQueryPool) {
+            sQueryPool.put(mCapacity, this);
+            prunePoolLocked();
+        }
+    }
+
+    private static void prunePoolLocked() {
+        if (sQueryPool.size() > POOL_LIMIT) {
+            int toBeRemoved = sQueryPool.size() - DESIRED_POOL_SIZE;
+            final Iterator<Integer> iterator = sQueryPool.descendingKeySet().iterator();
+            while (toBeRemoved-- > 0) {
+                iterator.next();
+                iterator.remove();
+            }
+        }
+    }
+
+    @Override
+    public String getSql() {
+        return mQuery;
+    }
+
+    public int getArgCount() {
+        return mArgCount;
+    }
+
+    @Override
+    public void bindTo(SupportSQLiteProgram program) {
+        for (int index = 1; index <= mArgCount; index++) {
+            switch (mBindingTypes[index]) {
+                case NULL:
+                    program.bindNull(index);
+                    break;
+                case LONG:
+                    program.bindLong(index, mLongBindings[index]);
+                    break;
+                case DOUBLE:
+                    program.bindDouble(index, mDoubleBindings[index]);
+                    break;
+                case STRING:
+                    program.bindString(index, mStringBindings[index]);
+                    break;
+                case BLOB:
+                    program.bindBlob(index, mBlobBindings[index]);
+                    break;
+            }
+        }
+    }
+
+    @Override
+    public void bindNull(int index) {
+        mBindingTypes[index] = NULL;
+    }
+
+    @Override
+    public void bindLong(int index, long value) {
+        mBindingTypes[index] = LONG;
+        mLongBindings[index] = value;
+    }
+
+    @Override
+    public void bindDouble(int index, double value) {
+        mBindingTypes[index] = DOUBLE;
+        mDoubleBindings[index] = value;
+    }
+
+    @Override
+    public void bindString(int index, String value) {
+        mBindingTypes[index] = STRING;
+        mStringBindings[index] = value;
+    }
+
+    @Override
+    public void bindBlob(int index, byte[] value) {
+        mBindingTypes[index] = BLOB;
+        mBlobBindings[index] = value;
+    }
+
+    @Override
+    public void close() throws Exception {
+        // no-op. not calling release because it is internal API.
+    }
+
+    /**
+     * Copies arguments from another RoomSQLiteQuery into this query.
+     *
+     * @param other The other query, which holds the arguments to be copied.
+     */
+    public void copyArgumentsFrom(RoomSQLiteQuery other) {
+        int argCount = other.getArgCount() + 1; // +1 for the binding offsets
+        System.arraycopy(other.mBindingTypes, 0, mBindingTypes, 0, argCount);
+        System.arraycopy(other.mLongBindings, 0, mLongBindings, 0, argCount);
+        System.arraycopy(other.mStringBindings, 0, mStringBindings, 0, argCount);
+        System.arraycopy(other.mBlobBindings, 0, mBlobBindings, 0, argCount);
+        System.arraycopy(other.mDoubleBindings, 0, mDoubleBindings, 0, argCount);
+    }
+
+    @Override
+    public void clearBindings() {
+        Arrays.fill(mBindingTypes, NULL);
+        Arrays.fill(mStringBindings, null);
+        Arrays.fill(mBlobBindings, null);
+        mQuery = null;
+        // no need to clear others
+    }
+
+    private static final int NULL = 1;
+    private static final int LONG = 2;
+    private static final int DOUBLE = 3;
+    private static final int STRING = 4;
+    private static final int BLOB = 5;
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({NULL, LONG, DOUBLE, STRING, BLOB})
+    @interface Binding {
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/SharedSQLiteStatement.java b/room/runtime/src/main/java/android/arch/persistence/room/SharedSQLiteStatement.java
new file mode 100644
index 0000000..6b1f8ea
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/SharedSQLiteStatement.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.support.annotation.RestrictTo;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Represents a prepared SQLite state that can be re-used multiple times.
+ * <p>
+ * This class is used by generated code. After it is used, {@code release} must be called so that
+ * it can be used by other threads.
+ * <p>
+ * To avoid re-entry even within the same thread, this class allows only 1 time access to the shared
+ * statement until it is released.
+ *
+ * @hide
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class SharedSQLiteStatement {
+    private final AtomicBoolean mLock = new AtomicBoolean(false);
+
+    private final RoomDatabase mDatabase;
+    private volatile SupportSQLiteStatement mStmt;
+
+    /**
+     * Creates an SQLite prepared statement that can be re-used across threads. If it is in use,
+     * it automatically creates a new one.
+     *
+     * @param database The database to create the statement in.
+     */
+    public SharedSQLiteStatement(RoomDatabase database) {
+        mDatabase = database;
+    }
+
+    /**
+     * Create the query.
+     *
+     * @return The SQL query to prepare.
+     */
+    protected abstract String createQuery();
+
+    protected void assertNotMainThread() {
+        mDatabase.assertNotMainThread();
+    }
+
+    private SupportSQLiteStatement createNewStatement() {
+        String query = createQuery();
+        return mDatabase.compileStatement(query);
+    }
+
+    private SupportSQLiteStatement getStmt(boolean canUseCached) {
+        final SupportSQLiteStatement stmt;
+        if (canUseCached) {
+            if (mStmt == null) {
+                mStmt = createNewStatement();
+            }
+            stmt = mStmt;
+        } else {
+            // it is in use, create a one off statement
+            stmt = createNewStatement();
+        }
+        return stmt;
+    }
+
+    /**
+     * Call this to get the statement. Must call {@link #release(SupportSQLiteStatement)} once done.
+     */
+    public SupportSQLiteStatement acquire() {
+        assertNotMainThread();
+        return getStmt(mLock.compareAndSet(false, true));
+    }
+
+    /**
+     * Must call this when statement will not be used anymore.
+     *
+     * @param statement The statement that was returned from acquire.
+     */
+    public void release(SupportSQLiteStatement statement) {
+        if (statement == mStmt) {
+            mLock.set(false);
+        }
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/migration/Migration.java b/room/runtime/src/main/java/android/arch/persistence/room/migration/Migration.java
new file mode 100644
index 0000000..907e624
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/migration/Migration.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.migration;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+
+/**
+ * Base class for a database migration.
+ * <p>
+ * Each migration can move between 2 versions that are defined by {@link #startVersion} and
+ * {@link #endVersion}.
+ * <p>
+ * A migration can handle more than 1 version (e.g. if you have a faster path to choose when
+ * going version 3 to 5 without going to version 4). If Room opens a database at version
+ * 3 and latest version is &gt;= 5, Room will use the migration object that can migrate from
+ * 3 to 5 instead of 3 to 4 and 4 to 5.
+ * <p>
+ * If there are not enough migrations provided to move from the current version to the latest
+ * version, Room will clear the database and recreate so even if you have no changes between 2
+ * versions, you should still provide a Migration object to the builder.
+ */
+public abstract class Migration {
+    public final int startVersion;
+    public final int endVersion;
+
+    /**
+     * Creates a new migration between {@code startVersion} and {@code endVersion}.
+     *
+     * @param startVersion The start version of the database.
+     * @param endVersion The end version of the database after this migration is applied.
+     */
+    public Migration(int startVersion, int endVersion) {
+        this.startVersion = startVersion;
+        this.endVersion = endVersion;
+    }
+
+    /**
+     * Should run the necessary migrations.
+     * <p>
+     * This class cannot access any generated Dao in this method.
+     * <p>
+     * This method is already called inside a transaction and that transaction might actually be a
+     * composite transaction of all necessary {@code Migration}s.
+     *
+     * @param database The database instance
+     */
+    public abstract void migrate(SupportSQLiteDatabase database);
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/package-info.java b/room/runtime/src/main/java/android/arch/persistence/room/package-info.java
new file mode 100644
index 0000000..faaa952
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/package-info.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+/**
+ * Room is a Database Object Mapping library that makes it easy to access database on Android
+ * applications.
+ * <p>
+ * Rather than hiding the detail of SQLite, Room tries to embrace them by providing convenient APIs
+ * to query the database and also verify such queries at compile time. This allows you to access
+ * the full power of SQLite while having the type safety provided by Java SQL query builders.
+ * <p>
+ * There are 3 major components in Room.
+ * <ul>
+ *     <li>{@link android.arch.persistence.room.Database Database}: This annotation marks a
+ *     class as a database. It should be an abstract class that extends
+ *     {@link android.arch.persistence.room.RoomDatabase RoomDatabase}. At runtime, you can acquire
+ *     an instance of it via {@link android.arch.persistence.room.Room#databaseBuilder(
+ *     android.content.Context,java.lang.Class, java.lang.String) Room.databaseBuilder} or
+ *     {@link android.arch.persistence.room.Room#inMemoryDatabaseBuilder(android.content.Context,
+ *     java.lang.Class) Room.inMemoryDatabaseBuilder}.
+ *     <p>
+ *         This class defines the list of entities and data access objects in the database. It is
+ *         also the main access point for the underlying connection.
+ *     </li>
+ *     <li>{@link android.arch.persistence.room.Entity Entity}: This annotation marks a class as a
+ *     database row. For each {@link android.arch.persistence.room.Entity Entity}, a database table
+ *     is created to hold the items. The Entity class must be referenced in the
+ *     {@link android.arch.persistence.room.Database#entities() Database#entities} array. Each field
+ *     of the Entity is persisted in the database unless it is annotated with
+ *     {@link android.arch.persistence.room.Ignore Ignore}. Entities must have no-arg constructors.
+ *     </li>
+ *     <li>{@link android.arch.persistence.room.Dao Dao}: This annotation marks a class or interface
+ *     as a Data Access Object. Data access objects are the main component of Room that are
+ *     responsible for defining the methods that access the database. The class that is annotated
+ *     with {@link android.arch.persistence.room.Database Database} must have an abstract method
+ *     that has 0 arguments and returns the class that is annotated with Dao. While generating the
+ *     code at compile time, Room will generate an implementation of this class.
+ *     <pre>
+ *     Using Dao classes for database access rather than query builders or direct queries allows you
+ *     to keep a separation between different components and easily mock the database access while
+ *     testing your application.
+ *     </li>
+ * </ul>
+ * Below is a sample of a simple database.
+ * <pre>
+ * // File: User.java
+ * {@literal @}Entity
+ * public class User {
+ *   {@literal @}PrimaryKey
+ *   private int uid;
+ *   private String name;
+ *   {@literal @}ColumnInfo(name = "last_name")
+ *   private String lastName;
+ *   // getters and setters are ignored for brevity but they are required for Room to work.
+ * }
+ * // File: UserDao.java
+ * {@literal @}Dao
+ * public interface UserDao {
+ *   {@literal @}Query("SELECT * FROM user")
+ *   List&lt;User&gt; loadAll();
+ *   {@literal @}Query("SELECT * FROM user WHERE uid IN (:userIds)")
+ *   List&lt;User&gt; loadAllByUserId(int... userIds);
+ *   {@literal @}Query("SELECT * FROM user where name LIKE :first AND last_name LIKE :last LIMIT 1")
+ *   User loadOneByNameAndLastName(String first, String last);
+ *   {@literal @}Insert
+ *   void insertAll(User... users);
+ *   {@literal @}Delete
+ *   void delete(User user);
+ * }
+ * // File: AppDatabase.java
+ * {@literal @}Database(entities = {User.java})
+ * public abstract class AppDatabase extends RoomDatabase {
+ *   public abstract UserDao userDao();
+ * }
+ * </pre>
+ * You can create an instance of {@code AppDatabase} as follows:
+ * <pre>
+ * AppDatabase db = Room
+ *     .databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name")
+ *     .build();
+ * </pre>
+ * Since Room verifies your queries at compile time, it also detects information about which tables
+ * are accessed by the query or what columns are present in the response.
+ * <p>
+ * You can observe a particular table for changes using the
+ * {@link android.arch.persistence.room.InvalidationTracker InvalidationTracker} class which you can
+ * acquire via {@link android.arch.persistence.room.RoomDatabase#getInvalidationTracker()
+ * RoomDatabase.getInvalidationTracker}.
+ * <p>
+ * For convenience, Room allows you to return {@link android.arch.lifecycle.LiveData
+ * LiveData} from {@link android.arch.persistence.room.Query Query} methods. It will automatically
+ * observe the related tables as long as the {@code LiveData} has active observers.
+ * <pre>
+ * // This live data will automatically dispatch changes as the database changes.
+ * {@literal @}Query("SELECT * FROM user ORDER BY name LIMIT 5")
+ * LiveData&lt;User&gt; loadFirstFiveUsers();
+ * </pre>
+ * <p>
+ * You can also return arbitrary Java objects from your query results as long as the fields in the
+ * object match the list of columns in the query response. This makes it very easy to write
+ * applications that drive the UI from persistent storage.
+ * <pre>
+ * class IdAndFullName {
+ *     public int uid;
+ *     {@literal @}ColumnInfo(name = "full_name")
+ *     public String fullName;
+ * }
+ * // DAO
+ * {@literal @}Query("SELECT uid, name || lastName as full_name FROM user")
+ * public IdAndFullName[] loadFullNames();
+ * </pre>
+ * If there is a mismatch between the query result and the POJO, Room will print a warning during
+ * compilation.
+ * <p>
+ * Please see the documentation of individual classes for details.
+ */
+package android.arch.persistence.room;
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/paging/LimitOffsetDataSource.java b/room/runtime/src/main/java/android/arch/persistence/room/paging/LimitOffsetDataSource.java
new file mode 100644
index 0000000..750f2b7
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/paging/LimitOffsetDataSource.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.paging;
+
+import android.arch.persistence.room.InvalidationTracker;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.RoomSQLiteQuery;
+import android.arch.util.paging.CountedDataSource;
+import android.database.Cursor;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A simple data source implementation that uses Limit & Offset to page the query.
+ * <p>
+ * This is NOT the most efficient way to do paging on SQLite. It is
+ * <a href="http://www.sqlite.org/cvstrac/wiki?p=ScrollingCursor">recommended</a> to use an indexed
+ * ORDER BY statement but that requires a more complex API. This solution is technically equal to
+ * receiving a {@link Cursor} from a large query but avoids the need to manually manage it, and
+ * never returns inconsistent data if it is invalidated.
+ *
+ * @param <T> Data type returned by the data source.
+ *
+ * @hide
+ */
+@SuppressWarnings("unused")
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class LimitOffsetDataSource<T> extends CountedDataSource<T> {
+    private final RoomSQLiteQuery mSourceQuery;
+    private final String mCountQuery;
+    private final String mLimitOffsetQuery;
+    private final RoomDatabase mDb;
+    @SuppressWarnings("FieldCanBeLocal")
+    private final InvalidationTracker.Observer mObserver;
+
+    public Runnable invalidCallback;
+
+    protected LimitOffsetDataSource(RoomDatabase db, RoomSQLiteQuery query,
+            String... tables) {
+        mDb = db;
+        mSourceQuery = query;
+        mCountQuery = "SELECT COUNT(*) FROM ( " + mSourceQuery.getSql() + " )";
+        mLimitOffsetQuery = "SELECT * FROM ( " + mSourceQuery.getSql() + " ) LIMIT ? OFFSET ?";
+        mObserver = new InvalidationTracker.Observer(tables) {
+            @Override
+            public void onInvalidated(@NonNull Set<String> tables) {
+                invalidate();
+            }
+        };
+        db.getInvalidationTracker().addWeakObserver(mObserver);
+    }
+
+    @Override
+    public int loadCount() {
+        final RoomSQLiteQuery sqLiteQuery = RoomSQLiteQuery.acquire(mCountQuery,
+                mSourceQuery.getArgCount());
+        sqLiteQuery.copyArgumentsFrom(mSourceQuery);
+        Cursor cursor = mDb.query(sqLiteQuery);
+        try {
+            if (cursor.moveToFirst()) {
+                return cursor.getInt(0);
+            }
+            return 0;
+        } finally {
+            cursor.close();
+            sqLiteQuery.release();
+        }
+    }
+
+    @Override
+    public boolean isInvalid() {
+        mDb.getInvalidationTracker().refreshVersionsSync();
+        return super.isInvalid();
+    }
+
+    private List<T> queryRange(int offset, int limit) {
+        final RoomSQLiteQuery sqLiteQuery = RoomSQLiteQuery.acquire(mLimitOffsetQuery,
+                mSourceQuery.getArgCount() + 2);
+        sqLiteQuery.copyArgumentsFrom(mSourceQuery);
+        sqLiteQuery.bindLong(sqLiteQuery.getArgCount() - 1, limit);
+        sqLiteQuery.bindLong(sqLiteQuery.getArgCount(), offset);
+        Cursor cursor = mDb.query(sqLiteQuery);
+        try {
+            return convertRows(cursor);
+        } finally {
+            cursor.close();
+            sqLiteQuery.release();
+        }
+    }
+
+    @SuppressWarnings("WeakerAccess")
+    protected abstract List<T> convertRows(Cursor cursor);
+
+    @Nullable
+    @Override
+    public List<T> loadAfterInitial(int position, int pageSize) {
+        if (isInvalid()) {
+            return null;
+        }
+        List<T> result = queryRange(position + 1, pageSize);
+        if (isInvalid()) {
+            return null;
+        }
+        return result;
+    }
+
+    @Nullable
+    @Override
+    public List<T> loadAfter(int currentEndIndex, @NonNull T currentEndItem, int pageSize) {
+        if (isInvalid()) {
+            return null;
+        }
+        List<T> result = queryRange(currentEndIndex + 1, pageSize);
+        if (isInvalid()) {
+            return null;
+        }
+        return result;
+    }
+
+    @Nullable
+    @Override
+    public List<T> loadBefore(int currentBeginIndex, @NonNull T currentBeginItem, int pageSize) {
+        if (isInvalid()) {
+            return null;
+        }
+        int offset = Math.max(0, currentBeginIndex - pageSize);
+        final List<T> list = queryRange(offset, pageSize);
+        // reverse it
+        Collections.reverse(list);
+
+        if (isInvalid()) {
+            return null;
+        }
+        return list;
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/util/StringUtil.java b/room/runtime/src/main/java/android/arch/persistence/room/util/StringUtil.java
new file mode 100644
index 0000000..bee05dd
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/util/StringUtil.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.util;
+
+import android.support.annotation.Nullable;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+/**
+ * String utilities for Room
+ */
+@SuppressWarnings("WeakerAccess")
+public class StringUtil {
+    public static final String[] EMPTY_STRING_ARRAY = new String[0];
+    /**
+     * Returns a new StringBuilder to be used while producing SQL queries.
+     *
+     * @return A new or recycled StringBuilder
+     */
+    public static StringBuilder newStringBuilder() {
+        // TODO pool:
+        return new StringBuilder();
+    }
+
+    /**
+     * Adds bind variable placeholders (?) to the given string. Each placeholder is separated
+     * by a comma.
+     *
+     * @param builder The StringBuilder for the query
+     * @param count Number of placeholders
+     */
+    public static void appendPlaceholders(StringBuilder builder, int count) {
+        for (int i = 0; i < count; i++) {
+            builder.append("?");
+            if (i < count - 1) {
+                builder.append(",");
+            }
+        }
+    }
+    /**
+     * Splits a comma separated list of integers to integer list.
+     * <p>
+     * If an input is malformed, it is omitted from the result.
+     *
+     * @param input Comma separated list of integers.
+     * @return A List containing the integers or null if the input is null.
+     */
+    @Nullable
+    public static List<Integer> splitToIntList(@Nullable String input) {
+        if (input == null) {
+            return null;
+        }
+        List<Integer> result = new ArrayList<>();
+        StringTokenizer tokenizer = new StringTokenizer(input, ",");
+        while (tokenizer.hasMoreElements()) {
+            final String item = tokenizer.nextToken();
+            try {
+                result.add(Integer.parseInt(item));
+            } catch (NumberFormatException ex) {
+                Log.e("ROOM", "Malformed integer list", ex);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Joins the given list of integers into a comma separated list.
+     *
+     * @param input The list of integers.
+     * @return Comma separated string composed of integers in the list. If the list is null, return
+     * value is null.
+     */
+    @Nullable
+    public static String joinIntoString(@Nullable List<Integer> input) {
+        if (input == null) {
+            return null;
+        }
+
+        final int size = input.size();
+        if (size == 0) {
+            return "";
+        }
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < size; i++) {
+            sb.append(Integer.toString(input.get(i)));
+            if (i < size - 1) {
+                sb.append(",");
+            }
+        }
+        return sb.toString();
+    }
+}
diff --git a/room/runtime/src/main/java/android/arch/persistence/room/util/TableInfo.java b/room/runtime/src/main/java/android/arch/persistence/room/util/TableInfo.java
new file mode 100644
index 0000000..bcd2e9e
--- /dev/null
+++ b/room/runtime/src/main/java/android/arch/persistence/room/util/TableInfo.java
@@ -0,0 +1,382 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.util;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.database.Cursor;
+import android.os.Build;
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A data class that holds the information about a table.
+ * <p>
+ * It directly maps to the result of {@code PRAGMA table_info(<table_name>)}. Check the
+ * <a href="http://www.sqlite.org/pragma.html#pragma_table_info">PRAGMA table_info</a>
+ * documentation for more details.
+ * <p>
+ * Even though SQLite column names are case insensitive, this class uses case sensitive matching.
+ *
+ * @hide
+ */
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+@SuppressWarnings({"WeakerAccess", "unused", "TryFinallyCanBeTryWithResources"})
+// if you change this class, you must change TableInfoWriter.kt
+public class TableInfo {
+    /**
+     * The table name.
+     */
+    public final String name;
+    /**
+     * Unmodifiable map of columns keyed by column name.
+     */
+    public final Map<String, Column> columns;
+
+    public final Set<ForeignKey> foreignKeys;
+
+    @SuppressWarnings("unused")
+    public TableInfo(String name, Map<String, Column> columns, Set<ForeignKey> foreignKeys) {
+        this.name = name;
+        this.columns = Collections.unmodifiableMap(columns);
+        this.foreignKeys = Collections.unmodifiableSet(foreignKeys);
+    }
+
+    /**
+     * Reads the table information from the given database.
+     *
+     * @param database  The database to read the information from.
+     * @param tableName The table name.
+     * @return A TableInfo containing the schema information for the provided table name.
+     */
+    @SuppressWarnings("SameParameterValue")
+    public static TableInfo read(SupportSQLiteDatabase database, String tableName) {
+        Map<String, Column> columns = readColumns(database, tableName);
+        Set<ForeignKey> foreignKeys = readForeignKeys(database, tableName);
+        return new TableInfo(tableName, columns, foreignKeys);
+    }
+
+    private static Set<ForeignKey> readForeignKeys(SupportSQLiteDatabase database,
+            String tableName) {
+        Set<ForeignKey> foreignKeys = new HashSet<>();
+        // this seems to return everything in order but it is not documented so better be safe
+        Cursor cursor = database.query("PRAGMA foreign_key_list(`" + tableName + "`)");
+        try {
+            final int idColumnIndex = cursor.getColumnIndex("id");
+            final int seqColumnIndex = cursor.getColumnIndex("seq");
+            final int tableColumnIndex = cursor.getColumnIndex("table");
+            final int onDeleteColumnIndex = cursor.getColumnIndex("on_delete");
+            final int onUpdateColumnIndex = cursor.getColumnIndex("on_update");
+
+            final List<ForeignKeyWithSequence> ordered = readForeignKeyFieldMappings(cursor);
+            final int count = cursor.getCount();
+            for (int position = 0; position < count; position++) {
+                cursor.moveToPosition(position);
+                final int seq = cursor.getInt(seqColumnIndex);
+                if (seq != 0) {
+                    continue;
+                }
+                final int id = cursor.getInt(idColumnIndex);
+                List<String> myColumns = new ArrayList<>();
+                List<String> refColumns = new ArrayList<>();
+                for (ForeignKeyWithSequence key : ordered) {
+                    if (key.mId == id) {
+                        myColumns.add(key.mFrom);
+                        refColumns.add(key.mTo);
+                    }
+                }
+                foreignKeys.add(new ForeignKey(
+                        cursor.getString(tableColumnIndex),
+                        cursor.getString(onDeleteColumnIndex),
+                        cursor.getString(onUpdateColumnIndex),
+                        myColumns,
+                        refColumns
+                ));
+            }
+        } finally {
+            cursor.close();
+        }
+        return foreignKeys;
+    }
+
+    private static List<ForeignKeyWithSequence> readForeignKeyFieldMappings(Cursor cursor) {
+        final int idColumnIndex = cursor.getColumnIndex("id");
+        final int seqColumnIndex = cursor.getColumnIndex("seq");
+        final int fromColumnIndex = cursor.getColumnIndex("from");
+        final int toColumnIndex = cursor.getColumnIndex("to");
+        final int count = cursor.getCount();
+        List<ForeignKeyWithSequence> result = new ArrayList<>();
+        for (int i = 0; i < count; i++) {
+            cursor.moveToPosition(i);
+            result.add(new ForeignKeyWithSequence(
+                    cursor.getInt(idColumnIndex),
+                    cursor.getInt(seqColumnIndex),
+                    cursor.getString(fromColumnIndex),
+                    cursor.getString(toColumnIndex)
+            ));
+        }
+        Collections.sort(result);
+        return result;
+    }
+
+    private static Map<String, Column> readColumns(SupportSQLiteDatabase database,
+            String tableName) {
+        Cursor cursor = database
+                .query("PRAGMA table_info(`" + tableName + "`)");
+        //noinspection TryFinallyCanBeTryWithResources
+        Map<String, Column> columns = new HashMap<>();
+        try {
+            if (cursor.getColumnCount() > 0) {
+                int nameIndex = cursor.getColumnIndex("name");
+                int typeIndex = cursor.getColumnIndex("type");
+                int notNullIndex = cursor.getColumnIndex("notnull");
+                int pkIndex = cursor.getColumnIndex("pk");
+
+                while (cursor.moveToNext()) {
+                    final String name = cursor.getString(nameIndex);
+                    final String type = cursor.getString(typeIndex);
+                    final boolean notNull = 0 != cursor.getInt(notNullIndex);
+                    final int primaryKeyPosition = cursor.getInt(pkIndex);
+                    columns.put(name, new Column(name, type, notNull, primaryKeyPosition));
+                }
+            }
+        } finally {
+            cursor.close();
+        }
+        return columns;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        TableInfo tableInfo = (TableInfo) o;
+
+        if (!name.equals(tableInfo.name)) return false;
+        //noinspection SimplifiableIfStatement
+        if (!columns.equals(tableInfo.columns)) return false;
+        return foreignKeys.equals(tableInfo.foreignKeys);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = name.hashCode();
+        result = 31 * result + columns.hashCode();
+        result = 31 * result + foreignKeys.hashCode();
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "TableInfo{"
+                + "name='" + name + '\''
+                + ", columns=" + columns
+                + ", foreignKeys=" + foreignKeys
+                + '}';
+    }
+
+    /**
+     * Holds the information about a database column.
+     */
+    @SuppressWarnings("WeakerAccess")
+    public static class Column {
+        /**
+         * The column name.
+         */
+        public final String name;
+        /**
+         * The column type affinity.
+         */
+        public final String type;
+        /**
+         * Whether or not the column can be NULL.
+         */
+        public final boolean notNull;
+        /**
+         * The position of the column in the list of primary keys, 0 if the column is not part
+         * of the primary key.
+         * <p>
+         * This information is only available in API 20+.
+         * <a href="https://www.sqlite.org/releaselog/3_7_16_2.html">(SQLite version 3.7.16.2)</a>
+         * On older platforms, it will be 1 if the column is part of the primary key and 0
+         * otherwise.
+         * <p>
+         * The {@link #equals(Object)} implementation handles this inconsistency based on
+         * API levels os if you are using a custom SQLite deployment, it may return false
+         * positives.
+         */
+        public final int primaryKeyPosition;
+
+        // if you change this constructor, you must change TableInfoWriter.kt
+        public Column(String name, String type, boolean notNull, int primaryKeyPosition) {
+            this.name = name;
+            this.type = type;
+            this.notNull = notNull;
+            this.primaryKeyPosition = primaryKeyPosition;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            Column column = (Column) o;
+            if (Build.VERSION.SDK_INT >= 20) {
+                if (primaryKeyPosition != column.primaryKeyPosition) return false;
+            } else {
+                if (isPrimaryKey() != column.isPrimaryKey()) return false;
+            }
+
+            if (!name.equals(column.name)) return false;
+            //noinspection SimplifiableIfStatement
+            if (notNull != column.notNull) return false;
+            return type != null ? type.equalsIgnoreCase(column.type) : column.type == null;
+        }
+
+        /**
+         * Returns whether this column is part of the primary key or not.
+         *
+         * @return True if this column is part of the primary key, false otherwise.
+         */
+        public boolean isPrimaryKey() {
+            return primaryKeyPosition > 0;
+        }
+
+        @Override
+        public int hashCode() {
+            int result = name.hashCode();
+            result = 31 * result + (type != null ? type.hashCode() : 0);
+            result = 31 * result + (notNull ? 1231 : 1237);
+            result = 31 * result + primaryKeyPosition;
+            return result;
+        }
+
+        @Override
+        public String toString() {
+            return "Column{"
+                    + "name='" + name + '\''
+                    + ", type='" + type + '\''
+                    + ", notNull=" + notNull
+                    + ", primaryKeyPosition=" + primaryKeyPosition
+                    + '}';
+        }
+    }
+
+    /**
+     * Holds the information about an SQLite foreign key
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static class ForeignKey {
+        @NonNull
+        public final String referenceTable;
+        @NonNull
+        public final String onDelete;
+        @NonNull
+        public final String onUpdate;
+        @NonNull
+        public final List<String> columnNames;
+        @NonNull
+        public final List<String> referenceColumnNames;
+
+        public ForeignKey(@NonNull String referenceTable, @NonNull String onDelete,
+                @NonNull String onUpdate,
+                @NonNull List<String> columnNames, @NonNull List<String> referenceColumnNames) {
+            this.referenceTable = referenceTable;
+            this.onDelete = onDelete;
+            this.onUpdate = onUpdate;
+            this.columnNames = Collections.unmodifiableList(columnNames);
+            this.referenceColumnNames = Collections.unmodifiableList(referenceColumnNames);
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            ForeignKey that = (ForeignKey) o;
+
+            if (!referenceTable.equals(that.referenceTable)) return false;
+            if (!onDelete.equals(that.onDelete)) return false;
+            if (!onUpdate.equals(that.onUpdate)) return false;
+            //noinspection SimplifiableIfStatement
+            if (!columnNames.equals(that.columnNames)) return false;
+            return referenceColumnNames.equals(that.referenceColumnNames);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = referenceTable.hashCode();
+            result = 31 * result + onDelete.hashCode();
+            result = 31 * result + onUpdate.hashCode();
+            result = 31 * result + columnNames.hashCode();
+            result = 31 * result + referenceColumnNames.hashCode();
+            return result;
+        }
+
+        @Override
+        public String toString() {
+            return "ForeignKey{"
+                    + "referenceTable='" + referenceTable + '\''
+                    + ", onDelete='" + onDelete + '\''
+                    + ", onUpdate='" + onUpdate + '\''
+                    + ", columnNames=" + columnNames
+                    + ", referenceColumnNames=" + referenceColumnNames
+                    + '}';
+        }
+    }
+
+    /**
+     * Temporary data holder for a foreign key row in the pragma result. We need this to ensure
+     * sorting in the generated foreign key object.
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    static class ForeignKeyWithSequence implements Comparable<ForeignKeyWithSequence> {
+        final int mId;
+        final int mSequence;
+        final String mFrom;
+        final String mTo;
+
+        ForeignKeyWithSequence(int id, int sequence, String from, String to) {
+            mId = id;
+            mSequence = sequence;
+            mFrom = from;
+            mTo = to;
+        }
+
+        @Override
+        public int compareTo(ForeignKeyWithSequence o) {
+            final int idCmp = mId - o.mId;
+            if (idCmp == 0) {
+                return mSequence - o.mSequence;
+            } else {
+                return idCmp;
+            }
+        }
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest.java b/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest.java
new file mode 100644
index 0000000..0728cca
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.mock;
+
+import static java.util.Arrays.asList;
+
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.migration.Migration;
+import android.content.Context;
+
+import org.hamcrest.CoreMatchers;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.List;
+
+@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
+@RunWith(JUnit4.class)
+public class BuilderTest {
+    @Test(expected = IllegalArgumentException.class)
+    public void nullContext() {
+        //noinspection ConstantConditions
+        Room.databaseBuilder(null, RoomDatabase.class, "bla").build();
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void nullContext2() {
+        //noinspection ConstantConditions
+        Room.inMemoryDatabaseBuilder(null, RoomDatabase.class).build();
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void nullName() {
+        //noinspection ConstantConditions
+        Room.databaseBuilder(mock(Context.class), RoomDatabase.class, null).build();
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void emptyName() {
+        Room.databaseBuilder(mock(Context.class), RoomDatabase.class, "  ").build();
+    }
+
+    @Test
+    public void migration() {
+        Migration m1 = new EmptyMigration(0, 1);
+        Migration m2 = new EmptyMigration(1, 2);
+        TestDatabase db = Room.databaseBuilder(mock(Context.class), TestDatabase.class, "foo")
+                .addMigrations(m1, m2).build();
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        RoomDatabase.MigrationContainer migrations = config.migrationContainer;
+        assertThat(migrations.findMigrationPath(0, 1), is(asList(m1)));
+        assertThat(migrations.findMigrationPath(1, 2), is(asList(m2)));
+        assertThat(migrations.findMigrationPath(0, 2), is(asList(m1, m2)));
+        assertThat(migrations.findMigrationPath(2, 0), CoreMatchers.<List<Migration>>nullValue());
+        assertThat(migrations.findMigrationPath(0, 3), CoreMatchers.<List<Migration>>nullValue());
+    }
+
+    @Test
+    public void migrationOverride() {
+        Migration m1 = new EmptyMigration(0, 1);
+        Migration m2 = new EmptyMigration(1, 2);
+        Migration m3 = new EmptyMigration(0, 1);
+        TestDatabase db = Room.databaseBuilder(mock(Context.class), TestDatabase.class, "foo")
+                .addMigrations(m1, m2, m3).build();
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        RoomDatabase.MigrationContainer migrations = config.migrationContainer;
+        assertThat(migrations.findMigrationPath(0, 1), is(asList(m3)));
+        assertThat(migrations.findMigrationPath(1, 2), is(asList(m2)));
+        assertThat(migrations.findMigrationPath(0, 3), CoreMatchers.<List<Migration>>nullValue());
+    }
+
+    @Test
+    public void migrationJump() {
+        Migration m1 = new EmptyMigration(0, 1);
+        Migration m2 = new EmptyMigration(1, 2);
+        Migration m3 = new EmptyMigration(2, 3);
+        Migration m4 = new EmptyMigration(0, 3);
+        TestDatabase db = Room.databaseBuilder(mock(Context.class), TestDatabase.class, "foo")
+                .addMigrations(m1, m2, m3, m4).build();
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        RoomDatabase.MigrationContainer migrations = config.migrationContainer;
+        assertThat(migrations.findMigrationPath(0, 3), is(asList(m4)));
+        assertThat(migrations.findMigrationPath(1, 3), is(asList(m2, m3)));
+    }
+
+    @Test
+    public void skipMigration() {
+        Context context = mock(Context.class);
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class)
+                .fallbackToDestructiveMigration().build();
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        assertThat(config.requireMigration, is(false));
+    }
+
+    @Test
+    public void createBasic() {
+        Context context = mock(Context.class);
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
+        assertThat(db, instanceOf(BuilderTest_TestDatabase_Impl.class));
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        assertThat(config, notNullValue());
+        assertThat(config.context, is(context));
+        assertThat(config.name, is(nullValue()));
+        assertThat(config.allowMainThreadQueries, is(false));
+        assertThat(config.sqliteOpenHelperFactory,
+                instanceOf(FrameworkSQLiteOpenHelperFactory.class));
+    }
+
+    @Test
+    public void createAllowMainThread() {
+        Context context = mock(Context.class);
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class)
+                .allowMainThreadQueries()
+                .build();
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        assertThat(config.allowMainThreadQueries, is(true));
+    }
+
+    @Test
+    public void createWithFactoryAndVersion() {
+        Context context = mock(Context.class);
+        SupportSQLiteOpenHelper.Factory factory = mock(SupportSQLiteOpenHelper.Factory.class);
+
+        TestDatabase db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class)
+                .openHelperFactory(factory)
+                .build();
+        assertThat(db, instanceOf(BuilderTest_TestDatabase_Impl.class));
+        DatabaseConfiguration config = ((BuilderTest_TestDatabase_Impl) db).mConfig;
+        assertThat(config, notNullValue());
+        assertThat(config.sqliteOpenHelperFactory, is(factory));
+    }
+
+    abstract static class TestDatabase extends RoomDatabase {
+    }
+
+    static class EmptyMigration extends Migration {
+        EmptyMigration(int start, int end) {
+            super(start, end);
+        }
+
+        @Override
+        public void migrate(SupportSQLiteDatabase database) {
+        }
+    }
+
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest_TestDatabase_Impl.java b/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest_TestDatabase_Impl.java
new file mode 100644
index 0000000..d261454
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/BuilderTest_TestDatabase_Impl.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+
+public class BuilderTest_TestDatabase_Impl extends BuilderTest.TestDatabase {
+    DatabaseConfiguration mConfig;
+    @Override
+    public void init(DatabaseConfiguration configuration) {
+        super.init(configuration);
+        mConfig = configuration;
+    }
+
+    @Override
+    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config) {
+        return null;
+    }
+
+    @Override
+    protected InvalidationTracker createInvalidationTracker() {
+        return null;
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/InvalidationTrackerTest.java b/room/runtime/src/test/java/android/arch/persistence/room/InvalidationTrackerTest.java
new file mode 100644
index 0000000..f0b730a
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/InvalidationTrackerTest.java
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsCollectionContaining.hasItem;
+import static org.hamcrest.core.IsCollectionContaining.hasItems;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.JunitTaskExecutorRule;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.SupportSQLiteStatement;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteException;
+import android.support.annotation.NonNull;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Locale;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+@RunWith(JUnit4.class)
+public class InvalidationTrackerTest {
+    private InvalidationTracker mTracker;
+    private RoomDatabase mRoomDatabase;
+    private SupportSQLiteOpenHelper mOpenHelper;
+    @Rule
+    public JunitTaskExecutorRule mTaskExecutorRule = new JunitTaskExecutorRule(1, true);
+
+    @Before
+    public void setup() {
+        mRoomDatabase = mock(RoomDatabase.class);
+        SupportSQLiteDatabase sqliteDb = mock(SupportSQLiteDatabase.class);
+        final SupportSQLiteStatement statement = mock(SupportSQLiteStatement.class);
+        mOpenHelper = mock(SupportSQLiteOpenHelper.class);
+
+        doReturn(statement).when(sqliteDb).compileStatement(eq(InvalidationTracker.CLEANUP_SQL));
+        doReturn(sqliteDb).when(mOpenHelper).getWritableDatabase();
+        doReturn(true).when(mRoomDatabase).isOpen();
+        ReentrantLock closeLock = new ReentrantLock();
+        doReturn(closeLock).when(mRoomDatabase).getCloseLock();
+        //noinspection ResultOfMethodCallIgnored
+        doReturn(mOpenHelper).when(mRoomDatabase).getOpenHelper();
+
+        mTracker = new InvalidationTracker(mRoomDatabase, "a", "B", "i");
+        mTracker.internalInit(sqliteDb);
+    }
+
+    @Before
+    public void setLocale() {
+        Locale.setDefault(Locale.forLanguageTag("tr-TR"));
+    }
+
+    @After
+    public void unsetLocale() {
+        Locale.setDefault(Locale.US);
+    }
+
+    @Test
+    public void tableIds() {
+        assertThat(mTracker.mTableIdLookup.get("a"), is(0));
+        assertThat(mTracker.mTableIdLookup.get("b"), is(1));
+    }
+
+    @Test
+    public void testWeak() throws InterruptedException {
+        final AtomicInteger data = new AtomicInteger(0);
+        InvalidationTracker.Observer observer = new InvalidationTracker.Observer("a") {
+            @Override
+            public void onInvalidated(@NonNull Set<String> tables) {
+                data.incrementAndGet();
+            }
+        };
+        mTracker.addWeakObserver(observer);
+        setVersions(1, 0);
+        refreshSync();
+        assertThat(data.get(), is(1));
+        observer = null;
+        forceGc();
+        setVersions(2, 0);
+        refreshSync();
+        assertThat(data.get(), is(1));
+    }
+
+    @Test
+    public void addRemoveObserver() throws Exception {
+        InvalidationTracker.Observer observer = new LatchObserver(1, "a");
+        mTracker.addObserver(observer);
+        drainTasks();
+        assertThat(mTracker.mObserverMap.size(), is(1));
+        mTracker.removeObserver(new LatchObserver(1, "a"));
+        drainTasks();
+        assertThat(mTracker.mObserverMap.size(), is(1));
+        mTracker.removeObserver(observer);
+        drainTasks();
+        assertThat(mTracker.mObserverMap.size(), is(0));
+    }
+
+    private void drainTasks() throws InterruptedException {
+        mTaskExecutorRule.drainTasks(200);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void badObserver() {
+        InvalidationTracker.Observer observer = new LatchObserver(1, "x");
+        mTracker.addObserver(observer);
+    }
+
+    @Test
+    public void refreshReadValues() throws Exception {
+        setVersions(1, 0, 2, 1);
+        refreshSync();
+        assertThat(mTracker.mTableVersions, is(new long[]{1, 2, 0}));
+
+        setVersions(3, 1);
+        refreshSync();
+        assertThat(mTracker.mTableVersions, is(new long[]{1, 3, 0}));
+
+        setVersions(7, 0);
+        refreshSync();
+        assertThat(mTracker.mTableVersions, is(new long[]{7, 3, 0}));
+
+        refreshSync();
+        assertThat(mTracker.mTableVersions, is(new long[]{7, 3, 0}));
+    }
+
+    private void refreshSync() throws InterruptedException {
+        mTracker.refreshVersionsAsync();
+        drainTasks();
+    }
+
+    @Test
+    public void refreshCheckTasks() throws Exception {
+        when(mRoomDatabase.query(anyString(), any(Object[].class)))
+                .thenReturn(mock(Cursor.class));
+        mTracker.refreshVersionsAsync();
+        mTracker.refreshVersionsAsync();
+        verify(mTaskExecutorRule.getTaskExecutor()).executeOnDiskIO(mTracker.mRefreshRunnable);
+        drainTasks();
+
+        reset(mTaskExecutorRule.getTaskExecutor());
+        mTracker.refreshVersionsAsync();
+        verify(mTaskExecutorRule.getTaskExecutor()).executeOnDiskIO(mTracker.mRefreshRunnable);
+    }
+
+    @Test
+    public void observe1Table() throws Exception {
+        LatchObserver observer = new LatchObserver(1, "a");
+        mTracker.addObserver(observer);
+        setVersions(1, 0, 2, 1);
+        refreshSync();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables().size(), is(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("a"));
+
+        setVersions(3, 1);
+        observer.reset(1);
+        refreshSync();
+        assertThat(observer.await(), is(false));
+
+        setVersions(4, 0);
+        refreshSync();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables().size(), is(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("a"));
+    }
+
+    @Test
+    public void observe2Tables() throws Exception {
+        LatchObserver observer = new LatchObserver(1, "A", "B");
+        mTracker.addObserver(observer);
+        setVersions(1, 0, 2, 1);
+        refreshSync();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables().size(), is(2));
+        assertThat(observer.getInvalidatedTables(), hasItems("A", "B"));
+
+        setVersions(3, 1);
+        observer.reset(1);
+        refreshSync();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables().size(), is(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("B"));
+
+        setVersions(4, 0);
+        observer.reset(1);
+        refreshSync();
+        assertThat(observer.await(), is(true));
+        assertThat(observer.getInvalidatedTables().size(), is(1));
+        assertThat(observer.getInvalidatedTables(), hasItem("A"));
+
+        observer.reset(1);
+        refreshSync();
+        assertThat(observer.await(), is(false));
+    }
+
+    @Test
+    public void locale() {
+        LatchObserver observer = new LatchObserver(1, "I");
+        mTracker.addObserver(observer);
+    }
+
+    @Test
+    public void closedDb() {
+        doThrow(new IllegalStateException("foo")).when(mOpenHelper).getWritableDatabase();
+        mTracker.addObserver(new LatchObserver(1, "a", "b"));
+        mTracker.syncTriggers();
+        mTracker.mRefreshRunnable.run();
+    }
+
+    @Test
+    public void closedDbAfterOpen() throws InterruptedException {
+        setVersions(3, 1);
+        mTracker.addObserver(new LatchObserver(1, "a", "b"));
+        mTracker.syncTriggers();
+        mTracker.mRefreshRunnable.run();
+        doThrow(new SQLiteException("foo")).when(mRoomDatabase).query(
+                Mockito.eq(InvalidationTracker.SELECT_UPDATED_TABLES_SQL),
+                any(Object[].class));
+        mTracker.mPendingRefresh.set(true);
+        mTracker.mRefreshRunnable.run();
+    }
+
+    /**
+     * Key value pairs of VERSION, TABLE_ID
+     */
+    private void setVersions(int... keyValuePairs) throws InterruptedException {
+        // mockito does not like multi-threaded access so before setting versions, make sure we
+        // sync background tasks.
+        drainTasks();
+        Cursor cursor = createCursorWithValues(keyValuePairs);
+        doReturn(cursor).when(mRoomDatabase).query(
+                Mockito.eq(InvalidationTracker.SELECT_UPDATED_TABLES_SQL),
+                any(Object[].class)
+        );
+    }
+
+    private Cursor createCursorWithValues(final int... keyValuePairs) {
+        Cursor cursor = mock(Cursor.class);
+        final AtomicInteger index = new AtomicInteger(-2);
+        when(cursor.moveToNext()).thenAnswer(new Answer<Boolean>() {
+            @Override
+            public Boolean answer(InvocationOnMock invocation) throws Throwable {
+                return index.addAndGet(2) < keyValuePairs.length;
+            }
+        });
+        Answer<Integer> intAnswer = new Answer<Integer>() {
+            @Override
+            public Integer answer(InvocationOnMock invocation) throws Throwable {
+                return keyValuePairs[index.intValue() + (Integer) invocation.getArguments()[0]];
+            }
+        };
+        Answer<Long> longAnswer = new Answer<Long>() {
+            @Override
+            public Long answer(InvocationOnMock invocation) throws Throwable {
+                return (long) keyValuePairs[index.intValue()
+                        + (Integer) invocation.getArguments()[0]];
+            }
+        };
+        when(cursor.getInt(anyInt())).thenAnswer(intAnswer);
+        when(cursor.getLong(anyInt())).thenAnswer(longAnswer);
+        return cursor;
+    }
+
+    static class LatchObserver extends InvalidationTracker.Observer {
+        private CountDownLatch mLatch;
+        private Set<String> mInvalidatedTables;
+
+        LatchObserver(int count, String... tableNames) {
+            super(tableNames);
+            mLatch = new CountDownLatch(count);
+        }
+
+        boolean await() throws InterruptedException {
+            return mLatch.await(3, TimeUnit.SECONDS);
+        }
+
+        @Override
+        public void onInvalidated(@NonNull Set<String> tables) {
+            mInvalidatedTables = tables;
+            mLatch.countDown();
+        }
+
+        void reset(@SuppressWarnings("SameParameterValue") int count) {
+            mInvalidatedTables = null;
+            mLatch = new CountDownLatch(count);
+        }
+
+        Set<String> getInvalidatedTables() {
+            return mInvalidatedTables;
+        }
+    }
+
+    private static void forceGc() {
+        // Use a random index in the list to detect the garbage collection each time because
+        // .get() may accidentally trigger a strong reference during collection.
+        ArrayList<WeakReference<byte[]>> leak = new ArrayList<>();
+        do {
+            WeakReference<byte[]> arr = new WeakReference<>(new byte[100]);
+            leak.add(arr);
+        } while (leak.get((int) (Math.random() * leak.size())).get() != null);
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/ObservedTableTrackerTest.java b/room/runtime/src/test/java/android/arch/persistence/room/ObservedTableTrackerTest.java
new file mode 100644
index 0000000..ffddee9
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/ObservedTableTrackerTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+
+import static android.arch.persistence.room.InvalidationTracker.ObservedTableTracker.ADD;
+import static android.arch.persistence.room.InvalidationTracker.ObservedTableTracker.NO_OP;
+import static android.arch.persistence.room.InvalidationTracker.ObservedTableTracker.REMOVE;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.Arrays;
+
+@RunWith(JUnit4.class)
+public class ObservedTableTrackerTest {
+    private static final int TABLE_COUNT = 5;
+    private InvalidationTracker.ObservedTableTracker mTracker;
+
+    @Before
+    public void setup() {
+        mTracker = new InvalidationTracker.ObservedTableTracker(TABLE_COUNT);
+    }
+
+    @Test
+    public void basicAdd() {
+        mTracker.onAdded(2, 3);
+        assertThat(mTracker.getTablesToSync(), is(createResponse(2, ADD, 3, ADD)));
+    }
+
+    @Test
+    public void basicRemove() {
+        initState(2, 3);
+        mTracker.onRemoved(3);
+        assertThat(mTracker.getTablesToSync(), is(createResponse(3, REMOVE)));
+    }
+
+    @Test
+    public void noChange() {
+        initState(1, 3);
+        mTracker.onAdded(3);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+    }
+
+    @Test
+    public void returnNullUntilSync() {
+        initState(1, 3);
+        mTracker.onAdded(4);
+        assertThat(mTracker.getTablesToSync(), is(createResponse(4, ADD)));
+        mTracker.onAdded(0);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+        mTracker.onSyncCompleted();
+        assertThat(mTracker.getTablesToSync(), is(createResponse(0, ADD)));
+    }
+
+    @Test
+    public void multipleAdditionsDeletions() {
+        initState(2, 4);
+        mTracker.onAdded(2);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+        mTracker.onAdded(2, 4);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+        mTracker.onRemoved(2);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+        mTracker.onRemoved(2, 4);
+        assertThat(mTracker.getTablesToSync(), is(nullValue()));
+        mTracker.onAdded(1, 3);
+        mTracker.onRemoved(2, 4);
+        assertThat(mTracker.getTablesToSync(), is(
+                createResponse(1, ADD, 2, REMOVE, 3, ADD, 4, REMOVE)));
+    }
+
+    private void initState(int... tableIds) {
+        mTracker.onAdded(tableIds);
+        mTracker.getTablesToSync();
+        mTracker.onSyncCompleted();
+    }
+
+    private static int[] createResponse(int... tuples) {
+        int[] result = new int[TABLE_COUNT];
+        Arrays.fill(result, NO_OP);
+        for (int i = 0; i < tuples.length; i += 2) {
+            result[tuples[i]] = tuples[i + 1];
+        }
+        return result;
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/RoomSQLiteQueryTest.java b/room/runtime/src/test/java/android/arch/persistence/room/RoomSQLiteQueryTest.java
new file mode 100644
index 0000000..e7a8644
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/RoomSQLiteQueryTest.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import android.arch.persistence.db.SupportSQLiteProgram;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+@RunWith(JUnit4.class)
+public class RoomSQLiteQueryTest {
+    @Before
+    public void clear() {
+        RoomSQLiteQuery.sQueryPool.clear();
+    }
+
+    @Test
+    public void acquireBasic() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 3);
+        assertThat(query.getSql(), is("abc"));
+        assertThat(query.mArgCount, is(3));
+        assertThat(query.mBlobBindings.length, is(4));
+        assertThat(query.mLongBindings.length, is(4));
+        assertThat(query.mStringBindings.length, is(4));
+        assertThat(query.mDoubleBindings.length, is(4));
+    }
+
+    @Test
+    public void acquireSameSizeAgain() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 3);
+        query.release();
+        assertThat(RoomSQLiteQuery.acquire("blah", 3), sameInstance(query));
+    }
+
+    @Test
+    public void acquireSameSizeWithoutRelease() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 3);
+        assertThat(RoomSQLiteQuery.acquire("fda", 3), not(sameInstance(query)));
+    }
+
+    @Test
+    public void bindings() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 6);
+        byte[] myBlob = new byte[3];
+        long myLong = 3L;
+        double myDouble = 7.0;
+        String myString = "ss";
+        query.bindBlob(1, myBlob);
+        query.bindLong(2, myLong);
+        query.bindNull(3);
+        query.bindDouble(4, myDouble);
+        query.bindString(5, myString);
+        query.bindNull(6);
+        SupportSQLiteProgram program = mock(SupportSQLiteProgram.class);
+        query.bindTo(program);
+
+        verify(program).bindBlob(1, myBlob);
+        verify(program).bindLong(2, myLong);
+        verify(program).bindNull(3);
+        verify(program).bindDouble(4, myDouble);
+        verify(program).bindString(5, myString);
+        verify(program).bindNull(6);
+    }
+
+    @Test
+    public void dontKeepSameSizeTwice() {
+        RoomSQLiteQuery query1 = RoomSQLiteQuery.acquire("abc", 3);
+        RoomSQLiteQuery query2 = RoomSQLiteQuery.acquire("zx", 3);
+        RoomSQLiteQuery query3 = RoomSQLiteQuery.acquire("qw", 0);
+
+        query1.release();
+        query2.release();
+        assertThat(RoomSQLiteQuery.sQueryPool.size(), is(1));
+
+        query3.release();
+        assertThat(RoomSQLiteQuery.sQueryPool.size(), is(2));
+    }
+
+    @Test
+    public void returnExistingForSmallerSize() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 3);
+        query.release();
+        assertThat(RoomSQLiteQuery.acquire("dsa", 2), sameInstance(query));
+    }
+
+    @Test
+    public void returnNewForBigger() {
+        RoomSQLiteQuery query = RoomSQLiteQuery.acquire("abc", 3);
+        query.release();
+        assertThat(RoomSQLiteQuery.acquire("dsa", 4), not(sameInstance(query)));
+    }
+
+    @Test
+    public void pruneCache() {
+        for (int i = 0; i < RoomSQLiteQuery.POOL_LIMIT; i++) {
+            RoomSQLiteQuery.acquire("dsdsa", i).release();
+        }
+        pruneCacheTest();
+    }
+
+    @Test
+    public void pruneCacheReverseInsertion() {
+        List<RoomSQLiteQuery> queries = new ArrayList<>();
+        for (int i = RoomSQLiteQuery.POOL_LIMIT - 1; i >= 0; i--) {
+            queries.add(RoomSQLiteQuery.acquire("dsdsa", i));
+        }
+        for (RoomSQLiteQuery query : queries) {
+            query.release();
+        }
+        pruneCacheTest();
+    }
+
+    private void pruneCacheTest() {
+        assertThat(RoomSQLiteQuery.sQueryPool.size(), is(RoomSQLiteQuery.POOL_LIMIT));
+        RoomSQLiteQuery.acquire("dsadsa", RoomSQLiteQuery.POOL_LIMIT + 1).release();
+        assertThat(RoomSQLiteQuery.sQueryPool.size(), is(RoomSQLiteQuery.DESIRED_POOL_SIZE));
+        Iterator<RoomSQLiteQuery> itr = RoomSQLiteQuery.sQueryPool.values().iterator();
+        for (int i = 0; i < RoomSQLiteQuery.DESIRED_POOL_SIZE; i++) {
+            assertThat(itr.next().mCapacity, is(i));
+        }
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/SharedSQLiteStatementTest.java b/room/runtime/src/test/java/android/arch/persistence/room/SharedSQLiteStatementTest.java
new file mode 100644
index 0000000..4e715e9
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/SharedSQLiteStatementTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.arch.persistence.db.SupportSQLiteStatement;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+
+@RunWith(JUnit4.class)
+public class SharedSQLiteStatementTest {
+    private SharedSQLiteStatement mSharedStmt;
+    RoomDatabase mDb;
+    @Before
+    public void init() {
+        mDb = mock(RoomDatabase.class);
+        when(mDb.compileStatement(anyString())).thenAnswer(new Answer<SupportSQLiteStatement>() {
+
+            @Override
+            public SupportSQLiteStatement answer(InvocationOnMock invocation) throws Throwable {
+                return mock(SupportSQLiteStatement.class);
+            }
+        });
+        when(mDb.getInvalidationTracker()).thenReturn(mock(InvalidationTracker.class));
+        mSharedStmt = new SharedSQLiteStatement(mDb) {
+            @Override
+            protected String createQuery() {
+                return "foo";
+            }
+        };
+    }
+
+    @Test
+    public void checkMainThread() {
+        mSharedStmt.acquire();
+        verify(mDb).assertNotMainThread();
+    }
+
+    @Test
+    public void basic() {
+        assertThat(mSharedStmt.acquire(), notNullValue());
+    }
+
+    @Test
+    public void getTwiceWithoutReleasing() {
+        SupportSQLiteStatement stmt1 = mSharedStmt.acquire();
+        SupportSQLiteStatement stmt2 = mSharedStmt.acquire();
+        assertThat(stmt1, notNullValue());
+        assertThat(stmt2, notNullValue());
+        assertThat(stmt1, is(not(stmt2)));
+    }
+
+    @Test
+    public void getTwiceWithReleasing() {
+        SupportSQLiteStatement stmt1 = mSharedStmt.acquire();
+        mSharedStmt.release(stmt1);
+        SupportSQLiteStatement stmt2 = mSharedStmt.acquire();
+        assertThat(stmt1, notNullValue());
+        assertThat(stmt1, is(stmt2));
+    }
+
+    @Test
+    public void getFromAnotherThreadWhileHolding() throws ExecutionException, InterruptedException {
+        SupportSQLiteStatement stmt1 = mSharedStmt.acquire();
+        FutureTask<SupportSQLiteStatement> task = new FutureTask<>(
+                new Callable<SupportSQLiteStatement>() {
+                    @Override
+                    public SupportSQLiteStatement call() throws Exception {
+                        return mSharedStmt.acquire();
+                    }
+                });
+        new Thread(task).run();
+        SupportSQLiteStatement stmt2 = task.get();
+        assertThat(stmt1, notNullValue());
+        assertThat(stmt2, notNullValue());
+        assertThat(stmt1, is(not(stmt2)));
+    }
+
+    @Test
+    public void getFromAnotherThreadAfterReleasing() throws ExecutionException,
+            InterruptedException {
+        SupportSQLiteStatement stmt1 = mSharedStmt.acquire();
+        mSharedStmt.release(stmt1);
+        FutureTask<SupportSQLiteStatement> task = new FutureTask<>(
+                new Callable<SupportSQLiteStatement>() {
+                    @Override
+                    public SupportSQLiteStatement call() throws Exception {
+                        return mSharedStmt.acquire();
+                    }
+                });
+        new Thread(task).run();
+        SupportSQLiteStatement stmt2 = task.get();
+        assertThat(stmt1, notNullValue());
+        assertThat(stmt1, is(stmt2));
+    }
+}
diff --git a/room/runtime/src/test/java/android/arch/persistence/room/util/StringUtilTest.java b/room/runtime/src/test/java/android/arch/persistence/room/util/StringUtilTest.java
new file mode 100644
index 0000000..c10fab6
--- /dev/null
+++ b/room/runtime/src/test/java/android/arch/persistence/room/util/StringUtilTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2016 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 android.arch.persistence.room.util;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import static java.util.Arrays.asList;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.Collections;
+
+@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
+@RunWith(JUnit4.class)
+public class StringUtilTest {
+    @Test
+    public void testEmpty() {
+        assertThat(StringUtil.splitToIntList(""), is(Collections.<Integer>emptyList()));
+        assertThat(StringUtil.joinIntoString(Collections.<Integer>emptyList()), is(""));
+    }
+
+    @Test
+    public void testNull() {
+        assertThat(StringUtil.splitToIntList(null), nullValue());
+        assertThat(StringUtil.joinIntoString(null), nullValue());
+    }
+
+    @Test
+    public void testSingle() {
+        assertThat(StringUtil.splitToIntList("4"), is(asList(4)));
+        assertThat(StringUtil.joinIntoString(asList(4)), is("4"));
+    }
+
+    @Test
+    public void testMultiple() {
+        assertThat(StringUtil.splitToIntList("4,5"), is(asList(4, 5)));
+        assertThat(StringUtil.joinIntoString(asList(4, 5)), is("4,5"));
+    }
+
+    @Test
+    public void testNegative() {
+        assertThat(StringUtil.splitToIntList("-4,-5,6,-7"), is(asList(-4, -5, 6, -7)));
+        assertThat(StringUtil.joinIntoString(asList(-4, -5, 6, -7)), is("-4,-5,6,-7"));
+    }
+
+    @Test
+    public void ignoreMalformed() {
+        assertThat(StringUtil.splitToIntList("-4,a,5,7"), is(asList(-4, 5, 7)));
+    }
+}
diff --git a/room/rxjava2/build.gradle b/room/rxjava2/build.gradle
new file mode 100644
index 0000000..d7b5ceb
--- /dev/null
+++ b/room/rxjava2/build.gradle
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile project(":room:common")
+    compile project(":room:runtime")
+    compile project(":arch:runtime")
+    compile libs.support.core_utils
+    compile libs.rx_java
+    testCompile libs.junit
+    testCompile libs.mockito_core
+    testCompile project(":arch:core-testing")
+}
+
+archivesBaseName = "rxjava2"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/room/rxjava2/src/main/AndroidManifest.xml b/room/rxjava2/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..33279c6
--- /dev/null
+++ b/room/rxjava2/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.room.rxjava2">
+</manifest>
diff --git a/room/rxjava2/src/main/java/android/arch/persistence/room/EmptyResultSetException.java b/room/rxjava2/src/main/java/android/arch/persistence/room/EmptyResultSetException.java
new file mode 100644
index 0000000..0f2d281
--- /dev/null
+++ b/room/rxjava2/src/main/java/android/arch/persistence/room/EmptyResultSetException.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+/**
+ * Thrown by Room when the query needs to return a result (e.g. in a Single&lt;T> query) but the
+ * returned result set from the database is empty.
+ */
+public class EmptyResultSetException extends RuntimeException {
+    /**
+     * Constructs a new EmptyResultSetException with the exception.
+     * @param message The SQL query which didn't return any results.
+     */
+    public EmptyResultSetException(String message) {
+        super(message);
+    }
+}
diff --git a/room/rxjava2/src/main/java/android/arch/persistence/room/RxRoom.java b/room/rxjava2/src/main/java/android/arch/persistence/room/RxRoom.java
new file mode 100644
index 0000000..adfca27
--- /dev/null
+++ b/room/rxjava2/src/main/java/android/arch/persistence/room/RxRoom.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import android.arch.core.executor.AppToolkitTaskExecutor;
+import android.support.annotation.Nullable;
+import android.support.annotation.RestrictTo;
+
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import io.reactivex.BackpressureStrategy;
+import io.reactivex.Flowable;
+import io.reactivex.FlowableEmitter;
+import io.reactivex.FlowableOnSubscribe;
+import io.reactivex.Scheduler;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.disposables.Disposable;
+import io.reactivex.disposables.Disposables;
+import io.reactivex.functions.Action;
+import io.reactivex.functions.Function;
+import io.reactivex.functions.Predicate;
+
+/**
+ * Helper class to add RxJava2 support to Room.
+ */
+@SuppressWarnings("WeakerAccess")
+public class RxRoom {
+    /**
+     * Data dispatched by the publisher created by {@link #createFlowable(RoomDatabase, String...)}.
+     */
+    public static final Object NOTHING = new Object();
+
+    /**
+     * Creates a {@link Flowable} that emits at least once and also re-emits whenever one of the
+     * observed tables is updated.
+     * <p>
+     * You can easily chain a database operation to downstream of this {@link Flowable} to ensure
+     * that it re-runs when database is modified.
+     * <p>
+     * Since database invalidation is batched, multiple changes in the database may results in just
+     * 1 emission.
+     *
+     * @param database   The database instance
+     * @param tableNames The list of table names that should be observed
+     * @return A {@link Flowable} which emits {@link #NOTHING} when one of the observed tables
+     * is modified (also once when the invalidation tracker connection is established).
+     */
+    public static Flowable<Object> createFlowable(final RoomDatabase database,
+            final String... tableNames) {
+        return Flowable.create(new FlowableOnSubscribe<Object>() {
+            @Override
+            public void subscribe(final FlowableEmitter<Object> emitter) throws Exception {
+                final InvalidationTracker.Observer observer = new InvalidationTracker.Observer(
+                        tableNames) {
+                    @Override
+                    public void onInvalidated(
+                            @android.support.annotation.NonNull Set<String> tables) {
+                        if (!emitter.isCancelled()) {
+                            emitter.onNext(NOTHING);
+                        }
+                    }
+                };
+                if (!emitter.isCancelled()) {
+                    database.getInvalidationTracker().addObserver(observer);
+                    emitter.setDisposable(Disposables.fromAction(new Action() {
+                        @Override
+                        public void run() throws Exception {
+                            database.getInvalidationTracker().removeObserver(observer);
+                        }
+                    }));
+                }
+
+                // emit once to avoid missing any data and also easy chaining
+                if (!emitter.isCancelled()) {
+                    emitter.onNext(NOTHING);
+                }
+            }
+        }, BackpressureStrategy.LATEST);
+    }
+
+    /**
+     * Helper method used by generated code to bind a Callable such that it will be run in
+     * our disk io thread and will automatically block null values since RxJava2 does not like null.
+     *
+     * @hide
+     */
+    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+    public static <T> Flowable<T> createFlowable(final RoomDatabase database,
+            final String[] tableNames, final Callable<T> callable) {
+        return createFlowable(database, tableNames).observeOn(sAppToolkitIOScheduler)
+                .map(new Function<Object, Optional<T>>() {
+                    @Override
+                    public Optional<T> apply(@NonNull Object o) throws Exception {
+                        T data = callable.call();
+                        return new Optional<>(data);
+                    }
+                }).filter(new Predicate<Optional<T>>() {
+                    @Override
+                    public boolean test(@NonNull Optional<T> optional) throws Exception {
+                        return optional.mValue != null;
+                    }
+                }).map(new Function<Optional<T>, T>() {
+                    @Override
+                    public T apply(@NonNull Optional<T> optional) throws Exception {
+                        return optional.mValue;
+                    }
+                });
+    }
+
+    private static Scheduler sAppToolkitIOScheduler = new Scheduler() {
+        @Override
+        public Worker createWorker() {
+            final AtomicBoolean mDisposed = new AtomicBoolean(false);
+            return new Worker() {
+                @Override
+                public Disposable schedule(@NonNull Runnable run, long delay,
+                        @NonNull TimeUnit unit) {
+                    DisposableRunnable disposable = new DisposableRunnable(run, mDisposed);
+                    AppToolkitTaskExecutor.getInstance().executeOnDiskIO(run);
+                    return disposable;
+                }
+
+                @Override
+                public void dispose() {
+                    mDisposed.set(true);
+                }
+
+                @Override
+                public boolean isDisposed() {
+                    return mDisposed.get();
+                }
+            };
+        }
+    };
+
+    private static class DisposableRunnable implements Disposable, Runnable {
+        private final Runnable mActual;
+        private volatile boolean mDisposed = false;
+        private final AtomicBoolean mGlobalDisposed;
+
+        DisposableRunnable(Runnable actual, AtomicBoolean globalDisposed) {
+            mActual = actual;
+            mGlobalDisposed = globalDisposed;
+        }
+
+        @Override
+        public void dispose() {
+            mDisposed = true;
+        }
+
+        @Override
+        public boolean isDisposed() {
+            return mDisposed || mGlobalDisposed.get();
+        }
+
+        @Override
+        public void run() {
+            if (!isDisposed()) {
+                mActual.run();
+            }
+        }
+    }
+
+    static class Optional<T> {
+        @Nullable
+        final T mValue;
+
+        Optional(@Nullable T value) {
+            this.mValue = value;
+        }
+    }
+}
diff --git a/room/rxjava2/src/test/java/android/arch/persistence/room/RxRoomTest.java b/room/rxjava2/src/test/java/android/arch/persistence/room/RxRoomTest.java
new file mode 100644
index 0000000..502eaa1
--- /dev/null
+++ b/room/rxjava2/src/test/java/android/arch/persistence/room/RxRoomTest.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.arch.core.executor.JunitTaskExecutorRule;
+
+import org.hamcrest.CoreMatchers;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
+
+import io.reactivex.Flowable;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.disposables.Disposable;
+import io.reactivex.functions.Consumer;
+import io.reactivex.subscribers.TestSubscriber;
+
+@RunWith(JUnit4.class)
+public class RxRoomTest {
+    @Rule
+    public JunitTaskExecutorRule mExecutor = new JunitTaskExecutorRule(1, false);
+    private RoomDatabase mDatabase;
+    private InvalidationTracker mInvalidationTracker;
+    private List<InvalidationTracker.Observer> mAddedObservers = new ArrayList<>();
+
+    @Before
+    public void init() {
+        mDatabase = mock(RoomDatabase.class);
+        mInvalidationTracker = mock(InvalidationTracker.class);
+        when(mDatabase.getInvalidationTracker()).thenReturn(mInvalidationTracker);
+        doAnswer(new Answer() {
+            @Override
+            public Object answer(InvocationOnMock invocation) throws Throwable {
+                mAddedObservers.add((InvalidationTracker.Observer) invocation.getArguments()[0]);
+                return null;
+            }
+        }).when(mInvalidationTracker).addObserver(any(InvalidationTracker.Observer.class));
+    }
+
+    @Test
+    public void basicAddRemove() {
+        Flowable<Object> flowable = RxRoom.createFlowable(mDatabase, "a", "b");
+        verify(mInvalidationTracker, never()).addObserver(any(InvalidationTracker.Observer.class));
+        Disposable disposable = flowable.subscribe();
+        verify(mInvalidationTracker).addObserver(any(InvalidationTracker.Observer.class));
+        assertThat(mAddedObservers.size(), CoreMatchers.is(1));
+
+        InvalidationTracker.Observer observer = mAddedObservers.get(0);
+        disposable.dispose();
+
+        verify(mInvalidationTracker).removeObserver(observer);
+
+        disposable = flowable.subscribe();
+        verify(mInvalidationTracker, times(2))
+                .addObserver(any(InvalidationTracker.Observer.class));
+        assertThat(mAddedObservers.size(), CoreMatchers.is(2));
+        assertThat(mAddedObservers.get(1), CoreMatchers.not(CoreMatchers.sameInstance(observer)));
+        InvalidationTracker.Observer observer2 = mAddedObservers.get(1);
+        disposable.dispose();
+        verify(mInvalidationTracker).removeObserver(observer2);
+    }
+
+    @Test
+    public void basicNotify() throws InterruptedException {
+        String[] tables = {"a", "b"};
+        Set<String> tableSet = new HashSet<>(Arrays.asList(tables));
+        Flowable<Object> flowable = RxRoom.createFlowable(mDatabase, tables);
+        CountingConsumer consumer = new CountingConsumer();
+        Disposable disposable = flowable.subscribe(consumer);
+        assertThat(mAddedObservers.size(), CoreMatchers.is(1));
+        InvalidationTracker.Observer observer = mAddedObservers.get(0);
+        assertThat(consumer.mCount, CoreMatchers.is(1));
+        observer.onInvalidated(tableSet);
+        assertThat(consumer.mCount, CoreMatchers.is(2));
+        observer.onInvalidated(tableSet);
+        assertThat(consumer.mCount, CoreMatchers.is(3));
+        disposable.dispose();
+        observer.onInvalidated(tableSet);
+        assertThat(consumer.mCount, CoreMatchers.is(3));
+    }
+
+    @Test
+    public void internalCallable() throws InterruptedException {
+        final AtomicReference<String> value = new AtomicReference<>(null);
+        String[] tables = {"a", "b"};
+        Set<String> tableSet = new HashSet<>(Arrays.asList(tables));
+        final Flowable<String> flowable = RxRoom.createFlowable(mDatabase, tables,
+                new Callable<String>() {
+                    @Override
+                    public String call() throws Exception {
+                        return value.get();
+                    }
+                });
+        final CountingConsumer consumer = new CountingConsumer();
+        flowable.subscribe(consumer);
+        InvalidationTracker.Observer observer = mAddedObservers.get(0);
+        drain();
+        // no value because it is null
+        assertThat(consumer.mCount, CoreMatchers.is(0));
+        value.set("bla");
+        observer.onInvalidated(tableSet);
+        drain();
+        // get value
+        assertThat(consumer.mCount, CoreMatchers.is(1));
+        observer.onInvalidated(tableSet);
+        drain();
+        // get value
+        assertThat(consumer.mCount, CoreMatchers.is(2));
+        value.set(null);
+        observer.onInvalidated(tableSet);
+        drain();
+        // no value
+        assertThat(consumer.mCount, CoreMatchers.is(2));
+    }
+
+    private void drain() throws InterruptedException {
+        mExecutor.drainTasks(2);
+    }
+
+    @Test
+    public void exception() throws InterruptedException {
+        final Flowable<String> flowable = RxRoom.createFlowable(mDatabase, new String[]{"a"},
+                new Callable<String>() {
+                    @Override
+                    public String call() throws Exception {
+                        throw new Exception("i want exception");
+                    }
+                });
+        TestSubscriber<String> subscriber = new TestSubscriber<>();
+        flowable.subscribe(subscriber);
+        drain();
+        assertThat(subscriber.errorCount(), CoreMatchers.is(1));
+        assertThat(subscriber.errors().get(0).getMessage(), CoreMatchers.is("i want exception"));
+    }
+
+    private static class CountingConsumer implements Consumer<Object> {
+        int mCount = 0;
+
+        @Override
+        public void accept(@NonNull Object o) throws Exception {
+            mCount++;
+        }
+    }
+}
diff --git a/room/testing/build.gradle b/room/testing/build.gradle
new file mode 100644
index 0000000..d378d84
--- /dev/null
+++ b/room/testing/build.gradle
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+import com.android.builder.core.BuilderConstants
+apply plugin: 'com.android.library'
+apply plugin: 'maven'
+
+android {
+    compileSdkVersion tools.current_sdk
+    buildToolsVersion tools.build_tools_version
+
+    defaultConfig {
+        minSdkVersion flatfoot.min_sdk
+        targetSdkVersion tools.current_sdk
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+    testOptions {
+        unitTests.returnDefaultValues = true
+    }
+    compileOptions {
+        sourceCompatibility JavaVersion.VERSION_1_7
+        targetCompatibility JavaVersion.VERSION_1_7
+    }
+}
+
+dependencies {
+    compile project(":room:common")
+    compile project(":room:runtime")
+    compile project(":room:db")
+    compile project(":room:db-impl")
+    compile project(":room:migration")
+    compile project(":arch:runtime")
+    compile libs.support.core_utils
+    compile libs.junit
+}
+
+archivesBaseName = "testing"
+
+createAndroidCheckstyle(project)
+
+android.libraryVariants.all { variant ->
+    def name = variant.buildType.name
+    def suffix = name.capitalize()
+    project.tasks.create(name: "jar${suffix}", type: Jar){
+        dependsOn variant.javaCompile
+        from variant.javaCompile.destinationDir
+        destinationDir new File(project.buildDir, "libJar")
+    }
+}
diff --git a/room/testing/src/main/AndroidManifest.xml b/room/testing/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..594f016
--- /dev/null
+++ b/room/testing/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.arch.persistence.room.testing">
+</manifest>
diff --git a/room/testing/src/main/java/android/arch/persistence/room/testing/MigrationTestHelper.java b/room/testing/src/main/java/android/arch/persistence/room/testing/MigrationTestHelper.java
new file mode 100644
index 0000000..aea3e96
--- /dev/null
+++ b/room/testing/src/main/java/android/arch/persistence/room/testing/MigrationTestHelper.java
@@ -0,0 +1,420 @@
+/*
+ * Copyright (C) 2017 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 android.arch.persistence.room.testing;
+
+import android.app.Instrumentation;
+import android.arch.persistence.db.SupportSQLiteDatabase;
+import android.arch.persistence.db.SupportSQLiteOpenHelper;
+import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;
+import android.arch.persistence.room.DatabaseConfiguration;
+import android.arch.persistence.room.Room;
+import android.arch.persistence.room.RoomDatabase;
+import android.arch.persistence.room.RoomOpenHelper;
+import android.arch.persistence.room.migration.Migration;
+import android.arch.persistence.room.migration.bundle.DatabaseBundle;
+import android.arch.persistence.room.migration.bundle.EntityBundle;
+import android.arch.persistence.room.migration.bundle.FieldBundle;
+import android.arch.persistence.room.migration.bundle.ForeignKeyBundle;
+import android.arch.persistence.room.migration.bundle.SchemaBundle;
+import android.arch.persistence.room.util.TableInfo;
+import android.content.Context;
+import android.database.Cursor;
+import android.util.Log;
+
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A class that can be used in your Instrumentation tests that can create the database in an
+ * older schema.
+ * <p>
+ * You must copy the schema json files (created by passing {@code room.schemaLocation} argument
+ * into the annotation processor) into your test assets and pass in the path for that folder into
+ * the constructor. This class will read the folder and extract the schemas from there.
+ * <pre>
+ * android {
+ *   defaultConfig {
+ *     javaCompileOptions {
+ *       annotationProcessorOptions {
+ *         arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
+ *       }
+ *     }
+ *   }
+ *   sourceSets {
+ *     androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
+ *   }
+ * }
+ * </pre>
+ */
+public class MigrationTestHelper extends TestWatcher {
+    private static final String TAG = "MigrationTestHelper";
+    private final String mAssetsFolder;
+    private final SupportSQLiteOpenHelper.Factory mOpenFactory;
+    private List<WeakReference<SupportSQLiteDatabase>> mManagedDatabases = new ArrayList<>();
+    private List<WeakReference<RoomDatabase>> mManagedRoomDatabases = new ArrayList<>();
+    private boolean mTestStarted;
+    private Instrumentation mInstrumentation;
+
+    /**
+     * Creates a new migration helper. It uses the Instrumentation context to load the schema
+     * (falls back to the app resources) and the target context to create the database.
+     *
+     * @param instrumentation The instrumentation instance.
+     * @param assetsFolder    The asset folder in the assets directory.
+     */
+    public MigrationTestHelper(Instrumentation instrumentation, String assetsFolder) {
+        this(instrumentation, assetsFolder, new FrameworkSQLiteOpenHelperFactory());
+    }
+
+    /**
+     * Creates a new migration helper. It uses the Instrumentation context to load the schema
+     * (falls back to the app resources) and the target context to create the database.
+     *
+     * @param instrumentation The instrumentation instance.
+     * @param assetsFolder    The asset folder in the assets directory.
+     * @param openFactory     Factory class that allows creation of {@link SupportSQLiteOpenHelper}
+     */
+    public MigrationTestHelper(Instrumentation instrumentation, String assetsFolder,
+            SupportSQLiteOpenHelper.Factory openFactory) {
+        mInstrumentation = instrumentation;
+        if (assetsFolder.endsWith("/")) {
+            assetsFolder = assetsFolder.substring(0, assetsFolder.length() - 1);
+        }
+        mAssetsFolder = assetsFolder;
+        mOpenFactory = openFactory;
+    }
+
+    @Override
+    protected void starting(Description description) {
+        super.starting(description);
+        mTestStarted = true;
+    }
+
+    /**
+     * Creates the database in the given version.
+     * If the database file already exists, it tries to delete it first. If delete fails, throws
+     * an exception.
+     *
+     * @param name    The name of the database.
+     * @param version The version in which the database should be created.
+     * @return A database connection which has the schema in the requested version.
+     * @throws IOException If it cannot find the schema description in the assets folder.
+     */
+    @SuppressWarnings("SameParameterValue")
+    public SupportSQLiteDatabase createDatabase(String name, int version) throws IOException {
+        File dbPath = mInstrumentation.getTargetContext().getDatabasePath(name);
+        if (dbPath.exists()) {
+            Log.d(TAG, "deleting database file " + name);
+            if (!dbPath.delete()) {
+                throw new IllegalStateException("there is a database file and i could not delete"
+                        + " it. Make sure you don't have any open connections to that database"
+                        + " before calling this method.");
+            }
+        }
+        SchemaBundle schemaBundle = loadSchema(version);
+        RoomDatabase.MigrationContainer container = new RoomDatabase.MigrationContainer();
+        DatabaseConfiguration configuration = new DatabaseConfiguration(
+                mInstrumentation.getTargetContext(), name, mOpenFactory, container, null, true,
+                true);
+        RoomOpenHelper roomOpenHelper = new RoomOpenHelper(configuration,
+                new CreatingDelegate(schemaBundle.getDatabase()),
+                schemaBundle.getDatabase().getIdentityHash());
+        return openDatabase(name, version, roomOpenHelper);
+    }
+
+    /**
+     * Runs the given set of migrations on the provided database.
+     * <p>
+     * It uses the same algorithm that Room uses to choose migrations so the migrations instances
+     * that are provided to this method must be sufficient to bring the database from current
+     * version to the desired version.
+     * <p>
+     * After the migration, the method validates the database schema to ensure that migration
+     * result matches the expected schema. Handling of dropped tables depends on the
+     * {@code validateDroppedTables} argument. If set to true, the verification will fail if it
+     * finds a table that is not registered in the Database. If set to false, extra tables in the
+     * database will be ignored (this is the runtime library behavior).
+     *
+     * @param name                  The database name. You must first create this database via
+     *                              {@link #createDatabase(String, int)}.
+     * @param version               The final version after applying the migrations.
+     * @param validateDroppedTables If set to true, validation will fail if the database has
+     *                              unknown
+     *                              tables.
+     * @param migrations            The list of available migrations.
+     * @throws IOException           If it cannot find the schema for {@code toVersion}.
+     * @throws IllegalStateException If the schema validation fails.
+     */
+    public SupportSQLiteDatabase runMigrationsAndValidate(String name, int version,
+            boolean validateDroppedTables, Migration... migrations) throws IOException {
+        File dbPath = mInstrumentation.getTargetContext().getDatabasePath(name);
+        if (!dbPath.exists()) {
+            throw new IllegalStateException("Cannot find the database file for " + name + ". "
+                    + "Before calling runMigrations, you must first create the database via "
+                    + "createDatabase.");
+        }
+        SchemaBundle schemaBundle = loadSchema(version);
+        RoomDatabase.MigrationContainer container = new RoomDatabase.MigrationContainer();
+        container.addMigrations(migrations);
+        DatabaseConfiguration configuration = new DatabaseConfiguration(
+                mInstrumentation.getTargetContext(), name, mOpenFactory, container, null, true,
+                true);
+        RoomOpenHelper roomOpenHelper = new RoomOpenHelper(configuration,
+                new MigratingDelegate(schemaBundle.getDatabase(), validateDroppedTables),
+                schemaBundle.getDatabase().getIdentityHash());
+        return openDatabase(name, version, roomOpenHelper);
+    }
+
+    private SupportSQLiteDatabase openDatabase(String name, int version,
+            RoomOpenHelper roomOpenHelper) {
+        SupportSQLiteOpenHelper.Configuration config =
+                SupportSQLiteOpenHelper.Configuration
+                        .builder(mInstrumentation.getTargetContext())
+                        .callback(roomOpenHelper)
+                        .name(name)
+                        .version(version)
+                        .build();
+        SupportSQLiteDatabase db = mOpenFactory.create(config).getWritableDatabase();
+        mManagedDatabases.add(new WeakReference<>(db));
+        return db;
+    }
+
+    @Override
+    protected void finished(Description description) {
+        super.finished(description);
+        for (WeakReference<SupportSQLiteDatabase> dbRef : mManagedDatabases) {
+            SupportSQLiteDatabase db = dbRef.get();
+            if (db != null && db.isOpen()) {
+                try {
+                    db.close();
+                } catch (Throwable ignored) {
+                }
+            }
+        }
+        for (WeakReference<RoomDatabase> dbRef : mManagedRoomDatabases) {
+            final RoomDatabase roomDatabase = dbRef.get();
+            if (roomDatabase != null) {
+                roomDatabase.close();
+            }
+        }
+    }
+
+    /**
+     * Registers a database connection to be automatically closed when the test finishes.
+     * <p>
+     * This only works if {@code MigrationTestHelper} is registered as a Junit test rule via
+     * {@link org.junit.Rule Rule} annotation.
+     *
+     * @param db The database connection that should be closed after the test finishes.
+     */
+    public void closeWhenFinished(SupportSQLiteDatabase db) {
+        if (!mTestStarted) {
+            throw new IllegalStateException("You cannot register a database to be closed before"
+                    + " the test starts. Maybe you forgot to annotate MigrationTestHelper as a"
+                    + " test rule? (@Rule)");
+        }
+        mManagedDatabases.add(new WeakReference<>(db));
+    }
+
+    /**
+     * Registers a database connection to be automatically closed when the test finishes.
+     * <p>
+     * This only works if {@code MigrationTestHelper} is registered as a Junit test rule via
+     * {@link org.junit.Rule Rule} annotation.
+     *
+     * @param db The RoomDatabase instance which holds the database.
+     */
+    public void closeWhenFinished(RoomDatabase db) {
+        if (!mTestStarted) {
+            throw new IllegalStateException("You cannot register a database to be closed before"
+                    + " the test starts. Maybe you forgot to annotate MigrationTestHelper as a"
+                    + " test rule? (@Rule)");
+        }
+        mManagedRoomDatabases.add(new WeakReference<>(db));
+    }
+
+    private SchemaBundle loadSchema(int version) throws IOException {
+        try {
+            return loadSchema(mInstrumentation.getContext(), version);
+        } catch (FileNotFoundException testAssetsIOExceptions) {
+            Log.w(TAG, "Could not find the schema file in the test assets. Checking the"
+                    + " application assets");
+            try {
+                return loadSchema(mInstrumentation.getTargetContext(), version);
+            } catch (FileNotFoundException appAssetsException) {
+                // throw the test assets exception instead
+                throw new FileNotFoundException("Cannot find the schema file in the assets folder. "
+                        + "Make sure to include the exported json schemas in your test assert "
+                        + "inputs. See "
+                        + "https://developer.android.com/topic/libraries/architecture/"
+                        + "room.html#db-migration-testing for details. Missing file: "
+                        + testAssetsIOExceptions.getMessage());
+            }
+        }
+    }
+
+    private SchemaBundle loadSchema(Context context, int version) throws IOException {
+        InputStream input = context.getAssets().open(mAssetsFolder + "/" + version + ".json");
+        return SchemaBundle.deserialize(input);
+    }
+
+    private static TableInfo toTableInfo(EntityBundle entityBundle) {
+        return new TableInfo(entityBundle.getTableName(), toColumnMap(entityBundle),
+                toForeignKeys(entityBundle.getForeignKeys()));
+    }
+
+    private static Set<TableInfo.ForeignKey> toForeignKeys(
+            List<ForeignKeyBundle> bundles) {
+        if (bundles == null) {
+            return Collections.emptySet();
+        }
+        Set<TableInfo.ForeignKey> result = new HashSet<>(bundles.size());
+        for (ForeignKeyBundle bundle : bundles) {
+            result.add(new TableInfo.ForeignKey(bundle.getTable(),
+                    bundle.getOnDelete(), bundle.getOnUpdate(),
+                    bundle.getColumns(), bundle.getReferencedColumns()));
+        }
+        return result;
+    }
+
+    private static Map<String, TableInfo.Column> toColumnMap(EntityBundle entity) {
+        Map<String, TableInfo.Column> result = new HashMap<>();
+        for (FieldBundle bundle : entity.getFields()) {
+            TableInfo.Column column = toColumn(entity, bundle);
+            result.put(column.name, column);
+        }
+        return result;
+    }
+
+    private static TableInfo.Column toColumn(EntityBundle entity, FieldBundle field) {
+        return new TableInfo.Column(field.getColumnName(), field.getAffinity(),
+                field.isNonNull(), findPrimaryKeyPosition(entity, field));
+    }
+
+    private static int findPrimaryKeyPosition(EntityBundle entity, FieldBundle field) {
+        List<String> columnNames = entity.getPrimaryKey().getColumnNames();
+        int i = 0;
+        for (String columnName : columnNames) {
+            i++;
+            if (field.getColumnName().equalsIgnoreCase(columnName)) {
+                return i;
+            }
+        }
+        return 0;
+    }
+
+    class MigratingDelegate extends RoomOpenHelperDelegate {
+        private final boolean mVerifyDroppedTables;
+
+        MigratingDelegate(DatabaseBundle databaseBundle, boolean verifyDroppedTables) {
+            super(databaseBundle);
+            mVerifyDroppedTables = verifyDroppedTables;
+        }
+
+        @Override
+        protected void createAllTables(SupportSQLiteDatabase database) {
+            throw new UnsupportedOperationException("Was expecting to migrate but received create."
+                    + "Make sure you have created the database first.");
+        }
+
+        @Override
+        protected void validateMigration(SupportSQLiteDatabase db) {
+            final Map<String, EntityBundle> tables = mDatabaseBundle.getEntitiesByTableName();
+            for (EntityBundle entity : tables.values()) {
+                final TableInfo expected = toTableInfo(entity);
+                final TableInfo found = TableInfo.read(db, entity.getTableName());
+                if (!expected.equals(found)) {
+                    throw new IllegalStateException(
+                            "Migration failed. expected:" + expected + " , found:" + found);
+                }
+            }
+            if (mVerifyDroppedTables) {
+                // now ensure tables that should be removed are removed.
+                Cursor cursor = db.query("SELECT name FROM sqlite_master WHERE type='table'"
+                                + " AND name NOT IN(?, ?, ?)",
+                        new String[]{Room.MASTER_TABLE_NAME, "android_metadata",
+                                "sqlite_sequence"});
+                //noinspection TryFinallyCanBeTryWithResources
+                try {
+                    while (cursor.moveToNext()) {
+                        final String tableName = cursor.getString(0);
+                        if (!tables.containsKey(tableName)) {
+                            throw new IllegalStateException("Migration failed. Unexpected table "
+                                    + tableName);
+                        }
+                    }
+                } finally {
+                    cursor.close();
+                }
+            }
+        }
+    }
+
+    static class CreatingDelegate extends RoomOpenHelperDelegate {
+
+        CreatingDelegate(DatabaseBundle databaseBundle) {
+            super(databaseBundle);
+        }
+
+        @Override
+        protected void createAllTables(SupportSQLiteDatabase database) {
+            for (String query : mDatabaseBundle.buildCreateQueries()) {
+                database.execSQL(query);
+            }
+        }
+
+        @Override
+        protected void validateMigration(SupportSQLiteDatabase db) {
+            throw new UnsupportedOperationException("This open helper just creates the database but"
+                    + " it received a migration request.");
+        }
+    }
+
+    abstract static class RoomOpenHelperDelegate extends RoomOpenHelper.Delegate {
+        final DatabaseBundle mDatabaseBundle;
+
+        RoomOpenHelperDelegate(DatabaseBundle databaseBundle) {
+            mDatabaseBundle = databaseBundle;
+        }
+
+        @Override
+        protected void dropAllTables(SupportSQLiteDatabase database) {
+            throw new UnsupportedOperationException("cannot drop all tables in the test");
+        }
+
+        @Override
+        protected void onCreate(SupportSQLiteDatabase database) {
+        }
+
+        @Override
+        protected void onOpen(SupportSQLiteDatabase database) {
+        }
+    }
+}
diff --git a/samples/Support13Demos/AndroidManifest.xml b/samples/Support13Demos/AndroidManifest.xml
index cdc246f..af7fad2 100644
--- a/samples/Support13Demos/AndroidManifest.xml
+++ b/samples/Support13Demos/AndroidManifest.xml
@@ -24,8 +24,6 @@
 
     <uses-permission android:name="android.permission.READ_CONTACTS" />
 
-    <uses-sdk android:minSdkVersion="14" />
-
     <!-- The smallest screen this app works on is a phone.  The app will
          scale its UI to larger screens but doesn't make good use of them
          so allow the compatibility mode button to be shown (mostly because
diff --git a/samples/Support13Demos/build.gradle b/samples/Support13Demos/build.gradle
index aa64333..4c015ae 100644
--- a/samples/Support13Demos/build.gradle
+++ b/samples/Support13Demos/build.gradle
@@ -1,7 +1,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-v13')
+    implementation project(':support-v13')
 }
 
 android {
@@ -9,6 +9,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -21,6 +22,7 @@
     lintOptions {
         checkReleaseBuilds false
         abortOnError false
+        check 'NewApi'
     }
 
     signingConfigs {
diff --git a/samples/Support4Demos/AndroidManifest.xml b/samples/Support4Demos/AndroidManifest.xml
index 893259c..812d4e8 100644
--- a/samples/Support4Demos/AndroidManifest.xml
+++ b/samples/Support4Demos/AndroidManifest.xml
@@ -26,8 +26,6 @@
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
 
-    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="22" />
-
     <!-- The smallest screen this app works on is a phone.  The app will
          scale its UI to larger screens but doesn't make good use of them
          so allow the compatibility mode button to be shown (mostly because
@@ -51,7 +49,7 @@
         <activity android:name=".app.SendResult"
                 android:theme="@style/ThemeDialogWhenLarge">
         </activity>
-        
+
         <!-- Fragment Support Samples -->
 
         <activity android:name=".app.FragmentAlertDialogSupport"
@@ -144,7 +142,7 @@
                 <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
             </intent-filter>
         </activity>
-        
+
         <activity android:name=".app.FragmentRetainInstanceSupport"
                 android:label="@string/fragment_retain_instance_support">
             <intent-filter>
@@ -216,7 +214,7 @@
                 <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
             </intent-filter>
         </activity>
-        
+
         <activity android:name=".app.LoaderCustomSupport"
                 android:label="@string/loader_custom_support">
             <intent-filter>
diff --git a/samples/Support4Demos/build.gradle b/samples/Support4Demos/build.gradle
index b6bbcec..e265698 100644
--- a/samples/Support4Demos/build.gradle
+++ b/samples/Support4Demos/build.gradle
@@ -1,7 +1,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-v4')
+    implementation project(':support-v4')
 }
 
 android {
@@ -9,6 +9,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -28,6 +29,7 @@
     lintOptions {
         checkReleaseBuilds false
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/Support4Demos/src/com/example/android/supportv4/accessibility/AccessibilityManagerSupportActivity.java b/samples/Support4Demos/src/com/example/android/supportv4/accessibility/AccessibilityManagerSupportActivity.java
index 4ffc0ef..061ed21 100644
--- a/samples/Support4Demos/src/com/example/android/supportv4/accessibility/AccessibilityManagerSupportActivity.java
+++ b/samples/Support4Demos/src/com/example/android/supportv4/accessibility/AccessibilityManagerSupportActivity.java
@@ -22,7 +22,6 @@
 import android.content.pm.ResolveInfo;
 import android.os.Bundle;
 import android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat;
-import android.support.v4.view.accessibility.AccessibilityManagerCompat;
 import android.view.accessibility.AccessibilityManager;
 import android.widget.TextView;
 import android.widget.Toast;
@@ -79,20 +78,16 @@
      * when the global accessibility state on the device changes.
      */
     private void registerAccessibilityStateChangeListener() {
-        // The AccessibilityStateChange listener APIs were added in ICS. Therefore to be
-        // backwards compatible we use the APIs in the support library. Note that if the
-        // platform API version is lower and the called API is not available no listener
-        // is added and you will not receive a call of onAccessibilityStateChanged.
-        AccessibilityManagerCompat.addAccessibilityStateChangeListener(mAccessibilityManager,
-                new AccessibilityManagerCompat.AccessibilityStateChangeListener() {
-            @Override
-            public void onAccessibilityStateChanged(boolean enabled) {
-                Toast.makeText(AccessibilityManagerSupportActivity.this,
-                        getString(R.string.accessibility_manager_accessibility_state,
-                                Boolean.toString(enabled)),
-                        Toast.LENGTH_SHORT).show();
-            }
-        });
+        mAccessibilityManager.addAccessibilityStateChangeListener(
+                new AccessibilityManager.AccessibilityStateChangeListener() {
+                    @Override
+                    public void onAccessibilityStateChanged(boolean enabled) {
+                        Toast.makeText(AccessibilityManagerSupportActivity.this,
+                                getString(R.string.accessibility_manager_accessibility_state,
+                                        Boolean.toString(enabled)),
+                                Toast.LENGTH_SHORT).show();
+                    }
+                });
     }
 
     /**
@@ -100,13 +95,9 @@
      * accessibility services.
      */
     private void updateAccessibilityStateView() {
-        // The API for getting the enabled accessibility services based on feedback
-        // type was added in ICS. Therefore to be backwards compatible we use the
-        // APIs in the support library. Note that if the platform API version is lower
-        // and the called API is not available an empty list of services is returned.
         List<AccessibilityServiceInfo> enabledServices =
-            AccessibilityManagerCompat.getEnabledAccessibilityServiceList(mAccessibilityManager,
-                    AccessibilityServiceInfo.FEEDBACK_SPOKEN);
+                mAccessibilityManager.getEnabledAccessibilityServiceList(
+                        AccessibilityServiceInfo.FEEDBACK_SPOKEN);
         if (!enabledServices.isEmpty()) {
             StringBuilder builder = new StringBuilder();
             final int enabledServiceCount = enabledServices.size();
diff --git a/samples/Support7Demos/AndroidManifest.xml b/samples/Support7Demos/AndroidManifest.xml
index 25b2427..1604267 100644
--- a/samples/Support7Demos/AndroidManifest.xml
+++ b/samples/Support7Demos/AndroidManifest.xml
@@ -34,8 +34,6 @@
     <!-- Permission for ACCESS_COARSE_LOCATION is required for DayNight themes. -->
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 
-    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="21" />
-
     <!-- The smallest screen this app works on is a phone.  The app will
          scale its UI to larger screens but doesn't make good use of them
          so allow the compatibility mode button to be shown (mostly because
diff --git a/samples/Support7Demos/build.gradle b/samples/Support7Demos/build.gradle
index 2873794..49b38ec 100644
--- a/samples/Support7Demos/build.gradle
+++ b/samples/Support7Demos/build.gradle
@@ -1,12 +1,12 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-appcompat-v7')
-    compile project(':support-cardview-v7')
-    compile project(':support-gridlayout-v7')
-    compile project(':support-mediarouter-v7')
-    compile project(':support-palette-v7')
-    compile project(':support-recyclerview-v7')
+    implementation project(':support-appcompat-v7')
+    implementation project(':support-cardview-v7')
+    implementation project(':support-gridlayout-v7')
+    implementation project(':support-mediarouter-v7')
+    implementation project(':support-palette-v7')
+    implementation project(':support-recyclerview-v7')
 }
 
 android {
@@ -14,6 +14,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
         vectorDrawables.useSupportLibrary = true
     }
 
@@ -33,6 +34,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/Support7Demos/src/com/example/android/supportv7/media/OverlayDisplayWindow.java b/samples/Support7Demos/src/com/example/android/supportv7/media/OverlayDisplayWindow.java
index 6558f86..d6a82ef 100644
--- a/samples/Support7Demos/src/com/example/android/supportv7/media/OverlayDisplayWindow.java
+++ b/samples/Support7Demos/src/com/example/android/supportv7/media/OverlayDisplayWindow.java
@@ -126,8 +126,15 @@
 
                 Display display = mWindowManager.getDefaultDisplay();
 
-                WindowManager.LayoutParams params = new WindowManager.LayoutParams(
-                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+                WindowManager.LayoutParams params;
+                if (Build.VERSION.SDK_INT >= 26) {
+                    // TYPE_SYSTEM_ALERT is deprecated in android O.
+                    params = new WindowManager.LayoutParams(
+                            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
+                } else {
+                    params = new WindowManager.LayoutParams(
+                            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+                }
                 params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                         | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                         | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
@@ -298,8 +305,14 @@
                     R.id.overlay_display_window_title);
             mNameTextView.setText(mName);
 
-            mWindowParams = new WindowManager.LayoutParams(
-                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+            if (Build.VERSION.SDK_INT >= 26) {
+                // TYPE_SYSTEM_ALERT is deprecated in android O.
+                mWindowParams = new WindowManager.LayoutParams(
+                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
+            } else {
+                mWindowParams = new WindowManager.LayoutParams(
+                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+            }
             mWindowParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                     | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
diff --git a/samples/Support7Demos/src/com/example/android/supportv7/media/SampleMediaRouterActivity.java b/samples/Support7Demos/src/com/example/android/supportv7/media/SampleMediaRouterActivity.java
index 846c5e0..c486a1a 100644
--- a/samples/Support7Demos/src/com/example/android/supportv7/media/SampleMediaRouterActivity.java
+++ b/samples/Support7Demos/src/com/example/android/supportv7/media/SampleMediaRouterActivity.java
@@ -29,6 +29,7 @@
 import android.os.Environment;
 import android.os.Handler;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.media.session.MediaSessionCompat;
 import android.support.v4.view.MenuItemCompat;
@@ -216,6 +217,13 @@
         // Be sure to call the super class.
         super.onCreate(savedInstanceState);
 
+        // Need overlay permission for emulating remote display.
+        if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(this)) {
+            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
+                    Uri.parse("package:" + getPackageName()));
+            startActivityForResult(intent, 0);
+        }
+
         // Get the media router service.
         mMediaRouter = MediaRouter.getInstance(this);
 
diff --git a/samples/SupportAnimationDemos/AndroidManifest.xml b/samples/SupportAnimationDemos/AndroidManifest.xml
index 25e5ec8..243e6e4 100644
--- a/samples/SupportAnimationDemos/AndroidManifest.xml
+++ b/samples/SupportAnimationDemos/AndroidManifest.xml
@@ -16,9 +16,6 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.android.support.animation">
-
-    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
-
     <application android:label="@string/activity_sample_code"
             android:supportsRtl="true"
             android:icon="@drawable/app_sample_code"
diff --git a/samples/SupportAnimationDemos/build.gradle b/samples/SupportAnimationDemos/build.gradle
index 91f8c78..d1ea614 100644
--- a/samples/SupportAnimationDemos/build.gradle
+++ b/samples/SupportAnimationDemos/build.gradle
@@ -1,7 +1,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-dynamic-animation')
+    implementation project(':support-dynamic-animation')
 }
 
 android {
@@ -9,6 +9,7 @@
 
     defaultConfig {
         minSdkVersion 16
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -27,6 +28,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportAppNavigation/AndroidManifest.xml b/samples/SupportAppNavigation/AndroidManifest.xml
index c8e4fa8..4681b33 100644
--- a/samples/SupportAppNavigation/AndroidManifest.xml
+++ b/samples/SupportAppNavigation/AndroidManifest.xml
@@ -18,9 +18,6 @@
         android:versionName="1"
         xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.example.android.support.appnavigation">
-
-    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
-
     <application android:label="@string/app_name">
         <activity android:name=".app.AppNavHomeActivity"
                 android:label="@string/app_nav_home_label">
diff --git a/samples/SupportAppNavigation/build.gradle b/samples/SupportAppNavigation/build.gradle
index fdbad1b..c7d03b8 100644
--- a/samples/SupportAppNavigation/build.gradle
+++ b/samples/SupportAppNavigation/build.gradle
@@ -17,7 +17,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-v4')
+    implementation project(':support-v4')
 }
 
 android {
@@ -25,6 +25,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -33,8 +34,16 @@
         main.res.srcDirs = ['res']
     }
 
+    signingConfigs {
+        debug {
+            // Use a local debug keystore to avoid build server issues.
+            storeFile project.rootProject.init.debugKeystore
+        }
+    }
+
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportDesignDemos/AndroidManifest.xml b/samples/SupportDesignDemos/AndroidManifest.xml
index 88c423a..bedbea9 100644
--- a/samples/SupportDesignDemos/AndroidManifest.xml
+++ b/samples/SupportDesignDemos/AndroidManifest.xml
@@ -22,8 +22,6 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.android.support.design">
 
-    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
-
     <application android:label="@string/activity_sample_code"
             android:supportsRtl="true"
             android:icon="@drawable/app_sample_code"
diff --git a/samples/SupportDesignDemos/build.gradle b/samples/SupportDesignDemos/build.gradle
index 129fd51..48dfc9c 100644
--- a/samples/SupportDesignDemos/build.gradle
+++ b/samples/SupportDesignDemos/build.gradle
@@ -1,7 +1,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-design')
+    implementation project(':support-design')
 }
 
 android {
@@ -9,6 +9,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
         vectorDrawables.useSupportLibrary = true
     }
 
@@ -28,6 +29,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportDesignDemos/res/menu/sample_bottom_menu.xml b/samples/SupportDesignDemos/res/menu/sample_bottom_menu.xml
index d6d4761..f485789 100644
--- a/samples/SupportDesignDemos/res/menu/sample_bottom_menu.xml
+++ b/samples/SupportDesignDemos/res/menu/sample_bottom_menu.xml
@@ -13,14 +13,21 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+      xmlns:app="http://schemas.android.com/apk/res-auto">
     <item android:id="@+id/action_search"
           android:title="@string/menu_search"
+          app:contentDescription="@string/menu_search"
+          app:tooltipText="@string/menu_search"
           android:icon="@drawable/ic_search"/>
     <item android:id="@+id/action_settings"
           android:title="@string/menu_settings"
+          app:contentDescription="@string/menu_settings"
+          app:tooltipText="@string/menu_settings"
           android:icon="@drawable/ic_add"/>
     <item android:id="@+id/action_music"
           android:title="@string/tab_text"
+          app:contentDescription="@string/tab_text"
+          app:tooltipText="@string/tab_text"
           android:icon="@drawable/ic_action_navigation_menu"/>
-</menu>
\ No newline at end of file
+</menu>
diff --git a/samples/SupportEmojiDemos/build.gradle b/samples/SupportEmojiDemos/build.gradle
index d02dddd..c5be42e 100644
--- a/samples/SupportEmojiDemos/build.gradle
+++ b/samples/SupportEmojiDemos/build.gradle
@@ -21,9 +21,9 @@
 }
 
 dependencies {
-    compile project(':support-emoji')
-    compile project(':support-emoji-bundled')
-    compile project(':support-emoji-appcompat')
+    implementation project(':support-emoji')
+    implementation project(':support-emoji-bundled')
+    implementation project(':support-emoji-appcompat')
 }
 
 android {
@@ -31,6 +31,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -40,6 +41,11 @@
         main.assets.srcDirs = [new File(fontDir, "supported-emojis").getAbsolutePath()]
     }
 
+    lintOptions {
+        abortOnError true
+        check 'NewApi'
+    }
+
     signingConfigs {
         debug {
             // Use a local debug keystore to avoid build server issues.
diff --git a/samples/SupportEmojiDemos/src/com/example/android/support/text/emoji/Config.java b/samples/SupportEmojiDemos/src/com/example/android/support/text/emoji/Config.java
index d70c43f..ea58121 100644
--- a/samples/SupportEmojiDemos/src/com/example/android/support/text/emoji/Config.java
+++ b/samples/SupportEmojiDemos/src/com/example/android/support/text/emoji/Config.java
@@ -107,9 +107,9 @@
                 config = new BundledEmojiCompatConfig(mContext);
             }
         } else {
-            config = new EmojiCompat.Config(new EmojiCompat.MetadataLoader() {
+            config = new EmojiCompat.Config(new EmojiCompat.MetadataRepoLoader() {
                 @Override
-                public void load(@NonNull EmojiCompat.LoaderCallback loaderCallback) {
+                public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
                     loaderCallback.onFailed(new RuntimeException("Disable"));
                 }
             }) {
diff --git a/samples/SupportLeanbackDemos/AndroidManifest.xml b/samples/SupportLeanbackDemos/AndroidManifest.xml
index 067bb36..010c297 100644
--- a/samples/SupportLeanbackDemos/AndroidManifest.xml
+++ b/samples/SupportLeanbackDemos/AndroidManifest.xml
@@ -4,7 +4,6 @@
     android:versionCode="1"
     android:versionName="1.0">
 
-    <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="23" />
     <uses-permission android:name="android.permission.RECORD_AUDIO" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
@@ -190,5 +189,8 @@
 
         <activity android:name=".VideoSupportActivity"
             android:exported="true" />
+
+        <activity android:name=".VideoActivityWithDetailedCard"
+                  android:exported="true" />
     </application>
 </manifest>
diff --git a/samples/SupportLeanbackDemos/build.gradle b/samples/SupportLeanbackDemos/build.gradle
index 260bd8b..4ec403e 100644
--- a/samples/SupportLeanbackDemos/build.gradle
+++ b/samples/SupportLeanbackDemos/build.gradle
@@ -1,8 +1,8 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-leanback-v17')
-    compile project(':support-preference-leanback-v17')
+    implementation project(':support-leanback-v17')
+    implementation project(':support-preference-leanback-v17')
 }
 
 android {
@@ -10,6 +10,7 @@
 
     defaultConfig {
         minSdkVersion 17
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -28,6 +29,7 @@
 
     lintOptions {
         abortOnError false
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportLeanbackDemos/res/drawable/google_map.jpg b/samples/SupportLeanbackDemos/res/drawable/google_map.jpg
new file mode 100644
index 0000000..447de09
--- /dev/null
+++ b/samples/SupportLeanbackDemos/res/drawable/google_map.jpg
Binary files differ
diff --git a/samples/SupportLeanbackDemos/res/layout/video_activity_detailed_card.xml b/samples/SupportLeanbackDemos/res/layout/video_activity_detailed_card.xml
new file mode 100644
index 0000000..ddacf0f
--- /dev/null
+++ b/samples/SupportLeanbackDemos/res/layout/video_activity_detailed_card.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:id="@+id/videoFragment">
+
+</RelativeLayout>
\ No newline at end of file
diff --git a/samples/SupportLeanbackDemos/res/values/strings.xml b/samples/SupportLeanbackDemos/res/values/strings.xml
index 6de7d7b..4e4a398 100644
--- a/samples/SupportLeanbackDemos/res/values/strings.xml
+++ b/samples/SupportLeanbackDemos/res/values/strings.xml
@@ -79,6 +79,8 @@
     <string name="onboarding">Onboarding</string>
     <string name="onboarding_description">Show onboarding activity.</string>
     <string name="onboarding_support">Onboarding(support version)</string>
+    <string name="video_play_with_detail_card">A video play activity with detail card</string>
+    <string name="video_play_with_detail_card_description">A video play activity with detail card</string>
 
     <!-- Strings related to guided sequence activity -->
     <string name="guidedstep_first_title">First</string>
diff --git a/samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsPresenterSelectionActivity.java b/samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsPresenterSelectionActivity.java
index 4f8546e..e6cf32f 100644
--- a/samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsPresenterSelectionActivity.java
+++ b/samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsPresenterSelectionActivity.java
@@ -69,7 +69,10 @@
                 .build());
     }
 
-    private static class SetupFragment extends GuidedStepFragment {
+    /**
+     * Fragment hosted in DetailsPresenterSelectionActivity.
+     */
+    public static class SetupFragment extends GuidedStepFragment {
 
         @Override
         public Guidance onCreateGuidance(Bundle savedInstanceState) {
diff --git a/samples/SupportLeanbackDemos/src/com/example/android/leanback/MainActivity.java b/samples/SupportLeanbackDemos/src/com/example/android/leanback/MainActivity.java
index 733697c..4293dbb 100644
--- a/samples/SupportLeanbackDemos/src/com/example/android/leanback/MainActivity.java
+++ b/samples/SupportLeanbackDemos/src/com/example/android/leanback/MainActivity.java
@@ -60,43 +60,45 @@
             addAction(actions, BrowseSupportActivity.class, R.string.browse_support,
                     R.string.browse_support_description);
             addAction(actions, SearchActivity.class, R.string.search, R.string.search_description);
-            addAction(actions, SearchSupportActivity.class, R.string.search_support, R.string.search_support_description);
+            addAction(actions, SearchSupportActivity.class, R.string.search_support,
+                    R.string.search_support_description);
 
             addAction(actions, DetailsActivity.class, R.string.details,
                     R.string.details_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
             addAction(actions, DetailsSupportActivity.class, R.string.details_support,
                     R.string.details_support_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
 
             addAction(actions, DetailsVideoActivity.class, R.string.details_video,
                     R.string.details_video_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
             addAction(actions, DetailsVideoSupportActivity.class, R.string.details_video_support,
                     R.string.details_video_support_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
 
             addAction(actions, DetailsCustomTitleActivity.class, R.string.details_custom_title,
                     R.string.details_custom_title_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
             addAction(actions, DetailsCustomTitleSupportActivity.class,
                     R.string.details_custom_title_support,
                     R.string.details_custom_title_support_description);
-            actions.get(actions.size()-1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(DetailsSupportActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
 
             addAction(actions, SearchDetailsActivity.class, R.string.search_details,
                     R.string.search_details_description);
-            actions.get(actions.size()-1).getIntent().putExtra(SearchDetailsActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(SearchDetailsActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
             addAction(actions, SearchDetailsSupportActivity.class, R.string.search_details_support,
                     R.string.search_details_support_description);
-            actions.get(actions.size()-1).getIntent().putExtra(SearchDetailsSupportActivity.EXTRA_ITEM,
+            actions.get(actions.size() - 1).getIntent().putExtra(
+                    SearchDetailsSupportActivity.EXTRA_ITEM,
                     new PhotoItem("Hello world", R.drawable.gallery_photo_1));
             addAction(actions, VerticalGridActivity.class, R.string.vgrid,
                     R.string.vgrid_description);
@@ -109,8 +111,8 @@
             addAction(actions, GuidedStepHalfScreenActivity.class, R.string.guidedstephalfscreen,
                     R.string.guidedstep_description);
             addAction(actions, GuidedStepSupportHalfScreenActivity.class,
-                R.string.guidedstepsupporthalfscreen,
-                R.string.guidedstep_description);
+                    R.string.guidedstepsupporthalfscreen,
+                    R.string.guidedstep_description);
             addAction(actions, BrowseErrorActivity.class, R.string.browseerror,
                     R.string.browseerror_description);
             addAction(actions, BrowseErrorSupportActivity.class, R.string.browseerror_support,
@@ -141,6 +143,9 @@
             addAction(actions, OnboardingSupportActivity.class,
                     R.string.onboarding_support,
                     R.string.onboarding_description);
+            addAction(actions, VideoActivityWithDetailedCard.class,
+                    R.string.video_play_with_detail_card,
+                    R.string.video_play_with_detail_card_description);
         }
 
         private void addAction(List<GuidedAction> actions, Class cls, int titleRes, int descRes) {
diff --git a/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoActivityWithDetailedCard.java b/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoActivityWithDetailedCard.java
new file mode 100644
index 0000000..5acecd7
--- /dev/null
+++ b/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoActivityWithDetailedCard.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 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.example.android.leanback;
+
+import android.app.Activity;
+import android.app.FragmentTransaction;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.support.v4.os.BuildCompat;
+
+/**
+ * Activity that hosts VideoConsumptionExampleFragment.
+ *
+ * The main purpose to add this activity is to observe the bug b/28003943
+ */
+public class VideoActivityWithDetailedCard extends Activity {
+
+    public static final String TAG = "VideoExampleActivity";
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.video_activity_detailed_card);
+
+        if (savedInstanceState == null) {
+            FragmentTransaction ft = getFragmentManager().beginTransaction();
+            ft.add(R.id.videoFragment, new VideoConsumptionWithDetailCardFragment(),
+                    VideoConsumptionWithDetailCardFragment.TAG);
+            ft.commit();
+        }
+    }
+
+    @Override
+    protected void onNewIntent(Intent intent) {
+        super.onNewIntent(intent);
+        // This part is necessary to ensure that getIntent returns the latest intent when
+        // VideoExampleActivity is started. By default, getIntent() returns the initial intent
+        // that was set from another activity that started VideoExampleActivity. However, we need
+        // to update this intent when for example, user clicks on another video when the currently
+        // playing video is in PIP mode, and a new video needs to be started.
+        setIntent(intent);
+    }
+
+    /**
+     * Helper function to determine if picture in picture mode is supported or not
+     * @param context current context
+     * @return if Picture in Picture mode is supported or not
+     */
+    public static boolean supportsPictureInPicture(Context context) {
+        return BuildCompat.isAtLeastN()
+                && context.getPackageManager().hasSystemFeature(
+                        PackageManager.FEATURE_PICTURE_IN_PICTURE);
+    }
+}
+
diff --git a/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoConsumptionWithDetailCardFragment.java b/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoConsumptionWithDetailCardFragment.java
new file mode 100644
index 0000000..dd40c8f
--- /dev/null
+++ b/samples/SupportLeanbackDemos/src/com/example/android/leanback/VideoConsumptionWithDetailCardFragment.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2017 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.example.android.leanback;
+
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.v17.leanback.app.VideoFragment;
+import android.support.v17.leanback.app.VideoFragmentGlueHost;
+import android.support.v17.leanback.media.MediaPlayerAdapter;
+import android.support.v17.leanback.media.PlaybackBannerControlGlue;
+import android.support.v17.leanback.media.PlaybackGlue;
+
+/**
+ * Fragment used as Control Glue's host
+ */
+public class VideoConsumptionWithDetailCardFragment extends VideoFragment {
+
+    public static final String TAG = "VideoConsumptionWithDetailCardFragment";
+    // A valid video URL to play video. So the progress bar can be seen to reproduce the bug.
+    private static final String VIDEO_URL =
+            "https://storage.googleapis.com/android-tv/Sample videos/"
+                    + "April Fool's 2013/Explore Treasure Mode with Google Maps.mp4";
+    public static final String TITLE = "Diving with Sharks";
+    public static final String SUBTITLE = "A Googler";
+
+    private PlaybackBannerControlGlue<MediaPlayerAdapter> mMediaPlayerGlue;
+    final VideoFragmentGlueHost mHost = new VideoFragmentGlueHost(this);
+
+    /**
+     * helper function for playBackGlue to add/ remove callbacks
+     *
+     * @param glue The playback glue attached to this fragment
+     */
+    private static void playWhenReady(PlaybackGlue glue) {
+        if (glue.isPrepared()) {
+            glue.play();
+        } else {
+            glue.addPlayerCallback(new PlaybackGlue.PlayerCallback() {
+                @Override
+                public void onPreparedStateChanged(PlaybackGlue glue) {
+                    if (glue.isPrepared()) {
+                        glue.removePlayerCallback(this);
+                        glue.play();
+                    }
+                }
+            });
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        int[] defuatSpeed = new int[]{1};
+        mMediaPlayerGlue = new PlaybackBannerControlGlue<>(getActivity(), defuatSpeed,
+                new MediaPlayerAdapter(getActivity()));
+        // attach player glue to current host
+        mMediaPlayerGlue.setHost(mHost);
+
+        // add image resource to the PlaybackControlGlue
+        mMediaPlayerGlue.setArt(getActivity().getDrawable(R.drawable.google_map));
+
+        // meta information for video player
+        mMediaPlayerGlue.setTitle(TITLE);
+        mMediaPlayerGlue.setSubtitle(SUBTITLE);
+        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(VIDEO_URL));
+        playWhenReady(mMediaPlayerGlue);
+        setBackgroundType(BG_LIGHT);
+    }
+
+    @Override
+    public void onPause() {
+        if (mMediaPlayerGlue != null) {
+            mMediaPlayerGlue.pause();
+        }
+        super.onPause();
+    }
+}
+
diff --git a/samples/SupportLeanbackJank/AndroidManifest.xml b/samples/SupportLeanbackJank/AndroidManifest.xml
index 87be772..348f2d6 100644
--- a/samples/SupportLeanbackJank/AndroidManifest.xml
+++ b/samples/SupportLeanbackJank/AndroidManifest.xml
@@ -17,11 +17,6 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.google.android.leanbackjank">
-
-    <uses-sdk
-        android:minSdkVersion="21"
-        android:targetSdkVersion="24"/>
-
     <uses-feature
         android:name="android.hardware.touchscreen"
         android:required="false"/>
diff --git a/samples/SupportLeanbackJank/build.gradle b/samples/SupportLeanbackJank/build.gradle
index 0072ea6..4900a65 100644
--- a/samples/SupportLeanbackJank/build.gradle
+++ b/samples/SupportLeanbackJank/build.gradle
@@ -1,9 +1,9 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile 'com.github.bumptech.glide:glide:3.6.1'
-    compile project(':support-leanback-v17')
-    compile project(':support-preference-leanback-v17')
+    implementation 'com.github.bumptech.glide:glide:3.6.1'
+    implementation project(':support-leanback-v17')
+    implementation project(':support-preference-leanback-v17')
 }
 
 android {
@@ -11,6 +11,7 @@
 
     defaultConfig {
         minSdkVersion 17
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -29,6 +30,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportLeanbackShowcase/app/src/main/res/drawable-xhdpi/google_map.jpg b/samples/SupportLeanbackShowcase/app/src/main/res/drawable-xhdpi/google_map.jpg
new file mode 100644
index 0000000..447de09
--- /dev/null
+++ b/samples/SupportLeanbackShowcase/app/src/main/res/drawable-xhdpi/google_map.jpg
Binary files differ
diff --git a/samples/SupportPercentDemos/AndroidManifest.xml b/samples/SupportPercentDemos/AndroidManifest.xml
index 5c22277..c720dbd 100644
--- a/samples/SupportPercentDemos/AndroidManifest.xml
+++ b/samples/SupportPercentDemos/AndroidManifest.xml
@@ -21,9 +21,6 @@
      to come from a domain that you own or have control over. -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.android.support.percent">
-
-    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
-
     <application android:label="@string/activity_sample_code"
             android:supportsRtl="true"
             android:icon="@drawable/app_sample_code">
diff --git a/samples/SupportPercentDemos/build.gradle b/samples/SupportPercentDemos/build.gradle
index 03f8a8c..863da83 100644
--- a/samples/SupportPercentDemos/build.gradle
+++ b/samples/SupportPercentDemos/build.gradle
@@ -1,7 +1,7 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-percent')
+    implementation project(':support-percent')
 }
 
 android {
@@ -9,6 +9,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -20,6 +21,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     signingConfigs {
diff --git a/samples/SupportPreferenceDemos/AndroidManifest.xml b/samples/SupportPreferenceDemos/AndroidManifest.xml
index f6554b3..4fb2492 100644
--- a/samples/SupportPreferenceDemos/AndroidManifest.xml
+++ b/samples/SupportPreferenceDemos/AndroidManifest.xml
@@ -19,7 +19,7 @@
     xmlns:tools="http://schemas.android.com/tools"
     package="com.example.android.supportpreference">
 
-    <uses-sdk android:targetSdkVersion="24"
+    <uses-sdk
         tools:overrideLibrary="android.support.v17.preference, android.support.v17.leanback" />
 
     <uses-feature android:name="android.software.Leanback" android:required="false" />
diff --git a/samples/SupportPreferenceDemos/build.gradle b/samples/SupportPreferenceDemos/build.gradle
index e714e69..d09e3db 100644
--- a/samples/SupportPreferenceDemos/build.gradle
+++ b/samples/SupportPreferenceDemos/build.gradle
@@ -1,12 +1,12 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-appcompat-v7')
-    compile project(':support-recyclerview-v7')
-    compile project(':support-preference-v7')
-    compile project(':support-preference-v14')
-    compile project(':support-leanback-v17')
-    compile project(':support-preference-leanback-v17')
+    implementation project(':support-appcompat-v7')
+    implementation project(':support-recyclerview-v7')
+    implementation project(':support-preference-v7')
+    implementation project(':support-preference-v14')
+    implementation project(':support-leanback-v17')
+    implementation project(':support-preference-leanback-v17')
 }
 
 android {
@@ -14,6 +14,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -32,6 +33,7 @@
 
     lintOptions {
         abortOnError false
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportTransitionDemos/AndroidManifest.xml b/samples/SupportTransitionDemos/AndroidManifest.xml
index a6f52db..a58c189 100644
--- a/samples/SupportTransitionDemos/AndroidManifest.xml
+++ b/samples/SupportTransitionDemos/AndroidManifest.xml
@@ -21,9 +21,6 @@
      to come from a domain that you own or have control over. -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.android.support.transition">
-
-    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23" />
-
     <application android:label="@string/activity_sample_code"
             android:supportsRtl="true"
             android:icon="@drawable/app_sample_code"
diff --git a/samples/SupportTransitionDemos/build.gradle b/samples/SupportTransitionDemos/build.gradle
index dfed279..2a4fffc 100644
--- a/samples/SupportTransitionDemos/build.gradle
+++ b/samples/SupportTransitionDemos/build.gradle
@@ -1,8 +1,8 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-transition')
-    compile project(':support-appcompat-v7')
+    implementation project(':support-transition')
+    implementation project(':support-appcompat-v7')
 }
 
 android {
@@ -10,6 +10,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
     }
 
     sourceSets {
@@ -21,6 +22,7 @@
 
     lintOptions {
         abortOnError true
+        check 'NewApi'
     }
 
     signingConfigs {
diff --git a/samples/SupportVectorDrawableDemos/AndroidManifest.xml b/samples/SupportVectorDrawableDemos/AndroidManifest.xml
index 1de3a5f..b9ccf77 100644
--- a/samples/SupportVectorDrawableDemos/AndroidManifest.xml
+++ b/samples/SupportVectorDrawableDemos/AndroidManifest.xml
@@ -16,9 +16,6 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.android.support.vectordrawable" >
-
-    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="23"/>
-
     <application android:icon="@drawable/app_sample_code" android:label="SupportVectorDrawableDemos" >
         <activity android:name="com.example.android.support.vectordrawable.app.SupportVectorDrawableDemos">
             <intent-filter>
diff --git a/samples/SupportVectorDrawableDemos/build.gradle b/samples/SupportVectorDrawableDemos/build.gradle
index b7c2167..79383ca 100644
--- a/samples/SupportVectorDrawableDemos/build.gradle
+++ b/samples/SupportVectorDrawableDemos/build.gradle
@@ -17,9 +17,9 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-vector-drawable')
-    compile project(':support-animated-vector-drawable')
-    compile project(':support-appcompat-v7')
+    implementation project(':support-vector-drawable')
+    implementation project(':support-animated-vector-drawable')
+    implementation project(':support-appcompat-v7')
 }
 
 android {
@@ -27,6 +27,7 @@
 
     defaultConfig {
         minSdkVersion 14
+        targetSdkVersion project.ext.currentSdk
         vectorDrawables.useSupportLibrary = true
     }
 
diff --git a/samples/SupportWearDemos/AndroidManifest.xml b/samples/SupportWearDemos/AndroidManifest.xml
index df77ef7..4e4fb60 100644
--- a/samples/SupportWearDemos/AndroidManifest.xml
+++ b/samples/SupportWearDemos/AndroidManifest.xml
@@ -18,9 +18,14 @@
     package="com.example.android.support.wear" >
     <uses-feature android:name="android.hardware.type.watch" />
 
-    <application android:icon="@drawable/app_sample_code" android:label="SupportWearDemos" >
+    <application android:icon="@drawable/app_sample_code" android:label="SupportWearDemos"
+            android:theme="@android:style/Theme.DeviceDefault">
         <activity android:name="com.example.android.support.wear.app.SimpleWearableRecyclerViewDemo">
         </activity>
+        <activity android:name="com.example.android.support.wear.app.WearableSwitchDemo">
+        </activity>
+        <activity android:name="com.example.android.support.wear.app.CircularProgressLayoutDemo">
+        </activity>
         <activity android:name="com.example.android.support.wear.app.MainDemoActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/samples/SupportWearDemos/build.gradle b/samples/SupportWearDemos/build.gradle
index 2819768..4a22995 100644
--- a/samples/SupportWearDemos/build.gradle
+++ b/samples/SupportWearDemos/build.gradle
@@ -17,14 +17,14 @@
 apply plugin: 'com.android.application'
 
 dependencies {
-    compile project(':support-wear')
+    implementation project(':support-wear')
 }
 
 android {
     compileSdkVersion project.ext.currentSdk
 
     defaultConfig {
-        minSdkVersion 23
+        minSdkVersion 24
         targetSdkVersion project.ext.currentSdk
     }
 
@@ -45,6 +45,7 @@
     lintOptions {
         checkReleaseBuilds false
         abortOnError false
+        check 'NewApi'
     }
 
     compileOptions {
diff --git a/samples/SupportWearDemos/res/layout/cpl_demo.xml b/samples/SupportWearDemos/res/layout/cpl_demo.xml
new file mode 100644
index 0000000..cf29663
--- /dev/null
+++ b/samples/SupportWearDemos/res/layout/cpl_demo.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+             xmlns:app="http://schemas.android.com/apk/res-auto"
+             android:layout_width="match_parent"
+             android:layout_height="match_parent"
+             android:orientation="vertical">
+
+    <android.support.wear.widget.CircularProgressLayout
+        android:id="@+id/circularProgressLayout_layout"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:padding="10dp"
+        app:backgroundColor="@color/cpl_light_yellow"
+        app:colorSchemeColors="@color/cpl_light_blue"
+        app:strokeWidth="10dp">
+        <TextView
+            android:id="@+id/circularProgressLayout_child"
+            android:layout_width="60dp"
+            android:layout_height="60dp"
+            android:layout_gravity="center"
+            android:gravity="center"
+            android:textColor="@color/cpl_black"
+            android:text="@string/cpl_click_me"/>
+    </android.support.wear.widget.CircularProgressLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/samples/SupportWearDemos/res/layout/switch_demo.xml b/samples/SupportWearDemos/res/layout/switch_demo.xml
new file mode 100644
index 0000000..921568c
--- /dev/null
+++ b/samples/SupportWearDemos/res/layout/switch_demo.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<merge xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent" >
+    <Switch
+            style="@style/Widget.Wear.RoundSwitch"
+            android:layout_gravity="center"
+            android:layout_height="wrap_content"
+            android:layout_width="wrap_content"/>
+</merge>
diff --git a/samples/SupportWearDemos/res/values/colors.xml b/samples/SupportWearDemos/res/values/colors.xml
new file mode 100644
index 0000000..95c0119
--- /dev/null
+++ b/samples/SupportWearDemos/res/values/colors.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <color name="cpl_light_yellow">#fff176</color>
+    <color name="cpl_light_red">#ef5350</color>
+    <color name="cpl_light_green">#66bb6a</color>
+    <color name="cpl_light_blue">#4fc3f7</color>
+    <color name="cpl_black">#000000</color>
+</resources>
\ No newline at end of file
diff --git a/samples/SupportWearDemos/res/values/strings.xml b/samples/SupportWearDemos/res/values/strings.xml
new file mode 100644
index 0000000..7f92211
--- /dev/null
+++ b/samples/SupportWearDemos/res/values/strings.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <string name="cpl_click_me">Click me!</string>
+    <string name="cpl_clicked">Clicked!</string>
+    <string name="cpl_finished">Finished!</string>
+</resources>
\ No newline at end of file
diff --git a/samples/SupportWearDemos/src/com/example/android/support/wear/app/CircularProgressLayoutDemo.java b/samples/SupportWearDemos/src/com/example/android/support/wear/app/CircularProgressLayoutDemo.java
new file mode 100644
index 0000000..6bd4438
--- /dev/null
+++ b/samples/SupportWearDemos/src/com/example/android/support/wear/app/CircularProgressLayoutDemo.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2017 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.example.android.support.wear.app;
+
+import android.app.Activity;
+import android.os.Build;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
+import android.support.v4.content.ContextCompat;
+import android.support.wear.widget.CircularProgressLayout;
+import android.view.View;
+import android.widget.TextView;
+
+import com.example.android.support.wear.R;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Main activity for the CircularProgressLayout demo.
+ */
+@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
+public class CircularProgressLayoutDemo extends Activity implements
+        CircularProgressLayout.OnTimerFinishedListener, View.OnClickListener {
+
+    private static final long TOTAL_TIME = TimeUnit.SECONDS.toMillis(10);
+
+    CircularProgressLayout mCircularProgressLayout;
+    TextView mChildView;
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.cpl_demo);
+        mCircularProgressLayout = findViewById(R.id.circularProgressLayout_layout);
+        mChildView = findViewById(R.id.circularProgressLayout_child);
+
+        mCircularProgressLayout.setOnClickListener(this);
+        mCircularProgressLayout.setOnTimerFinishedListener(this);
+
+        mCircularProgressLayout.setTotalTime(TOTAL_TIME);
+        mCircularProgressLayout.startTimer();
+    }
+
+    @Override
+    public void onTimerFinished(CircularProgressLayout layout) {
+        if (layout == mCircularProgressLayout) {
+            mChildView.setText(getString(R.string.cpl_finished));
+            mCircularProgressLayout.setBackgroundColor(
+                    ContextCompat.getColor(this, R.color.cpl_light_green));
+        }
+    }
+
+    @Override
+    public void onClick(View view) {
+        if (view == mCircularProgressLayout && mCircularProgressLayout.isTimerRunning()) {
+            mCircularProgressLayout.stopTimer();
+            mChildView.setText(getString(R.string.cpl_clicked));
+            mCircularProgressLayout.setBackgroundColor(
+                    ContextCompat.getColor(this, R.color.cpl_light_red));
+        }
+    }
+}
diff --git a/samples/SupportWearDemos/src/com/example/android/support/wear/app/MainDemoActivity.java b/samples/SupportWearDemos/src/com/example/android/support/wear/app/MainDemoActivity.java
index 26dbef7..313457b 100644
--- a/samples/SupportWearDemos/src/com/example/android/support/wear/app/MainDemoActivity.java
+++ b/samples/SupportWearDemos/src/com/example/android/support/wear/app/MainDemoActivity.java
@@ -50,15 +50,19 @@
 
     private Map<String, Intent> createContentMap() {
         Map<String, Intent> contentMap = new HashMap<>();
-        Intent intent = new Intent();
-        intent.setClass(MainDemoActivity.this, SimpleWearableRecyclerViewDemo.class);
-        contentMap.put("Wearable Recycler View", intent);
+        contentMap.put("Wearable Recycler View", new Intent(
+                this, SimpleWearableRecyclerViewDemo.class));
+        contentMap.put("Wearable Switch", new Intent(
+                this, WearableSwitchDemo.class));
+        contentMap.put("Circular Progress Layout", new Intent(
+                this, CircularProgressLayoutDemo.class));
 
         return contentMap;
     }
 
     private class ViewHolder extends RecyclerView.ViewHolder {
         Button mView;
+
         ViewHolder(Button itemView) {
             super(itemView);
             mView = itemView;
diff --git a/samples/SupportWearDemos/src/com/example/android/support/wear/app/WearableSwitchDemo.java b/samples/SupportWearDemos/src/com/example/android/support/wear/app/WearableSwitchDemo.java
new file mode 100644
index 0000000..774021b
--- /dev/null
+++ b/samples/SupportWearDemos/src/com/example/android/support/wear/app/WearableSwitchDemo.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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.example.android.support.wear.app;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import com.example.android.support.wear.R;
+
+/** Main activity for the Switch demo. */
+public class WearableSwitchDemo extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.switch_demo);
+    }
+}
diff --git a/settings.gradle b/settings.gradle
index dd3db92..ffc34ee 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -94,9 +94,6 @@
 include ':support-tv-provider'
 project(':support-tv-provider').projectDir = new File(rootDir, 'tv-provider')
 
-include ':support-instantvideo'
-project(':support-instantvideo').projectDir = new File(rootDir, 'instantvideo')
-
 include ':support-emoji'
 project(':support-emoji').projectDir = new File(rootDir, 'emoji/core')
 
diff --git a/transition/api14/android/support/transition/GhostViewApi14.java b/transition/api14/android/support/transition/GhostViewApi14.java
index c918651..38acef2 100644
--- a/transition/api14/android/support/transition/GhostViewApi14.java
+++ b/transition/api14/android/support/transition/GhostViewApi14.java
@@ -150,8 +150,8 @@
         final int[] viewLocation = new int[2];
         getLocationOnScreen(location);
         mView.getLocationOnScreen(viewLocation);
-        viewLocation[0] -= mView.getTranslationX();
-        viewLocation[1] -= mView.getTranslationY();
+        viewLocation[0] = (int) (viewLocation[0] - mView.getTranslationX());
+        viewLocation[1] = (int) (viewLocation[1] - mView.getTranslationY());
         mDeltaX = viewLocation[0] - location[0];
         mDeltaY = viewLocation[1] - location[1];
         // Monitor invalidation of the target view.
diff --git a/transition/build.gradle b/transition/build.gradle
index 44d18d7..ef23aef 100644
--- a/transition/build.gradle
+++ b/transition/build.gradle
@@ -3,18 +3,17 @@
 archivesBaseName = 'transition'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-v4')
+    api project(':support-annotations')
+    api project(':support-v4')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/transition/lint-baseline.xml b/transition/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/transition/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/transition/tests/AndroidManifest.xml b/transition/tests/AndroidManifest.xml
index 4db27af..35be32b 100755
--- a/transition/tests/AndroidManifest.xml
+++ b/transition/tests/AndroidManifest.xml
@@ -15,14 +15,8 @@
   limitations under the License.
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.transition.test">
-
-    <uses-sdk
-        android:minSdkVersion="14"
-        android:targetSdkVersion="23"
-        tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application
         android:supportsRtl="true">
diff --git a/tv-provider/build.gradle b/tv-provider/build.gradle
index 23146c9..e16394e 100644
--- a/tv-provider/build.gradle
+++ b/tv-provider/build.gradle
@@ -2,9 +2,10 @@
 archivesBaseName = 'support-tv-provider'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
-    androidTestCompile (libs.test_runner) {
+    api project(':support-annotations')
+    api project(':support-compat')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/tv-provider/lint-baseline.xml b/tv-provider/lint-baseline.xml
new file mode 100644
index 0000000..4eaddc8
--- /dev/null
+++ b/tv-provider/lint-baseline.xml
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PreviewProgramColumns.TYPE_MOVIE, PreviewProgramColumns.TYPE_TV_SERIES, PreviewProgramColumns.TYPE_TV_SEASON, PreviewProgramColumns.TYPE_TV_EPISODE, PreviewProgramColumns.TYPE_CLIP, PreviewProgramColumns.TYPE_EVENT, PreviewProgramColumns.TYPE_CHANNEL, PreviewProgramColumns.TYPE_TRACK, PreviewProgramColumns.TYPE_ALBUM, PreviewProgramColumns.TYPE_ARTIST, PreviewProgramColumns.TYPE_PLAYLIST, PreviewProgramColumns.TYPE_STATION"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BasePreviewProgram.java"
+            line="129"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PreviewProgramColumns.ASPECT_RATIO_16_9, PreviewProgramColumns.ASPECT_RATIO_3_2, PreviewProgramColumns.ASPECT_RATIO_4_3, PreviewProgramColumns.ASPECT_RATIO_1_1, PreviewProgramColumns.ASPECT_RATIO_2_3"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BasePreviewProgram.java"
+            line="139"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PreviewProgramColumns.ASPECT_RATIO_16_9, PreviewProgramColumns.ASPECT_RATIO_3_2, PreviewProgramColumns.ASPECT_RATIO_4_3, PreviewProgramColumns.ASPECT_RATIO_1_1, PreviewProgramColumns.ASPECT_RATIO_2_3"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BasePreviewProgram.java"
+            line="149"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PreviewProgramColumns.AVAILABILITY_AVAILABLE, PreviewProgramColumns.AVAILABILITY_FREE_WITH_SUBSCRIPTION, PreviewProgramColumns.AVAILABILITY_PAID_CONTENT"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BasePreviewProgram.java"
+            line="167"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PreviewProgramColumns.INTERACTION_TYPE_VIEWS, PreviewProgramColumns.INTERACTION_TYPE_LISTENS, PreviewProgramColumns.INTERACTION_TYPE_FOLLOWERS, PreviewProgramColumns.INTERACTION_TYPE_FANS, PreviewProgramColumns.INTERACTION_TYPE_LIKES, PreviewProgramColumns.INTERACTION_TYPE_THUMBS, PreviewProgramColumns.INTERACTION_TYPE_VIEWERS"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BasePreviewProgram.java"
+            line="218"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: ProgramColumns.REVIEW_RATING_STYLE_STARS, ProgramColumns.REVIEW_RATING_STYLE_THUMBS_UP_DOWN, ProgramColumns.REVIEW_RATING_STYLE_PERCENTAGE"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/BaseProgram.java"
+            line="257"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: Genres.FAMILY_KIDS, Genres.SPORTS, Genres.SHOPPING, Genres.MOVIES, Genres.COMEDY, Genres.TRAVEL, Genres.DRAMA, Genres.EDUCATION, Genres.ANIMAL_WILDLIFE, Genres.NEWS, Genres.GAMING, Genres.ARTS, Genres.ENTERTAINMENT, Genres.LIFE_STYLE, Genres.MUSIC, Genres.PREMIER, Genres.TECH_SCIENCE"
+        errorLine1="            mValues.put(Programs.COLUMN_BROADCAST_GENRE, Programs.Genres.encode(genres));"
+        errorLine2="                                                                                ~~~~~~">
+        <location
+            file="src/android/support/media/tv/Program.java"
+            line="286"
+            column="81"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE, WatchNextPrograms.WATCH_NEXT_TYPE_NEXT, WatchNextPrograms.WATCH_NEXT_TYPE_NEW, WatchNextPrograms.WATCH_NEXT_TYPE_WATCHLIST"
+        errorLine1="        return i == null ? INVALID_INT_VALUE : i;"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/media/tv/WatchNextProgram.java"
+            line="99"
+            column="28"/>
+    </issue>
+
+</issues>
diff --git a/tv-provider/src/android/support/media/tv/BasePreviewProgram.java b/tv-provider/src/android/support/media/tv/BasePreviewProgram.java
index d9aaf82..6f2902a 100644
--- a/tv-provider/src/android/support/media/tv/BasePreviewProgram.java
+++ b/tv-provider/src/android/support/media/tv/BasePreviewProgram.java
@@ -38,6 +38,7 @@
 
 /**
  * Base class for derived classes that want to have common fields for preview programs.
+ * @hide
  */
 @TargetApi(26)
 public abstract class BasePreviewProgram extends BaseProgram {
diff --git a/tv-provider/src/android/support/media/tv/BaseProgram.java b/tv-provider/src/android/support/media/tv/BaseProgram.java
index 885b544..e4ce9d1 100644
--- a/tv-provider/src/android/support/media/tv/BaseProgram.java
+++ b/tv-provider/src/android/support/media/tv/BaseProgram.java
@@ -32,6 +32,7 @@
 /**
  * Base class for derived classes that want to have common fields for programs defined in
  * {@link TvContractCompat}.
+ * @hide
  */
 public abstract class BaseProgram {
     /**
diff --git a/tv-provider/src/android/support/media/tv/PreviewProgram.java b/tv-provider/src/android/support/media/tv/PreviewProgram.java
index ad8e957..3df3a74 100644
--- a/tv-provider/src/android/support/media/tv/PreviewProgram.java
+++ b/tv-provider/src/android/support/media/tv/PreviewProgram.java
@@ -20,9 +20,12 @@
 import android.annotation.TargetApi;
 import android.content.ContentValues;
 import android.database.Cursor;
+import android.media.tv.TvContentRating;  // For javadoc gen of super class
 import android.os.Build;
 import android.support.annotation.RestrictTo;
 import android.support.media.tv.TvContractCompat.PreviewPrograms;
+import android.support.media.tv.TvContractCompat.Programs;  // For javadoc gen of super class
+import android.support.media.tv.TvContractCompat.Programs.Genres;  // For javadoc gen of super class
 
 /**
  * A convenience class to access {@link PreviewPrograms} entries in the system content
diff --git a/tv-provider/src/android/support/media/tv/Program.java b/tv-provider/src/android/support/media/tv/Program.java
index 8dda52d..4e3bd7a 100644
--- a/tv-provider/src/android/support/media/tv/Program.java
+++ b/tv-provider/src/android/support/media/tv/Program.java
@@ -20,6 +20,7 @@
 import android.annotation.TargetApi;
 import android.content.ContentValues;
 import android.database.Cursor;
+import android.media.tv.TvContentRating;  // For javadoc gen of super class
 import android.os.Build;
 import android.support.annotation.NonNull;
 import android.support.annotation.RestrictTo;
diff --git a/tv-provider/src/android/support/media/tv/TvContractCompat.java b/tv-provider/src/android/support/media/tv/TvContractCompat.java
index d108ade..5773061 100644
--- a/tv-provider/src/android/support/media/tv/TvContractCompat.java
+++ b/tv-provider/src/android/support/media/tv/TvContractCompat.java
@@ -556,6 +556,13 @@
     }
 
     /**
+     * Returns {@code true}, if {@code uri} is a recorded program URI.
+     */
+    public static boolean isRecordedProgramUri(Uri uri) {
+        return isTvUri(uri) && isTwoSegmentUriStartingWith(uri, PATH_RECORDED_PROGRAM);
+    }
+
+    /**
      * Requests to make a channel browsable.
      *
      * <p>Once called, the system will review the request and make the channel browsable based on
diff --git a/tv-provider/src/android/support/media/tv/TvContractUtils.java b/tv-provider/src/android/support/media/tv/TvContractUtils.java
index 2638e34..edcd917 100644
--- a/tv-provider/src/android/support/media/tv/TvContractUtils.java
+++ b/tv-provider/src/android/support/media/tv/TvContractUtils.java
@@ -20,6 +20,10 @@
 import android.media.tv.TvContentRating;
 import android.support.annotation.RestrictTo;
 import android.text.TextUtils;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * Static helper methods for working with {@link android.media.tv.TvContract}.
@@ -28,26 +32,34 @@
 @RestrictTo(LIBRARY_GROUP)
 public class TvContractUtils {
 
+    static final TvContentRating[] EMPTY = new TvContentRating[0];
+
     private static final String TAG = "TvContractUtils";
     private static final boolean DEBUG = false;
     private static final String DELIMITER = ",";
 
     /**
      * Parses a string of comma-separated ratings into an array of {@link TvContentRating}.
+     * <p>Invalid strings are droppped. Duplicates are not removed. The order is preserved.</p>
      *
      * @param commaSeparatedRatings String containing various ratings, separated by commas.
      * @return An array of TvContentRatings.
      */
     public static TvContentRating[] stringToContentRatings(String commaSeparatedRatings) {
         if (TextUtils.isEmpty(commaSeparatedRatings)) {
-            return null;
+            return EMPTY;
         }
         String[] ratings = commaSeparatedRatings.split("\\s*,\\s*");
-        TvContentRating[] contentRatings = new TvContentRating[ratings.length];
-        for (int i = 0; i < contentRatings.length; ++i) {
-            contentRatings[i] = TvContentRating.unflattenFromString(ratings[i]);
+        List<TvContentRating> contentRatings = new ArrayList<>(ratings.length);
+        for (String rating : ratings) {
+            try {
+                contentRatings.add(TvContentRating.unflattenFromString(rating));
+            } catch (IllegalArgumentException e) {
+                Log.w(TAG, "Can't parse the content rating: '" + rating + "', skipping", e);
+            }
         }
-        return contentRatings;
+        return contentRatings.size() == 0 ? EMPTY
+                : contentRatings.toArray(new TvContentRating[contentRatings.size()]);
     }
 
     /**
diff --git a/tv-provider/src/android/support/media/tv/WatchNextProgram.java b/tv-provider/src/android/support/media/tv/WatchNextProgram.java
index b0b6b1c..f466584 100644
--- a/tv-provider/src/android/support/media/tv/WatchNextProgram.java
+++ b/tv-provider/src/android/support/media/tv/WatchNextProgram.java
@@ -20,8 +20,12 @@
 import android.annotation.TargetApi;
 import android.content.ContentValues;
 import android.database.Cursor;
+import android.media.tv.TvContentRating;  // For javadoc gen of super class
 import android.os.Build;
 import android.support.annotation.RestrictTo;
+import android.support.media.tv.TvContractCompat.PreviewPrograms;  // For javadoc gen of super class
+import android.support.media.tv.TvContractCompat.Programs;  // For javadoc gen of super class
+import android.support.media.tv.TvContractCompat.Programs.Genres;  // For javadoc gen of super class
 import android.support.media.tv.TvContractCompat.WatchNextPrograms;
 import android.support.media.tv.TvContractCompat.WatchNextPrograms.WatchNextType;
 
diff --git a/tv-provider/tests/AndroidManifest.xml b/tv-provider/tests/AndroidManifest.xml
index bcb6bdc..0cba0d7 100644
--- a/tv-provider/tests/AndroidManifest.xml
+++ b/tv-provider/tests/AndroidManifest.xml
@@ -15,13 +15,6 @@
    limitations under the License.
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.media.tv.test">
-
-    <uses-sdk
-            android:minSdkVersion="21"
-            android:targetSdkVersion="24"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
-
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 </manifest>
diff --git a/tv-provider/tests/src/android/support/media/tv/TvContractUtilsTest.java b/tv-provider/tests/src/android/support/media/tv/TvContractUtilsTest.java
new file mode 100644
index 0000000..bf9ea40
--- /dev/null
+++ b/tv-provider/tests/src/android/support/media/tv/TvContractUtilsTest.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2017 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 android.support.media.tv;
+
+import static org.junit.Assert.assertArrayEquals;
+
+import android.media.tv.TvContentRating;
+import android.os.Build;
+import android.support.test.filters.SdkSuppress;
+import android.support.test.filters.SmallTest;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+@SmallTest
+@SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
+public class TvContractUtilsTest extends TestCase {
+
+    @Test
+    public void testStringToContentRatings_nullInput() {
+        assertArrayEquals(TvContractUtils.EMPTY, TvContractUtils.stringToContentRatings(null));
+    }
+
+    @Test
+    public void testStringToContentRatings_emptyInput() {
+        assertArrayEquals(TvContractUtils.EMPTY, TvContractUtils.stringToContentRatings(""));
+    }
+
+    @Test
+    public void testStringToContentRatings_singleRating() {
+        TvContentRating[] ratings = new TvContentRating[1];
+        ratings[0] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_PG",
+                "US_TV_D",
+                "US_TV_L",
+                "US_TV_S",
+                "US_TV_V");
+        assertArrayEquals(ratings, TvContractUtils.stringToContentRatings(
+                "com.android.tv/US_TV/US_TV_PG/US_TV_D/US_TV_L/US_TV_S/US_TV_V"));
+    }
+
+    @Test
+    public void testStringToContentRatings_multipleRatings() {
+        TvContentRating[] ratings = new TvContentRating[3];
+        ratings[0] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_MV",
+                "US_MV_NC17");
+        ratings[1] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_Y7");
+        ratings[2] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_PG",
+                "US_TV_D",
+                "US_TV_L",
+                "US_TV_S",
+                "US_TV_V");
+        assertArrayEquals(ratings, TvContractUtils.stringToContentRatings(
+                "com.android.tv/US_MV/US_MV_NC17,"
+                        + "com.android.tv/US_TV/US_TV_Y7,"
+                        + "com.android.tv/US_TV/US_TV_PG/US_TV_D/US_TV_L/US_TV_S/US_TV_V"));
+    }
+
+    @Test
+    public void testStringToContentRatings_allRatingsInvalid() {
+        assertArrayEquals(TvContractUtils.EMPTY, TvContractUtils.stringToContentRatings(
+                "com.android.tv/US_MV," // Invalid
+                        + "com.android.tv")); // Invalid
+    }
+
+    @Test
+    public void testStringToContentRatings_someRatingsInvalid() {
+        TvContentRating[] ratings = new TvContentRating[1];
+        ratings[0] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_PG",
+                "US_TV_D",
+                "US_TV_L",
+                "US_TV_S",
+                "US_TV_V");
+        assertArrayEquals(ratings, TvContractUtils.stringToContentRatings(
+                "com.android.tv/US_MV," // Invalid
+                        + "com.android.tv/US_TV/US_TV_PG/US_TV_D/US_TV_L/US_TV_S/US_TV_V," // Valid
+                        + "com.android.tv")); // Invalid
+    }
+
+    @Test
+    public void testContentRatingsToString_nullInput() {
+        assertEquals(null, TvContractUtils.contentRatingsToString(null));
+    }
+
+    @Test
+    public void testContentRatingsToString_emptyInput() {
+        assertEquals(null, TvContractUtils.contentRatingsToString(new TvContentRating[0]));
+    }
+
+    @Test
+    public void testContentRatingsToString_singleRating() {
+        TvContentRating[] ratings = new TvContentRating[1];
+        ratings[0] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_PG",
+                "US_TV_D",
+                "US_TV_L",
+                "US_TV_S",
+                "US_TV_V");
+        assertEquals("com.android.tv/US_TV/US_TV_PG/US_TV_D/US_TV_L/US_TV_S/US_TV_V",
+                TvContractUtils.contentRatingsToString(ratings));
+    }
+
+    @Test
+    public void testContentRatingsToString_multipleRatings() {
+        TvContentRating[] ratings = new TvContentRating[3];
+        ratings[0] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_MV",
+                "US_MV_NC17");
+        ratings[1] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_PG",
+                "US_TV_D",
+                "US_TV_L",
+                "US_TV_S",
+                "US_TV_V");
+        ratings[2] = TvContentRating.createRating(
+                "com.android.tv",
+                "US_TV",
+                "US_TV_Y7");
+        String ratingString = "com.android.tv/US_MV/US_MV_NC17,"
+                + "com.android.tv/US_TV/US_TV_PG/US_TV_D/US_TV_L/US_TV_S/US_TV_V,"
+                + "com.android.tv/US_TV/US_TV_Y7";
+        assertEquals(ratingString, TvContractUtils.contentRatingsToString(ratings));
+    }
+}
diff --git a/v13/build.gradle b/v13/build.gradle
index 261bb70..477f31d 100644
--- a/v13/build.gradle
+++ b/v13/build.gradle
@@ -2,18 +2,17 @@
 archivesBaseName = 'support-v13'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-v4')
+    api project(':support-annotations')
+    api project(':support-v4')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/v13/lint-baseline.xml b/v13/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v13/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v13/tests/AndroidManifest.xml b/v13/tests/AndroidManifest.xml
index 8d89114..b2d04c9 100644
--- a/v13/tests/AndroidManifest.xml
+++ b/v13/tests/AndroidManifest.xml
@@ -15,14 +15,8 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    package="android.support.v13.test">
-
-    <uses-sdk
-        android:minSdkVersion="14"
-        android:targetSdkVersion="24"
-        tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+          package="android.support.v13.test">
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application>
         <activity android:name="android.support.v13.view.DragStartHelperTestActivity"/>
diff --git a/v13/tests/java/android/support/v13/view/DragStartHelperTest.java b/v13/tests/java/android/support/v13/view/DragStartHelperTest.java
index c92de6a..993a4e5 100644
--- a/v13/tests/java/android/support/v13/view/DragStartHelperTest.java
+++ b/v13/tests/java/android/support/v13/view/DragStartHelperTest.java
@@ -44,7 +44,6 @@
 import android.view.View;
 import android.view.ViewConfiguration;
 
-import org.hamcrest.Description;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -135,7 +134,7 @@
                 action, buttonState, anchor, offsetX, offsetY));
     }
 
-    static class TouchPositionMatcher extends ArgumentMatcher<Point> {
+    static class TouchPositionMatcher implements ArgumentMatcher<Point> {
 
         private final Point mExpectedPosition;
 
@@ -148,13 +147,13 @@
         }
 
         @Override
-        public boolean matches(Object actual) {
+        public boolean matches(Point actual) {
             return mExpectedPosition.equals(actual);
         }
 
         @Override
-        public void describeTo(Description description) {
-            description.appendText("TouchPositionMatcher: " + mExpectedPosition);
+        public String toString() {
+            return "TouchPositionMatcher: " + mExpectedPosition;
         }
     }
 
diff --git a/v14/preference/build.gradle b/v14/preference/build.gradle
index e36ab82..7df48af 100644
--- a/v14/preference/build.gradle
+++ b/v14/preference/build.gradle
@@ -18,10 +18,10 @@
 archivesBaseName = 'preference-v14'
 
 dependencies {
-    compile project(':support-v4')
-    compile project(':support-appcompat-v7')
-    compile project(':support-recyclerview-v7')
-    compile project(':support-preference-v7')
+    api project(':support-v4')
+    api project(':support-appcompat-v7')
+    api project(':support-recyclerview-v7')
+    api project(':support-preference-v7')
 }
 
 android {
diff --git a/v14/preference/lint-baseline.xml b/v14/preference/lint-baseline.xml
new file mode 100644
index 0000000..1d140cc
--- /dev/null
+++ b/v14/preference/lint-baseline.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        android:layout_width=&quot;0dp&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout-v17/preference_dropdown_material.xml"
+            line="32"
+            column="9"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        android:layout_width=&quot;0dp&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout-v21/preference_dropdown_material.xml"
+            line="32"
+            column="9"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        android:layout_width=&quot;0dp&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/preference_dropdown_material.xml"
+            line="32"
+            column="9"/>
+    </issue>
+
+</issues>
diff --git a/v17/leanback/build.gradle b/v17/leanback/build.gradle
index d0c1832..ea11627 100644
--- a/v17/leanback/build.gradle
+++ b/v17/leanback/build.gradle
@@ -2,21 +2,16 @@
 archivesBaseName = 'leanback-v17'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-core-ui')
-    compile project(':support-media-compat')
-    compile project(':support-fragment')
-    compile project(':support-recyclerview-v7')
+    api project(':support-compat')
+    api project(':support-core-ui')
+    api project(':support-media-compat')
+    api project(':support-fragment')
+    api project(':support-recyclerview-v7')
 
-    androidTestCompile (libs.test_runner) {
-        exclude module: 'support-annotations'
-    }
-    androidTestCompile (libs.espresso_core) {
-        exclude module: 'support-annotations'
-    }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.test_runner,      { exclude module: 'support-annotations' }
+    androidTestImplementation libs.espresso_core,    { exclude module: 'support-annotations' }
+    androidTestImplementation libs.mockito_core,     { exclude group: 'net.bytebuddy' } // DexMaker has it"s own MockMaker
+    androidTestImplementation libs.dexmaker_mockito, { exclude group: 'net.bytebuddy' } // DexMaker has it"s own MockMaker
 }
 
 android {
@@ -35,11 +30,6 @@
         ]
         main.res.srcDir 'res'
     }
-
-    lintOptions {
-        // Remove this once all NewApi breakages have been fixed.
-        disable "NewApi"
-    }
 }
 
 supportLibrary {
diff --git a/v17/leanback/kitkat/android/support/v17/leanback/transition/LeanbackTransitionHelperKitKat.java b/v17/leanback/kitkat/android/support/v17/leanback/transition/LeanbackTransitionHelperKitKat.java
index 872e836..bb30b00 100644
--- a/v17/leanback/kitkat/android/support/v17/leanback/transition/LeanbackTransitionHelperKitKat.java
+++ b/v17/leanback/kitkat/android/support/v17/leanback/transition/LeanbackTransitionHelperKitKat.java
@@ -35,7 +35,7 @@
         SlideKitkat slide = new SlideKitkat();
         slide.setSlideEdge(Gravity.TOP);
         slide.setInterpolator(AnimationUtils.loadInterpolator(context,
-                R.animator.lb_decelerator_4));
+                R.anim.lb_decelerator_4));
         slide.addTarget(R.id.browse_title_group);
         return slide;
     }
diff --git a/v17/leanback/lint-baseline.xml b/v17/leanback/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v17/leanback/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v17/leanback/res/animator/lb_decelerator_2.xml b/v17/leanback/res/anim/lb_decelerator_2.xml
similarity index 100%
rename from v17/leanback/res/animator/lb_decelerator_2.xml
rename to v17/leanback/res/anim/lb_decelerator_2.xml
diff --git a/v17/leanback/res/animator/lb_decelerator_4.xml b/v17/leanback/res/anim/lb_decelerator_4.xml
similarity index 100%
rename from v17/leanback/res/animator/lb_decelerator_4.xml
rename to v17/leanback/res/anim/lb_decelerator_4.xml
diff --git a/v17/leanback/res/animator-v21/lb_onboarding_description_enter.xml b/v17/leanback/res/animator-v21/lb_onboarding_description_enter.xml
new file mode 100644
index 0000000..3cb5843
--- /dev/null
+++ b/v17/leanback/res/animator-v21/lb_onboarding_description_enter.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:propertyName="alpha"
+        android:valueFrom="0.0"
+        android:valueTo="1.0"
+        android:duration="533"
+        android:startOffset="@integer/lb_onboarding_header_description_delay"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+    <objectAnimator
+        android:propertyName="translationY"
+        android:valueFrom="60dp"
+        android:valueTo="0dp"
+        android:duration="533"
+        android:startOffset="@integer/lb_onboarding_header_description_delay"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+</set>
diff --git a/v17/leanback/res/animator-v21/lb_onboarding_logo_enter.xml b/v17/leanback/res/animator-v21/lb_onboarding_logo_enter.xml
new file mode 100644
index 0000000..76a4609
--- /dev/null
+++ b/v17/leanback/res/animator-v21/lb_onboarding_logo_enter.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:propertyName="alpha"
+        android:valueFrom="0.0"
+        android:valueTo="1.0"
+        android:duration="333"
+        android:interpolator="@android:interpolator/linear_out_slow_in" />
+</set>
diff --git a/v17/leanback/res/animator-v21/lb_onboarding_logo_exit.xml b/v17/leanback/res/animator-v21/lb_onboarding_logo_exit.xml
new file mode 100644
index 0000000..40b618e
--- /dev/null
+++ b/v17/leanback/res/animator-v21/lb_onboarding_logo_exit.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:propertyName="alpha"
+        android:valueFrom="1.0"
+        android:valueTo="0.0"
+        android:duration="666"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+</set>
diff --git a/v17/leanback/res/animator-v21/lb_onboarding_page_indicator_enter.xml b/v17/leanback/res/animator-v21/lb_onboarding_page_indicator_enter.xml
new file mode 100644
index 0000000..e9fc46e
--- /dev/null
+++ b/v17/leanback/res/animator-v21/lb_onboarding_page_indicator_enter.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:propertyName="alpha"
+        android:valueFrom="0.0"
+        android:valueTo="1.0"
+        android:duration="500"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+</set>
diff --git a/v17/leanback/res/animator-v21/lb_onboarding_title_enter.xml b/v17/leanback/res/animator-v21/lb_onboarding_title_enter.xml
new file mode 100644
index 0000000..9b65b48
--- /dev/null
+++ b/v17/leanback/res/animator-v21/lb_onboarding_title_enter.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 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.
+  -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android">
+    <objectAnimator
+        android:propertyName="alpha"
+        android:valueFrom="0.0"
+        android:valueTo="1.0"
+        android:duration="533"
+        android:startOffset="@integer/lb_onboarding_header_title_delay"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+    <objectAnimator
+        android:propertyName="translationY"
+        android:valueFrom="60dp"
+        android:valueTo="0dp"
+        android:duration="533"
+        android:startOffset="@integer/lb_onboarding_header_title_delay"
+        android:interpolator="@android:interpolator/fast_out_slow_in" />
+</set>
diff --git a/v17/leanback/res/animator/lb_onboarding_description_enter.xml b/v17/leanback/res/animator/lb_onboarding_description_enter.xml
index 3cb5843..d8393bd 100644
--- a/v17/leanback/res/animator/lb_onboarding_description_enter.xml
+++ b/v17/leanback/res/animator/lb_onboarding_description_enter.xml
@@ -21,13 +21,11 @@
         android:valueFrom="0.0"
         android:valueTo="1.0"
         android:duration="533"
-        android:startOffset="@integer/lb_onboarding_header_description_delay"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:startOffset="@integer/lb_onboarding_header_description_delay" />
     <objectAnimator
         android:propertyName="translationY"
         android:valueFrom="60dp"
         android:valueTo="0dp"
         android:duration="533"
-        android:startOffset="@integer/lb_onboarding_header_description_delay"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:startOffset="@integer/lb_onboarding_header_description_delay" />
 </set>
diff --git a/v17/leanback/res/animator/lb_onboarding_logo_enter.xml b/v17/leanback/res/animator/lb_onboarding_logo_enter.xml
index 76a4609..5d8d762 100644
--- a/v17/leanback/res/animator/lb_onboarding_logo_enter.xml
+++ b/v17/leanback/res/animator/lb_onboarding_logo_enter.xml
@@ -20,6 +20,5 @@
         android:propertyName="alpha"
         android:valueFrom="0.0"
         android:valueTo="1.0"
-        android:duration="333"
-        android:interpolator="@android:interpolator/linear_out_slow_in" />
+        android:duration="333" />
 </set>
diff --git a/v17/leanback/res/animator/lb_onboarding_logo_exit.xml b/v17/leanback/res/animator/lb_onboarding_logo_exit.xml
index 40b618e..820ba8e 100644
--- a/v17/leanback/res/animator/lb_onboarding_logo_exit.xml
+++ b/v17/leanback/res/animator/lb_onboarding_logo_exit.xml
@@ -20,6 +20,5 @@
         android:propertyName="alpha"
         android:valueFrom="1.0"
         android:valueTo="0.0"
-        android:duration="666"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:duration="666" />
 </set>
diff --git a/v17/leanback/res/animator/lb_onboarding_page_indicator_enter.xml b/v17/leanback/res/animator/lb_onboarding_page_indicator_enter.xml
index e9fc46e..b8bd083 100644
--- a/v17/leanback/res/animator/lb_onboarding_page_indicator_enter.xml
+++ b/v17/leanback/res/animator/lb_onboarding_page_indicator_enter.xml
@@ -20,6 +20,5 @@
         android:propertyName="alpha"
         android:valueFrom="0.0"
         android:valueTo="1.0"
-        android:duration="500"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:duration="500" />
 </set>
diff --git a/v17/leanback/res/animator/lb_onboarding_title_enter.xml b/v17/leanback/res/animator/lb_onboarding_title_enter.xml
index 9b65b48..011f51c 100644
--- a/v17/leanback/res/animator/lb_onboarding_title_enter.xml
+++ b/v17/leanback/res/animator/lb_onboarding_title_enter.xml
@@ -21,13 +21,11 @@
         android:valueFrom="0.0"
         android:valueTo="1.0"
         android:duration="533"
-        android:startOffset="@integer/lb_onboarding_header_title_delay"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:startOffset="@integer/lb_onboarding_header_title_delay" />
     <objectAnimator
         android:propertyName="translationY"
         android:valueFrom="60dp"
         android:valueTo="0dp"
         android:duration="533"
-        android:startOffset="@integer/lb_onboarding_header_title_delay"
-        android:interpolator="@android:interpolator/fast_out_slow_in" />
+        android:startOffset="@integer/lb_onboarding_header_title_delay" />
 </set>
diff --git a/v17/leanback/res/layout/lb_playback_controls_row.xml b/v17/leanback/res/layout/lb_playback_controls_row.xml
index b449fa9..30d06bd 100644
--- a/v17/leanback/res/layout/lb_playback_controls_row.xml
+++ b/v17/leanback/res/layout/lb_playback_controls_row.xml
@@ -67,7 +67,7 @@
             <Space
                 android:id="@+id/spacer"
                 android:layout_width="match_parent"
-                android:layout_height="24dp" />
+                android:layout_height="16dp" />
 
             <FrameLayout
                 android:id="@+id/controls_dock"
diff --git a/v17/leanback/res/layout/lb_playback_transport_controls_row.xml b/v17/leanback/res/layout/lb_playback_transport_controls_row.xml
index 1b32be6..8b692f3 100644
--- a/v17/leanback/res/layout/lb_playback_transport_controls_row.xml
+++ b/v17/leanback/res/layout/lb_playback_transport_controls_row.xml
@@ -18,16 +18,14 @@
 <!-- Note: clipChildren/clipToPadding false are needed to apply shadows to child
      views with no padding of their own. Also to allow for negative margin on description. -->
 
-<android.support.v17.leanback.widget.PlaybackTransportRowView
+<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:clipChildren="false"
     android:clipToPadding="false"
-    android:paddingBottom="@dimen/lb_playback_transport_control_row_padding_bottom"
-    android:paddingStart="?attr/browsePaddingStart"
-    android:paddingEnd="?attr/browsePaddingEnd" >
+    android:paddingBottom="@dimen/lb_playback_transport_control_row_padding_bottom" >
 
     <FrameLayout
         android:layout_width="match_parent"
@@ -36,8 +34,10 @@
             android:id="@+id/controls_card"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:clipChildren="false"
+            android:layout_gravity="bottom"
             android:clipToPadding="false"
+            android:paddingStart="?attr/browsePaddingStart"
+            android:paddingEnd="?attr/browsePaddingEnd"
             android:layout_marginBottom="@dimen/lb_playback_transport_control_info_margin_bottom"
             android:orientation="horizontal" >
 
@@ -64,64 +64,76 @@
             android:visibility="invisible"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:layout_gravity="bottom" />
+            android:layout_gravity="bottom"
+            android:layout_marginBottom="@dimen/lb_playback_transport_thumbs_bottom_margin" />
     </FrameLayout>
 
-    <FrameLayout
-        android:id="@+id/controls_dock"
+    <android.support.v17.leanback.widget.PlaybackTransportRowView
         android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layoutDirection="ltr"
-        android:layout_marginLeft="@dimen/lb_playback_transport_controlbar_margin_start"
-    />
-
-    <android.support.v17.leanback.widget.SeekBar
-        android:id="@+id/playback_progress"
-        android:layout_width="match_parent"
-        android:layout_height="@dimen/lb_playback_transport_progressbar_height"
-        android:focusable="true" />
-
-    <RelativeLayout android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:layoutDirection="ltr"
-                    android:layout_marginLeft="@dimen/lb_playback_transport_controlbar_margin_start">
+        android:layout_height="match_parent"
+        android:id="@+id/transport_row"
+        android:orientation="vertical"
+        android:paddingStart="?attr/browsePaddingStart"
+        android:paddingEnd="?attr/browsePaddingEnd"
+        android:clipChildren="false"
+        android:clipToPadding="false">
         <FrameLayout
-            android:id="@+id/secondary_controls_dock"
-            android:layout_width="wrap_content"
+            android:id="@+id/controls_dock"
+            android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:layout_alignParentStart="true" >
-        </FrameLayout>
+            android:layoutDirection="ltr"
+            android:layout_marginLeft="@dimen/lb_playback_transport_controlbar_margin_start"
+        />
 
-        <TextView
-            android:id="@+id/current_time"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="top"
-            android:layout_toStartOf="@+id/separate_time"
-            android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
-            android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
-            style="?attr/playbackControlsTimeStyle" />
+        <android.support.v17.leanback.widget.SeekBar
+            android:id="@+id/playback_progress"
+            android:layout_width="match_parent"
+            android:layout_height="@dimen/lb_playback_transport_progressbar_height"
+            android:focusable="true" />
 
-        <TextView
-            android:id="@+id/separate_time"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/lb_playback_time_separator"
-            android:layout_gravity="top"
-            android:layout_toStartOf="@+id/total_time"
-            android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
-            android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
-            style="?attr/playbackControlsTimeStyle" />
+        <RelativeLayout android:layout_width="match_parent"
+                        android:layout_height="wrap_content"
+                        android:layoutDirection="ltr"
+                        android:layout_marginLeft="@dimen/lb_playback_transport_controlbar_margin_start">
+            <FrameLayout
+                android:id="@+id/secondary_controls_dock"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentStart="true" >
+            </FrameLayout>
 
-        <TextView
-            android:id="@+id/total_time"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="top"
-            android:layout_alignParentEnd="true"
-            android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
-            android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
-            style="?attr/playbackControlsTimeStyle" />
-    </RelativeLayout>
+            <TextView
+                android:id="@+id/current_time"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_gravity="top"
+                android:layout_toStartOf="@+id/separate_time"
+                android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
+                android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
+                style="?attr/playbackControlsTimeStyle" />
 
-</android.support.v17.leanback.widget.PlaybackTransportRowView>
+            <TextView
+                android:id="@+id/separate_time"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:text="@string/lb_playback_time_separator"
+                android:layout_gravity="top"
+                android:layout_toStartOf="@+id/total_time"
+                android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
+                android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
+                style="?attr/playbackControlsTimeStyle" />
+
+            <TextView
+                android:id="@+id/total_time"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_gravity="top"
+                android:layout_alignParentEnd="true"
+                android:layout_marginStart="@dimen/lb_playback_transport_time_margin"
+                android:layout_marginTop="@dimen/lb_playback_transport_time_margin_top"
+                style="?attr/playbackControlsTimeStyle" />
+        </RelativeLayout>
+
+
+    </android.support.v17.leanback.widget.PlaybackTransportRowView>
+</LinearLayout>
diff --git a/v17/leanback/res/layout/lb_row_media_item.xml b/v17/leanback/res/layout/lb_row_media_item.xml
index b25e922..e76e281 100644
--- a/v17/leanback/res/layout/lb_row_media_item.xml
+++ b/v17/leanback/res/layout/lb_row_media_item.xml
@@ -62,6 +62,7 @@
 
             <LinearLayout
                     android:id="@+id/mediaItemActionsContainer"
+                    android:orientation="horizontal"
                     android:layout_width="wrap_content"
                     android:layout_height="match_parent"
                     android:paddingStart="16dip" />
diff --git a/v17/leanback/res/layout/lb_search_bar.xml b/v17/leanback/res/layout/lb_search_bar.xml
index 37cdfb3..73a5985 100644
--- a/v17/leanback/res/layout/lb_search_bar.xml
+++ b/v17/leanback/res/layout/lb_search_bar.xml
@@ -54,7 +54,7 @@
                     android:id="@+id/lb_search_text_editor"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
-                    android:layout_gravity="center_vertical|end"
+                    android:layout_gravity="center_vertical|start"
                     android:layout_marginStart="@dimen/lb_search_bar_edit_text_margin_start"
                     android:layout_centerVertical="true"
                     android:cursorVisible="true"
diff --git a/v17/leanback/res/transition-v21/lb_title_out.xml b/v17/leanback/res/transition-v21/lb_title_out.xml
index 69735ab..2402857 100644
--- a/v17/leanback/res/transition-v21/lb_title_out.xml
+++ b/v17/leanback/res/transition-v21/lb_title_out.xml
@@ -18,7 +18,7 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:lb="http://schemas.android.com/apk/res-auto"
     class="android.support.v17.leanback.transition.SlideKitkat"
-    android:interpolator="@animator/lb_decelerator_2"
+    android:interpolator="@anim/lb_decelerator_2"
     lb:lb_slideEdge="top" >
     <targets>
         <target android:targetId="@id/browse_title_group" />
diff --git a/v17/leanback/res/values-v18/themes.xml b/v17/leanback/res/values-v18/themes.xml
new file mode 100644
index 0000000..9fc7722
--- /dev/null
+++ b/v17/leanback/res/values-v18/themes.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2014 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.
+-->
+
+<resources>
+    <style name="Theme.LeanbackBase" parent="android:Theme.Holo.NoActionBar">
+        <item name="playbackProgressPrimaryColor">@color/lb_playback_progress_color_no_theme</item>
+        <item name="playbackControlsIconHighlightColor">@color/lb_playback_icon_highlight_no_theme</item>
+        <item name="defaultBrandColor">@color/lb_default_brand_color</item>
+        <item name="defaultBrandColorDark">@color/lb_default_brand_color_dark</item>
+
+        <item name="android:windowOverscan">true</item>
+        <item name="guidedStepTheme">@style/Theme.Leanback.GuidedStep</item>
+    </style>
+</resources>
diff --git a/v17/leanback/res/values-v21/styles.xml b/v17/leanback/res/values-v21/styles.xml
index 89029c4..cd81934 100644
--- a/v17/leanback/res/values-v21/styles.xml
+++ b/v17/leanback/res/values-v21/styles.xml
@@ -25,4 +25,9 @@
         <item name="android:background">@drawable/lb_action_bg</item>
     </style>
 
+    <style name="Widget.Leanback.OnboardingStartButtonStyleBase">
+        <item name="android:elevation">1.5dp</item>
+        <item name="android:stateListAnimator">@null</item>
+    </style>
+
 </resources>
\ No newline at end of file
diff --git a/v17/leanback/res/values-v21/themes.xml b/v17/leanback/res/values-v21/themes.xml
index 886077a..4e5bd5a 100644
--- a/v17/leanback/res/values-v21/themes.xml
+++ b/v17/leanback/res/values-v21/themes.xml
@@ -26,10 +26,49 @@
 
         <item name="android:windowOverscan">true</item>
         <item name="guidedStepTheme">@style/Theme.Leanback.GuidedStep</item>
+
+        <!-- android:windowSharedElementEnterTransition is kept for backward compatibility for apps still refer
+        to Theme.Leanback, app should use Theme.Leanback.Details instead -->
+        <item name="android:windowSharedElementEnterTransition">@transition/lb_shared_element_enter_transition</item>
+        <!-- android:windowSharedElementReturnTransition is kept for backward compatibility for apps still refer
+        to Theme.Leanback, app should use Theme.Leanback.Details instead -->
+        <item name="android:windowSharedElementReturnTransition">@transition/lb_shared_element_return_transition</item>
+        <item name="android:windowEnterTransition">@transition/lb_enter_transition</item>
+        <item name="android:windowReturnTransition">@transition/lb_return_transition</item>
+        <item name="android:windowTransitionBackgroundFadeDuration">350</item>
+
+    </style>
+
+    <style name="Theme.Leanback.Browse" parent="Theme.Leanback">
+        <item name="android:windowEnterTransition">@transition/lb_browse_enter_transition</item>
+        <item name="android:windowReturnTransition">@transition/lb_browse_return_transition</item>
+    </style>
+
+    <style name="Theme.Leanback.VerticalGrid" parent="Theme.Leanback">
+        <item name="android:windowEnterTransition">@transition/lb_vertical_grid_enter_transition</item>
+        <item name="android:windowReturnTransition">@transition/lb_vertical_grid_return_transition</item>
+    </style>
+
+    <style name="Theme.Leanback.Details" parent="Theme.Leanback">
+        <item name="android:windowEnterTransition">@transition/lb_details_enter_transition</item>
+        <item name="android:windowReturnTransition">@transition/lb_details_return_transition</item>
+        <item name="android:windowSharedElementEnterTransition">@transition/lb_shared_element_enter_transition</item>
+        <item name="android:windowSharedElementReturnTransition">@transition/lb_shared_element_return_transition</item>
+    </style>
+
+    <style name="Theme.Leanback.Details.NoSharedElementTransition">
+        <item name="android:windowSharedElementEnterTransition">@null</item>
+        <item name="android:windowSharedElementReturnTransition">@null</item>
     </style>
 
     <style name="Theme.Leanback.GuidedStepBase" parent="Theme.LeanbackBase">
         <item name="guidedActionsSelectorDrawable">@drawable/lb_selectable_item_rounded_rect</item>
+        <item name="android:windowEnterTransition">@transition/lb_guidedstep_activity_enter</item>
+        <item name="android:windowTransitionBackgroundFadeDuration">@integer/lb_guidedstep_activity_background_fade_duration_ms</item>
+    </style>
+
+    <style name="Theme.Leanback.GuidedStep.HalfBase" parent="Theme.Leanback.GuidedStep">
+        <item name="android:windowEnterTransition">@transition/lb_guidedstep_activity_enter_bottom</item>
     </style>
 
 </resources>
diff --git a/v17/leanback/res/values/dimens.xml b/v17/leanback/res/values/dimens.xml
index 0a2b485..7a39b78 100644
--- a/v17/leanback/res/values/dimens.xml
+++ b/v17/leanback/res/values/dimens.xml
@@ -176,6 +176,14 @@
     <!-- radius of thumb when focused -->
     <dimen name="lb_playback_transport_progressbar_active_radius">6dp</dimen>
 
+    <!-- Thumbs bar -->
+    <dimen name="lb_playback_transport_thumbs_width">154dp</dimen>
+    <dimen name="lb_playback_transport_thumbs_height">154dp</dimen>
+    <dimen name="lb_playback_transport_hero_thumbs_width">192dp</dimen>
+    <dimen name="lb_playback_transport_hero_thumbs_height">192dp</dimen>
+    <dimen name="lb_playback_transport_thumbs_margin">4dp</dimen>
+    <dimen name="lb_playback_transport_thumbs_bottom_margin">18dp</dimen>
+
     <dimen name="lb_playback_transport_time_margin">8dp</dimen>
     <dimen name="lb_playback_transport_time_margin_top">8dp</dimen>
 
diff --git a/v17/leanback/res/values/styles.xml b/v17/leanback/res/values/styles.xml
index d10260d..b7e3da2 100644
--- a/v17/leanback/res/values/styles.xml
+++ b/v17/leanback/res/values/styles.xml
@@ -751,19 +751,20 @@
         <item name="arrowBgColor">@color/lb_page_indicator_arrow_background</item>
     </style>
 
+    <style name="Widget.Leanback.OnboardingStartButtonStyleBase">
+    </style>
+
     <!-- Style for the start button in OnboardingFragment. -->
-    <style name="Widget.Leanback.OnboardingStartButtonStyle">
+    <style name="Widget.Leanback.OnboardingStartButtonStyle" parent="Widget.Leanback.OnboardingStartButtonStyleBase">
         <item name="android:layout_width">wrap_content</item>
         <item name="android:layout_height">36dp</item>
         <item name="android:layout_gravity">center_horizontal</item>
         <item name="android:layout_marginBottom">4dp</item>
         <item name="android:background">@drawable/lb_onboarding_start_button_background</item>
-        <item name="android:elevation">1.5dp</item>
         <item name="android:fontFamily">sans-serif</item>
         <item name="android:gravity">center_vertical</item>
         <item name="android:paddingEnd">24dp</item>
         <item name="android:paddingStart">24dp</item>
-        <item name="android:stateListAnimator">@null</item>
         <item name="android:text">@string/lb_onboarding_get_started</item>
         <item name="android:textAllCaps">true</item>
         <item name="android:textColor">#014269</item>
diff --git a/v17/leanback/res/values/themes.xml b/v17/leanback/res/values/themes.xml
index e5b98f6..d40734e 100644
--- a/v17/leanback/res/values/themes.xml
+++ b/v17/leanback/res/values/themes.xml
@@ -24,7 +24,6 @@
         <item name="defaultBrandColor">@color/lb_default_brand_color</item>
         <item name="defaultBrandColorDark">@color/lb_default_brand_color_dark</item>
 
-        <item name="android:windowOverscan">true</item>
         <item name="guidedStepTheme">@style/Theme.Leanback.GuidedStep</item>
     </style>
 
@@ -103,16 +102,6 @@
 
         <item name="defaultSectionHeaderColor">?attr/defaultSearchColor</item>
 
-        <!-- android:windowSharedElementEnterTransition is kept for backward compatibility for apps still refer
-        to Theme.Leanback, app should use Theme.Leanback.Details instead -->
-        <item name="android:windowSharedElementEnterTransition">@transition/lb_shared_element_enter_transition</item>
-        <!-- android:windowSharedElementReturnTransition is kept for backward compatibility for apps still refer
-        to Theme.Leanback, app should use Theme.Leanback.Details instead -->
-        <item name="android:windowSharedElementReturnTransition">@transition/lb_shared_element_return_transition</item>
-        <item name="android:windowEnterTransition">@transition/lb_enter_transition</item>
-        <item name="android:windowReturnTransition">@transition/lb_return_transition</item>
-        <item name="android:windowTransitionBackgroundFadeDuration">350</item>
-
         <item name="overlayDimMaskColor">@color/lb_view_dim_mask_color</item>
         <item name="overlayDimActiveLevel">@fraction/lb_view_active_level</item>
         <item name="overlayDimDimmedLevel">@fraction/lb_view_dimmed_level</item>
@@ -120,26 +109,16 @@
     </style>
 
     <style name="Theme.Leanback.Browse" parent="Theme.Leanback">
-        <item name="android:windowEnterTransition">@transition/lb_browse_enter_transition</item>
-        <item name="android:windowReturnTransition">@transition/lb_browse_return_transition</item>
     </style>
 
     <style name="Theme.Leanback.VerticalGrid" parent="Theme.Leanback">
-        <item name="android:windowEnterTransition">@transition/lb_vertical_grid_enter_transition</item>
-        <item name="android:windowReturnTransition">@transition/lb_vertical_grid_return_transition</item>
     </style>
 
     <style name="Theme.Leanback.Details" parent="Theme.Leanback">
-        <item name="android:windowEnterTransition">@transition/lb_details_enter_transition</item>
-        <item name="android:windowReturnTransition">@transition/lb_details_return_transition</item>
-        <item name="android:windowSharedElementEnterTransition">@transition/lb_shared_element_enter_transition</item>
-        <item name="android:windowSharedElementReturnTransition">@transition/lb_shared_element_return_transition</item>
     </style>
 
     <!-- Theme for the details without shared element transition -->
     <style name="Theme.Leanback.Details.NoSharedElementTransition">
-        <item name="android:windowSharedElementEnterTransition">@null</item>
-        <item name="android:windowSharedElementReturnTransition">@null</item>
     </style>
 
     <style name="Theme.Leanback.GuidedStepBase" parent="Theme.LeanbackBase">
@@ -150,7 +129,6 @@
         <item name="guidedStepThemeFlag">true</item>
         <item name="guidedStepHeightWeight">@string/lb_guidedstep_height_weight</item>
 
-        <item name="android:windowEnterTransition">@transition/lb_guidedstep_activity_enter</item>
 
         <!-- background applied to each GuidedStepFragment by default-->
         <item name="guidedStepBackground">?android:attr/colorBackground</item>
@@ -158,7 +136,6 @@
              But We still need a dumb background to keep the temporary translucent state last
              as long as the background view fade-in transition -->
         <item name="android:windowBackground">@android:color/transparent</item>
-        <item name="android:windowTransitionBackgroundFadeDuration">@integer/lb_guidedstep_activity_background_fade_duration_ms</item>
 
         <item name="guidedStepImeAppearingAnimation">@animator/lb_guidedstep_slide_up</item>
         <item name="guidedStepImeDisappearingAnimation">@animator/lb_guidedstep_slide_down</item>
@@ -198,8 +175,10 @@
         <item name="guidedStepKeyline">@string/lb_guidedstep_keyline</item>
     </style>
 
-    <style name="Theme.Leanback.GuidedStep.Half" parent="Theme.Leanback.GuidedStep">
-      <item name="android:windowEnterTransition">@transition/lb_guidedstep_activity_enter_bottom</item>
+    <style name="Theme.Leanback.GuidedStep.HalfBase" parent="Theme.Leanback.GuidedStep">
+    </style>
+
+    <style name="Theme.Leanback.GuidedStep.Half" parent="Theme.Leanback.GuidedStep.HalfBase">
       <item name="guidedStepHeightWeight">@string/lb_guidedstep_height_weight_translucent</item>
       <item name="android:windowIsTranslucent">true</item>
       <item name="android:windowBackground">@android:color/transparent</item>
diff --git a/v17/leanback/src/android/support/v17/leanback/app/BackgroundManager.java b/v17/leanback/src/android/support/v17/leanback/app/BackgroundManager.java
index 65d2c44..262a5a6 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/BackgroundManager.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/BackgroundManager.java
@@ -37,7 +37,6 @@
 import android.support.v17.leanback.widget.BackgroundHelper;
 import android.support.v4.content.ContextCompat;
 import android.support.v4.graphics.drawable.DrawableCompat;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.view.animation.FastOutLinearInInterpolator;
 import android.util.Log;
 import android.view.View;
@@ -674,7 +673,7 @@
         // Activity transition below O has ghost effect for null window background where we
         // need set a transparent background to force redraw the whole window.
         mContext.getWindow().getDecorView().setBackground(
-                BuildCompat.isAtLeastO() ? null : new ColorDrawable(Color.TRANSPARENT));
+                Build.VERSION.SDK_INT >= 26 ? null : new ColorDrawable(Color.TRANSPARENT));
     }
 
     void attachToViewInternal(View sceneRoot) {
diff --git a/v17/leanback/src/android/support/v17/leanback/app/BrowseFragment.java b/v17/leanback/src/android/support/v17/leanback/app/BrowseFragment.java
index 698b5f2..fd930ee 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/BrowseFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/BrowseFragment.java
@@ -1026,7 +1026,8 @@
                         ? mHeadersFragment.getVerticalGridView() : mMainFragment.getView();
             }
 
-            boolean isRtl = ViewCompat.getLayoutDirection(focused) == View.LAYOUT_DIRECTION_RTL;
+            boolean isRtl = ViewCompat.getLayoutDirection(focused)
+                    == ViewCompat.LAYOUT_DIRECTION_RTL;
             int towardStart = isRtl ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
             int towardEnd = isRtl ? View.FOCUS_LEFT : View.FOCUS_RIGHT;
             if (mCanShowHeaders && direction == towardStart) {
diff --git a/v17/leanback/src/android/support/v17/leanback/app/BrowseSupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/BrowseSupportFragment.java
index 34c6775..094fef9 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/BrowseSupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/BrowseSupportFragment.java
@@ -1029,7 +1029,8 @@
                         ? mHeadersSupportFragment.getVerticalGridView() : mMainFragment.getView();
             }
 
-            boolean isRtl = ViewCompat.getLayoutDirection(focused) == View.LAYOUT_DIRECTION_RTL;
+            boolean isRtl = ViewCompat.getLayoutDirection(focused)
+                    == ViewCompat.LAYOUT_DIRECTION_RTL;
             int towardStart = isRtl ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
             int towardEnd = isRtl ? View.FOCUS_LEFT : View.FOCUS_RIGHT;
             if (mCanShowHeaders && direction == towardStart) {
diff --git a/v17/leanback/src/android/support/v17/leanback/app/GuidedStepFragment.java b/v17/leanback/src/android/support/v17/leanback/app/GuidedStepFragment.java
index 3eea164..a01cf26 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/GuidedStepFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/GuidedStepFragment.java
@@ -35,6 +35,7 @@
 import android.support.v17.leanback.widget.GuidedActionAdapter;
 import android.support.v17.leanback.widget.GuidedActionAdapterGroup;
 import android.support.v17.leanback.widget.GuidedActionsStylist;
+import android.support.v17.leanback.widget.NonOverlappingLinearLayout;
 import android.support.v4.app.ActivityCompat;
 import android.support.v7.widget.RecyclerView;
 import android.util.Log;
@@ -233,7 +234,7 @@
     @RestrictTo(LIBRARY_GROUP)
     public static final int SLIDE_FROM_BOTTOM = 1;
 
-    private static final String TAG = "GuidedStepFragment";
+    private static final String TAG = "GuidedStepF";
     private static final boolean DEBUG = false;
 
     /**
@@ -1045,6 +1046,7 @@
 
         ViewGroup guidanceContainer = (ViewGroup) root.findViewById(R.id.content_fragment);
         ViewGroup actionContainer = (ViewGroup) root.findViewById(R.id.action_fragment);
+        ((NonOverlappingLinearLayout) actionContainer).setFocusableViewAvailableFixEnabled(true);
 
         Guidance guidance = onCreateGuidance(savedInstanceState);
         View guidanceView = mGuidanceStylist.onCreateView(inflater, guidanceContainer, guidance);
diff --git a/v17/leanback/src/android/support/v17/leanback/app/GuidedStepSupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/GuidedStepSupportFragment.java
index a1fd860..ed34548 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/GuidedStepSupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/GuidedStepSupportFragment.java
@@ -38,6 +38,7 @@
 import android.support.v17.leanback.widget.GuidedActionAdapter;
 import android.support.v17.leanback.widget.GuidedActionAdapterGroup;
 import android.support.v17.leanback.widget.GuidedActionsStylist;
+import android.support.v17.leanback.widget.NonOverlappingLinearLayout;
 import android.support.v4.app.ActivityCompat;
 import android.support.v7.widget.RecyclerView;
 import android.util.Log;
@@ -236,7 +237,7 @@
     @RestrictTo(LIBRARY_GROUP)
     public static final int SLIDE_FROM_BOTTOM = 1;
 
-    private static final String TAG = "GuidedStepSupportFragment";
+    private static final String TAG = "GuidedStepF";
     private static final boolean DEBUG = false;
 
     /**
@@ -1048,6 +1049,7 @@
 
         ViewGroup guidanceContainer = (ViewGroup) root.findViewById(R.id.content_fragment);
         ViewGroup actionContainer = (ViewGroup) root.findViewById(R.id.action_fragment);
+        ((NonOverlappingLinearLayout) actionContainer).setFocusableViewAvailableFixEnabled(true);
 
         Guidance guidance = onCreateGuidance(savedInstanceState);
         View guidanceView = mGuidanceStylist.onCreateView(inflater, guidanceContainer, guidance);
diff --git a/v17/leanback/src/android/support/v17/leanback/app/OnboardingFragment.java b/v17/leanback/src/android/support/v17/leanback/app/OnboardingFragment.java
index ab61c4a..22dd211 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/OnboardingFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/OnboardingFragment.java
@@ -152,7 +152,7 @@
  * @attr ref R.styleable#LeanbackOnboardingTheme_onboardingLogoStyle
  */
 abstract public class OnboardingFragment extends Fragment {
-    private static final String TAG = "OnboardingFragment";
+    private static final String TAG = "OnboardingF";
     private static final boolean DEBUG = false;
 
     private static final long LOGO_SPLASH_PAUSE_DURATION_MS = 1333;
@@ -593,6 +593,9 @@
 
     boolean startLogoAnimation() {
         final Context context = FragmentUtil.getContext(this);
+        if (context == null) {
+            return false;
+        }
         Animator animator = null;
         if (mLogoResourceId != 0) {
             mLogoView.setVisibility(View.VISIBLE);
@@ -713,12 +716,15 @@
      *                          been done in the past, {@code false} otherwise
      */
     protected final void startEnterAnimation(boolean force) {
+        final Context context = FragmentUtil.getContext(this);
+        if (context == null) {
+            return;
+        }
         hideLogoView();
         if (mEnterAnimationFinished && !force) {
             return;
         }
         List<Animator> animators = new ArrayList<>();
-        final Context context = FragmentUtil.getContext(this);
         Animator animator = AnimatorInflater.loadAnimator(context,
                 R.animator.lb_onboarding_page_indicator_enter);
         animator.setTarget(getPageCount() <= 1 ? mStartButton : mPageIndicator);
diff --git a/v17/leanback/src/android/support/v17/leanback/app/OnboardingSupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/OnboardingSupportFragment.java
index 0c7cc4c..a24ea4d 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/OnboardingSupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/OnboardingSupportFragment.java
@@ -155,7 +155,7 @@
  * @attr ref R.styleable#LeanbackOnboardingTheme_onboardingLogoStyle
  */
 abstract public class OnboardingSupportFragment extends Fragment {
-    private static final String TAG = "OnboardingSupportFragment";
+    private static final String TAG = "OnboardingF";
     private static final boolean DEBUG = false;
 
     private static final long LOGO_SPLASH_PAUSE_DURATION_MS = 1333;
@@ -596,6 +596,9 @@
 
     boolean startLogoAnimation() {
         final Context context = getContext();
+        if (context == null) {
+            return false;
+        }
         Animator animator = null;
         if (mLogoResourceId != 0) {
             mLogoView.setVisibility(View.VISIBLE);
@@ -716,12 +719,15 @@
      *                          been done in the past, {@code false} otherwise
      */
     protected final void startEnterAnimation(boolean force) {
+        final Context context = getContext();
+        if (context == null) {
+            return;
+        }
         hideLogoView();
         if (mEnterAnimationFinished && !force) {
             return;
         }
         List<Animator> animators = new ArrayList<>();
-        final Context context = getContext();
         Animator animator = AnimatorInflater.loadAnimator(context,
                 R.animator.lb_onboarding_page_indicator_enter);
         animator.setTarget(getPageCount() <= 1 ? mStartButton : mPageIndicator);
diff --git a/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlayFragment.java b/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlayFragment.java
index c934f6b..d4b532b 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlayFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlayFragment.java
@@ -96,7 +96,7 @@
         }
     }
 
-    static final String TAG = "PlaybackOverlayFragment";
+    static final String TAG = "PlaybackOF";
     static final boolean DEBUG = false;
     private static final int ANIMATION_MULTIPLIER = 1;
 
diff --git a/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlaySupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlaySupportFragment.java
index ecabdaa..d751320 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlaySupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/PlaybackOverlaySupportFragment.java
@@ -99,7 +99,7 @@
         }
     }
 
-    static final String TAG = "PlaybackOverlaySupportFragment";
+    static final String TAG = "PlaybackOF";
     static final boolean DEBUG = false;
     private static final int ANIMATION_MULTIPLIER = 1;
 
diff --git a/v17/leanback/src/android/support/v17/leanback/app/RowsFragment.java b/v17/leanback/src/android/support/v17/leanback/app/RowsFragment.java
index fe0e26f..dd0dbed 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/RowsFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/RowsFragment.java
@@ -141,6 +141,7 @@
     boolean mViewsCreated;
     private int mAlignedTop = ALIGN_TOP_NOT_SET;
     boolean mAfterEntranceTransition = true;
+    boolean mFreezeRows;
 
     BaseOnItemViewSelectedListener mOnItemViewSelectedListener;
     BaseOnItemViewClickedListener mOnItemViewClickedListener;
@@ -367,6 +368,10 @@
             RowPresenter rowPresenter = (RowPresenter) vh.getPresenter();
             RowPresenter.ViewHolder rowVh = rowPresenter.getRowViewHolder(vh.getViewHolder());
             rowPresenter.setEntranceTransitionState(rowVh, mAfterEntranceTransition);
+
+            // freeze the rows attached after RowsFragment#freezeRows() is called
+            rowPresenter.freeze(rowVh, mFreezeRows);
+
             if (mExternalAdapterListener != null) {
                 mExternalAdapterListener.onAttachedToWindow(vh);
             }
@@ -450,6 +455,7 @@
     }
 
     private void freezeRows(boolean freeze) {
+        mFreezeRows = freeze;
         VerticalGridView verticalView = getVerticalGridView();
         if (verticalView != null) {
             final int count = verticalView.getChildCount();
diff --git a/v17/leanback/src/android/support/v17/leanback/app/RowsSupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/RowsSupportFragment.java
index 9f55aa2..c00f78b 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/RowsSupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/RowsSupportFragment.java
@@ -144,6 +144,7 @@
     boolean mViewsCreated;
     private int mAlignedTop = ALIGN_TOP_NOT_SET;
     boolean mAfterEntranceTransition = true;
+    boolean mFreezeRows;
 
     BaseOnItemViewSelectedListener mOnItemViewSelectedListener;
     BaseOnItemViewClickedListener mOnItemViewClickedListener;
@@ -370,6 +371,10 @@
             RowPresenter rowPresenter = (RowPresenter) vh.getPresenter();
             RowPresenter.ViewHolder rowVh = rowPresenter.getRowViewHolder(vh.getViewHolder());
             rowPresenter.setEntranceTransitionState(rowVh, mAfterEntranceTransition);
+
+            // freeze the rows attached after RowsSupportFragment#freezeRows() is called
+            rowPresenter.freeze(rowVh, mFreezeRows);
+
             if (mExternalAdapterListener != null) {
                 mExternalAdapterListener.onAttachedToWindow(vh);
             }
@@ -453,6 +458,7 @@
     }
 
     private void freezeRows(boolean freeze) {
+        mFreezeRows = freeze;
         VerticalGridView verticalView = getVerticalGridView();
         if (verticalView != null) {
             final int count = verticalView.getChildCount();
diff --git a/v17/leanback/src/android/support/v17/leanback/app/VerticalGridFragment.java b/v17/leanback/src/android/support/v17/leanback/app/VerticalGridFragment.java
index 9e80dfc..5cf5799 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/VerticalGridFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/VerticalGridFragment.java
@@ -38,7 +38,7 @@
  * an {@link ObjectAdapter}.
  */
 public class VerticalGridFragment extends BaseFragment {
-    static final String TAG = "VerticalGridFragment";
+    static final String TAG = "VerticalGF";
     static boolean DEBUG = false;
 
     private ObjectAdapter mAdapter;
diff --git a/v17/leanback/src/android/support/v17/leanback/app/VerticalGridSupportFragment.java b/v17/leanback/src/android/support/v17/leanback/app/VerticalGridSupportFragment.java
index 6327790..a38bac5 100644
--- a/v17/leanback/src/android/support/v17/leanback/app/VerticalGridSupportFragment.java
+++ b/v17/leanback/src/android/support/v17/leanback/app/VerticalGridSupportFragment.java
@@ -41,7 +41,7 @@
  * an {@link ObjectAdapter}.
  */
 public class VerticalGridSupportFragment extends BaseSupportFragment {
-    static final String TAG = "VerticalGridSupportFragment";
+    static final String TAG = "VerticalGF";
     static boolean DEBUG = false;
 
     private ObjectAdapter mAdapter;
diff --git a/v17/leanback/src/android/support/v17/leanback/transition/LeanbackTransitionHelper.java b/v17/leanback/src/android/support/v17/leanback/transition/LeanbackTransitionHelper.java
index 2598969..f97d64e 100644
--- a/v17/leanback/src/android/support/v17/leanback/transition/LeanbackTransitionHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/transition/LeanbackTransitionHelper.java
@@ -17,6 +17,7 @@
 
 import android.content.Context;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.support.v17.leanback.R;
 
@@ -36,6 +37,7 @@
      * Kitkat does not allow load custom transition from resource, calling
      * LeanbackTransitionHelperKitKat to build custom transition in code.
      */
+    @RequiresApi(19)
     static class LeanbackTransitionHelperKitKatImpl implements LeanbackTransitionHelperVersion {
 
         @Override
diff --git a/v17/leanback/src/android/support/v17/leanback/transition/TransitionHelper.java b/v17/leanback/src/android/support/v17/leanback/transition/TransitionHelper.java
index 9f92066..de8b374 100644
--- a/v17/leanback/src/android/support/v17/leanback/transition/TransitionHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/transition/TransitionHelper.java
@@ -17,6 +17,7 @@
 
 import android.content.Context;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.view.Gravity;
 import android.view.View;
@@ -427,6 +428,7 @@
     /**
      * Implementation used on KitKat (and above).
      */
+    @RequiresApi(19)
     static class TransitionHelperKitkatImpl extends TransitionHelperStubImpl {
 
         @Override
@@ -566,6 +568,7 @@
         }
     }
 
+    @RequiresApi(21)
     static final class TransitionHelperApi21Impl extends TransitionHelperKitkatImpl {
 
         @Override
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/BackgroundHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/BackgroundHelper.java
index 62d94d2..6bc2462 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/BackgroundHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/BackgroundHelper.java
@@ -19,6 +19,7 @@
 
 import android.graphics.drawable.Drawable;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.view.View;
 
@@ -47,6 +48,7 @@
         }
     }
 
+    @RequiresApi(19)
     private static final class BackgroundHelperKitkatImpl implements BackgroundHelperVersionImpl {
         BackgroundHelperKitkatImpl() {
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/BaseCardView.java b/v17/leanback/src/android/support/v17/leanback/widget/BaseCardView.java
index 9ca331f..735bb99 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/BaseCardView.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/BaseCardView.java
@@ -891,7 +891,7 @@
          * @param source The layout params to copy from.
          */
         public LayoutParams(LayoutParams source) {
-            super(source);
+            super((ViewGroup.MarginLayoutParams) source);
 
             this.viewType = source.viewType;
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewRowPresenter.java b/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewRowPresenter.java
index d484bcc..98b9f78 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewRowPresenter.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewRowPresenter.java
@@ -61,7 +61,7 @@
 @Deprecated
 public class DetailsOverviewRowPresenter extends RowPresenter {
 
-    static final String TAG = "DetailsOverviewRowPresenter";
+    static final String TAG = "DetailsOverviewRowP";
     static final boolean DEBUG = false;
 
     private static final int MORE_ACTIONS_FADE_MS = 100;
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewSharedElementHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewSharedElementHelper.java
index 50f0da3..0d86cfd 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewSharedElementHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/DetailsOverviewSharedElementHelper.java
@@ -177,6 +177,9 @@
         mViewHolder.mActionsRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
         mViewHolder.mActionsRow.setVisibility(View.VISIBLE);
         mViewHolder.mActionsRow.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
+        // switch focusability to VISIBLE wont trigger focusableViewAvailable() on O because
+        // shared element details_frame is still INVISIBLE. b/63544781
+        mViewHolder.mActionsRow.requestFocus();
         mViewHolder.mDetailsDescriptionFrame.setVisibility(View.VISIBLE);
     }
 
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/FocusHighlightHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/FocusHighlightHelper.java
index 394142d..49565ab 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/FocusHighlightHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/FocusHighlightHelper.java
@@ -25,6 +25,7 @@
 import android.support.v17.leanback.app.HeadersFragment;
 import android.support.v17.leanback.graphics.ColorOverlayDimmer;
 import android.support.v7.widget.RecyclerView;
+import android.util.TypedValue;
 import android.view.View;
 import android.view.ViewParent;
 import android.view.animation.AccelerateDecelerateInterpolator;
@@ -272,11 +273,15 @@
         void lazyInit(View view) {
             if (!mInitialized) {
                 Resources res = view.getResources();
-                mSelectScale = mScaleEnabled
-                        ? Float.parseFloat(res.getString(R.dimen.lb_browse_header_select_scale))
-                        : 1f;
-                mDuration =
-                        Integer.parseInt(res.getString(R.dimen.lb_browse_header_select_duration));
+                TypedValue value = new TypedValue();
+                if (mScaleEnabled) {
+                    res.getValue(R.dimen.lb_browse_header_select_scale, value, true);
+                    mSelectScale = value.getFloat();
+                } else {
+                    mSelectScale = 1f;
+                }
+                res.getValue(R.dimen.lb_browse_header_select_duration, value, true);
+                mDuration = value.data;
                 mInitialized = true;
             }
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/ForegroundHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/ForegroundHelper.java
index 64cb769..4c2a857 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/ForegroundHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/ForegroundHelper.java
@@ -2,6 +2,7 @@
 
 import android.graphics.drawable.Drawable;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.view.View;
 
 final class ForegroundHelper {
@@ -22,6 +23,7 @@
     /**
      * Implementation used on api 23 (and above).
      */
+    @RequiresApi(23)
     private static final class ForegroundHelperApi23Impl implements ForegroundHelperVersionImpl {
         ForegroundHelperApi23Impl() {
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/FullWidthDetailsOverviewRowPresenter.java b/v17/leanback/src/android/support/v17/leanback/widget/FullWidthDetailsOverviewRowPresenter.java
index 189dfe6..dad4414 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/FullWidthDetailsOverviewRowPresenter.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/FullWidthDetailsOverviewRowPresenter.java
@@ -62,7 +62,7 @@
  */
 public class FullWidthDetailsOverviewRowPresenter extends RowPresenter {
 
-    static final String TAG = "FullWidthDetailsOverviewRowPresenter";
+    static final String TAG = "FullWidthDetailsRP";
     static final boolean DEBUG = false;
 
     private static Rect sTmpRect = new Rect();
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/GridLayoutManager.java b/v17/leanback/src/android/support/v17/leanback/widget/GridLayoutManager.java
index c554cde..f2dae95 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/GridLayoutManager.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/GridLayoutManager.java
@@ -504,7 +504,8 @@
     /**
      * override child visibility
      */
-    int mChildVisibility = -1;
+    @Visibility
+    int mChildVisibility;
 
     /**
      * Pixels that scrolled in secondary forward direction. Negative value means backward.
@@ -668,6 +669,7 @@
 
     public GridLayoutManager(BaseGridView baseGridView) {
         mBaseGridView = baseGridView;
+        mChildVisibility = -1;
     }
 
     public void setOrientation(int orientation) {
@@ -1267,8 +1269,7 @@
         if (TRACE) TraceCompat.beginSection("processRowSizeSecondary");
         CircularIntArray[] rows = mGrid == null ? null : mGrid.getItemPositionsInRows();
         boolean changed = false;
-        int scrapChildWidth = -1;
-        int scrapChildHeight = -1;
+        int scrapeChildSize = -1;
 
         for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
             CircularIntArray row = rows == null ? null : rows[rowIndex];
@@ -1279,7 +1280,7 @@
                 final int rowIndexStart = row.get(rowItemPairIndex);
                 final int rowIndexEnd = row.get(rowItemPairIndex + 1);
                 for (int i = rowIndexStart; i <= rowIndexEnd; i++) {
-                    final View view = findViewByPosition(i);
+                    final View view = findViewByPosition(i - mPositionDeltaInPreLayout);
                     if (view == null) {
                         continue;
                     }
@@ -1297,27 +1298,49 @@
 
             final int itemCount = mState.getItemCount();
             if (!mBaseGridView.hasFixedSize() && measure && rowSize < 0 && itemCount > 0) {
-                if (scrapChildWidth < 0 && scrapChildHeight < 0) {
-                    int position;
-                    if (mFocusPosition == NO_POSITION) {
+                if (scrapeChildSize < 0) {
+                    // measure a child that is close to mFocusPosition but not currently visible
+                    int position = mFocusPosition;
+                    if (position < 0) {
                         position = 0;
-                    } else if (mFocusPosition >= itemCount) {
+                    } else if (position >= itemCount) {
                         position = itemCount - 1;
-                    } else {
-                        position = mFocusPosition;
                     }
-                    measureScrapChild(position,
-                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
-                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
-                            mMeasuredDimension);
-                    scrapChildWidth = mMeasuredDimension[0];
-                    scrapChildHeight = mMeasuredDimension[1];
-                    if (DEBUG) {
-                        Log.v(TAG, "measured scrap child: " + scrapChildWidth + " "
-                                + scrapChildHeight);
+                    if (getChildCount() > 0) {
+                        int firstPos = mBaseGridView.getChildViewHolder(
+                                getChildAt(0)).getLayoutPosition();
+                        int lastPos = mBaseGridView.getChildViewHolder(
+                                getChildAt(getChildCount() - 1)).getLayoutPosition();
+                        // if mFocusPosition is between first and last, choose either
+                        // first - 1 or last + 1
+                        if (position >= firstPos && position <= lastPos) {
+                            position = (position - firstPos <= lastPos - position)
+                                    ? (firstPos - 1) : (lastPos + 1);
+                            // try the other value if the position is invalid. if both values are
+                            // invalid, skip measureScrapChild below.
+                            if (position < 0 && lastPos < itemCount - 1) {
+                                position = lastPos + 1;
+                            } else if (position >= itemCount && firstPos > 0) {
+                                position = firstPos - 1;
+                            }
+                        }
+                    }
+                    if (position >= 0 && position < itemCount) {
+                        measureScrapChild(position,
+                                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
+                                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
+                                mMeasuredDimension);
+                        scrapeChildSize = mOrientation == HORIZONTAL ? mMeasuredDimension[0] :
+                                mMeasuredDimension[1];
+                        if (DEBUG) {
+                            Log.v(TAG, "measured scrap child: " + mMeasuredDimension[0] + " "
+                                    + mMeasuredDimension[1]);
+                        }
                     }
                 }
-                rowSize = mOrientation == HORIZONTAL ? scrapChildHeight : scrapChildWidth;
+                if (scrapeChildSize >= 0) {
+                    rowSize = scrapeChildSize;
+                }
             }
             if (rowSize < 0) {
                 rowSize = 0;
@@ -1402,7 +1425,10 @@
                 mRowSizeSecondary = new int[mNumRows];
             }
 
-            // Measure all current children and update cached row heights
+            if (mState.isPreLayout()) {
+                updatePositionDeltaInPreLayout();
+            }
+            // Measure all current children and update cached row height or column width
             processRowSizeSecondary(true);
 
             switch (modeSecondary) {
@@ -2055,6 +2081,22 @@
         mPositionToRowInPostLayout.clear();
     }
 
+    // in prelayout, first child's getViewPosition can be smaller than old adapter position
+    // if there were items removed before first visible index. For example:
+    // visible items are 3, 4, 5, 6, deleting 1, 2, 3 from adapter; the view position in
+    // prelayout are not 3(deleted), 4, 5, 6. Instead it's 1(deleted), 2, 3, 4.
+    // So there is a delta (2 in this case) between last cached position and prelayout position.
+    void updatePositionDeltaInPreLayout() {
+        if (getChildCount() > 0) {
+            View view = getChildAt(0);
+            LayoutParams lp = (LayoutParams) view.getLayoutParams();
+            mPositionDeltaInPreLayout = mGrid.getFirstVisibleIndex()
+                    - lp.getViewLayoutPosition();
+        } else {
+            mPositionDeltaInPreLayout = 0;
+        }
+    }
+
     // Lays out items based on the current scroll position
     @Override
     public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
@@ -2092,6 +2134,7 @@
 
         saveContext(recycler, state);
         if (state.isPreLayout()) {
+            updatePositionDeltaInPreLayout();
             int childCount = getChildCount();
             if (mGrid != null && childCount > 0) {
                 int minChangedEdge = Integer.MAX_VALUE;
@@ -2103,12 +2146,6 @@
                 for (int i = 0; i < childCount; i++) {
                     View view = getChildAt(i);
                     LayoutParams lp = (LayoutParams) view.getLayoutParams();
-                    if (i == 0) {
-                        // first child's layout position can be smaller than index if there were
-                        // items removed before first visible index.
-                        mPositionDeltaInPreLayout = mGrid.getFirstVisibleIndex()
-                                - lp.getViewLayoutPosition();
-                    }
                     int newAdapterPosition = mBaseGridView.getChildAdapterPosition(view);
                     // if either of following happening
                     // 1. item itself has changed or layout parameter changed
@@ -3319,6 +3356,15 @@
         return count == 0 || mBaseGridView.findViewHolderForAdapterPosition(0) != null;
     }
 
+    boolean isItemFullyVisible(int pos) {
+        RecyclerView.ViewHolder vh = mBaseGridView.findViewHolderForAdapterPosition(pos);
+        if (vh == null) {
+            return false;
+        }
+        return vh.itemView.getLeft() >= 0 && vh.itemView.getRight() < mBaseGridView.getWidth()
+                && vh.itemView.getTop() >= 0 && vh.itemView.getBottom() < mBaseGridView.getHeight();
+    }
+
     boolean canScrollTo(View view) {
         return view.getVisibility() == View.VISIBLE && (!hasFocus() || view.hasFocusable());
     }
@@ -3613,11 +3659,10 @@
         saveContext(recycler, state);
         switch (action) {
             case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD:
-                // try to focus all the way to the last visible item on the same row.
-                processSelectionMoves(false, -mState.getItemCount());
+                processSelectionMoves(false, -1);
                 break;
             case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD:
-                processSelectionMoves(false, mState.getItemCount());
+                processSelectionMoves(false, 1);
                 break;
         }
         leaveContext();
@@ -3682,11 +3727,12 @@
     public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state,
             AccessibilityNodeInfoCompat info) {
         saveContext(recycler, state);
-        if (mScrollEnabled && !hasCreatedFirstItem()) {
+        int count = state.getItemCount();
+        if (mScrollEnabled && count > 1 && !isItemFullyVisible(0)) {
             info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
             info.setScrollable(true);
         }
-        if (mScrollEnabled && !hasCreatedLastItem()) {
+        if (mScrollEnabled && count > 1 && !isItemFullyVisible(count - 1)) {
             info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
             info.setScrollable(true);
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/HorizontalHoverCardSwitcher.java b/v17/leanback/src/android/support/v17/leanback/widget/HorizontalHoverCardSwitcher.java
index eff822b..8aead19 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/HorizontalHoverCardSwitcher.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/HorizontalHoverCardSwitcher.java
@@ -47,7 +47,7 @@
         // end edge with row view's end edge, otherwise align start edges.
         view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
         MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
-        boolean isRtl = ViewCompat.getLayoutDirection(view) == View.LAYOUT_DIRECTION_RTL;
+        boolean isRtl = ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL;
         if (!isRtl && mCardLeft + view.getMeasuredWidth() > rightLimit) {
             params.leftMargin = rightLimit  - view.getMeasuredWidth();
         } else if (isRtl && mCardLeft < leftLimit) {
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/ListRowPresenter.java b/v17/leanback/src/android/support/v17/leanback/widget/ListRowPresenter.java
index ca70eda..e888f6d 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/ListRowPresenter.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/ListRowPresenter.java
@@ -829,6 +829,7 @@
     public void freeze(RowPresenter.ViewHolder holder, boolean freeze) {
         ViewHolder vh = (ViewHolder) holder;
         vh.mGridView.setScrollEnabled(!freeze);
+        vh.mGridView.setAnimateChildLayout(!freeze);
     }
 
     @Override
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/NonOverlappingLinearLayout.java b/v17/leanback/src/android/support/v17/leanback/widget/NonOverlappingLinearLayout.java
index 28a5c0c..8985f82 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/NonOverlappingLinearLayout.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/NonOverlappingLinearLayout.java
@@ -13,11 +13,26 @@
  */
 package android.support.v17.leanback.widget;
 
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
 import android.content.Context;
+import android.support.annotation.RestrictTo;
 import android.util.AttributeSet;
+import android.view.View;
 import android.widget.LinearLayout;
 
-class NonOverlappingLinearLayout extends LinearLayout {
+import java.util.ArrayList;
+
+/**
+ * @hide
+ */
+@RestrictTo(LIBRARY_GROUP)
+public class NonOverlappingLinearLayout extends LinearLayout {
+
+    boolean mFocusableViewAvailableFixEnabled = false;
+    boolean mDeferFocusableViewAvailableInLayout;
+    final ArrayList<ArrayList<View>> mSortedAvailableViews = new ArrayList();
+
 
     public NonOverlappingLinearLayout(Context context) {
         this(context, null);
@@ -38,4 +53,60 @@
     public boolean hasOverlappingRendering() {
         return false;
     }
+
+    public void setFocusableViewAvailableFixEnabled(boolean enabled) {
+        mFocusableViewAvailableFixEnabled = enabled;
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int l, int t, int r, int b) {
+        try {
+            mDeferFocusableViewAvailableInLayout = mFocusableViewAvailableFixEnabled
+                    && getOrientation() == HORIZONTAL
+                    && getLayoutDirection() == LAYOUT_DIRECTION_RTL;
+            if (mDeferFocusableViewAvailableInLayout) {
+                while (mSortedAvailableViews.size() > getChildCount()) {
+                    mSortedAvailableViews.remove(mSortedAvailableViews.size() - 1);
+                }
+                while (mSortedAvailableViews.size() < getChildCount()) {
+                    mSortedAvailableViews.add(new ArrayList());
+                }
+            }
+            super.onLayout(changed, l, t, r, b);
+            if (mDeferFocusableViewAvailableInLayout) {
+                for (int i = 0; i < mSortedAvailableViews.size(); i++) {
+                    for (int j = 0; j < mSortedAvailableViews.get(i).size(); j++) {
+                        super.focusableViewAvailable(mSortedAvailableViews.get(i).get(j));
+                    }
+                }
+            }
+        } finally {
+            if (mDeferFocusableViewAvailableInLayout) {
+                mDeferFocusableViewAvailableInLayout = false;
+                for (int i = 0; i < mSortedAvailableViews.size(); i++) {
+                    mSortedAvailableViews.get(i).clear();
+                }
+            }
+        }
+    }
+
+    @Override
+    public void focusableViewAvailable(View v) {
+        if (mDeferFocusableViewAvailableInLayout) {
+            View i = v;
+            int index = -1;
+            while (i != this && i != null) {
+                if (i.getParent() == this) {
+                    index = indexOfChild(i);
+                    break;
+                }
+                i = (View) i.getParent();
+            }
+            if (index != -1) {
+                mSortedAvailableViews.get(index).add(v);
+            }
+        } else {
+            super.focusableViewAvailable(v);
+        }
+    }
 }
\ No newline at end of file
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/PlaybackTransportRowPresenter.java b/v17/leanback/src/android/support/v17/leanback/widget/PlaybackTransportRowPresenter.java
index 4c99a3b..4505944 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/PlaybackTransportRowPresenter.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/PlaybackTransportRowPresenter.java
@@ -380,7 +380,7 @@
             } else {
                 mPositionsLength = 0;
             }
-            mControlsVh.view.setVisibility(View.INVISIBLE);
+            mControlsVh.view.setVisibility(View.GONE);
             mSecondaryControlsVh.view.setVisibility(View.INVISIBLE);
             mDescriptionViewHolder.view.setVisibility(View.INVISIBLE);
             mThumbsBar.setVisibility(View.VISIBLE);
@@ -666,8 +666,8 @@
         vh.mSecondaryControlsVh = (ControlBarPresenter.ViewHolder) mSecondaryControlsPresenter
                 .onCreateViewHolder(vh.mSecondaryControlsDock);
         vh.mSecondaryControlsDock.addView(vh.mSecondaryControlsVh.view);
-        ((PlaybackTransportRowView) vh.view).setOnUnhandledKeyListener(
-                new PlaybackTransportRowView.OnUnhandledKeyListener() {
+        ((PlaybackTransportRowView) vh.view.findViewById(R.id.transport_row))
+                .setOnUnhandledKeyListener(new PlaybackTransportRowView.OnUnhandledKeyListener() {
                 @Override
                 public boolean onUnhandledKey(KeyEvent event) {
                     if (vh.getOnKeyListener() != null) {
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/RoundedRectHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/RoundedRectHelper.java
index f9382ff..60fedf2 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/RoundedRectHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/RoundedRectHelper.java
@@ -13,8 +13,9 @@
  */
 package android.support.v17.leanback.widget;
 
-import android.support.v17.leanback.R;
 import android.os.Build;
+import android.support.annotation.RequiresApi;
+import android.support.v17.leanback.R;
 import android.view.View;
 
 /**
@@ -71,6 +72,7 @@
     /**
      * Implementation used on api 21 (and above).
      */
+    @RequiresApi(21)
     private static final class Api21Impl implements Impl {
         Api21Impl() {
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/ShadowHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/ShadowHelper.java
index e5fb61d..cbdddbf 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/ShadowHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/ShadowHelper.java
@@ -14,6 +14,7 @@
 package android.support.v17.leanback.widget;
 
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.view.View;
 
 
@@ -64,6 +65,7 @@
     /**
      * Implementation used on api 21 (and above).
      */
+    @RequiresApi(21)
     private static final class ShadowHelperApi21Impl implements ShadowHelperVersionImpl {
         ShadowHelperApi21Impl() {
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/StaticShadowHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/StaticShadowHelper.java
index 4422d62..436668f 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/StaticShadowHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/StaticShadowHelper.java
@@ -16,6 +16,7 @@
 package android.support.v17.leanback.widget;
 
 import android.os.Build;
+import android.support.annotation.RequiresApi;
 import android.view.ViewGroup;
 
 
@@ -64,6 +65,7 @@
     /**
      * Implementation used on JBMR2 (and above).
      */
+    @RequiresApi(19)
     private static final class ShadowHelperJbmr2Impl implements ShadowHelperVersionImpl {
         ShadowHelperJbmr2Impl() {
         }
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/ThumbsBar.java b/v17/leanback/src/android/support/v17/leanback/widget/ThumbsBar.java
index 85dde7f..ca6eaca 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/ThumbsBar.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/ThumbsBar.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.support.annotation.RestrictTo;
+import android.support.v17.leanback.R;
 import android.util.AttributeSet;
 import android.util.SparseArray;
 import android.view.View;
@@ -33,24 +34,39 @@
 @RestrictTo(LIBRARY_GROUP)
 public class ThumbsBar extends LinearLayout {
 
-    static final int DEFAULT_NUM_OF_THUMBS = 7;
-
-    int mMinimalMargin = 16;
-    int mNumOfThumbs;
-    int mThumbWidth = 160;
-    int mThumbHeight = 160;
-    int mHeroThumbWidth = 240;
-    int mHeroThumbHeight = 240;
-    int mMeasuredMargin;
+    // initial value for Thumb's number before measuring the screen size
+    int mNumOfThumbs = -1;
+    int mThumbWidthInPixel;
+    int mThumbHeightInPixel;
+    int mHeroThumbWidthInPixel;
+    int mHeroThumbHeightInPixel;
+    int mMeasuredMarginInPixel;
     final SparseArray<Bitmap> mBitmaps = new SparseArray<>();
 
+    // flag to determine if the number of thumbs in thumbs bar is set by user through
+    // setNumberofThumbs API or auto-calculated according to android tv design spec.
+    private boolean mIsUserSets = false;
+
     public ThumbsBar(Context context, AttributeSet attrs) {
         this(context, attrs, 0);
     }
 
     public ThumbsBar(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
-        setNumberOfThumbs(DEFAULT_NUM_OF_THUMBS);
+        // According to the spec,
+        // the width of non-hero thumb should be 80% of HeroThumb's Width, i.e. 0.8 * 192dp = 154dp
+        mThumbWidthInPixel = context.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_thumbs_width);
+        mThumbHeightInPixel = context.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_thumbs_height);
+        // According to the spec, the width of HeroThumb should be 192dp
+        mHeroThumbHeightInPixel = context.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_hero_thumbs_width);
+        mHeroThumbWidthInPixel = context.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_hero_thumbs_height);
+        // According to the spec, the margin between thumbs to be 4dp
+        mMeasuredMarginInPixel = context.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_thumbs_margin);
     }
 
     /**
@@ -64,8 +80,8 @@
      * Set size of thumb view in pixels
      */
     public void setThumbSize(int width, int height) {
-        mThumbHeight = height;
-        mThumbWidth = width;
+        mThumbHeightInPixel = height;
+        mThumbWidthInPixel = width;
         int heroIndex = getHeroIndex();
         for (int i = 0; i < getChildCount(); i++) {
             if (heroIndex != i) {
@@ -91,8 +107,8 @@
      * Set size of hero thumb view in pixels, it is usually larger than other thumbs.
      */
     public void setHeroThumbSize(int width, int height) {
-        mHeroThumbHeight = height;
-        mHeroThumbWidth = width;
+        mHeroThumbHeightInPixel = height;
+        mHeroThumbWidthInPixel = width;
         int heroIndex = getHeroIndex();
         for (int i = 0; i < getChildCount(); i++) {
             if (heroIndex == i) {
@@ -115,23 +131,34 @@
     }
 
     /**
-     * Set number of thumb views. It must be odd or it will be increasing one.
+     * Set the space between thumbs in pixels
+     */
+    public void setThumbSpace(int spaceInPixel) {
+        mMeasuredMarginInPixel = spaceInPixel;
+        requestLayout();
+    }
+
+    /**
+     * Set number of thumb views.
      */
     public void setNumberOfThumbs(int numOfThumbs) {
-        if (numOfThumbs < 0) {
-            throw new IllegalArgumentException();
-        }
-        if ((numOfThumbs & 1) == 0) {
-            // make it odd number
-            numOfThumbs++;
-        }
+        mIsUserSets = true;
         mNumOfThumbs = numOfThumbs;
+        setNumberOfThumbsInternal();
+    }
+
+    /**
+     * Helper function for setNumberOfThumbs.
+     * Will Update the layout settings in ThumbsBar based on mNumOfThumbs
+     */
+    private void setNumberOfThumbsInternal() {
         while (getChildCount() > mNumOfThumbs) {
             removeView(getChildAt(getChildCount() - 1));
         }
         while (getChildCount() < mNumOfThumbs) {
             View view = createThumbView(this);
-            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mThumbWidth, mThumbHeight);
+            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mThumbWidthInPixel,
+                    mThumbHeightInPixel);
             addView(view, lp);
         }
         int heroIndex = getHeroIndex();
@@ -139,30 +166,69 @@
             View child = getChildAt(i);
             LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
             if (heroIndex == i) {
-                lp.width = mHeroThumbWidth;
-                lp.height = mHeroThumbHeight;
+                lp.width = mHeroThumbWidthInPixel;
+                lp.height = mHeroThumbHeightInPixel;
             } else {
-                lp.width = mThumbWidth;
-                lp.height = mThumbHeight;
+                lp.width = mThumbWidthInPixel;
+                lp.height = mThumbHeightInPixel;
             }
             child.setLayoutParams(lp);
         }
     }
 
+    private static int roundUp(int num, int divisor) {
+        return (num + divisor - 1) / divisor;
+    }
+
+    /**
+     * Helper function to compute how many thumbs should be put in the screen
+     * Assume we should put x's non-hero thumbs in the screen, the equation should be
+     *   192dp (width of hero thumbs) +
+     *   154dp (width of common thumbs) * x +
+     *   4dp (width of the margin between thumbs) * x
+     *     = width
+     * So the calculated number of non-hero thumbs should be (width - 192dp) / 158dp.
+     * If the calculated number of non-hero thumbs is less than 2, it will be updated to 2
+     * or if the calculated number or non-hero thumbs is not an even number, it will be
+     * decremented by one.
+     * This processing is used to make sure the arrangement of non-hero thumbs
+     * in ThumbsBar is symmetrical.
+     * Also there should be a hero thumb in the middle of the ThumbsBar,
+     * the final result should be non-hero thumbs (after processing) + 1.
+     *
+     * @param  widthInPixel measured width in pixel
+     * @return The number of thumbs
+     */
+    private int calculateNumOfThumbs(int widthInPixel) {
+        int nonHeroThumbNum = roundUp(widthInPixel - mHeroThumbWidthInPixel,
+                mThumbWidthInPixel + mMeasuredMarginInPixel);
+        if (nonHeroThumbNum < 2) {
+            // If the calculated number of non-hero thumbs is less than 2,
+            // it will be updated to 2
+            nonHeroThumbNum = 2;
+        } else if ((nonHeroThumbNum & 1) != 0) {
+            // If the calculated number or non-hero thumbs is not an even number,
+            // it will be increased by one.
+            nonHeroThumbNum++;
+        }
+        // Count Hero Thumb to the final result
+        return nonHeroThumbNum + 1;
+    }
+
     @Override
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         int width = getMeasuredWidth();
-        int spaceForMargin = 0;
-        while (mNumOfThumbs > 1) {
-            spaceForMargin = width - mHeroThumbWidth - mThumbWidth * (mNumOfThumbs - 1);
-            if (spaceForMargin < mMinimalMargin * (mNumOfThumbs - 1)) {
-                setNumberOfThumbs(mNumOfThumbs - 2);
-            } else {
-                break;
+        // If the number of thumbs in ThumbsBar is not set by user explicitly, it will be
+        // recalculated based on Android TV Design Spec
+        if (!mIsUserSets) {
+            int numOfThumbs = calculateNumOfThumbs(width);
+            // Set new number of thumbs when calculation result is different with current number
+            if (mNumOfThumbs != numOfThumbs) {
+                mNumOfThumbs = numOfThumbs;
+                setNumberOfThumbsInternal();
             }
         }
-        mMeasuredMargin = mNumOfThumbs > 0 ? spaceForMargin / (mNumOfThumbs - 1) : 0;
     }
 
     @Override
@@ -177,7 +243,7 @@
         int heroCenter = getPaddingTop() + heroView.getMeasuredHeight() / 2;
 
         for (int i = heroIndex - 1; i >= 0; i--) {
-            heroLeft -= mMeasuredMargin;
+            heroLeft -= mMeasuredMarginInPixel;
             View child = getChildAt(i);
             child.layout(heroLeft - child.getMeasuredWidth(),
                     heroCenter - child.getMeasuredHeight() / 2,
@@ -186,7 +252,7 @@
             heroLeft -= child.getMeasuredWidth();
         }
         for (int i = heroIndex + 1; i < mNumOfThumbs; i++) {
-            heroRight += mMeasuredMargin;
+            heroRight += mMeasuredMarginInPixel;
             View child = getChildAt(i);
             child.layout(heroRight,
                     heroCenter - child.getMeasuredHeight() / 2,
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/TitleHelper.java b/v17/leanback/src/android/support/v17/leanback/widget/TitleHelper.java
index f12d8d0..3aba59d 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/TitleHelper.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/TitleHelper.java
@@ -46,7 +46,7 @@
                 return mTitleView;
             }
             final boolean isRtl = ViewCompat.getLayoutDirection(focused)
-                    == View.LAYOUT_DIRECTION_RTL;
+                    == ViewCompat.LAYOUT_DIRECTION_RTL;
             final int forward = isRtl ? View.FOCUS_LEFT : View.FOCUS_RIGHT;
             if (mTitleView.hasFocus() && (direction == View.FOCUS_DOWN || direction == forward)) {
                 return mSceneRoot;
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/Visibility.java b/v17/leanback/src/android/support/v17/leanback/widget/Visibility.java
new file mode 100644
index 0000000..b16a2f9
--- /dev/null
+++ b/v17/leanback/src/android/support/v17/leanback/widget/Visibility.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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 android.support.v17.leanback.widget;
+
+import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
+
+import android.support.annotation.IntDef;
+import android.support.annotation.RestrictTo;
+import android.view.View;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/** @hide */
+@RestrictTo(LIBRARY_GROUP)
+@IntDef({View.VISIBLE, View.INVISIBLE, View.GONE})
+@Retention(RetentionPolicy.SOURCE)
+public @interface Visibility {}
diff --git a/v17/leanback/src/android/support/v17/leanback/widget/WindowAlignment.java b/v17/leanback/src/android/support/v17/leanback/widget/WindowAlignment.java
index a651b2e..3ddb6f0 100644
--- a/v17/leanback/src/android/support/v17/leanback/widget/WindowAlignment.java
+++ b/v17/leanback/src/android/support/v17/leanback/widget/WindowAlignment.java
@@ -254,27 +254,49 @@
                 }
             }
             if (!isMaxUnknown && !isMinUnknown) {
-                if (!mReversedFlow ? (mWindowAlignment & WINDOW_ALIGN_LOW_EDGE) != 0
-                        : (mWindowAlignment & WINDOW_ALIGN_HIGH_EDGE) != 0) {
-                    if (!mReversedFlow ? isPreferKeylineOverLowEdge()
-                            : isPreferKeylineOverHighEdge()) {
-                        // if we prefer key line, might align max child to key line for minScroll
-                        mMinScroll = Math.min(mMinScroll,
-                                calculateScrollToKeyLine(maxChildViewCenter, keyLine));
-                    } else {
-                        // don't over scroll max
-                        mMaxScroll = Math.max(mMinScroll, mMaxScroll);
+                if (!mReversedFlow) {
+                    if ((mWindowAlignment & WINDOW_ALIGN_LOW_EDGE) != 0) {
+                        if (isPreferKeylineOverLowEdge()) {
+                            // if we prefer key line, might align max child to key line for
+                            // minScroll
+                            mMinScroll = Math.min(mMinScroll,
+                                    calculateScrollToKeyLine(maxChildViewCenter, keyLine));
+                        } else {
+                            // don't over scroll max
+                            mMaxScroll = Math.max(mMinScroll, mMaxScroll);
+                        }
+                    } else if ((mWindowAlignment & WINDOW_ALIGN_HIGH_EDGE) != 0) {
+                        if (isPreferKeylineOverHighEdge()) {
+                            // if we prefer key line, might align min child to key line for
+                            // maxScroll
+                            mMaxScroll = Math.max(mMaxScroll,
+                                    calculateScrollToKeyLine(minChildViewCenter, keyLine));
+                        } else {
+                            // don't over scroll min
+                            mMinScroll = Math.min(mMinScroll, mMaxScroll);
+                        }
                     }
-                } else if (!mReversedFlow ? (mWindowAlignment & WINDOW_ALIGN_HIGH_EDGE) != 0
-                        : (mWindowAlignment & WINDOW_ALIGN_LOW_EDGE) != 0) {
-                    if (!mReversedFlow ? isPreferKeylineOverHighEdge()
-                            : isPreferKeylineOverLowEdge()) {
-                        // if we prefer key line, might align min child to key line for maxScroll
-                        mMaxScroll = Math.max(mMaxScroll,
-                                calculateScrollToKeyLine(minChildViewCenter, keyLine));
-                    } else {
-                        // don't over scroll min
-                        mMinScroll = Math.min(mMinScroll, mMaxScroll);
+                } else {
+                    if ((mWindowAlignment & WINDOW_ALIGN_LOW_EDGE) != 0) {
+                        if (isPreferKeylineOverLowEdge()) {
+                            // if we prefer key line, might align min child to key line for
+                            // maxScroll
+                            mMaxScroll = Math.max(mMaxScroll,
+                                    calculateScrollToKeyLine(minChildViewCenter, keyLine));
+                        } else {
+                            // don't over scroll min
+                            mMinScroll = Math.min(mMinScroll, mMaxScroll);
+                        }
+                    } else if ((mWindowAlignment & WINDOW_ALIGN_HIGH_EDGE) != 0) {
+                        if (isPreferKeylineOverHighEdge()) {
+                            // if we prefer key line, might align max child to key line for
+                            // minScroll
+                            mMinScroll = Math.min(mMinScroll,
+                                    calculateScrollToKeyLine(maxChildViewCenter, keyLine));
+                        } else {
+                            // don't over scroll max
+                            mMaxScroll = Math.max(mMinScroll, mMaxScroll);
+                        }
                     }
                 }
             }
diff --git a/v17/leanback/tests/AndroidManifest.xml b/v17/leanback/tests/AndroidManifest.xml
index 0a3d15c..b21246e 100644
--- a/v17/leanback/tests/AndroidManifest.xml
+++ b/v17/leanback/tests/AndroidManifest.xml
@@ -15,53 +15,54 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.support.v17.leanback.test">
-    <uses-sdk android:minSdkVersion="17"  android:targetSdkVersion="23"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application
-            android:supportsRtl="true">
+        android:supportsRtl="true">
         <activity android:name="android.support.v17.leanback.widget.GridActivity"
-                  android:exported="true" />
+                  android:exported="true"/>
 
         <activity android:name="android.support.v17.leanback.widget.TimePickerActivity"
-                  android:theme="@style/Theme.Leanback"
-                  android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback"/>
 
         <activity android:name="android.support.v17.leanback.widget.DatePickerActivity"
-                  android:theme="@style/Theme.Leanback"
-                  android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback"/>
 
         <activity
-                android:name="android.support.v17.leanback.app.wizard.GuidedStepAttributesTestActivity"
-                android:theme="@style/Theme.Leanback.GuidedStep"
-                android:exported="true" />
+            android:name="android.support.v17.leanback.app.wizard.GuidedStepAttributesTestActivity"
+            android:exported="true"
+            android:theme="@style/Theme.Leanback.GuidedStep"/>
 
         <activity android:name="android.support.v17.leanback.app.SingleFragmentTestActivity"
-            android:theme="@style/Theme.Leanback"
-            android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback"/>
 
         <activity android:name="android.support.v17.leanback.app.BrowseFragmentTestActivity"
-                  android:theme="@style/Theme.Leanback.Browse"
-                  android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback.Browse"/>
 
         <activity android:name="android.support.v17.leanback.app.SingleSupportFragmentTestActivity"
-            android:theme="@style/Theme.Leanback"
-            android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback"/>
 
         <activity android:name="android.support.v17.leanback.app.BrowseSupportFragmentTestActivity"
-                  android:theme="@style/Theme.Leanback.Browse"
-                  android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback.Browse"/>
 
         <activity android:name="android.support.v17.leanback.app.GuidedStepFragmentTestActivity"
-                  android:theme="@style/Theme.Leanback.GuidedStep"
-                  android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback.GuidedStep"/>
 
-        <activity android:name="android.support.v17.leanback.app.GuidedStepSupportFragmentTestActivity"
-                  android:theme="@style/Theme.Leanback.GuidedStep"
-                  android:exported="true" />
+        <activity
+            android:name="android.support.v17.leanback.app.GuidedStepSupportFragmentTestActivity"
+            android:exported="true"
+            android:theme="@style/Theme.Leanback.GuidedStep"/>
 
         <activity android:name="android.support.v17.leanback.app.TestActivity"
-            android:theme="@style/Theme.Leanback"
-            android:exported="true" />
+                  android:exported="true"
+                  android:theme="@style/Theme.Leanback"/>
     </application>
 
 </manifest>
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTest.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTest.java
index bb8e94b..fa324bf 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTest.java
@@ -18,6 +18,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.timeout;
@@ -62,7 +63,7 @@
                 actions.add(new GuidedAction.Builder().id(1000).title("OK").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -80,13 +81,13 @@
         GuidedStepTestFragment.Provider second = mockProvider(secondFragmentName);
 
         GuidedStepFragmentTestActivity activity = launchTestActivity(firstFragmentName);
-        verify(first, times(1)).onCreate(any(Bundle.class));
-        verify(first, times(1)).onCreateGuidance(any(Bundle.class));
-        verify(first, times(1)).onCreateActions(any(List.class), any(Bundle.class));
-        verify(first, times(1)).onCreateButtonActions(any(List.class), any(Bundle.class));
+        verify(first, times(1)).onCreate(nullable(Bundle.class));
+        verify(first, times(1)).onCreateGuidance(nullable(Bundle.class));
+        verify(first, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
+        verify(first, times(1)).onCreateButtonActions(any(List.class), nullable(Bundle.class));
         verify(first, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(first, times(1)).onViewStateRestored(any(Bundle.class));
+                nullable(Bundle.class), any(View.class));
+        verify(first, times(1)).onViewStateRestored(nullable(Bundle.class));
         verify(first, times(1)).onStart();
         verify(first, times(1)).onResume();
 
@@ -97,13 +98,13 @@
         verify(first, times(1)).onPause();
         verify(first, times(1)).onStop();
         verify(first, times(1)).onDestroyView();
-        verify(second, times(1)).onCreate(any(Bundle.class));
-        verify(second, times(1)).onCreateGuidance(any(Bundle.class));
-        verify(second, times(1)).onCreateActions(any(List.class), any(Bundle.class));
-        verify(second, times(1)).onCreateButtonActions(any(List.class), any(Bundle.class));
-        verify(second, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(second, times(1)).onViewStateRestored(any(Bundle.class));
+        verify(second, times(1)).onCreate(nullable(Bundle.class));
+        verify(second, times(1)).onCreateGuidance(nullable(Bundle.class));
+        verify(second, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
+        verify(second, times(1)).onCreateButtonActions(any(List.class), nullable(Bundle.class));
+        verify(second, times(1)).onCreateView(any(LayoutInflater.class), nullable(ViewGroup.class),
+                nullable(Bundle.class), any(View.class));
+        verify(second, times(1)).onViewStateRestored(nullable(Bundle.class));
         verify(second, times(1)).onStart();
         verify(second, times(1)).onResume();
 
@@ -114,10 +115,10 @@
         verify(second, times(1)).onStop();
         verify(second, times(1)).onDestroyView();
         verify(second, times(1)).onDestroy();
-        verify(first, times(1)).onCreateActions(any(List.class), any(Bundle.class));
+        verify(first, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(first, times(2)).onViewStateRestored(any(Bundle.class));
+                nullable(Bundle.class), any(View.class));
+        verify(first, times(2)).onViewStateRestored(nullable(Bundle.class));
         verify(first, times(2)).onStart();
         verify(first, times(2)).onResume();
 
@@ -143,7 +144,7 @@
                         .autoSaveRestoreEnabled(false).build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -174,11 +175,11 @@
         });
         PollingCheck.waitFor(new EnterTransitionFinish(second));
         verify(first, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         verify(first, times(1)).onDestroy();
-        verify(second, times(2)).onCreate(any(Bundle.class));
+        verify(second, times(2)).onCreate(nullable(Bundle.class));
         verify(second, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         verify(second, times(1)).onDestroy();
 
         sendKey(KeyEvent.KEYCODE_BACK);
@@ -189,10 +190,10 @@
         verify(second, times(2)).onDestroy();
         assertEquals("modified text", first.getFragment().findActionById(1001).getTitle());
         assertEquals("text", first.getFragment().findActionById(1002).getTitle());
-        verify(first, times(2)).onCreate(any(Bundle.class));
-        verify(first, times(2)).onCreateActions(any(List.class), any(Bundle.class));
+        verify(first, times(2)).onCreate(nullable(Bundle.class));
+        verify(first, times(2)).onCreateActions(any(List.class), nullable(Bundle.class));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
     }
 
 
@@ -207,7 +208,7 @@
                 actions.add(new GuidedAction.Builder().id(1001).title("Finish activity").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -241,7 +242,7 @@
                 actions.add(new GuidedAction.Builder().id(1001).title("Finish fragments").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -284,7 +285,7 @@
                 return null;
             }
         }).when(first).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -296,7 +297,7 @@
                         .title("list").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Boolean>() {
             @Override
             public Boolean answer(InvocationOnMock invocation) {
@@ -345,14 +346,14 @@
 
         PollingCheck.waitFor(new EnterTransitionFinish(second));
         verify(second, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
 
         // test expand sub action when return to first fragment
         expandSubActionInOnCreateView[0] = true;
         sendKey(KeyEvent.KEYCODE_BACK);
         PollingCheck.waitFor(new EnterTransitionFinish(first));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         assertTrue(first.getFragment().isExpanded());
 
         sendKey(KeyEvent.KEYCODE_BACK);
@@ -378,7 +379,7 @@
                         .title("list").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Boolean>() {
             @Override
             public Boolean answer(InvocationOnMock invocation) {
@@ -419,4 +420,32 @@
 
     }
 
+    @Test
+    public void buttonActionsRtl() throws Throwable {
+        final String firstFragmentName = generateMethodTestName("first");
+        GuidedStepTestFragment.Provider first = mockProvider(firstFragmentName);
+        doAnswer(new Answer<Void>() {
+            @Override
+            public Void answer(InvocationOnMock invocation) {
+                List actions = (List) invocation.getArguments()[0];
+                actions.add(new GuidedAction.Builder().id(1000).title("action").build());
+                return null;
+            }
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
+        doAnswer(new Answer<Void>() {
+            @Override
+            public Void answer(InvocationOnMock invocation) {
+                List actions = (List) invocation.getArguments()[0];
+                actions.add(new GuidedAction.Builder().id(1001).title("button action").build());
+                return null;
+            }
+        }).when(first).onCreateButtonActions(any(List.class), nullable(Bundle.class));
+
+        final GuidedStepFragmentTestActivity activity = launchTestActivity(firstFragmentName,
+                true, View.LAYOUT_DIRECTION_RTL);
+
+        assertEquals(View.LAYOUT_DIRECTION_RTL, first.getFragment().getView().getLayoutDirection());
+        View firstView = first.getFragment().getActionItemView(0);
+        assertTrue(firstView.hasFocus());
+    }
 }
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestActivity.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestActivity.java
index 06beab6..4dcf188 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestActivity.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestActivity.java
@@ -32,12 +32,21 @@
      */
     public static final String EXTRA_ADD_AS_ROOT = "addAsRoot";
 
+    /**
+     * Layout direction
+     */
+    public static final String EXTRA_LAYOUT_DIRECTION = "layoutDir";
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         Intent intent = getIntent();
 
+        int layoutDirection = intent.getIntExtra(EXTRA_LAYOUT_DIRECTION, -1);
+        if (layoutDirection != -1) {
+            findViewById(android.R.id.content).setLayoutDirection(layoutDirection);
+        }
         if (savedInstanceState == null) {
             String firstTestName = intent.getStringExtra(EXTRA_TEST_NAME);
             if (firstTestName != null) {
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestBase.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestBase.java
index 6ed254a..7059c9a 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestBase.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepFragmentTestBase.java
@@ -125,6 +125,15 @@
         return activityTestRule.launchActivity(intent);
     }
 
+    public GuidedStepFragmentTestActivity launchTestActivity(String firstTestName,
+            boolean addAsRoot, int layoutDirection) {
+        Intent intent = new Intent();
+        intent.putExtra(GuidedStepFragmentTestActivity.EXTRA_TEST_NAME, firstTestName);
+        intent.putExtra(GuidedStepFragmentTestActivity.EXTRA_ADD_AS_ROOT, addAsRoot);
+        intent.putExtra(GuidedStepFragmentTestActivity.EXTRA_LAYOUT_DIRECTION, layoutDirection);
+        return activityTestRule.launchActivity(intent);
+    }
+
     public GuidedStepTestFragment.Provider mockProvider(String testName) {
         GuidedStepTestFragment.Provider test = mock(GuidedStepTestFragment.Provider.class);
         when(test.getActivity()).thenCallRealMethod();
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTest.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTest.java
index f2ac612..b4d9b59 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTest.java
@@ -21,6 +21,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.timeout;
@@ -65,7 +66,7 @@
                 actions.add(new GuidedAction.Builder().id(1000).title("OK").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -83,13 +84,13 @@
         GuidedStepTestSupportFragment.Provider second = mockProvider(secondFragmentName);
 
         GuidedStepSupportFragmentTestActivity activity = launchTestActivity(firstFragmentName);
-        verify(first, times(1)).onCreate(any(Bundle.class));
-        verify(first, times(1)).onCreateGuidance(any(Bundle.class));
-        verify(first, times(1)).onCreateActions(any(List.class), any(Bundle.class));
-        verify(first, times(1)).onCreateButtonActions(any(List.class), any(Bundle.class));
+        verify(first, times(1)).onCreate(nullable(Bundle.class));
+        verify(first, times(1)).onCreateGuidance(nullable(Bundle.class));
+        verify(first, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
+        verify(first, times(1)).onCreateButtonActions(any(List.class), nullable(Bundle.class));
         verify(first, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(first, times(1)).onViewStateRestored(any(Bundle.class));
+                nullable(Bundle.class), any(View.class));
+        verify(first, times(1)).onViewStateRestored(nullable(Bundle.class));
         verify(first, times(1)).onStart();
         verify(first, times(1)).onResume();
 
@@ -100,13 +101,13 @@
         verify(first, times(1)).onPause();
         verify(first, times(1)).onStop();
         verify(first, times(1)).onDestroyView();
-        verify(second, times(1)).onCreate(any(Bundle.class));
-        verify(second, times(1)).onCreateGuidance(any(Bundle.class));
-        verify(second, times(1)).onCreateActions(any(List.class), any(Bundle.class));
-        verify(second, times(1)).onCreateButtonActions(any(List.class), any(Bundle.class));
-        verify(second, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(second, times(1)).onViewStateRestored(any(Bundle.class));
+        verify(second, times(1)).onCreate(nullable(Bundle.class));
+        verify(second, times(1)).onCreateGuidance(nullable(Bundle.class));
+        verify(second, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
+        verify(second, times(1)).onCreateButtonActions(any(List.class), nullable(Bundle.class));
+        verify(second, times(1)).onCreateView(any(LayoutInflater.class), nullable(ViewGroup.class),
+                nullable(Bundle.class), any(View.class));
+        verify(second, times(1)).onViewStateRestored(nullable(Bundle.class));
         verify(second, times(1)).onStart();
         verify(second, times(1)).onResume();
 
@@ -117,10 +118,10 @@
         verify(second, times(1)).onStop();
         verify(second, times(1)).onDestroyView();
         verify(second, times(1)).onDestroy();
-        verify(first, times(1)).onCreateActions(any(List.class), any(Bundle.class));
+        verify(first, times(1)).onCreateActions(any(List.class), nullable(Bundle.class));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
-        verify(first, times(2)).onViewStateRestored(any(Bundle.class));
+                nullable(Bundle.class), any(View.class));
+        verify(first, times(2)).onViewStateRestored(nullable(Bundle.class));
         verify(first, times(2)).onStart();
         verify(first, times(2)).onResume();
 
@@ -146,7 +147,7 @@
                         .autoSaveRestoreEnabled(false).build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -177,11 +178,11 @@
         });
         PollingCheck.waitFor(new EnterTransitionFinish(second));
         verify(first, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         verify(first, times(1)).onDestroy();
-        verify(second, times(2)).onCreate(any(Bundle.class));
+        verify(second, times(2)).onCreate(nullable(Bundle.class));
         verify(second, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         verify(second, times(1)).onDestroy();
 
         sendKey(KeyEvent.KEYCODE_BACK);
@@ -192,10 +193,10 @@
         verify(second, times(2)).onDestroy();
         assertEquals("modified text", first.getFragment().findActionById(1001).getTitle());
         assertEquals("text", first.getFragment().findActionById(1002).getTitle());
-        verify(first, times(2)).onCreate(any(Bundle.class));
-        verify(first, times(2)).onCreateActions(any(List.class), any(Bundle.class));
+        verify(first, times(2)).onCreate(nullable(Bundle.class));
+        verify(first, times(2)).onCreateActions(any(List.class), nullable(Bundle.class));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
     }
 
 
@@ -210,7 +211,7 @@
                 actions.add(new GuidedAction.Builder().id(1001).title("Finish activity").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -244,7 +245,7 @@
                 actions.add(new GuidedAction.Builder().id(1001).title("Finish fragments").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -287,7 +288,7 @@
                 return null;
             }
         }).when(first).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         doAnswer(new Answer<Void>() {
             @Override
             public Void answer(InvocationOnMock invocation) {
@@ -299,7 +300,7 @@
                         .title("list").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Boolean>() {
             @Override
             public Boolean answer(InvocationOnMock invocation) {
@@ -348,14 +349,14 @@
 
         PollingCheck.waitFor(new EnterTransitionFinish(second));
         verify(second, times(1)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
 
         // test expand sub action when return to first fragment
         expandSubActionInOnCreateView[0] = true;
         sendKey(KeyEvent.KEYCODE_BACK);
         PollingCheck.waitFor(new EnterTransitionFinish(first));
         verify(first, times(2)).onCreateView(any(LayoutInflater.class), any(ViewGroup.class),
-                any(Bundle.class), any(View.class));
+                nullable(Bundle.class), any(View.class));
         assertTrue(first.getFragment().isExpanded());
 
         sendKey(KeyEvent.KEYCODE_BACK);
@@ -381,7 +382,7 @@
                         .title("list").build());
                 return null;
             }
-        }).when(first).onCreateActions(any(List.class), any(Bundle.class));
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
         doAnswer(new Answer<Boolean>() {
             @Override
             public Boolean answer(InvocationOnMock invocation) {
@@ -422,4 +423,32 @@
 
     }
 
+    @Test
+    public void buttonActionsRtl() throws Throwable {
+        final String firstFragmentName = generateMethodTestName("first");
+        GuidedStepTestSupportFragment.Provider first = mockProvider(firstFragmentName);
+        doAnswer(new Answer<Void>() {
+            @Override
+            public Void answer(InvocationOnMock invocation) {
+                List actions = (List) invocation.getArguments()[0];
+                actions.add(new GuidedAction.Builder().id(1000).title("action").build());
+                return null;
+            }
+        }).when(first).onCreateActions(any(List.class), nullable(Bundle.class));
+        doAnswer(new Answer<Void>() {
+            @Override
+            public Void answer(InvocationOnMock invocation) {
+                List actions = (List) invocation.getArguments()[0];
+                actions.add(new GuidedAction.Builder().id(1001).title("button action").build());
+                return null;
+            }
+        }).when(first).onCreateButtonActions(any(List.class), nullable(Bundle.class));
+
+        final GuidedStepSupportFragmentTestActivity activity = launchTestActivity(firstFragmentName,
+                true, View.LAYOUT_DIRECTION_RTL);
+
+        assertEquals(View.LAYOUT_DIRECTION_RTL, first.getFragment().getView().getLayoutDirection());
+        View firstView = first.getFragment().getActionItemView(0);
+        assertTrue(firstView.hasFocus());
+    }
 }
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestActivity.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestActivity.java
index 2fc8d1e..fb877ed 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestActivity.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestActivity.java
@@ -35,12 +35,21 @@
      */
     public static final String EXTRA_ADD_AS_ROOT = "addAsRoot";
 
+    /**
+     * Layout direction
+     */
+    public static final String EXTRA_LAYOUT_DIRECTION = "layoutDir";
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         Intent intent = getIntent();
 
+        int layoutDirection = intent.getIntExtra(EXTRA_LAYOUT_DIRECTION, -1);
+        if (layoutDirection != -1) {
+            findViewById(android.R.id.content).setLayoutDirection(layoutDirection);
+        }
         if (savedInstanceState == null) {
             String firstTestName = intent.getStringExtra(EXTRA_TEST_NAME);
             if (firstTestName != null) {
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestBase.java b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestBase.java
index 4fe4a24..17533fa 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestBase.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/GuidedStepSupportFragmentTestBase.java
@@ -128,6 +128,15 @@
         return activityTestRule.launchActivity(intent);
     }
 
+    public GuidedStepSupportFragmentTestActivity launchTestActivity(String firstTestName,
+            boolean addAsRoot, int layoutDirection) {
+        Intent intent = new Intent();
+        intent.putExtra(GuidedStepSupportFragmentTestActivity.EXTRA_TEST_NAME, firstTestName);
+        intent.putExtra(GuidedStepSupportFragmentTestActivity.EXTRA_ADD_AS_ROOT, addAsRoot);
+        intent.putExtra(GuidedStepSupportFragmentTestActivity.EXTRA_LAYOUT_DIRECTION, layoutDirection);
+        return activityTestRule.launchActivity(intent);
+    }
+
     public GuidedStepTestSupportFragment.Provider mockProvider(String testName) {
         GuidedStepTestSupportFragment.Provider test = mock(GuidedStepTestSupportFragment.Provider.class);
         when(test.getActivity()).thenCallRealMethod();
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/RowsFragmentTest.java b/v17/leanback/tests/java/android/support/v17/leanback/app/RowsFragmentTest.java
index f5f7bdf..b902678 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/RowsFragmentTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/RowsFragmentTest.java
@@ -21,15 +21,19 @@
 import static org.junit.Assert.assertTrue;
 
 import android.graphics.Rect;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.SystemClock;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.MediumTest;
+import android.support.test.filters.SdkSuppress;
 import android.support.test.runner.AndroidJUnit4;
+import android.support.v17.leanback.R;
 import android.support.v17.leanback.testutils.PollingCheck;
 import android.support.v17.leanback.widget.ArrayObjectAdapter;
 import android.support.v17.leanback.widget.HeaderItem;
+import android.support.v17.leanback.widget.HorizontalGridView;
 import android.support.v17.leanback.widget.ItemBridgeAdapter;
 import android.support.v17.leanback.widget.ListRow;
 import android.support.v17.leanback.widget.ListRowPresenter;
@@ -38,6 +42,7 @@
 import android.support.v17.leanback.widget.Presenter;
 import android.support.v17.leanback.widget.Row;
 import android.support.v17.leanback.widget.RowPresenter;
+import android.support.v17.leanback.widget.SinglePresenterSelector;
 import android.support.v17.leanback.widget.VerticalGridView;
 import android.view.KeyEvent;
 import android.view.View;
@@ -46,6 +51,7 @@
 import org.junit.runner.RunWith;
 
 import java.lang.ref.WeakReference;
+import java.util.ArrayList;
 
 @MediumTest
 @RunWith(AndroidJUnit4.class)
@@ -331,4 +337,128 @@
         );
     }
 
+    static class StableIdAdapter extends ObjectAdapter {
+        ArrayList<Integer> mList = new ArrayList();
+
+        @Override
+        public long getId(int position) {
+            return mList.get(position).longValue();
+        }
+
+        @Override
+        public Object get(int position) {
+            return mList.get(position);
+        }
+
+        @Override
+        public int size() {
+            return mList.size();
+        }
+    }
+
+    public static class F_rowNotifyItemRangeChange extends BrowseFragment {
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ListRowPresenter lrp = new ListRowPresenter();
+            final ArrayObjectAdapter adapter = new ArrayObjectAdapter(lrp);
+            for (int i = 0; i < 2; i++) {
+                StableIdAdapter listRowAdapter = new StableIdAdapter();
+                listRowAdapter.setHasStableIds(true);
+                listRowAdapter.setPresenterSelector(
+                        new SinglePresenterSelector(sCardPresenter));
+                int index = 0;
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                HeaderItem header = new HeaderItem(i, "Row " + i);
+                adapter.add(new ListRow(header, listRowAdapter));
+            }
+            setAdapter(adapter);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    StableIdAdapter rowAdapter = (StableIdAdapter)
+                            ((ListRow) adapter.get(1)).getAdapter();
+                    rowAdapter.notifyItemRangeChanged(0, 3);
+                }
+            }, 500);
+        }
+    }
+
+    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
+    @Test
+    public void rowNotifyItemRangeChange() throws InterruptedException {
+        SingleFragmentTestActivity activity = launchAndWaitActivity(
+                RowsFragmentTest.F_rowNotifyItemRangeChange.class, 2000);
+
+        VerticalGridView verticalGridView = ((BrowseFragment) activity.getTestFragment())
+                .getRowsFragment().getVerticalGridView();
+        for (int i = 0; i < verticalGridView.getChildCount(); i++) {
+            HorizontalGridView horizontalGridView = verticalGridView.getChildAt(i)
+                    .findViewById(R.id.row_content);
+            for (int j = 0; j < horizontalGridView.getChildCount(); j++) {
+                assertEquals(horizontalGridView.getPaddingTop(),
+                        horizontalGridView.getChildAt(j).getTop());
+            }
+        }
+    }
+
+    public static class F_rowNotifyItemRangeChangeWithTransition extends BrowseFragment {
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ListRowPresenter lrp = new ListRowPresenter();
+            prepareEntranceTransition();
+            final ArrayObjectAdapter adapter = new ArrayObjectAdapter(lrp);
+            for (int i = 0; i < 2; i++) {
+                StableIdAdapter listRowAdapter = new StableIdAdapter();
+                listRowAdapter.setHasStableIds(true);
+                listRowAdapter.setPresenterSelector(
+                        new SinglePresenterSelector(sCardPresenter));
+                int index = 0;
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                HeaderItem header = new HeaderItem(i, "Row " + i);
+                adapter.add(new ListRow(header, listRowAdapter));
+            }
+            setAdapter(adapter);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    StableIdAdapter rowAdapter = (StableIdAdapter)
+                            ((ListRow) adapter.get(1)).getAdapter();
+                    rowAdapter.notifyItemRangeChanged(0, 3);
+                }
+            }, 500);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    startEntranceTransition();
+                }
+            }, 520);
+        }
+    }
+
+    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
+    @Test
+    public void rowNotifyItemRangeChangeWithTransition() throws InterruptedException {
+        SingleFragmentTestActivity activity = launchAndWaitActivity(
+                        RowsFragmentTest.F_rowNotifyItemRangeChangeWithTransition.class, 3000);
+
+        VerticalGridView verticalGridView = ((BrowseFragment) activity.getTestFragment())
+                .getRowsFragment().getVerticalGridView();
+        for (int i = 0; i < verticalGridView.getChildCount(); i++) {
+            HorizontalGridView horizontalGridView = verticalGridView.getChildAt(i)
+                    .findViewById(R.id.row_content);
+            for (int j = 0; j < horizontalGridView.getChildCount(); j++) {
+                assertEquals(horizontalGridView.getPaddingTop(),
+                        horizontalGridView.getChildAt(j).getTop());
+                assertEquals(0, horizontalGridView.getChildAt(j).getTranslationY(), 0.1f);
+            }
+        }
+    }
 }
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/app/RowsSupportFragmentTest.java b/v17/leanback/tests/java/android/support/v17/leanback/app/RowsSupportFragmentTest.java
index 7d40644..a46730d 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/app/RowsSupportFragmentTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/app/RowsSupportFragmentTest.java
@@ -24,15 +24,19 @@
 import static org.junit.Assert.assertTrue;
 
 import android.graphics.Rect;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.SystemClock;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.MediumTest;
+import android.support.test.filters.SdkSuppress;
 import android.support.test.runner.AndroidJUnit4;
+import android.support.v17.leanback.R;
 import android.support.v17.leanback.testutils.PollingCheck;
 import android.support.v17.leanback.widget.ArrayObjectAdapter;
 import android.support.v17.leanback.widget.HeaderItem;
+import android.support.v17.leanback.widget.HorizontalGridView;
 import android.support.v17.leanback.widget.ItemBridgeAdapter;
 import android.support.v17.leanback.widget.ListRow;
 import android.support.v17.leanback.widget.ListRowPresenter;
@@ -41,6 +45,7 @@
 import android.support.v17.leanback.widget.Presenter;
 import android.support.v17.leanback.widget.Row;
 import android.support.v17.leanback.widget.RowPresenter;
+import android.support.v17.leanback.widget.SinglePresenterSelector;
 import android.support.v17.leanback.widget.VerticalGridView;
 import android.view.KeyEvent;
 import android.view.View;
@@ -49,6 +54,7 @@
 import org.junit.runner.RunWith;
 
 import java.lang.ref.WeakReference;
+import java.util.ArrayList;
 
 @MediumTest
 @RunWith(AndroidJUnit4.class)
@@ -334,4 +340,128 @@
         );
     }
 
+    static class StableIdAdapter extends ObjectAdapter {
+        ArrayList<Integer> mList = new ArrayList();
+
+        @Override
+        public long getId(int position) {
+            return mList.get(position).longValue();
+        }
+
+        @Override
+        public Object get(int position) {
+            return mList.get(position);
+        }
+
+        @Override
+        public int size() {
+            return mList.size();
+        }
+    }
+
+    public static class F_rowNotifyItemRangeChange extends BrowseSupportFragment {
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ListRowPresenter lrp = new ListRowPresenter();
+            final ArrayObjectAdapter adapter = new ArrayObjectAdapter(lrp);
+            for (int i = 0; i < 2; i++) {
+                StableIdAdapter listRowAdapter = new StableIdAdapter();
+                listRowAdapter.setHasStableIds(true);
+                listRowAdapter.setPresenterSelector(
+                        new SinglePresenterSelector(sCardPresenter));
+                int index = 0;
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                HeaderItem header = new HeaderItem(i, "Row " + i);
+                adapter.add(new ListRow(header, listRowAdapter));
+            }
+            setAdapter(adapter);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    StableIdAdapter rowAdapter = (StableIdAdapter)
+                            ((ListRow) adapter.get(1)).getAdapter();
+                    rowAdapter.notifyItemRangeChanged(0, 3);
+                }
+            }, 500);
+        }
+    }
+
+    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
+    @Test
+    public void rowNotifyItemRangeChange() throws InterruptedException {
+        SingleSupportFragmentTestActivity activity = launchAndWaitActivity(
+                RowsSupportFragmentTest.F_rowNotifyItemRangeChange.class, 2000);
+
+        VerticalGridView verticalGridView = ((BrowseSupportFragment) activity.getTestFragment())
+                .getRowsSupportFragment().getVerticalGridView();
+        for (int i = 0; i < verticalGridView.getChildCount(); i++) {
+            HorizontalGridView horizontalGridView = verticalGridView.getChildAt(i)
+                    .findViewById(R.id.row_content);
+            for (int j = 0; j < horizontalGridView.getChildCount(); j++) {
+                assertEquals(horizontalGridView.getPaddingTop(),
+                        horizontalGridView.getChildAt(j).getTop());
+            }
+        }
+    }
+
+    public static class F_rowNotifyItemRangeChangeWithTransition extends BrowseSupportFragment {
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ListRowPresenter lrp = new ListRowPresenter();
+            prepareEntranceTransition();
+            final ArrayObjectAdapter adapter = new ArrayObjectAdapter(lrp);
+            for (int i = 0; i < 2; i++) {
+                StableIdAdapter listRowAdapter = new StableIdAdapter();
+                listRowAdapter.setHasStableIds(true);
+                listRowAdapter.setPresenterSelector(
+                        new SinglePresenterSelector(sCardPresenter));
+                int index = 0;
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                listRowAdapter.mList.add(index++);
+                HeaderItem header = new HeaderItem(i, "Row " + i);
+                adapter.add(new ListRow(header, listRowAdapter));
+            }
+            setAdapter(adapter);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    StableIdAdapter rowAdapter = (StableIdAdapter)
+                            ((ListRow) adapter.get(1)).getAdapter();
+                    rowAdapter.notifyItemRangeChanged(0, 3);
+                }
+            }, 500);
+            new Handler().postDelayed(new Runnable() {
+                @Override
+                public void run() {
+                    startEntranceTransition();
+                }
+            }, 520);
+        }
+    }
+
+    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
+    @Test
+    public void rowNotifyItemRangeChangeWithTransition() throws InterruptedException {
+        SingleSupportFragmentTestActivity activity = launchAndWaitActivity(
+                        RowsSupportFragmentTest.F_rowNotifyItemRangeChangeWithTransition.class, 3000);
+
+        VerticalGridView verticalGridView = ((BrowseSupportFragment) activity.getTestFragment())
+                .getRowsSupportFragment().getVerticalGridView();
+        for (int i = 0; i < verticalGridView.getChildCount(); i++) {
+            HorizontalGridView horizontalGridView = verticalGridView.getChildAt(i)
+                    .findViewById(R.id.row_content);
+            for (int j = 0; j < horizontalGridView.getChildCount(); j++) {
+                assertEquals(horizontalGridView.getPaddingTop(),
+                        horizontalGridView.getChildAt(j).getTop());
+                assertEquals(0, horizontalGridView.getChildAt(j).getTranslationY(), 0.1f);
+            }
+        }
+    }
 }
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/widget/GridWidgetTest.java b/v17/leanback/tests/java/android/support/v17/leanback/widget/GridWidgetTest.java
index 1a173b4..61974cc 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/widget/GridWidgetTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/widget/GridWidgetTest.java
@@ -920,8 +920,7 @@
 
     void preparePredictiveLayout() throws Throwable {
         Intent intent = new Intent();
-        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID,
-                R.layout.horizontal_linear);
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID, R.layout.horizontal_linear);
         intent.putExtra(GridActivity.EXTRA_NUM_ITEMS, 100);
         initActivity(intent);
         mOrientation = BaseGridView.HORIZONTAL;
@@ -1016,6 +1015,50 @@
     }
 
     @Test
+    public void testPredictiveOnMeasureWrapContent() throws Throwable {
+        Intent intent = new Intent();
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID,
+                R.layout.horizontal_linear_wrap_content);
+        int count = 50;
+        intent.putExtra(GridActivity.EXTRA_NUM_ITEMS, count);
+        initActivity(intent);
+        mOrientation = BaseGridView.HORIZONTAL;
+        mNumRows = 1;
+
+        waitForScrollIdle(mVerifyLayout);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mGridView.setHasFixedSize(false);
+            }
+        });
+
+        for (int i = 0; i < 30; i++) {
+            final int oldCount = count;
+            final int newCount = i;
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if (oldCount > 0) {
+                        mActivity.removeItems(0, oldCount);
+                    }
+                    if (newCount > 0) {
+                        int[] newItems = new int[newCount];
+                        for (int i = 0; i < newCount; i++) {
+                            newItems[i] = 400;
+                        }
+                        mActivity.addItems(0, newItems);
+                    }
+                }
+            });
+            waitForItemAnimationStart();
+            waitForItemAnimation();
+            count = newCount;
+        }
+
+    }
+
+    @Test
     public void testPredictiveLayoutRemove4() throws Throwable {
         Intent intent = new Intent();
         intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID,
@@ -1419,6 +1462,27 @@
     }
 
     @Test
+    public void testItemMovedHorizontalRtl() throws Throwable {
+        Intent intent = new Intent();
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID,
+                R.layout.horizontal_linear_rtl);
+        intent.putExtra(GridActivity.EXTRA_STAGGERED, false);
+        intent.putExtra(GridActivity.EXTRA_ITEMS, new int[] {40, 40, 40});
+        initActivity(intent);
+        mOrientation = BaseGridView.HORIZONTAL;
+        mNumRows = 1;
+
+        performAndWaitForAnimation(new Runnable() {
+            @Override
+            public void run() {
+                mActivity.moveItem(0, 1, true);
+            }
+        });
+        assertEquals(mGridView.getWidth() - mGridView.getPaddingRight(),
+                mGridView.findViewHolderForAdapterPosition(0).itemView.getRight());
+    }
+
+    @Test
     public void testScrollSecondaryCannotScroll() throws Throwable {
         Intent intent = new Intent();
         intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID,
@@ -3116,7 +3180,6 @@
 
     }
 
-
     @Test
     public void testZeroFixedSecondarySize() throws Throwable {
         Intent intent = new Intent();
@@ -3888,6 +3951,108 @@
         assertTrue(selectedPosition2 < selectedPosition1);
     }
 
+    @Test
+    public void testAccessibilityScrollForwardHalfVisible() throws Throwable {
+        Intent intent = new Intent();
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID, R.layout.vertical_linear);
+        intent.putExtra(GridActivity.EXTRA_CHILD_LAYOUT_ID, R.layout.item_button_at_bottom);
+        intent.putExtra(GridActivity.EXTRA_ITEMS,  new int[]{});
+        intent.putExtra(GridActivity.EXTRA_STAGGERED, false);
+        initActivity(intent);
+        mOrientation = BaseGridView.VERTICAL;
+        mNumRows = 1;
+
+        int height = mGridView.getHeight() - mGridView.getPaddingTop()
+                - mGridView.getPaddingBottom();
+        final int childHeight = height - mGridView.getVerticalSpacing() - 100;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mGridView.setWindowAlignment(BaseGridView.WINDOW_ALIGN_NO_EDGE);
+                mGridView.setWindowAlignmentOffset(100);
+                mGridView.setWindowAlignmentOffsetPercent(BaseGridView
+                        .WINDOW_ALIGN_OFFSET_PERCENT_DISABLED);
+                mGridView.setItemAlignmentOffset(0);
+                mGridView.setItemAlignmentOffsetPercent(BaseGridView
+                        .ITEM_ALIGN_OFFSET_PERCENT_DISABLED);
+            }
+        });
+        mActivity.addItems(0, new int[]{childHeight, childHeight});
+        waitForItemAnimation();
+        setSelectedPosition(0);
+
+        final RecyclerViewAccessibilityDelegate delegateCompat = mGridView
+                .getCompatAccessibilityDelegate();
+        final AccessibilityNodeInfoCompat info = AccessibilityNodeInfoCompat.obtain();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                delegateCompat.onInitializeAccessibilityNodeInfo(mGridView, info);
+            }
+        });
+        assertTrue("test sanity", info.isScrollable());
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                delegateCompat.performAccessibilityAction(mGridView,
+                        AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD, null);
+            }
+        });
+        waitForScrollIdle(mVerifyLayout);
+        assertEquals(1, mGridView.getSelectedPosition());
+    }
+
+    @Test
+    public void testAccessibilityScrollBackwardHalfVisible() throws Throwable {
+        Intent intent = new Intent();
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID, R.layout.vertical_linear);
+        intent.putExtra(GridActivity.EXTRA_CHILD_LAYOUT_ID, R.layout.item_button_at_top);
+        intent.putExtra(GridActivity.EXTRA_ITEMS,  new int[]{});
+        intent.putExtra(GridActivity.EXTRA_STAGGERED, false);
+        initActivity(intent);
+        mOrientation = BaseGridView.VERTICAL;
+        mNumRows = 1;
+
+        int height = mGridView.getHeight() - mGridView.getPaddingTop()
+                - mGridView.getPaddingBottom();
+        final int childHeight = height - mGridView.getVerticalSpacing() - 100;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mGridView.setWindowAlignment(BaseGridView.WINDOW_ALIGN_NO_EDGE);
+                mGridView.setWindowAlignmentOffset(100);
+                mGridView.setWindowAlignmentOffsetPercent(BaseGridView
+                        .WINDOW_ALIGN_OFFSET_PERCENT_DISABLED);
+                mGridView.setItemAlignmentOffset(0);
+                mGridView.setItemAlignmentOffsetPercent(BaseGridView
+                        .ITEM_ALIGN_OFFSET_PERCENT_DISABLED);
+            }
+        });
+        mActivity.addItems(0, new int[]{childHeight, childHeight});
+        waitForItemAnimation();
+        setSelectedPosition(1);
+
+        final RecyclerViewAccessibilityDelegate delegateCompat = mGridView
+                .getCompatAccessibilityDelegate();
+        final AccessibilityNodeInfoCompat info = AccessibilityNodeInfoCompat.obtain();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                delegateCompat.onInitializeAccessibilityNodeInfo(mGridView, info);
+            }
+        });
+        assertTrue("test sanity", info.isScrollable());
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                delegateCompat.performAccessibilityAction(mGridView,
+                        AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD, null);
+            }
+        });
+        waitForScrollIdle(mVerifyLayout);
+        assertEquals(0, mGridView.getSelectedPosition());
+    }
+
     void slideInAndWaitIdle() throws Throwable {
         slideInAndWaitIdle(5000);
     }
@@ -4884,14 +5049,14 @@
 
     void prepareKeyLineTest(int numItems) throws Throwable {
         Intent intent = new Intent();
-        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID, R.layout.vertical_linear);
+        intent.putExtra(GridActivity.EXTRA_LAYOUT_RESOURCE_ID, R.layout.horizontal_linear);
         int[] items = new int[numItems];
         for (int i = 0; i < items.length; i++) {
             items[i] = 32;
         }
         intent.putExtra(GridActivity.EXTRA_ITEMS, items);
         intent.putExtra(GridActivity.EXTRA_STAGGERED, false);
-        mOrientation = BaseGridView.VERTICAL;
+        mOrientation = BaseGridView.HORIZONTAL;
         mNumRows = 1;
 
         initActivity(intent);
@@ -4932,51 +5097,76 @@
             final boolean preferKeyLineOverHigh,
             ItemAt assertFirstItemLocation,
             ItemAt assertLastItemLocation) throws Throwable {
+        TestPreferKeyLineOptions options = new TestPreferKeyLineOptions();
+        options.mAssertItemLocations = new ItemAt[] {assertFirstItemLocation,
+                assertLastItemLocation};
+        options.mPreferKeyLineOverLow = preferKeyLineOverLow;
+        options.mPreferKeyLineOverHigh = preferKeyLineOverHigh;
+        options.mWindowAlignment = windowAlignment;
+
+        options.mRtl = false;
+        testPreferKeyLine(options);
+
+        options.mRtl = true;
+        testPreferKeyLine(options);
+    }
+
+    static class TestPreferKeyLineOptions {
+        int mWindowAlignment;
+        boolean mPreferKeyLineOverLow;
+        boolean mPreferKeyLineOverHigh;
+        ItemAt[] mAssertItemLocations;
+        boolean mRtl;
+    }
+
+    public void testPreferKeyLine(final TestPreferKeyLineOptions options) throws Throwable {
         startWaitLayout();
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
             public void run() {
-                mGridView.setWindowAlignment(windowAlignment);
+                if (options.mRtl) {
+                    mGridView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
+                } else {
+                    mGridView.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
+                }
+                mGridView.setWindowAlignment(options.mWindowAlignment);
                 mGridView.setWindowAlignmentOffsetPercent(50);
                 mGridView.setWindowAlignmentOffset(0);
-                mGridView.setWindowAlignmentPreferKeyLineOverLowEdge(preferKeyLineOverLow);
-                mGridView.setWindowAlignmentPreferKeyLineOverHighEdge(preferKeyLineOverHigh);
+                mGridView.setWindowAlignmentPreferKeyLineOverLowEdge(options.mPreferKeyLineOverLow);
+                mGridView.setWindowAlignmentPreferKeyLineOverHighEdge(
+                        options.mPreferKeyLineOverHigh);
             }
         });
         waitForLayout();
 
-        final int lowPadding = mGridView.getPaddingTop();
-        final int highPadding = mGridView.getHeight() - mGridView.getPaddingBottom();
-        final int windowAlignCenter = mGridView.getHeight() / 2;
+        final int paddingStart = mGridView.getPaddingStart();
+        final int paddingEnd = mGridView.getPaddingEnd();
+        final int windowAlignCenter = mGridView.getWidth() / 2;
 
-        setSelectedPosition(assertFirstItemLocation.mScrollPosition);
-        View view = mGridView.findViewHolderForAdapterPosition(assertFirstItemLocation.mPosition)
-                .itemView;
-        switch (assertFirstItemLocation.mLocation) {
-            case ITEM_AT_LOW:
-                assertEquals(lowPadding, view.getTop());
-                break;
-            case ITEM_AT_HIGH:
-                assertEquals(highPadding, view.getBottom());
-                break;
-            case ITEM_AT_KEY_LINE:
-                assertEquals(windowAlignCenter, view.getTop() + view.getHeight() / 2, DELTA);
-                break;
-        }
-
-        setSelectedPosition(assertLastItemLocation.mScrollPosition);
-        view = mGridView.findViewHolderForAdapterPosition(assertLastItemLocation.mPosition)
-                .itemView;
-        switch (assertLastItemLocation.mLocation) {
-            case ITEM_AT_LOW:
-                assertEquals(lowPadding, view.getTop());
-                break;
-            case ITEM_AT_HIGH:
-                assertEquals(highPadding, view.getBottom());
-                break;
-            case ITEM_AT_KEY_LINE:
-                assertEquals(windowAlignCenter, view.getTop() + view.getHeight() / 2, DELTA);
-                break;
+        for (int i = 0; i < options.mAssertItemLocations.length; i++) {
+            ItemAt assertItemLocation = options.mAssertItemLocations[i];
+            setSelectedPosition(assertItemLocation.mScrollPosition);
+            View view = mGridView.findViewHolderForAdapterPosition(assertItemLocation.mPosition)
+                    .itemView;
+            switch (assertItemLocation.mLocation) {
+                case ITEM_AT_LOW:
+                    if (options.mRtl) {
+                        assertEquals(mGridView.getWidth() - paddingStart, view.getRight());
+                    } else {
+                        assertEquals(paddingStart, view.getLeft());
+                    }
+                    break;
+                case ITEM_AT_HIGH:
+                    if (options.mRtl) {
+                        assertEquals(paddingEnd, view.getLeft());
+                    } else {
+                        assertEquals(mGridView.getWidth() - paddingEnd, view.getRight());
+                    }
+                    break;
+                case ITEM_AT_KEY_LINE:
+                    assertEquals(windowAlignCenter, (view.getLeft() + view.getRight()) / 2, DELTA);
+                    break;
+            }
         }
     }
 
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackGlueHostImplWithViewHolder.java b/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackGlueHostImplWithViewHolder.java
index d6a1f86..2cee649 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackGlueHostImplWithViewHolder.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackGlueHostImplWithViewHolder.java
@@ -56,12 +56,13 @@
         if (mViewHolder == null && mPlaybackRowPresenter != null && mRow != null) {
             mViewHolder = (PlaybackRowPresenter.ViewHolder)
                     mPlaybackRowPresenter.onCreateViewHolder(mRootView = new FrameLayout(mContext));
+            // Bind ViewHolder before measure/layout so child views will get proper size
+            mPlaybackRowPresenter.onBindViewHolder(mViewHolder, mRow);
             mRootView.addView(mViewHolder.view, mLayoutWidth, mLayoutHeight);
             mRootView.measure(
                     View.MeasureSpec.makeMeasureSpec(1920, View.MeasureSpec.AT_MOST),
                     View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
             mRootView.layout(0, 0, mRootView.getMeasuredWidth(), mRootView.getMeasuredHeight());
-            mPlaybackRowPresenter.onBindViewHolder(mViewHolder, mRow);
             if (mViewHolder instanceof PlaybackSeekUi) {
                 ((PlaybackSeekUi) mViewHolder).setPlaybackSeekUiClient(mChainedClient);
             }
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackTransportRowPresenterTest.java b/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackTransportRowPresenterTest.java
index 54d27a3..db55725 100644
--- a/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackTransportRowPresenterTest.java
+++ b/v17/leanback/tests/java/android/support/v17/leanback/widget/PlaybackTransportRowPresenterTest.java
@@ -37,6 +37,8 @@
 import android.support.v17.leanback.widget.PlaybackSeekDataProvider.ResultCallback;
 import android.view.ContextThemeWrapper;
 import android.view.KeyEvent;
+import android.view.View;
+import android.view.ViewParent;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -65,7 +67,24 @@
         InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
             @Override
             public void run() {
-                mGlue = new PlaybackTransportControlGlue(mContext, mImpl);
+                mGlue = new PlaybackTransportControlGlue(mContext, mImpl) {
+                    @Override
+                    protected void onCreatePrimaryActions(ArrayObjectAdapter
+                            primaryActionsAdapter) {
+                        super.onCreatePrimaryActions(primaryActionsAdapter);
+                        primaryActionsAdapter.add(
+                                new PlaybackControlsRow.ClosedCaptioningAction(mContext));
+                    }
+
+                    @Override
+                    protected void onCreateSecondaryActions(ArrayObjectAdapter
+                            secondaryActionsAdapter) {
+                        secondaryActionsAdapter.add(
+                                new PlaybackControlsRow.HighQualityAction(mContext));
+                        secondaryActionsAdapter.add(
+                                new PlaybackControlsRow.PictureInPictureAction(mContext));
+                    }
+                };
                 mGlue.setHost(mHost);
 
             }
@@ -195,6 +214,107 @@
         assertSame(art, mViewHolder.mImageView.getDrawable());
     }
 
+    static boolean isDescendant(View view, View descendant) {
+        while (descendant != view) {
+            ViewParent p = descendant.getParent();
+            if (!(p instanceof View)) {
+                return false;
+            }
+            descendant = (View) p;
+        }
+        return true;
+    }
+
+    @Test
+    public void navigateRightInPrimary() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mControlsVh.mControlBar.getChildAt(0).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mControlsVh.mControlBar.getChildAt(0), view));
+        assertTrue(isDescendant(mViewHolder.mControlsVh.mControlBar.getChildAt(1),
+                view.focusSearch(View.FOCUS_RIGHT)));
+    }
+
+    @Test
+    public void navigateRightInSecondary() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(0).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(0), view));
+        assertTrue(isDescendant(mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(1),
+                view.focusSearch(View.FOCUS_RIGHT)));
+    }
+
+    @Test
+    public void navigatePrimaryDownToProgress() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mControlsVh.mControlBar.getChildAt(0).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mControlsVh.mControlBar.getChildAt(0), view));
+        assertSame(mViewHolder.mProgressBar, view.focusSearch(View.FOCUS_DOWN));
+    }
+
+    @Test
+    public void navigateProgressUpToPrimary() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mProgressBar.requestFocus();
+            }
+        });
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mProgressBar.focusSearch(View.FOCUS_UP).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mControlsVh.mControlBar.getChildAt(0), view));
+    }
+
+    @Test
+    public void navigateProgressDownToSecondary() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mProgressBar.requestFocus();
+            }
+        });
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mProgressBar.focusSearch(View.FOCUS_DOWN).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(0), view));
+    }
+
+    @Test
+    public void navigateSecondaryUpToProgress() {
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(0).requestFocus();
+            }
+        });
+        View view = mViewHolder.view.findFocus();
+        assertTrue(isDescendant(mViewHolder.mSecondaryControlsVh.mControlBar.getChildAt(0), view));
+        assertSame(mViewHolder.mProgressBar, view.focusSearch(View.FOCUS_UP));
+    }
+
     @Test
     public void seekAndConfirm() {
         when(mImpl.isPrepared()).thenReturn(true);
diff --git a/v17/leanback/tests/java/android/support/v17/leanback/widget/ThumbsBarTest.java b/v17/leanback/tests/java/android/support/v17/leanback/widget/ThumbsBarTest.java
new file mode 100644
index 0000000..394d723
--- /dev/null
+++ b/v17/leanback/tests/java/android/support/v17/leanback/widget/ThumbsBarTest.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2017 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 android.support.v17.leanback.widget;
+
+import static junit.framework.Assert.assertEquals;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v17.leanback.R;
+import android.view.View;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+
+public class ThumbsBarTest {
+    private Context mContext;
+    private ThumbsBar mBar;
+
+    /**
+     * Check ThumbsBar's initialization based on the constructor
+     */
+    @Test
+    public void checkThumbsBarInitialize() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        assertEquals(mBar.mThumbHeightInPixel, mContext.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_thumbs_height));
+        assertEquals(mBar.mThumbWidthInPixel, mContext.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_thumbs_width));
+        assertEquals(mBar.mHeroThumbHeightInPixel, mContext.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_hero_thumbs_height));
+        assertEquals(mBar.mHeroThumbWidthInPixel, mContext.getResources().getDimensionPixelSize(
+                R.dimen.lb_playback_transport_hero_thumbs_width));
+    }
+
+    /**
+     * Check getHeroIndex method when input is an even number
+     */
+    @Test
+    public void checkGetHeroIndexOnEvenNumber() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int childCountForTest = 4;
+        // according to the algorithm, hero thumb's index should be childCounts / 2
+        int expectedHeroIndex = 2;
+        when(mBar.getChildCount()).thenReturn(childCountForTest);
+        assertEquals(mBar.getHeroIndex(), expectedHeroIndex);
+    }
+
+    /**
+     * Check getHeroIndex method when input is an odd number.
+     */
+    @Test
+    public void checkGetHeroIndexOnOddNumber() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int childCountForTest = 5;
+        // according to the algorithm, hero thumb's index should be childCounts / 2
+        int expectedHeroIndex = 2;
+        when(mBar.getChildCount()).thenReturn(childCountForTest);
+        assertEquals(mBar.getHeroIndex(), expectedHeroIndex);
+    }
+
+    /**
+     * Check setThumbSize method.
+     */
+    @Test
+    public void checkSetThumbSize() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest = 2560;
+        int screenHeightInPixelForTest = 1600;
+        int thumbsWidthInPixelForTest = 128;
+        int thumbsHeightInPixelForTest = 256;
+        // set screen size explicitly so the thumbs bar will have child view inside of it
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(screenWidthInPixelForTest,
+                View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(screenHeightInPixelForTest,
+                        View.MeasureSpec.EXACTLY));
+
+        mBar.setThumbSize(thumbsWidthInPixelForTest, thumbsHeightInPixelForTest);
+        // Verify the behavior of setThumbSize method
+        assertEquals(mBar.mThumbWidthInPixel, thumbsWidthInPixelForTest);
+        assertEquals(mBar.mThumbHeightInPixel, thumbsHeightInPixelForTest);
+        // iterate through all child view to test if its width/ height has been set successfully
+        for (int i = 0; i < mBar.getChildCount(); i++) {
+            if (i != mBar.getHeroIndex()) {
+                assertEquals(mBar.getChildAt(i).getLayoutParams().width,
+                        thumbsWidthInPixelForTest);
+                assertEquals(mBar.getChildAt(i).getLayoutParams().height,
+                        thumbsHeightInPixelForTest);
+            } else {
+                assertEquals(mBar.getChildAt(i).getLayoutParams().width,
+                        mContext.getResources().getDimensionPixelSize(
+                                R.dimen.lb_playback_transport_hero_thumbs_width));
+                assertEquals(mBar.getChildAt(i).getLayoutParams().height,
+                        mContext.getResources().getDimensionPixelSize(
+                                R.dimen.lb_playback_transport_hero_thumbs_height));
+            }
+        }
+    }
+
+    /**
+     * Check setHeroThumbSize method.
+     */
+    @Test
+    public void checkSetHeroThumbSize() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest = 2560;
+        int screenHeightInPixelForTest = 1600;
+        int HeroThumbsWidthInPixelForTest = 256;
+        int HeroThumbsHeightInPixelForTest = 512;
+        // set screen size explicitly so the thumbs bar will have child view inside of it
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(
+                screenWidthInPixelForTest, View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(
+                        screenHeightInPixelForTest, View.MeasureSpec.EXACTLY));
+        mBar.setHeroThumbSize(HeroThumbsWidthInPixelForTest, HeroThumbsHeightInPixelForTest);
+        // Verify the behavior of setThumbSize method
+        assertEquals(mBar.mHeroThumbWidthInPixel, HeroThumbsWidthInPixelForTest);
+        assertEquals(mBar.mHeroThumbHeightInPixel, HeroThumbsHeightInPixelForTest);
+        // iterate through all child view to test if its width/ height has been set successfully
+        for (int i = 0; i < mBar.getChildCount(); i++) {
+            if (i != mBar.getHeroIndex()) {
+                assertEquals(mBar.getChildAt(i).getLayoutParams().width,
+                        mContext.getResources().getDimensionPixelSize(
+                                R.dimen.lb_playback_transport_thumbs_width));
+                assertEquals(mBar.getChildAt(i).getLayoutParams().height,
+                        mContext.getResources().getDimensionPixelSize(
+                                R.dimen.lb_playback_transport_thumbs_height));
+            } else {
+                assertEquals(mBar.getChildAt(i).getLayoutParams().width,
+                        HeroThumbsWidthInPixelForTest);
+                assertEquals(mBar.getChildAt(i).getLayoutParams().height,
+                        HeroThumbsHeightInPixelForTest);
+            }
+        }
+    }
+
+    /**
+     * Check setThumbSpace method.
+     */
+    @Test
+    public void checkSetThumbSpace() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int thumbSpaceInPixelForTest = 48;
+        mBar.setThumbSpace(thumbSpaceInPixelForTest);
+        assertEquals(mBar.mMeasuredMarginInPixel, thumbSpaceInPixelForTest);
+        verify(mBar).requestLayout();
+    }
+
+    /**
+     * check calculateNumberOfThumbs method when the result from roundUp function is less than 2
+     *
+     * Firstly, to make sure the test cases can run on different devices with different screen
+     * density (i.e. The return value from roundUp function should be the same no matter what kind
+     * of device/ emulator is connected),
+     * the screen width for test is set using dp, the pixel value will be computed by
+     * multiplying context.getResources().getDisplayMetrics().density
+     *
+     * In this test case, the screen width is set to 240 in dp, so the calculation result should
+     * be 1. According to the algorithm of calculateNumOfThumbs, it should be reassigned to 2 and
+     * the final result should be 3 after counting the hero thumb.
+     */
+    @Test
+    public void checkCalculateNumberOfThumbs1() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest =
+                (int) (240 * mContext.getResources().getDisplayMetrics().density);
+        int screenHeightInPixelForTest =
+                (int) (240 * mContext.getResources().getDisplayMetrics().density);
+        int expectedChildCounts = 3;
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(
+                screenWidthInPixelForTest, View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(
+                        screenHeightInPixelForTest, View.MeasureSpec.EXACTLY));
+        assertEquals(mBar.getChildCount(), expectedChildCounts);
+    }
+
+    /**
+     * check calculateNumberOfThumbs method when the result from roundUp function is an odd number
+     * and larger than 2.
+     *
+     * In this test case, the screen width is set to 680 in dp, so the calculation result should
+     * be 3. According to the algorithm of calculateNumOfThumbs, it should be incremented by 1, so
+     * the final result is 5 after counting the hero thumb.
+     */
+    @Test
+    public void checkCalculateNumberOfThumbs2() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest =
+                (int) (680 * mContext.getResources().getDisplayMetrics().density);
+        int screenHeightInPixelForTest =
+                (int) (680 * mContext.getResources().getDisplayMetrics().density);
+        int expectedChildCounts = 5;
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(
+                screenWidthInPixelForTest, View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(
+                        screenHeightInPixelForTest, View.MeasureSpec.EXACTLY));
+        assertEquals(mBar.getChildCount(), expectedChildCounts);
+    }
+
+    /**
+     * check calculateNumberOfThumbs method when the result from roundUp function is an even number
+     * and larger than 2
+     *
+     * In this test case, the screen width is set to 800 in dp, so the calculation result should
+     * be 4. Finally the result is expected to be 5 after counting the hero thumb.
+     */
+    @Test
+    public void checkCalculateNumberOfThumbs3() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest =
+                (int) (800 * mContext.getResources().getDisplayMetrics().density);
+        int screenHeightInPixelForTest =
+                (int) (800 * mContext.getResources().getDisplayMetrics().density);
+        int expectedChildCounts = 5;
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(
+                screenWidthInPixelForTest, View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(
+                        screenHeightInPixelForTest, View.MeasureSpec.EXACTLY));
+        assertEquals(mBar.getChildCount(), expectedChildCounts);
+    }
+
+    /**
+     * check setNumberOfThumbs method
+     *
+     * When user calling setNumberOfThumbs(int numOfThumbs) method. The flag mIsUserSets will be
+     * toggled to true to honor user's choice, and the result of child view's number should
+     * not be impacted by calculateNumberOfThumbs(int widthInPixel) method.
+     *
+     * In this test case, the screen width is set to 960 in dp, the calculation result from
+     * calculateNumberOfThumbs method should be 5. But after calling setNumberOfThumbs function to
+     * set thumbs' number to 3, this value should not impact the final result.
+     */
+    @Test
+    public void checkSetNumberOfThumbs() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
+            @Override
+            public void run() {
+                mBar = Mockito.spy(new ThumbsBar(mContext, null));
+            }
+        });
+        int screenWidthInPixelForTest =
+                (int) (960 * mContext.getResources().getDisplayMetrics().density);
+        int screenHeightInPixelForTest =
+                (int) (960 * mContext.getResources().getDisplayMetrics().density);
+        int numberOfThumbs = 3;
+        mBar.setNumberOfThumbs(numberOfThumbs);
+        mBar.measure(View.MeasureSpec.makeMeasureSpec(
+                screenWidthInPixelForTest, View.MeasureSpec.EXACTLY),
+                View.MeasureSpec.makeMeasureSpec(
+                        screenHeightInPixelForTest, View.MeasureSpec.EXACTLY));
+        assertEquals(mBar.getChildCount(), numberOfThumbs);
+    }
+}
diff --git a/v17/leanback/tests/res/layout/horizontal_linear_wrap_content.xml b/v17/leanback/tests/res/layout/horizontal_linear_wrap_content.xml
new file mode 100644
index 0000000..c0e2715
--- /dev/null
+++ b/v17/leanback/tests/res/layout/horizontal_linear_wrap_content.xml
@@ -0,0 +1,39 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:lb="http://schemas.android.com/apk/res-auto"
+    android:orientation="vertical"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    >
+  <android.support.v17.leanback.widget.HorizontalGridViewEx
+      android:id="@+id/gridview"
+      android:layout_width="match_parent"
+      android:layout_height="wrap_content"
+      android:clipToPadding="false"
+      android:focusable="true"
+      android:focusableInTouchMode="true"
+      android:background="#00ffff"
+      android:horizontalSpacing="12dip"
+      android:verticalSpacing="24dip"
+      lb:rowHeight="wrap_content"
+      android:paddingBottom="12dip"
+      android:paddingLeft="12dip"
+      android:paddingRight="12dip"
+      android:paddingTop="12dip" />
+</LinearLayout>
diff --git a/v17/leanback/tests/res/layout/item_button_at_bottom.xml b/v17/leanback/tests/res/layout/item_button_at_bottom.xml
new file mode 100644
index 0000000..8afc622
--- /dev/null
+++ b/v17/leanback/tests/res/layout/item_button_at_bottom.xml
@@ -0,0 +1,32 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="400dp"
+    android:layout_height="400dp"
+    >
+    <TextView
+        android:layout_alignParentTop="true"
+        android:text="unfocusable text"
+        android:layout_width="match_parent"
+        android:layout_height="50dp"/>
+    <Button
+        android:layout_alignParentBottom="true"
+        android:text="button"
+        android:focusable="true"
+        android:layout_width="match_parent"
+        android:layout_height="50dp"/>
+</RelativeLayout>
diff --git a/v17/leanback/tests/res/layout/item_button_at_top.xml b/v17/leanback/tests/res/layout/item_button_at_top.xml
new file mode 100644
index 0000000..5199193
--- /dev/null
+++ b/v17/leanback/tests/res/layout/item_button_at_top.xml
@@ -0,0 +1,33 @@
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="400dp"
+    android:layout_height="400dp"
+    >
+    <TextView
+        android:layout_alignParentBottom="true"
+        android:text="unfocusable text"
+        android:layout_width="match_parent"
+        android:layout_height="50dp"/>
+    <Button
+        android:layout_alignParentTop="true"
+        android:text="button"
+        android:focusable="true"
+        android:layout_width="match_parent"
+        android:layout_height="50dp"/>
+</RelativeLayout>
diff --git a/v17/preference-leanback/build.gradle b/v17/preference-leanback/build.gradle
index 8de4c00..23672e3 100644
--- a/v17/preference-leanback/build.gradle
+++ b/v17/preference-leanback/build.gradle
@@ -2,12 +2,12 @@
 archivesBaseName = 'preference-leanback-v17'
 
 dependencies {
-    compile project(':support-v4')
-    compile project(':support-appcompat-v7')
-    compile project(':support-recyclerview-v7')
-    compile project(':support-preference-v7')
-    compile project(':support-preference-v14')
-    compile project(':support-leanback-v17')
+    api project(':support-v4')
+    api project(':support-appcompat-v7')
+    api project(':support-recyclerview-v7')
+    api project(':support-preference-v7')
+    api project(':support-preference-v14')
+    api project(':support-leanback-v17')
 }
 
 android {
diff --git a/v17/preference-leanback/lint-baseline.xml b/v17/preference-leanback/lint-baseline.xml
new file mode 100644
index 0000000..22aaf9d
--- /dev/null
+++ b/v17/preference-leanback/lint-baseline.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        &lt;Space android:layout_width=&quot;0dp&quot; android:layout_height=&quot;@dimen/lb_preference_item_text_space_top&quot; />"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/leanback_list_preference_item_multi.xml"
+            line="42"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        &lt;Space android:layout_width=&quot;0dp&quot; android:layout_height=&quot;@dimen/lb_preference_item_text_space_top&quot; />"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/leanback_list_preference_item_single.xml"
+            line="42"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        &lt;Space android:layout_width=&quot;0dp&quot; android:layout_height=&quot;@dimen/lb_preference_item_text_space_top&quot; />"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/leanback_preference.xml"
+            line="47"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        &lt;Space android:layout_width=&quot;0dp&quot; android:layout_height=&quot;@dimen/lb_preference_item_text_space_top&quot; />"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/leanback_preference_information.xml"
+            line="34"
+            column="16"/>
+    </issue>
+
+</issues>
diff --git a/v4/build.gradle b/v4/build.gradle
index 87bc171..d363eba 100644
--- a/v4/build.gradle
+++ b/v4/build.gradle
@@ -2,11 +2,11 @@
 archivesBaseName = 'support-v4'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-media-compat')
-    compile project(':support-core-utils')
-    compile project(':support-core-ui')
-    compile project(':support-fragment')
+    api project(':support-compat')
+    api project(':support-media-compat')
+    api project(':support-core-utils')
+    api project(':support-core-ui')
+    api project(':support-fragment')
 }
 
 android {
diff --git a/v4/lint-baseline.xml b/v4/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v4/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v7/appcompat/build.gradle b/v7/appcompat/build.gradle
index 706d6d3..20d9393 100644
--- a/v7/appcompat/build.gradle
+++ b/v7/appcompat/build.gradle
@@ -2,21 +2,20 @@
 archivesBaseName = 'appcompat-v7'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-v4')
-    compile project(':support-vector-drawable')
-    compile project(':support-animated-vector-drawable')
+    api project(':support-annotations')
+    api project(':support-v4')
+    api project(':support-vector-drawable')
+    api project(':support-animated-vector-drawable')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 }
 
 android {
diff --git a/v7/appcompat/lint-baseline.xml b/v7/appcompat/lint-baseline.xml
new file mode 100644
index 0000000..f1b0c14
--- /dev/null
+++ b/v7/appcompat/lint-baseline.xml
@@ -0,0 +1,283 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="MissingPermission"
+        message="Missing permissions required by LocationManager.getLastKnownLocation: android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION"
+        errorLine1="                    return mLocationManager.getLastKnownLocation(provider);"
+        errorLine2="                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/app/TwilightManager.java"
+            line="128"
+            column="28"/>
+    </issue>
+
+    <issue
+        id="MissingSuperCall"
+        message="Overriding method should call `super.draw`"
+        errorLine1="    public void draw(Canvas canvas) {"
+        errorLine2="                ~~~~">
+        <location
+            file="src/android/support/v7/widget/ViewStubCompat.java"
+            line="151"
+            column="17"/>
+    </issue>
+
+    <issue
+        id="DuplicateIds"
+        message="Duplicate id `@+id/image`, already defined earlier in this layout"
+        errorLine1="        &lt;ImageView android:id=&quot;@+id/image&quot;"
+        errorLine2="                   ~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/abc_activity_chooser_view.xml"
+            line="62"
+            column="20"/>
+        <location
+            file="res/layout/abc_activity_chooser_view.xml"
+            line="40"
+            column="20"/>
+    </issue>
+
+    <issue
+        id="ResourceType"
+        message="Expected resource of type xml"
+        errorLine1="                    final XmlPullParser parser = res.getXml(resId);"
+        errorLine2="                                                            ~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="347"
+            column="61"/>
+    </issue>
+
+    <issue
+        id="ResourceType"
+        message="Expected resource of type layout"
+        errorLine1="            parser = mContext.getResources().getLayout(menuRes);"
+        errorLine2="                                                       ~~~~~~~">
+        <location
+            file="src/android/support/v7/view/SupportMenuInflater.java"
+            line="123"
+            column="56"/>
+    </issue>
+
+    <issue
+        id="Range"
+        message="Value must be ≥ 0 (was -2147483648)"
+        errorLine1="                                MeasureSpec.makeMeasureSpec(largestChildHeight,"
+        errorLine2="                                                            ~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/LinearLayoutCompat.java"
+            line="868"
+            column="61"/>
+    </issue>
+
+    <issue
+        id="Range"
+        message="Value must be ≥ 0 (was -2147483648)"
+        errorLine1="                                MeasureSpec.makeMeasureSpec(largestChildWidth, MeasureSpec.EXACTLY),"
+        errorLine2="                                                            ~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/LinearLayoutCompat.java"
+            line="1286"
+            column="61"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 30 (ActionBarDrawerToggleHoneycomb)"
+        errorLine1="                Log.w(TAG, &quot;Couldn&apos;t set home-as-up indicator via JB-MR2 API&quot;, e);"
+        errorLine2="                      ~~~">
+        <location
+            file="src/android/support/v7/app/ActionBarDrawerToggleHoneycomb.java"
+            line="62"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 30 (ActionBarDrawerToggleHoneycomb)"
+        errorLine1="            Log.w(TAG, &quot;Couldn&apos;t set home-as-up indicator&quot;);"
+        errorLine2="                  ~~~">
+        <location
+            file="src/android/support/v7/app/ActionBarDrawerToggleHoneycomb.java"
+            line="67"
+            column="19"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 30 (ActionBarDrawerToggleHoneycomb)"
+        errorLine1="                Log.w(TAG, &quot;Couldn&apos;t set content description via JB-MR2 API&quot;, e);"
+        errorLine2="                      ~~~">
+        <location
+            file="src/android/support/v7/app/ActionBarDrawerToggleHoneycomb.java"
+            line="87"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="                        Log.d(TAG, &quot;[loadDrawableFromDelegates] Skipping drawable: &quot;"
+        errorLine2="                              ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="315"
+            column="31"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="                    Log.i(TAG, &quot;[loadDrawableFromDelegates] Returning cached drawable: &quot; +"
+        errorLine2="                          ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="337"
+            column="27"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="                            Log.i(TAG, &quot;[loadDrawableFromDelegates] Saved drawable to cache: &quot; +"
+        errorLine2="                                  ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="372"
+            column="35"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="                    Log.e(TAG, &quot;Exception while inflating drawable&quot;, e);"
+        errorLine2="                          ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="377"
+            column="27"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="                Log.d(TAG, &quot;[tintDrawableUsingColorFilter] Tinted &quot;"
+        errorLine2="                      ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="482"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (AppCompatDrawableManager)"
+        errorLine1="            Log.d(TAG, &quot;Mutated drawable is not the same instance as the input.&quot;);"
+        errorLine2="                  ~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatDrawableManager.java"
+            line="698"
+            column="19"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: PixelFormat.UNKNOWN, PixelFormat.TRANSLUCENT, PixelFormat.TRANSPARENT, PixelFormat.OPAQUE"
+        errorLine1="        return 0;"
+        errorLine2="               ~">
+        <location
+            file="src/android/support/v7/widget/ActionBarBackgroundDrawable.java"
+            line="59"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="                    ? TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine2="                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatButton.java"
+            line="274"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="                    : TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;"
+        errorLine2="                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatButton.java"
+            line="275"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="        return TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatButton.java"
+            line="281"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="                    ? TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine2="                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatTextView.java"
+            line="280"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="                    : TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;"
+        errorLine2="                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatTextView.java"
+            line="281"
+            column="23"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one of: TextView.AUTO_SIZE_TEXT_TYPE_NONE, TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM"
+        errorLine1="        return TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;"
+        errorLine2="               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/widget/AppCompatTextView.java"
+            line="287"
+            column="16"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one or more of: ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_SHOW_HOME, ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_CUSTOM"
+        errorLine1="        setDisplayOptions(options, 0xffffffff);"
+        errorLine2="                                   ~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/app/ToolbarActionBar.java"
+            line="254"
+            column="36"/>
+    </issue>
+
+    <issue
+        id="WrongConstant"
+        message="Must be one or more of: ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_SHOW_HOME, ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_CUSTOM"
+        errorLine1="        setDisplayOptions(options, 0xffffffff);"
+        errorLine2="                                   ~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/app/ToolbarActionBar.java"
+            line="254"
+            column="36"/>
+    </issue>
+
+</issues>
diff --git a/v7/appcompat/res/drawable-v21/notification_action_background.xml b/v7/appcompat/res/drawable-v21/notification_action_background.xml
deleted file mode 100644
index 852c3f0..0000000
--- a/v7/appcompat/res/drawable-v21/notification_action_background.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<ripple xmlns:android="http://schemas.android.com/apk/res/android"
-    android:color="@color/ripple_material_light">
-    <item android:id="@android:id/mask"
-        android:drawable="@drawable/abc_btn_default_mtrl_shape" />
-</ripple>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v11/notification_media_action.xml b/v7/appcompat/res/layout-v11/notification_media_action.xml
deleted file mode 100644
index d546792..0000000
--- a/v7/appcompat/res/layout-v11/notification_media_action.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2012 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.
--->
-
-<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
-    style="?android:attr/borderlessButtonStyle"
-    android:id="@+id/action0"
-    android:layout_width="48dp"
-    android:layout_height="match_parent"
-    android:layout_marginLeft="2dp"
-    android:layout_marginRight="2dp"
-    android:layout_weight="1"
-    android:gravity="center"/>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v11/notification_media_cancel_action.xml b/v7/appcompat/res/layout-v11/notification_media_cancel_action.xml
deleted file mode 100644
index c2bd8c2..0000000
--- a/v7/appcompat/res/layout-v11/notification_media_cancel_action.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    style="?android:attr/borderlessButtonStyle"
-    android:id="@+id/cancel_action"
-    android:layout_width="48dp"
-    android:layout_height="match_parent"
-    android:layout_marginLeft="2dp"
-    android:layout_marginRight="2dp"
-    android:layout_weight="1"
-    android:src="@android:drawable/ic_menu_close_clear_cancel"
-    android:gravity="center"
-    android:visibility="gone"/>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v11/notification_template_big_media.xml b/v7/appcompat/res/layout-v11/notification_template_big_media.xml
deleted file mode 100644
index b72fd97..0000000
--- a/v7/appcompat/res/layout-v11/notification_template_big_media.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="128dp"
-    >
-    <include layout="@layout/notification_template_icon_group"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-    />
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="48dp"
-        android:layout_marginLeft="2dp"
-        android:layout_marginRight="2dp"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentEnd="true" />
-    <include layout="@layout/notification_template_lines_media"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="fill_vertical"
-        android:layout_marginLeft="@dimen/notification_large_icon_width"
-        android:layout_marginStart="@dimen/notification_large_icon_width"
-        android:layout_toLeftOf="@id/cancel_action"
-        android:layout_toStartOf="@id/cancel_action"/>
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="match_parent"
-        android:layout_height="48dp"
-        android:layout_alignParentBottom="true"
-        android:layout_marginLeft="12dp"
-        android:layout_marginRight="12dp"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <ImageView
-        android:layout_width="match_parent"
-        android:layout_height="1dp"
-        android:layout_above="@id/media_actions"
-        android:id="@+id/action_divider"
-        android:background="?android:attr/dividerHorizontal" />
-</RelativeLayout>
diff --git a/v7/appcompat/res/layout-v11/notification_template_big_media_custom.xml b/v7/appcompat/res/layout-v11/notification_template_big_media_custom.xml
deleted file mode 100644
index c88d799..0000000
--- a/v7/appcompat/res/layout-v11/notification_template_big_media_custom.xml
+++ /dev/null
@@ -1,107 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="128dp"
-    >
-    <include layout="@layout/notification_template_icon_group"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-    />
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="48dp"
-        android:layout_marginLeft="2dp"
-        android:layout_marginRight="2dp"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentEnd="true"/>
-    <LinearLayout
-        android:id="@+id/notification_main_column_container"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_marginLeft="@dimen/notification_large_icon_height"
-        android:layout_marginStart="@dimen/notification_large_icon_height"
-        android:minHeight="@dimen/notification_large_icon_height"
-        android:paddingTop="@dimen/notification_main_column_padding_top"
-        android:orientation="horizontal"
-        android:layout_toLeftOf="@id/cancel_action"
-        android:layout_toStartOf="@id/cancel_action">
-        <FrameLayout
-            android:id="@+id/notification_main_column"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_weight="1"
-            android:layout_marginLeft="@dimen/notification_content_margin_start"
-            android:layout_marginStart="@dimen/notification_content_margin_start"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:layout_marginBottom="8dp"
-        />
-        <FrameLayout
-            android:id="@+id/right_side"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:paddingTop="@dimen/notification_right_side_padding_top">
-            <DateTimeView android:id="@+id/time"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <Chronometer android:id="@+id/chronometer"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <TextView android:id="@+id/info"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginTop="20dp"
-                android:layout_gravity="end|bottom"
-                android:singleLine="true"
-            />
-        </FrameLayout>
-    </LinearLayout>
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="match_parent"
-        android:layout_height="48dp"
-        android:layout_alignParentBottom="true"
-        android:layout_marginLeft="12dp"
-        android:layout_marginRight="12dp"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <ImageView
-        android:layout_width="match_parent"
-        android:layout_height="1dp"
-        android:layout_above="@id/media_actions"
-        android:id="@+id/action_divider"
-        android:background="?android:attr/dividerHorizontal" />
-</RelativeLayout>
diff --git a/v7/appcompat/res/layout-v11/notification_template_big_media_narrow.xml b/v7/appcompat/res/layout-v11/notification_template_big_media_narrow.xml
deleted file mode 100644
index 979c8f4..0000000
--- a/v7/appcompat/res/layout-v11/notification_template_big_media_narrow.xml
+++ /dev/null
@@ -1,68 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<!-- Layout to be used with only max 3 actions. It has a much larger picture at the left side-->
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="128dp"
-    >
-    <ImageView android:id="@+id/icon"
-        android:layout_width="128dp"
-        android:layout_height="128dp"
-        android:scaleType="centerCrop"
-        />
-
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="48dp"
-        android:layout_marginLeft="2dp"
-        android:layout_marginRight="2dp"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentEnd="true"/>
-
-    <include layout="@layout/notification_template_lines_media"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:layout_marginLeft="128dp"
-        android:layout_marginStart="128dp"
-        android:layout_toLeftOf="@id/cancel_action"
-        android:layout_toStartOf="@id/cancel_action"/>
-
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="match_parent"
-        android:layout_height="48dp"
-        android:layout_toRightOf="@id/icon"
-        android:layout_toEndOf="@id/icon"
-        android:layout_alignParentBottom="true"
-        android:layout_marginLeft="12dp"
-        android:layout_marginRight="12dp"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <ImageView
-        android:layout_width="match_parent"
-        android:layout_height="1dp"
-        android:layout_toRightOf="@id/icon"
-        android:layout_toEndOf="@id/icon"
-        android:layout_above="@id/media_actions"
-        android:id="@+id/action_divider"
-        android:background="?android:attr/dividerHorizontal" />
-</RelativeLayout>
diff --git a/v7/appcompat/res/layout-v11/notification_template_big_media_narrow_custom.xml b/v7/appcompat/res/layout-v11/notification_template_big_media_narrow_custom.xml
deleted file mode 100644
index b7fbff7..0000000
--- a/v7/appcompat/res/layout-v11/notification_template_big_media_narrow_custom.xml
+++ /dev/null
@@ -1,115 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<!-- Layout to be used with only max 3 actions. It has a much larger picture at the left side-->
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="128dp"
-    >
-    <ImageView android:id="@+id/icon"
-        android:layout_width="128dp"
-        android:layout_height="128dp"
-        android:scaleType="centerCrop"
-        />
-
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="48dp"
-        android:layout_marginLeft="2dp"
-        android:layout_marginRight="2dp"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentEnd="true"/>
-
-    <LinearLayout
-        android:id="@+id/notification_main_column_container"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_marginLeft="128dp"
-        android:layout_marginStart="128dp"
-        android:minHeight="@dimen/notification_large_icon_height"
-        android:paddingTop="@dimen/notification_main_column_padding_top"
-        android:orientation="horizontal"
-        android:layout_toLeftOf="@id/cancel_action"
-        android:layout_toStartOf="@id/cancel_action">
-        <FrameLayout
-            android:id="@+id/notification_main_column"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_weight="1"
-            android:layout_marginLeft="@dimen/notification_media_narrow_margin"
-            android:layout_marginStart="@dimen/notification_media_narrow_margin"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:layout_marginBottom="8dp"/>
-        <FrameLayout
-            android:id="@+id/right_side"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:paddingTop="@dimen/notification_right_side_padding_top">
-            <DateTimeView android:id="@+id/time"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <Chronometer android:id="@+id/chronometer"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <TextView android:id="@+id/info"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginTop="20dp"
-                android:layout_gravity="end|bottom"
-                android:singleLine="true"
-            />
-        </FrameLayout>
-    </LinearLayout>
-
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="match_parent"
-        android:layout_height="48dp"
-        android:layout_toRightOf="@id/icon"
-        android:layout_toEndOf="@id/icon"
-        android:layout_alignParentBottom="true"
-        android:layout_marginLeft="12dp"
-        android:layout_marginRight="12dp"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <ImageView
-        android:layout_width="match_parent"
-        android:layout_height="1dp"
-        android:layout_toRightOf="@id/icon"
-        android:layout_toEndOf="@id/icon"
-        android:layout_above="@id/media_actions"
-        android:id="@+id/action_divider"
-        android:background="?android:attr/dividerHorizontal" />
-</RelativeLayout>
diff --git a/v7/appcompat/res/layout-v16/notification_template_custom_big.xml b/v7/appcompat/res/layout-v16/notification_template_custom_big.xml
deleted file mode 100644
index 24c3323..0000000
--- a/v7/appcompat/res/layout-v16/notification_template_custom_big.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/notification_background"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content" >
-    <ImageView android:id="@+id/icon"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-        android:scaleType="center"
-    />
-    <LinearLayout
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="top"
-        android:orientation="vertical" >
-        <LinearLayout
-            android:id="@+id/notification_main_column_container"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_marginLeft="@dimen/notification_large_icon_width"
-            android:layout_marginStart="@dimen/notification_large_icon_width"
-            android:paddingTop="@dimen/notification_main_column_padding_top"
-            android:minHeight="@dimen/notification_large_icon_height"
-            android:orientation="horizontal">
-            <FrameLayout
-                android:id="@+id/notification_main_column"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_weight="1"
-                android:layout_marginLeft="@dimen/notification_content_margin_start"
-                android:layout_marginStart="@dimen/notification_content_margin_start"
-                android:layout_marginBottom="8dp"
-                android:layout_marginRight="8dp"
-                android:layout_marginEnd="8dp" />
-            <FrameLayout
-                android:id="@+id/right_side"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginRight="8dp"
-                android:layout_marginEnd="8dp"
-                android:paddingTop="@dimen/notification_right_side_padding_top">
-                <ViewStub android:id="@+id/time"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_gravity="end|top"
-                    android:visibility="gone"
-                    android:layout="@layout/notification_template_part_time" />
-                <ViewStub android:id="@+id/chronometer"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_gravity="end|top"
-                    android:visibility="gone"
-                    android:layout="@layout/notification_template_part_chronometer" />
-                <LinearLayout
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:orientation="horizontal"
-                    android:layout_gravity="end|bottom"
-                    android:layout_marginTop="20dp">
-                    <TextView android:id="@+id/info"
-                        android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:singleLine="true"
-                    />
-                    <ImageView android:id="@+id/right_icon"
-                        android:layout_width="16dp"
-                        android:layout_height="16dp"
-                        android:layout_gravity="center"
-                        android:layout_marginLeft="8dp"
-                        android:layout_marginStart="8dp"
-                        android:scaleType="centerInside"
-                        android:visibility="gone"
-                        android:alpha="0.6"
-                    />
-                </LinearLayout>
-            </FrameLayout>
-        </LinearLayout>
-        <ImageView
-            android:layout_width="match_parent"
-            android:layout_height="1px"
-            android:id="@+id/action_divider"
-            android:visibility="gone"
-            android:layout_marginLeft="@dimen/notification_large_icon_width"
-            android:layout_marginStart="@dimen/notification_large_icon_width"
-            android:background="?android:attr/dividerHorizontal" />
-        <LinearLayout
-            android:id="@+id/actions"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal"
-            android:visibility="gone"
-            android:showDividers="middle"
-            android:divider="?android:attr/listDivider"
-            android:dividerPadding="12dp"
-            android:layout_marginLeft="@dimen/notification_large_icon_width"
-            android:layout_marginStart="@dimen/notification_large_icon_width" >
-            <!-- actions will be added here -->
-        </LinearLayout>
-    </LinearLayout>
-</FrameLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v21/notification_action.xml b/v7/appcompat/res/layout-v21/notification_action.xml
deleted file mode 100644
index c60bf7d..0000000
--- a/v7/appcompat/res/layout-v21/notification_action.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/Widget.AppCompat.NotificationActionContainer"
-    android:id="@+id/action_container"
-    android:layout_width="0dp"
-    android:layout_weight="1"
-    android:layout_height="48dp"
-    android:paddingStart="4dp"
-    android:orientation="horizontal">
-    <ImageView
-        android:id="@+id/action_image"
-        android:layout_width="@dimen/notification_action_icon_size"
-        android:layout_height="@dimen/notification_action_icon_size"
-        android:layout_gravity="center|start"
-        android:scaleType="centerInside"/>
-    <TextView
-        style="@style/Widget.AppCompat.NotificationActionText"
-        android:id="@+id/action_text"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center|start"
-        android:paddingStart="4dp"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:clickable="false"/>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v21/notification_action_tombstone.xml b/v7/appcompat/res/layout-v21/notification_action_tombstone.xml
deleted file mode 100644
index 1637c6f..0000000
--- a/v7/appcompat/res/layout-v21/notification_action_tombstone.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/Widget.AppCompat.NotificationActionContainer"
-    android:id="@+id/action_container"
-    android:layout_width="0dp"
-    android:layout_weight="1"
-    android:layout_height="48dp"
-    android:paddingStart="4dp"
-    android:orientation="horizontal"
-    android:enabled="false"
-    android:background="@null">
-    <ImageView
-        android:id="@+id/action_image"
-        android:layout_width="@dimen/notification_action_icon_size"
-        android:layout_height="@dimen/notification_action_icon_size"
-        android:layout_gravity="center|start"
-        android:scaleType="centerInside"
-        android:enabled="false"
-        android:alpha="0.5"/>
-    <TextView
-        style="@style/Widget.AppCompat.NotificationActionText"
-        android:id="@+id/action_text"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center|start"
-        android:paddingStart="4dp"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:clickable="false"
-        android:enabled="false"
-        android:alpha="0.5"/>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v21/notification_template_custom_big.xml b/v7/appcompat/res/layout-v21/notification_template_custom_big.xml
deleted file mode 100644
index 38332bd..0000000
--- a/v7/appcompat/res/layout-v21/notification_template_custom_big.xml
+++ /dev/null
@@ -1,90 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/notification_background"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content" >
-    <include layout="@layout/notification_template_icon_group"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-    />
-    <LinearLayout
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="top"
-        android:layout_marginStart="@dimen/notification_large_icon_width"
-        android:orientation="vertical" >
-        <LinearLayout
-            android:id="@+id/notification_main_column_container"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:minHeight="@dimen/notification_large_icon_height"
-            android:orientation="horizontal">
-            <FrameLayout
-                android:id="@+id/notification_main_column"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_weight="1"
-                android:layout_marginEnd="8dp"
-                android:layout_marginBottom="8dp"/>
-            <FrameLayout
-                android:id="@+id/right_side"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginEnd="8dp"
-                android:paddingTop="@dimen/notification_right_side_padding_top">
-                <ViewStub android:id="@+id/time"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_gravity="end|top"
-                    android:visibility="gone"
-                    android:layout="@layout/notification_template_part_time" />
-                <ViewStub android:id="@+id/chronometer"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_gravity="end|top"
-                    android:visibility="gone"
-                    android:layout="@layout/notification_template_part_chronometer" />
-                <TextView android:id="@+id/info"
-                    android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_marginTop="20dp"
-                    android:layout_gravity="end|bottom"
-                    android:singleLine="true"
-                />
-            </FrameLayout>
-        </LinearLayout>
-        <ImageView
-            android:layout_width="match_parent"
-            android:layout_height="1dp"
-            android:id="@+id/action_divider"
-            android:visibility="gone"
-            android:background="#29000000" />
-        <LinearLayout
-            android:id="@+id/actions"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_marginStart="-8dp"
-            android:orientation="horizontal"
-            android:visibility="gone"
-        >
-            <!-- actions will be added here -->
-        </LinearLayout>
-    </LinearLayout>
-</FrameLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout-v21/notification_template_icon_group.xml b/v7/appcompat/res/layout-v21/notification_template_icon_group.xml
deleted file mode 100644
index 6c19022..0000000
--- a/v7/appcompat/res/layout-v21/notification_template_icon_group.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="@dimen/notification_large_icon_width"
-    android:layout_height="@dimen/notification_large_icon_height"
-    android:id="@+id/icon_group"
->
-    <ImageView android:id="@+id/icon"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:layout_marginTop="@dimen/notification_big_circle_margin"
-        android:layout_marginBottom="@dimen/notification_big_circle_margin"
-        android:layout_marginStart="@dimen/notification_big_circle_margin"
-        android:layout_marginEnd="@dimen/notification_big_circle_margin"
-        android:scaleType="centerInside"
-    />
-    <ImageView android:id="@+id/right_icon"
-        android:layout_width="@dimen/notification_right_icon_size"
-        android:layout_height="@dimen/notification_right_icon_size"
-        android:layout_gravity="end|bottom"
-        android:scaleType="centerInside"
-        android:visibility="gone"
-        android:layout_marginEnd="8dp"
-        android:layout_marginBottom="8dp"
-    />
-</FrameLayout>
-
diff --git a/v7/appcompat/res/layout/notification_action.xml b/v7/appcompat/res/layout/notification_action.xml
deleted file mode 100644
index 82e95a5..0000000
--- a/v7/appcompat/res/layout/notification_action.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/Widget.AppCompat.NotificationActionContainer"
-    android:id="@+id/action_container"
-    android:layout_width="0dp"
-    android:layout_weight="1"
-    android:layout_height="48dp"
-    android:paddingLeft="4dp"
-    android:paddingStart="4dp"
-    android:orientation="horizontal">
-    <ImageView
-        android:id="@+id/action_image"
-        android:layout_width="@dimen/notification_action_icon_size"
-        android:layout_height="@dimen/notification_action_icon_size"
-        android:layout_gravity="center|start"
-        android:scaleType="centerInside"/>
-    <TextView
-        style="@style/Widget.AppCompat.NotificationActionText"
-        android:id="@+id/action_text"
-        android:textColor="#ccc"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center|start"
-        android:paddingLeft="4dp"
-        android:paddingStart="4dp"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:clickable="false"/>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout/notification_action_tombstone.xml b/v7/appcompat/res/layout/notification_action_tombstone.xml
deleted file mode 100644
index d491c78..0000000
--- a/v7/appcompat/res/layout/notification_action_tombstone.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/Widget.AppCompat.NotificationActionContainer"
-    android:id="@+id/action_container"
-    android:layout_width="0dp"
-    android:layout_weight="1"
-    android:layout_height="48dp"
-    android:paddingLeft="4dp"
-    android:paddingStart="4dp"
-    android:orientation="horizontal"
-    android:enabled="false"
-    android:background="@null">
-    <ImageView
-        android:id="@+id/action_image"
-        android:layout_width="@dimen/notification_action_icon_size"
-        android:layout_height="@dimen/notification_action_icon_size"
-        android:layout_gravity="center|start"
-        android:scaleType="centerInside"
-        android:enabled="false"
-        android:alpha="0.5"/>
-    <TextView
-        style="@style/Widget.AppCompat.NotificationActionText"
-        android:id="@+id/action_text"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center|start"
-        android:textColor="#ccc"
-        android:paddingLeft="4dp"
-        android:paddingStart="4dp"
-        android:singleLine="true"
-        android:ellipsize="end"
-        android:clickable="false"
-        android:enabled="false"
-        android:alpha="0.5"/>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout/notification_template_custom_big.xml b/v7/appcompat/res/layout/notification_template_custom_big.xml
deleted file mode 100644
index c922629..0000000
--- a/v7/appcompat/res/layout/notification_template_custom_big.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<LinearLayout android:id="@+id/notification_main_column_container"
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:minHeight="@dimen/notification_large_icon_height"
-    android:orientation="horizontal"
-    android:paddingRight="12dp"
-    android:paddingEnd="12dp">
-    <ImageView android:id="@+id/icon"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-        android:background="@drawable/notification_tile_bg"
-        android:scaleType="center"
-    />
-    <FrameLayout
-        android:id="@+id/notification_main_column"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingLeft="12dp"
-        android:paddingStart="12dp"
-        android:paddingTop="@dimen/notification_main_column_padding_top"
-        android:layout_weight="1"/>
-    <FrameLayout
-        android:id="@+id/right_side"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:paddingTop="12dp"
-        android:paddingLeft="12dp">
-        <include
-            layout="@layout/notification_template_part_time"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="end|top"
-            android:visibility="gone"/>
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_gravity="end|bottom"
-            android:layout_marginTop="18dp"
-            android:orientation="horizontal">
-            <TextView android:id="@+id/info"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_gravity="center"
-                android:singleLine="true"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info"
-            />
-            <ImageView android:id="@+id/right_icon"
-                android:layout_width="24dp"
-                android:layout_height="24dp"
-                android:layout_gravity="center"
-                android:layout_marginLeft="8dp"
-                android:alpha="0.7"
-                android:scaleType="center"
-                android:visibility="gone"
-            />
-        </LinearLayout>
-    </FrameLayout>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout/notification_template_icon_group.xml b/v7/appcompat/res/layout/notification_template_icon_group.xml
deleted file mode 100644
index dd564f8..0000000
--- a/v7/appcompat/res/layout/notification_template_icon_group.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<ImageView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/icon"
-    android:layout_width="@dimen/notification_large_icon_width"
-    android:layout_height="@dimen/notification_large_icon_height"
-    android:scaleType="centerCrop"
-/>
-
diff --git a/v7/appcompat/res/layout/notification_template_lines_media.xml b/v7/appcompat/res/layout/notification_template_lines_media.xml
deleted file mode 100644
index 9a7b788..0000000
--- a/v7/appcompat/res/layout/notification_template_lines_media.xml
+++ /dev/null
@@ -1,112 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:orientation="vertical"
-    android:paddingRight="8dp"
-    android:paddingEnd="8dp"
-    android:paddingTop="2dp"
-    android:paddingBottom="2dp"
-    >
-    <LinearLayout
-        android:id="@+id/line1"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:paddingTop="6dp"
-        android:layout_marginLeft="@dimen/notification_content_margin_start"
-        android:layout_marginStart="@dimen/notification_content_margin_start"
-        android:orientation="horizontal"
-        >
-        <TextView android:id="@+id/title"
-            android:textAppearance="@style/TextAppearance.AppCompat.Notification.Title.Media"
-            android:layout_width="fill_parent"
-            android:layout_height="wrap_content"
-            android:singleLine="true"
-            android:ellipsize="marquee"
-            android:fadingEdge="horizontal"
-            android:layout_weight="1"
-            />
-        <DateTimeView android:id="@+id/time"
-            android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:singleLine="true"
-            android:layout_gravity="center"
-            android:layout_weight="0"
-            android:visibility="gone"
-            android:paddingLeft="8dp"
-            android:paddingStart="8dp"
-        />
-        <Chronometer android:id="@+id/chronometer"
-            android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:singleLine="true"
-            android:layout_gravity="center"
-            android:layout_weight="0"
-            android:visibility="gone"
-            android:paddingLeft="8dp"
-            android:paddingStart="8dp"
-        />
-    </LinearLayout>
-    <TextView android:id="@+id/text2"
-        android:textAppearance="@style/TextAppearance.AppCompat.Notification.Line2.Media"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:layout_marginTop="-2dp"
-        android:layout_marginBottom="-2dp"
-        android:layout_marginLeft="@dimen/notification_content_margin_start"
-        android:layout_marginStart="@dimen/notification_content_margin_start"
-        android:singleLine="true"
-        android:fadingEdge="horizontal"
-        android:ellipsize="marquee"
-        android:visibility="gone"
-        />
-    <LinearLayout
-        android:id="@+id/line3"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:orientation="horizontal"
-        android:gravity="center_vertical"
-        android:layout_marginLeft="@dimen/notification_content_margin_start"
-        android:layout_marginStart="@dimen/notification_content_margin_start"
-        >
-        <TextView android:id="@+id/text"
-            android:textAppearance="@style/TextAppearance.AppCompat.Notification.Media"
-            android:layout_width="0dp"
-            android:layout_height="wrap_content"
-            android:layout_weight="1"
-            android:layout_gravity="center"
-            android:singleLine="true"
-            android:ellipsize="marquee"
-            android:fadingEdge="horizontal"
-            />
-        <TextView android:id="@+id/info"
-            android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info.Media"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center"
-            android:layout_weight="0"
-            android:singleLine="true"
-            android:gravity="center"
-            android:paddingLeft="8dp"
-            android:paddingStart="8dp"
-            />
-    </LinearLayout>
-</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/res/layout/notification_template_media.xml b/v7/appcompat/res/layout/notification_template_media.xml
deleted file mode 100644
index 6eac23b7..0000000
--- a/v7/appcompat/res/layout/notification_template_media.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="64dp"
-    android:orientation="horizontal"
-    >
-    <include layout="@layout/notification_template_icon_group"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-    />
-    <include layout="@layout/notification_template_lines_media"
-        android:layout_width="0dp"
-        android:layout_height="wrap_content"
-        android:layout_weight="1"/>
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="wrap_content"
-        android:layout_height="match_parent"
-        android:layout_gravity="center_vertical|end"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="match_parent"
-        android:layout_marginRight="6dp"
-        android:layout_marginEnd="6dp"/>
-    <ImageView android:id="@+id/end_padder"
-        android:layout_width="6dp"
-        android:layout_height="match_parent"
-        />
-</LinearLayout>
diff --git a/v7/appcompat/res/layout/notification_template_media_custom.xml b/v7/appcompat/res/layout/notification_template_media_custom.xml
deleted file mode 100644
index 62e07d4..0000000
--- a/v7/appcompat/res/layout/notification_template_media_custom.xml
+++ /dev/null
@@ -1,100 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/status_bar_latest_event_content"
-    android:layout_width="match_parent"
-    android:layout_height="64dp"
-    android:orientation="horizontal"
-    >
-    <include layout="@layout/notification_template_icon_group"
-        android:layout_width="@dimen/notification_large_icon_width"
-        android:layout_height="@dimen/notification_large_icon_height"
-    />
-    <LinearLayout
-        android:id="@+id/notification_main_column_container"
-        android:layout_width="0dp"
-        android:layout_weight="1"
-        android:layout_height="wrap_content"
-        android:paddingTop="@dimen/notification_main_column_padding_top"
-        android:minHeight="@dimen/notification_large_icon_height"
-        android:orientation="horizontal"
-        android:layout_toLeftOf="@id/cancel_action"
-        android:layout_toStartOf="@id/cancel_action">
-        <FrameLayout
-            android:id="@+id/notification_main_column"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_weight="1"
-            android:layout_marginLeft="@dimen/notification_content_margin_start"
-            android:layout_marginStart="@dimen/notification_content_margin_start"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:layout_marginBottom="8dp"/>
-        <FrameLayout
-            android:id="@+id/right_side"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_marginRight="8dp"
-            android:layout_marginEnd="8dp"
-            android:paddingTop="@dimen/notification_right_side_padding_top">
-            <DateTimeView android:id="@+id/time"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <Chronometer android:id="@+id/chronometer"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:singleLine="true"
-                android:layout_gravity="end|top"
-                android:visibility="gone"
-            />
-            <TextView android:id="@+id/info"
-                android:textAppearance="@style/TextAppearance.AppCompat.Notification.Info.Media"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginTop="20dp"
-                android:layout_gravity="end|bottom"
-                android:singleLine="true"
-            />
-        </FrameLayout>
-    </LinearLayout>
-    <LinearLayout
-        android:id="@+id/media_actions"
-        android:layout_width="wrap_content"
-        android:layout_height="match_parent"
-        android:layout_gravity="center_vertical|end"
-        android:orientation="horizontal"
-        android:layoutDirection="ltr"
-        >
-        <!-- media buttons will be added here -->
-    </LinearLayout>
-    <include layout="@layout/notification_media_cancel_action"
-        android:layout_width="48dp"
-        android:layout_height="match_parent"
-        android:layout_marginRight="6dp"
-        android:layout_marginEnd="6dp"/>
-    <ImageView android:id="@+id/end_padder"
-        android:layout_width="6dp"
-        android:layout_height="match_parent"
-        />
-</LinearLayout>
diff --git a/v7/appcompat/res/layout/notification_template_part_chronometer.xml b/v7/appcompat/res/layout/notification_template_part_chronometer.xml
deleted file mode 100644
index 9e58a38..0000000
--- a/v7/appcompat/res/layout/notification_template_part_chronometer.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<Chronometer android:id="@+id/chronometer" xmlns:android="http://schemas.android.com/apk/res/android"
-    android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:singleLine="true"
-    />
diff --git a/v7/appcompat/res/layout/notification_template_part_time.xml b/v7/appcompat/res/layout/notification_template_part_time.xml
deleted file mode 100644
index 810d1e3..0000000
--- a/v7/appcompat/res/layout/notification_template_part_time.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<DateTimeView android:id="@+id/time" xmlns:android="http://schemas.android.com/apk/res/android"
-    android:textAppearance="@style/TextAppearance.AppCompat.Notification.Time"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:singleLine="true"
-    />
diff --git a/v7/appcompat/res/values-v14/styles.xml b/v7/appcompat/res/values-v14/styles.xml
deleted file mode 100644
index 39419d2..0000000
--- a/v7/appcompat/res/values-v14/styles.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<!--
-  ~ Copyright (C) 2015 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
-  -->
-
-<resources>
-
-    <!-- Use platform styles -->
-    <style name="TextAppearance.StatusBar.EventContent"
-        parent="@android:style/TextAppearance.StatusBar.EventContent"/>
-
-    <style name="TextAppearance.StatusBar.EventContent.Title"
-        parent="@android:style/TextAppearance.StatusBar.EventContent.Title"/>
-
-    <!-- Use own styles for which platform styles are not public -->
-    <style name="TextAppearance.StatusBar.EventContent.Line2">
-        <item name="android:textSize">@dimen/notification_subtext_size</item>
-    </style>
-    <style name="TextAppearance.StatusBar.EventContent.Info"/>
-    <style name="TextAppearance.StatusBar.EventContent.Time"/>
-
-    <style name="TextAppearance.AppCompat.Notification.Title"
-        parent="@android:style/TextAppearance.StatusBar.EventContent.Title"/>
-
-    <style name="TextAppearance.AppCompat.Notification"
-        parent="@android:style/TextAppearance.StatusBar.EventContent"/>
-</resources>
\ No newline at end of file
diff --git a/v7/appcompat/res/values-v21/dimens.xml b/v7/appcompat/res/values-v21/dimens.xml
deleted file mode 100644
index de665a6..0000000
--- a/v7/appcompat/res/values-v21/dimens.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-
-<resources>
-    <!-- the margin at the beginning of the notification content -->
-    <dimen name="notification_content_margin_start">0dp</dimen>
-    <!-- image margin on the large icon in the narrow media template -->
-    <dimen name="notification_media_narrow_margin">12dp</dimen>
-    <!-- the top padding of the notification content -->
-    <dimen name="notification_main_column_padding_top">0dp</dimen>
-</resources>
\ No newline at end of file
diff --git a/v7/appcompat/res/values-v21/styles.xml b/v7/appcompat/res/values-v21/styles.xml
index 1c435ae..48d0366 100644
--- a/v7/appcompat/res/values-v21/styles.xml
+++ b/v7/appcompat/res/values-v21/styles.xml
@@ -18,16 +18,16 @@
 
     <!-- Use platform styles -->
     <style name="TextAppearance.AppCompat.Notification.Info"
-        parent="@android:style/TextAppearance.Material.Notification.Info"/>
+           parent="@android:style/TextAppearance.Material.Notification.Info"/>
 
     <style name="TextAppearance.AppCompat.Notification.Time"
-        parent="@android:style/TextAppearance.Material.Notification.Time"/>
+           parent="@android:style/TextAppearance.Material.Notification.Time"/>
 
     <style name="TextAppearance.AppCompat.Notification.Title"
-        parent="@android:style/TextAppearance.Material.Notification.Title"/>
+           parent="@android:style/TextAppearance.Material.Notification.Title"/>
 
     <style name="TextAppearance.AppCompat.Notification"
-        parent="@android:style/TextAppearance.Material.Notification"/>
+           parent="@android:style/TextAppearance.Material.Notification"/>
 
     <style name="TextAppearance.AppCompat.Notification.Media" >
         <item name="android:textColor">@color/secondary_text_default_material_dark</item>
@@ -44,15 +44,4 @@
     <style name="TextAppearance.AppCompat.Notification.Time.Media">
         <item name="android:textColor">@color/secondary_text_default_material_dark</item>
     </style>
-
-    <style name="Widget.AppCompat.NotificationActionText" parent="">
-        <item name="android:textAppearance">?android:attr/textAppearanceButton</item>
-        <item name="android:textColor">@color/secondary_text_default_material_light</item>
-        <item name="android:textSize">@dimen/notification_action_text_size</item>
-    </style>
-
-    <style name="Widget.AppCompat.NotificationActionContainer" parent="">
-        <item name="android:background">@drawable/notification_action_background</item>
-    </style>
-
 </resources>
\ No newline at end of file
diff --git a/v7/appcompat/res/values-v24/styles.xml b/v7/appcompat/res/values-v24/styles.xml
index 52bb3d4..4cd8461 100644
--- a/v7/appcompat/res/values-v24/styles.xml
+++ b/v7/appcompat/res/values-v24/styles.xml
@@ -15,7 +15,6 @@
   -->
 
 <resources>
-
     <!-- Use platform styles, Media is dark again -->
     <style name="TextAppearance.AppCompat.Notification.Media" />
 
@@ -24,5 +23,4 @@
     <style name="TextAppearance.AppCompat.Notification.Time.Media" />
 
     <style name="TextAppearance.AppCompat.Notification.Title.Media" />
-
-</resources>
\ No newline at end of file
+</resources>
diff --git a/v7/appcompat/res/values/colors.xml b/v7/appcompat/res/values/colors.xml
index e6bab86..6191fea 100644
--- a/v7/appcompat/res/values/colors.xml
+++ b/v7/appcompat/res/values/colors.xml
@@ -20,15 +20,6 @@
 
     <color name="abc_input_method_navigation_guard">@android:color/black</color>
 
-    <drawable name="notification_template_icon_bg">#3333B5E5</drawable>
-    <drawable name="notification_template_icon_low_bg">#0cffffff</drawable>
-    <color name="notification_action_color_filter">#ffffffff</color>
-    <color name="notification_icon_bg_color">#ff9e9e9e</color>
-
-    <!-- The color of the material notification background for media notifications when no custom
-     color is specified -->
-    <color name="notification_material_background_media_default_color">#ff424242</color>
-
     <!-- Tooltip specific colors -->
     <color name="tooltip_background_dark">#e6616161</color>
     <color name="tooltip_background_light">#e6FFFFFF</color>
diff --git a/v7/appcompat/res/values/config.xml b/v7/appcompat/res/values/config.xml
index 96916a8..0f99f6d 100644
--- a/v7/appcompat/res/values/config.xml
+++ b/v7/appcompat/res/values/config.xml
@@ -33,12 +33,6 @@
 
     <bool name="abc_config_closeDialogWhenTouchOutside">true</bool>
 
-    <!-- Maximum numerical value that will be shown in a status bar
-         notification icon or in the notification itself. Will be replaced
-         with @string/status_bar_notification_info_overflow when shown in the
-         UI. -->
-    <integer name="status_bar_notification_info_maxnum">999</integer>
-
     <integer name="cancel_button_image_alpha">127</integer>
 
     <!-- The duration (in milliseconds) of the tooltip show/hide animations. -->
diff --git a/v7/appcompat/res/values/dimens.xml b/v7/appcompat/res/values/dimens.xml
index 284bdf1..a02b7c0 100644
--- a/v7/appcompat/res/values/dimens.xml
+++ b/v7/appcompat/res/values/dimens.xml
@@ -95,52 +95,6 @@
     <!-- Minimum "smallest width" of the display for cascading menus to be enabled. -->
     <dimen name="abc_cascading_menus_min_smallest_width">720dp</dimen>
 
-    <!-- The width of the big icons in notifications. -->
-    <dimen name="notification_large_icon_width">64dp</dimen>
-
-    <!-- The width of the big icons in notifications. -->
-    <dimen name="notification_large_icon_height">64dp</dimen>
-
-    <!-- Size of smaller notification text (see TextAppearance.StatusBar.EventContent.Line2, Info,
-         Time) -->
-    <dimen name="notification_subtext_size">13sp</dimen>
-
-    <!-- Size of notification action text -->
-    <dimen name="notification_action_text_size">13sp</dimen>
-
-    <!-- Top padding for notifications in the standard layout. -->
-    <dimen name="notification_top_pad">10dp</dimen>
-
-    <!-- Top padding for notification when text is large -->
-    <dimen name="notification_top_pad_large_text">5dp</dimen>
-
-    <!-- The size of the action icons -->
-    <dimen name="notification_action_icon_size">32dp</dimen>
-
-    <!-- the size of the small icon on the right of the largeIcon -->
-    <dimen name="notification_right_icon_size">16dp</dimen>
-
-    <!-- the padding of the small icon to the circle -->
-    <dimen name="notification_small_icon_background_padding">3dp</dimen>
-
-    <!-- the side margin of the big notification circle -->
-    <dimen name="notification_big_circle_margin">12dp</dimen>
-
-    <!-- small icon size when placed as large icon -->
-    <dimen name="notification_small_icon_size_as_large">24dp</dimen>
-
-    <!-- the margin at the beginning of the notification content -->
-    <dimen name="notification_content_margin_start">8dp</dimen>
-
-    <!-- image margin on the large icon in the narrow media template -->
-    <dimen name="notification_media_narrow_margin">@dimen/notification_content_margin_start</dimen>
-
-    <!-- the top padding of the notification content -->
-    <dimen name="notification_main_column_padding_top">10dp</dimen>
-
-    <!-- the paddingtop on the right side of the notification (for time etc.) -->
-    <dimen name="notification_right_side_padding_top">2dp</dimen>
-
     <!-- Tooltip dimensions. -->
     <!-- Vertical offset from the edge of the anchor view for a touch-triggered tooltip. -->
     <dimen name="tooltip_y_offset_touch">16dp</dimen>
diff --git a/v7/appcompat/res/values/strings.xml b/v7/appcompat/res/values/strings.xml
index 3f1d959..55bf5ad 100644
--- a/v7/appcompat/res/values/strings.xml
+++ b/v7/appcompat/res/values/strings.xml
@@ -62,13 +62,6 @@
     <!-- Description of the choose target button in a ShareActionProvider (share UI). [CHAR LIMIT=NONE] -->
     <string name="abc_shareactionprovider_share_with">Share with</string>
 
-    <!-- Text to use when the number in a notification info is too large
-         (greater than status_bar_notification_info_maxnum, defined in
-         values/config.xml) and must be truncated. May need to be localized
-         for most appropriate textual indicator of "more than X".
-         [CHAR LIMIT=4] -->
-    <string name="status_bar_notification_info_overflow">999+</string>
-
     <!-- Default text for a button that can be toggled on and off. -->
     <string name="abc_capital_on">ON</string>
     <!-- Default text for a button that can be toggled on and off. -->
diff --git a/v7/appcompat/res/values/styles.xml b/v7/appcompat/res/values/styles.xml
index 394b1ec..ce74a89 100644
--- a/v7/appcompat/res/values/styles.xml
+++ b/v7/appcompat/res/values/styles.xml
@@ -329,22 +329,10 @@
     <style name="TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" parent="TextAppearance.AppCompat.Widget.PopupMenu.Large" />
     <style name="TextAppearance.AppCompat.Light.Widget.PopupMenu.Small" parent="TextAppearance.AppCompat.Widget.PopupMenu.Small" />
 
-    <!-- These styles didn't exist on v7. Since we only use the media template in later versions
-         (ICS+), just define it here and use the correct references in values/v14 -->
-    <style name="TextAppearance.StatusBar.EventContent" parent=""/>
-    <style name="TextAppearance.StatusBar.EventContent.Title" parent=""/>
-    <style name="TextAppearance.StatusBar.EventContent.Line2" parent=""/>
-    <style name="TextAppearance.StatusBar.EventContent.Info" parent=""/>
-    <style name="TextAppearance.StatusBar.EventContent.Time" parent=""/>
-
-    <style name="TextAppearance.AppCompat.Notification">
-        <item name="android:textSize">14sp</item>
-        <item name="android:textColor">?android:attr/textColorSecondary</item>
-    </style>
-    <style name="TextAppearance.AppCompat.Notification.Title">
-        <item name="android:textSize">16sp</item>
-        <item name="android:textColor">?android:attr/textColorPrimary</item>
-    </style>
+    <!-- These styles have moved to support-compat and should be removed when
+         android.support.v7.app.NotificationCompat is removed -->
+    <style name="TextAppearance.AppCompat.Notification" parent="@android:style/TextAppearance.StatusBar.EventContent" />
+    <style name="TextAppearance.AppCompat.Notification.Title" parent="@android:style/TextAppearance.StatusBar.EventContent.Title" />
     <style name="TextAppearance.AppCompat.Notification.Info">
         <item name="android:textSize">12sp</item>
         <item name="android:textColor">?android:attr/textColorSecondary</item>
@@ -355,16 +343,11 @@
     </style>
     <style name="TextAppearance.AppCompat.Notification.Line2" parent="TextAppearance.AppCompat.Notification.Info" />
 
+    <!-- These styles have moved to media-compat and should be removed when
+         android.support.v7.app.NotificationCompat is removed -->
     <style name="TextAppearance.AppCompat.Notification.Title.Media" />
-
     <style name="TextAppearance.AppCompat.Notification.Media" />
-
-    <style name="TextAppearance.AppCompat.Notification.Info.Media"/>
-
-    <style name="TextAppearance.AppCompat.Notification.Time.Media"/>
-
-    <style name="TextAppearance.AppCompat.Notification.Line2.Media" parent="TextAppearance.AppCompat.Notification.Info.Media"/>
-
-    <style name="Widget.AppCompat.NotificationActionText" parent=""/>
-    <style name="Widget.AppCompat.NotificationActionContainer" parent=""/>
+    <style name="TextAppearance.AppCompat.Notification.Info.Media" />
+    <style name="TextAppearance.AppCompat.Notification.Time.Media" />
+    <style name="TextAppearance.AppCompat.Notification.Line2.Media" parent="TextAppearance.AppCompat.Notification.Info.Media" />
 </resources>
diff --git a/v7/appcompat/src/android/support/v7/app/AlertController.java b/v7/appcompat/src/android/support/v7/app/AlertController.java
index d0f8fd6..986baf3 100644
--- a/v7/appcompat/src/android/support/v7/app/AlertController.java
+++ b/v7/appcompat/src/android/support/v7/app/AlertController.java
@@ -738,11 +738,11 @@
     static void manageScrollIndicators(View v, View upIndicator, View downIndicator) {
         if (upIndicator != null) {
             upIndicator.setVisibility(
-                    ViewCompat.canScrollVertically(v, -1) ? View.VISIBLE : View.INVISIBLE);
+                    v.canScrollVertically(-1) ? View.VISIBLE : View.INVISIBLE);
         }
         if (downIndicator != null) {
             downIndicator.setVisibility(
-                    ViewCompat.canScrollVertically(v, 1) ? View.VISIBLE : View.INVISIBLE);
+                    v.canScrollVertically(1) ? View.VISIBLE : View.INVISIBLE);
         }
     }
 
diff --git a/v7/appcompat/src/android/support/v7/app/AppCompatActivity.java b/v7/appcompat/src/android/support/v7/app/AppCompatActivity.java
index 78136e2..c8d7b0a 100644
--- a/v7/appcompat/src/android/support/v7/app/AppCompatActivity.java
+++ b/v7/appcompat/src/android/support/v7/app/AppCompatActivity.java
@@ -31,7 +31,6 @@
 import android.support.v4.app.FragmentActivity;
 import android.support.v4.app.NavUtils;
 import android.support.v4.app.TaskStackBuilder;
-import android.support.v4.os.BuildCompat;
 import android.support.v7.view.ActionMode;
 import android.support.v7.widget.Toolbar;
 import android.support.v7.widget.VectorEnabledTintResources;
@@ -549,7 +548,7 @@
      * and perform the corresponding action.
      */
     private boolean performMenuItemShortcut(int keycode, KeyEvent event) {
-        if (!BuildCompat.isAtLeastO() && !event.isCtrlPressed()
+        if (!(Build.VERSION.SDK_INT >= 26) && !event.isCtrlPressed()
                 && !KeyEvent.metaStateHasNoModifiers(event.getMetaState())
                 && event.getRepeatCount() == 0
                 && !KeyEvent.isModifierKey(event.getKeyCode())) {
diff --git a/v7/appcompat/src/android/support/v7/app/AppCompatDelegateImplV14.java b/v7/appcompat/src/android/support/v7/app/AppCompatDelegateImplV14.java
index e79a906..2a4022c 100644
--- a/v7/appcompat/src/android/support/v7/app/AppCompatDelegateImplV14.java
+++ b/v7/appcompat/src/android/support/v7/app/AppCompatDelegateImplV14.java
@@ -26,11 +26,11 @@
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.content.res.Resources;
+import android.os.Build;
 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.VisibleForTesting;
-import android.support.v4.os.BuildCompat;
 import android.support.v7.view.SupportActionModeWrapper;
 import android.util.DisplayMetrics;
 import android.util.Log;
@@ -217,7 +217,7 @@
                 res.updateConfiguration(config, metrics);
 
                 // We may need to flush the Resources' drawable cache due to framework bugs.
-                if (!BuildCompat.isAtLeastO()) {
+                if (!(Build.VERSION.SDK_INT >= 26)) {
                     ResourcesFlusher.flush(res);
                 }
             }
diff --git a/v7/appcompat/src/android/support/v7/app/NotificationCompat.java b/v7/appcompat/src/android/support/v7/app/NotificationCompat.java
index 2f5082a..b1c3e95 100644
--- a/v7/appcompat/src/android/support/v7/app/NotificationCompat.java
+++ b/v7/appcompat/src/android/support/v7/app/NotificationCompat.java
@@ -16,49 +16,42 @@
 
 package android.support.v7.app;
 
-import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
-
 import android.app.Notification;
 import android.app.PendingIntent;
 import android.content.Context;
-import android.content.res.ColorStateList;
-import android.graphics.Color;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.Parcel;
-import android.support.annotation.RequiresApi;
-import android.support.annotation.RestrictTo;
 import android.support.v4.app.BundleCompat;
-import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
 import android.support.v4.media.session.MediaSessionCompat;
-import android.support.v4.text.BidiFormatter;
-import android.support.v7.appcompat.R;
-import android.text.SpannableStringBuilder;
-import android.text.Spanned;
-import android.text.TextUtils;
-import android.text.style.TextAppearanceSpan;
 import android.widget.RemoteViews;
 
-import java.util.List;
-
 /**
- * An extension of {@link android.support.v4.app.NotificationCompat} which supports
- * {@link android.support.v7.app.NotificationCompat.MediaStyle},
- * {@link android.support.v7.app.NotificationCompat.DecoratedCustomViewStyle},
- * and {@link android.support.v7.app.NotificationCompat.DecoratedMediaCustomViewStyle}.
- * You should start using this variant if you need support any of these styles.
+ * An extension of {@link android.support.v4.app.NotificationCompat} which adds additional styles.
+ * @deprecated Use {@link android.support.v4.app.NotificationCompat}.
  */
+@Deprecated
 public class NotificationCompat extends android.support.v4.app.NotificationCompat {
 
     /**
+     * @deprecated Use the static classes in {@link android.support.v4.app.NotificationCompat}.
+     */
+    @Deprecated
+    public NotificationCompat() {
+    }
+
+    /**
      * Extracts a {@link MediaSessionCompat.Token} from the extra values
      * in the {@link MediaStyle} {@link android.app.Notification notification}.
      *
      * @param notification The notification to extract a {@link MediaSessionCompat.Token} from.
      * @return The {@link MediaSessionCompat.Token} in the {@code notification} if it contains,
      *         null otherwise.
+     * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+     * #getMediaSession(Notification)}.
      */
+    @Deprecated
     public static MediaSessionCompat.Token getMediaSession(Notification notification) {
         Bundle extras = getExtras(notification);
         if (extras != null) {
@@ -83,439 +76,22 @@
         return null;
     }
 
-    @RequiresApi(24)
-    private static void addStyleToBuilderApi24(NotificationBuilderWithBuilderAccessor builder,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            NotificationCompatImpl24.addDecoratedCustomViewStyle(builder);
-        } else if (b.mStyle instanceof DecoratedMediaCustomViewStyle) {
-            NotificationCompatImpl24.addDecoratedMediaCustomViewStyle(builder);
-        } else if (!(b.mStyle instanceof MessagingStyle)) {
-            addStyleGetContentViewLollipop(builder, b);
-        }
-    }
-
-    @RequiresApi(21)
-    private static RemoteViews addStyleGetContentViewLollipop(
-            NotificationBuilderWithBuilderAccessor builder,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.mStyle instanceof MediaStyle) {
-            MediaStyle mediaStyle = (MediaStyle) b.mStyle;
-            NotificationCompatImpl21.addMediaStyle(builder,
-                    mediaStyle.mActionsToShowInCompact,
-                    mediaStyle.mToken != null ? mediaStyle.mToken.getToken() : null);
-
-            boolean hasContentView = b.getContentView() != null;
-            // If we are on L/M the media notification will only be colored if the expanded version
-            // is of media style, so we have to create a custom view for the collapsed version as
-            // well in that case.
-            boolean isMorL = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
-                    && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M;
-            boolean createCustomContent = hasContentView
-                    || (isMorL && b.getBigContentView() != null);
-            if (b.mStyle instanceof DecoratedMediaCustomViewStyle && createCustomContent) {
-                RemoteViews contentViewMedia = NotificationCompatImplBase.overrideContentViewMedia(
-                        builder, b.mContext, b.mContentTitle, b.mContentText, b.mContentInfo,
-                        b.mNumber, b.mLargeIcon, b.mSubText, b.mUseChronometer,
-                        b.getWhenIfShowing(), b.getPriority(), b.mActions,
-                        mediaStyle.mActionsToShowInCompact, false /* no cancel button on L */,
-                        null /* cancelButtonIntent */, hasContentView /* isDecoratedCustomView */);
-                if (hasContentView) {
-                    NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, contentViewMedia,
-                            b.getContentView());
-                }
-                setBackgroundColor(b.mContext, contentViewMedia, b.getColor());
-                return contentViewMedia;
-            }
-            return null;
-        } else if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            return getDecoratedContentView(b);
-        }
-        return addStyleGetContentViewJellybean(builder, b);
-    }
-
-    @RequiresApi(16)
-    private static RemoteViews addStyleGetContentViewJellybean(
-            NotificationBuilderWithBuilderAccessor builder,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.mStyle instanceof MessagingStyle) {
-            addMessagingFallBackStyle((MessagingStyle) b.mStyle, builder, b);
-        }
-        return addStyleGetContentViewIcs(builder, b);
-    }
-
-    private static MessagingStyle.Message findLatestIncomingMessage(MessagingStyle style) {
-        List<MessagingStyle.Message> messages = style.getMessages();
-        for (int i = messages.size() - 1; i >= 0; i--) {
-            MessagingStyle.Message m = messages.get(i);
-            // Incoming messages have a non-empty sender.
-            if (!TextUtils.isEmpty(m.getSender())) {
-                return m;
-            }
-        }
-        if (!messages.isEmpty()) {
-            // No incoming messages, fall back to outgoing message
-            return messages.get(messages.size() - 1);
-        }
-        return null;
-    }
-
-    private static CharSequence makeMessageLine(android.support.v4.app.NotificationCompat.Builder b,
-            MessagingStyle style,
-            MessagingStyle.Message m) {
-        BidiFormatter bidi = BidiFormatter.getInstance();
-        SpannableStringBuilder sb = new SpannableStringBuilder();
-        boolean afterLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
-        int color = afterLollipop || Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1
-                ? Color.BLACK : Color.WHITE;
-        CharSequence replyName = m.getSender();
-        if (TextUtils.isEmpty(m.getSender())) {
-            replyName = style.getUserDisplayName() == null
-                    ? "" : style.getUserDisplayName();
-            color = afterLollipop && b.getColor() != NotificationCompat.COLOR_DEFAULT
-                    ? b.getColor()
-                    : color;
-        }
-        CharSequence senderText = bidi.unicodeWrap(replyName);
-        sb.append(senderText);
-        sb.setSpan(makeFontColorSpan(color),
-                sb.length() - senderText.length(),
-                sb.length(),
-                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE /* flags */);
-        CharSequence text = m.getText() == null ? "" : m.getText();
-        sb.append("  ").append(bidi.unicodeWrap(text));
-        return sb;
-    }
-
-    private static TextAppearanceSpan makeFontColorSpan(int color) {
-        return new TextAppearanceSpan(null, 0, 0, ColorStateList.valueOf(color), null);
-    }
-
-    @RequiresApi(16)
-    private static void addMessagingFallBackStyle(MessagingStyle style,
-            NotificationBuilderWithBuilderAccessor builder,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        SpannableStringBuilder completeMessage = new SpannableStringBuilder();
-        List<MessagingStyle.Message> messages = style.getMessages();
-        boolean showNames = style.getConversationTitle() != null
-                || hasMessagesWithoutSender(style.getMessages());
-        for (int i = messages.size() - 1; i >= 0; i--) {
-            MessagingStyle.Message m = messages.get(i);
-            CharSequence line;
-            line = showNames ? makeMessageLine(b, style, m) : m.getText();
-            if (i != messages.size() - 1) {
-                completeMessage.insert(0, "\n");
-            }
-            completeMessage.insert(0, line);
-        }
-        NotificationCompatImplJellybean.addBigTextStyle(builder, completeMessage);
-    }
-
-    private static boolean hasMessagesWithoutSender(
-            List<MessagingStyle.Message> messages) {
-        for (int i = messages.size() - 1; i >= 0; i--) {
-            MessagingStyle.Message m = messages.get(i);
-            if (m.getSender() == null) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @RequiresApi(14)
-    private static RemoteViews addStyleGetContentViewIcs(
-            NotificationBuilderWithBuilderAccessor builder,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.mStyle instanceof MediaStyle) {
-            MediaStyle mediaStyle = (MediaStyle) b.mStyle;
-            boolean isDecorated = b.mStyle instanceof DecoratedMediaCustomViewStyle
-                    && b.getContentView() != null;
-            RemoteViews contentViewMedia = NotificationCompatImplBase.overrideContentViewMedia(
-                    builder, b.mContext, b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber,
-                    b.mLargeIcon, b.mSubText, b.mUseChronometer, b.getWhenIfShowing(),
-                    b.getPriority(), b.mActions, mediaStyle.mActionsToShowInCompact,
-                    mediaStyle.mShowCancelButton, mediaStyle.mCancelButtonIntent, isDecorated);
-            if (isDecorated) {
-                NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, contentViewMedia,
-                        b.getContentView());
-                return contentViewMedia;
-            }
-        } else if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            return getDecoratedContentView(b);
-        }
-        return null;
-    }
-
-    @RequiresApi(16)
-    private static void addBigStyleToBuilderJellybean(Notification n,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.mStyle instanceof MediaStyle) {
-            MediaStyle mediaStyle = (MediaStyle) b.mStyle;
-            RemoteViews innerView = b.getBigContentView() != null
-                    ? b.getBigContentView()
-                    : b.getContentView();
-            boolean isDecorated = b.mStyle instanceof DecoratedMediaCustomViewStyle
-                    && innerView != null;
-            NotificationCompatImplBase.overrideMediaBigContentView(n, b.mContext,
-                    b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber, b.mLargeIcon,
-                    b.mSubText, b.mUseChronometer, b.getWhenIfShowing(), b.getPriority(), 0,
-                    b.mActions, mediaStyle.mShowCancelButton, mediaStyle.mCancelButtonIntent,
-                    isDecorated);
-            if (isDecorated) {
-                NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, n.bigContentView,
-                        innerView);
-            }
-        } else if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            addDecoratedBigStyleToBuilderJellybean(n, b);
-        }
-    }
-
-    private static RemoteViews getDecoratedContentView(
-            android.support.v4.app.NotificationCompat.Builder b) {
-        if (b.getContentView() == null) {
-            // No special content view
-            return null;
-        }
-        RemoteViews remoteViews = NotificationCompatImplBase.applyStandardTemplateWithActions(
-                b.mContext, b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber,
-                b.mNotification.icon, b.mLargeIcon, b.mSubText, b.mUseChronometer,
-                b.getWhenIfShowing(), b.getPriority(), b.getColor(),
-                R.layout.notification_template_custom_big, false /* fitIn1U */, null /* actions */);
-        NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, remoteViews,
-                b.getContentView());
-        return remoteViews;
-    }
-
-    @RequiresApi(16)
-    private static void addDecoratedBigStyleToBuilderJellybean(Notification n,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        RemoteViews bigContentView = b.getBigContentView();
-        RemoteViews innerView = bigContentView != null ? bigContentView : b.getContentView();
-        if (innerView == null) {
-            // No expandable notification
-            return;
-        }
-        RemoteViews remoteViews = NotificationCompatImplBase.applyStandardTemplateWithActions(
-                b.mContext, b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber,
-                n.icon ,b.mLargeIcon, b.mSubText, b.mUseChronometer, b.getWhenIfShowing(),
-                b.getPriority(), b.getColor(), R.layout.notification_template_custom_big,
-                false /* fitIn1U */, b.mActions);
-        NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, remoteViews, innerView);
-        n.bigContentView = remoteViews;
-    }
-
-    @RequiresApi(21)
-    private static void addDecoratedHeadsUpToBuilderLollipop(Notification n,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        RemoteViews headsUp = b.getHeadsUpContentView();
-        RemoteViews innerView = headsUp != null ? headsUp : b.getContentView();
-        if (headsUp == null) {
-            // No expandable notification
-            return;
-        }
-        RemoteViews remoteViews = NotificationCompatImplBase.applyStandardTemplateWithActions(
-                b.mContext, b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber, n.icon,
-                b.mLargeIcon, b.mSubText, b.mUseChronometer, b.getWhenIfShowing(), b.getPriority(),
-                b.getColor(), R.layout.notification_template_custom_big, false /* fitIn1U */,
-                b.mActions);
-        NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, remoteViews, innerView);
-        n.headsUpContentView = remoteViews;
-    }
-
-    @RequiresApi(21)
-    private static void addBigStyleToBuilderLollipop(Notification n,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        RemoteViews innerView = b.getBigContentView() != null
-                ? b.getBigContentView()
-                : b.getContentView();
-        if (b.mStyle instanceof DecoratedMediaCustomViewStyle && innerView != null) {
-            NotificationCompatImplBase.overrideMediaBigContentView(n, b.mContext,
-                    b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber, b.mLargeIcon,
-                    b.mSubText, b.mUseChronometer, b.getWhenIfShowing(), b.getPriority(), 0,
-                    b.mActions, false /* showCancelButton */, null /* cancelButtonIntent */,
-                    true /* decoratedCustomView */);
-                    NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, n.bigContentView,
-                            innerView);
-            setBackgroundColor(b.mContext, n.bigContentView, b.getColor());
-        } else if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            addDecoratedBigStyleToBuilderJellybean(n, b);
-        }
-    }
-
-    private static void setBackgroundColor(Context context, RemoteViews views, int color) {
-        if (color == COLOR_DEFAULT) {
-            color = context.getResources().getColor(
-                    R.color.notification_material_background_media_default_color);
-        }
-        views.setInt(R.id.status_bar_latest_event_content, "setBackgroundColor", color);
-    }
-
-    @RequiresApi(21)
-    private static void addHeadsUpToBuilderLollipop(Notification n,
-            android.support.v4.app.NotificationCompat.Builder b) {
-        RemoteViews innerView = b.getHeadsUpContentView() != null
-                ? b.getHeadsUpContentView()
-                : b.getContentView();
-        if (b.mStyle instanceof DecoratedMediaCustomViewStyle && innerView != null) {
-            n.headsUpContentView = NotificationCompatImplBase.generateMediaBigView(b.mContext,
-                    b.mContentTitle, b.mContentText, b.mContentInfo, b.mNumber,
-                    b.mLargeIcon, b.mSubText, b.mUseChronometer, b.getWhenIfShowing(),
-                    b.getPriority(), 0, b.mActions, false /* showCancelButton */,
-                    null /* cancelButtonIntent */, true /* decoratedCustomView */);
-            NotificationCompatImplBase.buildIntoRemoteViews(b.mContext, n.headsUpContentView,
-                    innerView);
-            setBackgroundColor(b.mContext, n.headsUpContentView, b.getColor());
-        } else if (b.mStyle instanceof DecoratedCustomViewStyle) {
-            addDecoratedHeadsUpToBuilderLollipop(n, b);
-        }
-    }
-
     /**
-     * See {@link android.support.v4.app.NotificationCompat}. In addition to the builder in v4, this
-     * builder also supports {@link MediaStyle}.
+     * @deprecated All {@link android.support.v4.app.NotificationCompat.Style styles} can now be
+     * used with {@link android.support.v4.app.NotificationCompat.Builder}.
      */
+    @Deprecated
     public static class Builder extends android.support.v4.app.NotificationCompat.Builder {
 
         /**
          * @inheritDoc
+         * @deprecated Use {@link android.support.v4.app.NotificationCompat.Builder
+         * #NotificationCompat.Builder(Context, String)}
          */
+        @Deprecated
         public Builder(Context context) {
             super(context);
         }
-
-        /**
-         * @return the text of the notification
-         *
-         * @hide
-         */
-        @RestrictTo(LIBRARY_GROUP)
-        @Override
-        protected CharSequence resolveText() {
-            if (mStyle instanceof MessagingStyle) {
-                MessagingStyle style = (MessagingStyle) mStyle;
-                MessagingStyle.Message m = findLatestIncomingMessage(style);
-                CharSequence conversationTitle = style.getConversationTitle();
-                if (m != null) {
-                    return conversationTitle != null ? makeMessageLine(this, style, m)
-                            : m.getText();
-                }
-            }
-            return super.resolveText();
-        }
-
-        /**
-         * @return the title of the notification
-         *
-         * @hide
-         */
-        @RestrictTo(LIBRARY_GROUP)
-        @Override
-        protected CharSequence resolveTitle() {
-            if (mStyle instanceof MessagingStyle) {
-                MessagingStyle style = (MessagingStyle) mStyle;
-                MessagingStyle.Message m = findLatestIncomingMessage(style);
-                CharSequence conversationTitle = style.getConversationTitle();
-                if (conversationTitle != null || m != null) {
-                    return conversationTitle != null ? conversationTitle : m.getSender();
-                }
-            }
-            return super.resolveTitle();
-        }
-
-        /**
-         * @hide
-         */
-        @RestrictTo(LIBRARY_GROUP)
-        @Override
-        protected BuilderExtender getExtender() {
-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
-                return new Api24Extender();
-            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
-                return new LollipopExtender();
-            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
-                return new JellybeanExtender();
-            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
-                return new IceCreamSandwichExtender();
-            } else {
-                return super.getExtender();
-            }
-        }
-    }
-
-    @RequiresApi(14)
-    private static class IceCreamSandwichExtender extends BuilderExtender {
-
-        IceCreamSandwichExtender() {
-        }
-
-        @Override
-        public Notification build(android.support.v4.app.NotificationCompat.Builder b,
-                NotificationBuilderWithBuilderAccessor builder) {
-            RemoteViews contentView = addStyleGetContentViewIcs(builder, b);
-            Notification n = builder.build();
-            // The above call might override decorated content views again, let's make sure it
-            // sticks.
-            if (contentView != null) {
-                n.contentView = contentView;
-            } else if (b.getContentView() != null) {
-                n.contentView = b.getContentView();
-            }
-            return n;
-        }
-    }
-
-    @RequiresApi(16)
-    private static class JellybeanExtender extends BuilderExtender {
-
-        JellybeanExtender() {
-        }
-
-        @Override
-        public Notification build(android.support.v4.app.NotificationCompat.Builder b,
-                NotificationBuilderWithBuilderAccessor builder) {
-            RemoteViews contentView = addStyleGetContentViewJellybean(builder, b);
-            Notification n = builder.build();
-            // The above call might override decorated content views again, let's make sure it
-            // sticks.
-            if (contentView != null) {
-                n.contentView = contentView;
-            }
-            addBigStyleToBuilderJellybean(n, b);
-            return n;
-        }
-    }
-
-    @RequiresApi(21)
-    private static class LollipopExtender extends BuilderExtender {
-
-        LollipopExtender() {
-        }
-
-        @Override
-        public Notification build(android.support.v4.app.NotificationCompat.Builder b,
-                NotificationBuilderWithBuilderAccessor builder) {
-            RemoteViews contentView = addStyleGetContentViewLollipop(builder, b);
-            Notification n = builder.build();
-            // The above call might override decorated content views again, let's make sure it
-            // sticks.
-            if (contentView != null) {
-                n.contentView = contentView;
-            }
-            addBigStyleToBuilderLollipop(n, b);
-            addHeadsUpToBuilderLollipop(n, b);
-            return n;
-        }
-    }
-
-    @RequiresApi(24)
-    private static class Api24Extender extends BuilderExtender {
-
-        @Override
-        public Notification build(android.support.v4.app.NotificationCompat.Builder b,
-                NotificationBuilderWithBuilderAccessor builder) {
-            addStyleToBuilderApi24(builder, b);
-            return builder.build();
-        }
     }
 
     /**
@@ -523,9 +99,11 @@
      *
      * In the expanded form, {@link Notification#bigContentView}, up to 5
      * {@link android.support.v4.app.NotificationCompat.Action}s specified with
-     * {@link NotificationCompat.Builder#addAction(int, CharSequence, PendingIntent) addAction} will
-     * be shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
-     * {@link NotificationCompat.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will
+     * {@link android.support.v4.app.NotificationCompat.Builder#addAction(int, CharSequence,
+     * PendingIntent) addAction} will be shown as icon-only pushbuttons, suitable for transport
+     * controls. The Bitmap given to
+     * {@link android.support.v4.app.NotificationCompat.Builder#setLargeIcon(
+     * android.graphics.Bitmap) setLargeIcon()} will
      * be treated as album artwork.
      *
      * Unlike the other styles provided here, MediaStyle can also modify the standard-size
@@ -535,7 +113,8 @@
      *
      * Notifications created with MediaStyle will have their category set to
      * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
-     * category using {@link NotificationCompat.Builder#setCategory(String) setCategory()}.
+     * category using {@link android.support.v4.app.NotificationCompat.Builder#setCategory(String)
+     * setCategory()}.
      *
      * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
      * {@link android.support.v7.app.NotificationCompat.MediaStyle#setMediaSession}, the System UI
@@ -543,7 +122,7 @@
      * accordingly (by showing album artwork in the lockscreen, for example).
      *
      * To use this style with your Notification, feed it to
-     * {@link NotificationCompat.Builder#setStyle} like so:
+     * {@link android.support.v4.app.NotificationCompat.Builder#setStyle} like so:
      * <pre class="prettyprint">
      * Notification noti = new NotificationCompat.Builder()
      *     .setSmallIcon(R.drawable.ic_stat_player)
@@ -555,20 +134,28 @@
      *     .build();
      * </pre>
      *
-     * @see Notification#bigContentView
+     * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle}.
      */
-    public static class MediaStyle extends android.support.v4.app.NotificationCompat.Style {
+    @Deprecated
+    public static class MediaStyle extends
+            android.support.v4.media.app.NotificationCompat.MediaStyle {
 
-        int[] mActionsToShowInCompact = null;
-        MediaSessionCompat.Token mToken;
-        boolean mShowCancelButton;
-        PendingIntent mCancelButtonIntent;
-
+        /**
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #MediaStyle()}
+         */
+        @Deprecated
         public MediaStyle() {
+            super();
         }
 
+        /**
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #MediaStyle(android.support.v4.app.NotificationCompat.Builder)}
+         */
+        @Deprecated
         public MediaStyle(android.support.v4.app.NotificationCompat.Builder builder) {
-            setBuilder(builder);
+            super(builder);
         }
 
         /**
@@ -576,19 +163,27 @@
          * notification view.
          *
          * @param actions the indices of the actions to show in the compact notification view
+         *
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #setShowActionsInCompactView(int...)}
          */
+        @Deprecated
+        @Override
         public MediaStyle setShowActionsInCompactView(int...actions) {
-            mActionsToShowInCompact = actions;
-            return this;
+            return (MediaStyle) super.setShowActionsInCompactView(actions);
         }
 
         /**
          * Attaches a {@link MediaSessionCompat.Token} to this Notification
          * to provide additional playback information and control to the SystemUI.
+         *
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #setMediaSession(MediaSessionCompat.Token)}
          */
+        @Deprecated
+        @Override
         public MediaStyle setMediaSession(MediaSessionCompat.Token token) {
-            mToken = token;
-            return this;
+            return (MediaStyle) super.setMediaSession(token);
         }
 
         /**
@@ -614,10 +209,14 @@
          * <p>Also note that this method is a no-op when running on Lollipop and later.
          *
          * @param show whether to show a cancel button
+         *
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #setShowCancelButton(boolean)}
          */
+        @Deprecated
+        @Override
         public MediaStyle setShowCancelButton(boolean show) {
-            mShowCancelButton = show;
-            return this;
+            return (MediaStyle) super.setShowCancelButton(show);
         }
 
         /**
@@ -625,10 +224,14 @@
          * #setShowCancelButton}.
          *
          * @param pendingIntent the intent to be sent when the cancel button is pressed
+         *
+         * @deprecated Use {@link android.support.v4.media.app.NotificationCompat.MediaStyle
+         * #setCancelButtonIntent(PendingIntent)}
          */
+        @Deprecated
+        @Override
         public MediaStyle setCancelButtonIntent(PendingIntent pendingIntent) {
-            mCancelButtonIntent = pendingIntent;
-            return this;
+            return (MediaStyle) super.setCancelButtonIntent(pendingIntent);
         }
     }
 
@@ -646,7 +249,7 @@
      * corresponding custom views to display.
      *
      * <p>To use this style with your Notification, feed it to
-     * {@link NotificationCompat.Builder#setStyle(Style)} like so:
+     * {@link android.support.v4.app.NotificationCompat.Builder#setStyle(Style)} like so:
      * <pre class="prettyprint">
      * Notification noti = new NotificationCompat.Builder()
      *     .setSmallIcon(R.drawable.ic_stat_player)
@@ -660,10 +263,23 @@
      * {@link android.support.v7.appcompat.R.style#TextAppearance_AppCompat_Notification} or
      * {@link android.support.v7.appcompat.R.style#TextAppearance_AppCompat_Notification_Title} in
      * your custom views in order to get the correct styling on each platform version.
+     *
+     * @deprecated Use {@link android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle}
+     * and {@link android.support.compat.R.style#TextAppearance_Compat_Notification} or
+     * {@link android.support.compat.R.style#TextAppearance_Compat_Notification_Title}.
      */
-    public static class DecoratedCustomViewStyle extends Style {
+    @Deprecated
+    public static class DecoratedCustomViewStyle extends
+            android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle {
 
+        /**
+         * @deprecated Use
+         * {@link android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle
+         * #DecoratedCustomViewStyle()}.
+         */
+        @Deprecated
         public DecoratedCustomViewStyle() {
+            super();
         }
     }
 
@@ -680,7 +296,7 @@
      * corresponding custom views to display.
      *
      * <p>To use this style with your Notification, feed it to
-     * {@link NotificationCompat.Builder#setStyle(Style)} like so:
+     * {@link android.support.v4.app.NotificationCompat.Builder#setStyle(Style)} like so:
      * <pre class="prettyprint">
      * Notification noti = new Notification.Builder()
      *     .setSmallIcon(R.drawable.ic_stat_player)
@@ -697,12 +313,26 @@
      * android.support.v7.appcompat.R.style#TextAppearance_AppCompat_Notification_Title_Media} in
      * your custom views in order to get the correct styling on each platform version.
      *
-     * @see DecoratedCustomViewStyle
-     * @see MediaStyle
+     * @see android.support.v4.app.NotificationCompat.DecoratedCustomViewStyle
+     * @see android.support.v4.media.app.NotificationCompat.MediaStyle
+     *
+     * @deprecated Use
+     * {@link android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle} and
+     * {@link android.support.mediacompat.R.style#TextAppearance_Compat_Notification_Media} and
+     * {@link android.support.mediacompat.R.style#TextAppearance_Compat_Notification_Title_Media}.
      */
-    public static class DecoratedMediaCustomViewStyle extends MediaStyle {
+    @Deprecated
+    public static class DecoratedMediaCustomViewStyle extends
+            android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle {
 
+        /**
+         * @deprecated Use
+         * {@link android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle
+         * #DecoratedMediaCustomViewStyle()}.
+         */
+        @Deprecated
         public DecoratedMediaCustomViewStyle() {
+            super();
         }
     }
 }
diff --git a/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl21.java b/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl21.java
deleted file mode 100644
index 2a4bf7b..0000000
--- a/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl21.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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 android.support.v7.app;
-
-import android.app.Notification;
-import android.media.session.MediaSession;
-import android.support.annotation.RequiresApi;
-import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
-
-@RequiresApi(21)
-class NotificationCompatImpl21 {
-
-    public static void addMediaStyle(NotificationBuilderWithBuilderAccessor b,
-            int[] actionsToShowInCompact,
-            Object token) {
-        Notification.MediaStyle style = new Notification.MediaStyle(b.getBuilder());
-        if (actionsToShowInCompact != null) {
-            style.setShowActionsInCompactView(actionsToShowInCompact);
-        }
-        if (token != null) {
-            style.setMediaSession((MediaSession.Token) token);
-        }
-    }
-}
diff --git a/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl24.java b/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl24.java
deleted file mode 100644
index c48e286..0000000
--- a/v7/appcompat/src/android/support/v7/app/NotificationCompatImpl24.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v7.app;
-
-import android.app.Notification;
-import android.support.annotation.RequiresApi;
-import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
-
-@RequiresApi(24)
-class NotificationCompatImpl24 {
-
-    public static void addDecoratedCustomViewStyle(NotificationBuilderWithBuilderAccessor b) {
-        Notification.Builder builder = b.getBuilder();
-        builder.setStyle(new Notification.DecoratedCustomViewStyle());
-    }
-
-    public static void addDecoratedMediaCustomViewStyle(NotificationBuilderWithBuilderAccessor b) {
-        Notification.Builder builder = b.getBuilder();
-        builder.setStyle(new Notification.DecoratedMediaCustomViewStyle());
-    }
-}
diff --git a/v7/appcompat/src/android/support/v7/app/NotificationCompatImplBase.java b/v7/appcompat/src/android/support/v7/app/NotificationCompatImplBase.java
deleted file mode 100644
index c1432c9..0000000
--- a/v7/appcompat/src/android/support/v7/app/NotificationCompatImplBase.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * Copyright (C) 2015 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 android.support.v7.app;
-
-import android.app.Notification;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffColorFilter;
-import android.graphics.drawable.Drawable;
-import android.os.Build;
-import android.os.SystemClock;
-import android.support.annotation.RequiresApi;
-import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
-import android.support.v4.app.NotificationCompat;
-import android.support.v4.app.NotificationCompatBase;
-import android.support.v7.appcompat.R;
-import android.util.TypedValue;
-import android.view.View;
-import android.widget.RemoteViews;
-
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Helper class to generate MediaStyle notifications for pre-Lollipop platforms. Overrides
- * contentView and bigContentView of the notification.
- */
-@RequiresApi(9)
-class NotificationCompatImplBase {
-
-    static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
-    static final int MAX_MEDIA_BUTTONS = 5;
-    private static final int MAX_ACTION_BUTTONS = 3;
-
-    @RequiresApi(11)
-    public static <T extends NotificationCompatBase.Action> RemoteViews overrideContentViewMedia(
-            NotificationBuilderWithBuilderAccessor builder,
-            Context context, CharSequence contentTitle, CharSequence contentText,
-            CharSequence contentInfo, int number, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, List<T> actions,
-            int[] actionsToShowInCompact, boolean showCancelButton,
-            PendingIntent cancelButtonIntent, boolean isDecoratedCustomView) {
-        RemoteViews views = generateContentViewMedia(context, contentTitle, contentText, contentInfo,
-                number, largeIcon, subText, useChronometer, when, priority, actions,
-                actionsToShowInCompact, showCancelButton, cancelButtonIntent,
-                isDecoratedCustomView);
-        builder.getBuilder().setContent(views);
-        if (showCancelButton) {
-            builder.getBuilder().setOngoing(true);
-        }
-        return views;
-    }
-
-    @RequiresApi(11)
-    private static <T extends NotificationCompatBase.Action> RemoteViews generateContentViewMedia(
-            Context context, CharSequence contentTitle, CharSequence contentText,
-            CharSequence contentInfo, int number, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, List<T> actions,
-            int[] actionsToShowInCompact, boolean showCancelButton,
-            PendingIntent cancelButtonIntent, boolean isDecoratedCustomView) {
-        RemoteViews view = applyStandardTemplate(context, contentTitle, contentText, contentInfo,
-                number, 0 /* smallIcon */, largeIcon, subText, useChronometer, when, priority,
-                0 /* color is unused on media */,
-                isDecoratedCustomView ? R.layout.notification_template_media_custom
-                        : R.layout.notification_template_media,
-                true /* fitIn1U */);
-
-        final int numActions = actions.size();
-        final int N = actionsToShowInCompact == null
-                ? 0
-                : Math.min(actionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
-        view.removeAllViews(R.id.media_actions);
-        if (N > 0) {
-            for (int i = 0; i < N; i++) {
-                if (i >= numActions) {
-                    throw new IllegalArgumentException(String.format(
-                            "setShowActionsInCompactView: action %d out of bounds (max %d)",
-                            i, numActions - 1));
-                }
-
-                final NotificationCompatBase.Action action = actions.get(actionsToShowInCompact[i]);
-                final RemoteViews button = generateMediaActionButton(context, action);
-                view.addView(R.id.media_actions, button);
-            }
-        }
-        if (showCancelButton) {
-            view.setViewVisibility(R.id.end_padder, View.GONE);
-            view.setViewVisibility(R.id.cancel_action, View.VISIBLE);
-            view.setOnClickPendingIntent(R.id.cancel_action, cancelButtonIntent);
-            view.setInt(R.id.cancel_action, "setAlpha",
-                    context.getResources().getInteger(R.integer.cancel_button_image_alpha));
-        } else {
-            view.setViewVisibility(R.id.end_padder, View.VISIBLE);
-            view.setViewVisibility(R.id.cancel_action, View.GONE);
-        }
-        return view;
-    }
-
-    @RequiresApi(16)
-    public static <T extends NotificationCompatBase.Action> void overrideMediaBigContentView(
-            Notification n, Context context, CharSequence contentTitle, CharSequence contentText,
-            CharSequence contentInfo, int number, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, int color, List<T> actions,
-            boolean showCancelButton, PendingIntent cancelButtonIntent,
-            boolean decoratedCustomView) {
-        n.bigContentView = generateMediaBigView(context, contentTitle, contentText, contentInfo,
-                number, largeIcon, subText, useChronometer, when, priority, color, actions,
-                showCancelButton, cancelButtonIntent, decoratedCustomView);
-        if (showCancelButton) {
-            n.flags |= Notification.FLAG_ONGOING_EVENT;
-        }
-    }
-
-    @RequiresApi(11)
-    public static <T extends NotificationCompatBase.Action> RemoteViews generateMediaBigView(
-            Context context, CharSequence contentTitle, CharSequence contentText,
-            CharSequence contentInfo, int number, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, int color, List<T> actions,
-            boolean showCancelButton, PendingIntent cancelButtonIntent,
-            boolean decoratedCustomView) {
-        final int actionCount = Math.min(actions.size(), MAX_MEDIA_BUTTONS);
-        RemoteViews big = applyStandardTemplate(context, contentTitle, contentText, contentInfo,
-                number, 0 /* smallIcon */, largeIcon, subText, useChronometer, when, priority,
-                color,  /* fitIn1U */getBigMediaLayoutResource(decoratedCustomView, actionCount),
-                false);
-
-        big.removeAllViews(R.id.media_actions);
-        if (actionCount > 0) {
-            for (int i = 0; i < actionCount; i++) {
-                final RemoteViews button = generateMediaActionButton(context, actions.get(i));
-                big.addView(R.id.media_actions, button);
-            }
-        }
-        if (showCancelButton) {
-            big.setViewVisibility(R.id.cancel_action, View.VISIBLE);
-            big.setInt(R.id.cancel_action, "setAlpha",
-                    context.getResources().getInteger(R.integer.cancel_button_image_alpha));
-            big.setOnClickPendingIntent(R.id.cancel_action, cancelButtonIntent);
-        } else {
-            big.setViewVisibility(R.id.cancel_action, View.GONE);
-        }
-        return big;
-    }
-
-    @RequiresApi(11)
-    private static RemoteViews generateMediaActionButton(Context context,
-            NotificationCompatBase.Action action) {
-        final boolean tombstone = (action.getActionIntent() == null);
-        RemoteViews button = new RemoteViews(context.getPackageName(),
-                R.layout.notification_media_action);
-        button.setImageViewResource(R.id.action0, action.getIcon());
-        if (!tombstone) {
-            button.setOnClickPendingIntent(R.id.action0, action.getActionIntent());
-        }
-        if (Build.VERSION.SDK_INT >= 15) {
-            button.setContentDescription(R.id.action0, action.getTitle());
-        }
-        return button;
-    }
-
-    @RequiresApi(11)
-    private static int getBigMediaLayoutResource(boolean decoratedCustomView, int actionCount) {
-        if (actionCount <= 3) {
-            return decoratedCustomView
-                    ? R.layout.notification_template_big_media_narrow_custom
-                    : R.layout.notification_template_big_media_narrow;
-        } else {
-            return decoratedCustomView
-                    ? R.layout.notification_template_big_media_custom
-                    : R.layout.notification_template_big_media;
-        }
-    }
-
-    public static RemoteViews applyStandardTemplateWithActions(Context context,
-            CharSequence contentTitle, CharSequence contentText, CharSequence contentInfo,
-            int number, int smallIcon, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, int color, int resId, boolean fitIn1U,
-            ArrayList<NotificationCompat.Action> actions) {
-        RemoteViews remoteViews = applyStandardTemplate(context, contentTitle, contentText,
-                contentInfo, number, smallIcon, largeIcon, subText, useChronometer, when, priority,
-                color, resId, fitIn1U);
-        remoteViews.removeAllViews(R.id.actions);
-        boolean actionsVisible = false;
-        if (actions != null) {
-            int N = actions.size();
-            if (N > 0) {
-                actionsVisible = true;
-                if (N > MAX_ACTION_BUTTONS) N = MAX_ACTION_BUTTONS;
-                for (int i = 0; i < N; i++) {
-                    final RemoteViews button = generateActionButton(context, actions.get(i));
-                    remoteViews.addView(R.id.actions, button);
-                }
-            }
-        }
-        int actionVisibility = actionsVisible ? View.VISIBLE : View.GONE;
-        remoteViews.setViewVisibility(R.id.actions, actionVisibility);
-        remoteViews.setViewVisibility(R.id.action_divider, actionVisibility);
-        return remoteViews;
-    }
-
-    private static RemoteViews generateActionButton(Context context,
-            NotificationCompat.Action action) {
-        final boolean tombstone = (action.actionIntent == null);
-        RemoteViews button =  new RemoteViews(context.getPackageName(),
-                tombstone ? getActionTombstoneLayoutResource()
-                        : getActionLayoutResource());
-        button.setImageViewBitmap(R.id.action_image,
-                createColoredBitmap(context, action.getIcon(),
-                        context.getResources().getColor(R.color.notification_action_color_filter)));
-        button.setTextViewText(R.id.action_text, action.title);
-        if (!tombstone) {
-            button.setOnClickPendingIntent(R.id.action_container, action.actionIntent);
-        }
-        if (Build.VERSION.SDK_INT >= 15) {
-            button.setContentDescription(R.id.action_container, action.title);
-        }
-        return button;
-    }
-
-    private static Bitmap createColoredBitmap(Context context, int iconId, int color) {
-        return createColoredBitmap(context, iconId, color, 0);
-    }
-
-    private static Bitmap createColoredBitmap(Context context, int iconId, int color, int size) {
-        Drawable drawable = context.getResources().getDrawable(iconId);
-        int width = size == 0 ? drawable.getIntrinsicWidth() : size;
-        int height = size == 0 ? drawable.getIntrinsicHeight() : size;
-        Bitmap resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
-        drawable.setBounds(0, 0, width, height);
-        if (color != 0) {
-            drawable.mutate().setColorFilter(
-                    new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
-        }
-        Canvas canvas = new Canvas(resultBitmap);
-        drawable.draw(canvas);
-        return resultBitmap;
-    }
-
-    private static int getActionLayoutResource() {
-        return R.layout.notification_action;
-    }
-
-    private static int getActionTombstoneLayoutResource() {
-        return R.layout.notification_action_tombstone;
-    }
-
-    public static RemoteViews applyStandardTemplate(Context context,
-            CharSequence contentTitle, CharSequence contentText, CharSequence contentInfo,
-            int number, int smallIcon, Bitmap largeIcon, CharSequence subText,
-            boolean useChronometer, long when, int priority, int color, int resId,
-            boolean fitIn1U) {
-        Resources res = context.getResources();
-        RemoteViews contentView = new RemoteViews(context.getPackageName(), resId);
-        boolean showLine3 = false;
-        boolean showLine2 = false;
-
-        boolean minPriority = priority < NotificationCompat.PRIORITY_LOW;
-        if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 21) {
-            // lets color the backgrounds
-            if (minPriority) {
-                contentView.setInt(R.id.notification_background,
-                        "setBackgroundResource", R.drawable.notification_bg_low);
-                contentView.setInt(R.id.icon,
-                        "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
-            } else {
-                contentView.setInt(R.id.notification_background,
-                        "setBackgroundResource", R.drawable.notification_bg);
-                contentView.setInt(R.id.icon,
-                        "setBackgroundResource", R.drawable.notification_template_icon_bg);
-            }
-        }
-
-        if (largeIcon != null) {
-            // On versions before Jellybean, the large icon was shown by SystemUI, so we need to hide
-            // it here.
-            if (Build.VERSION.SDK_INT >= 16) {
-                contentView.setViewVisibility(R.id.icon, View.VISIBLE);
-                contentView.setImageViewBitmap(R.id.icon, largeIcon);
-            } else {
-                contentView.setViewVisibility(R.id.icon, View.GONE);
-            }
-            if (smallIcon != 0) {
-                int backgroundSize = res.getDimensionPixelSize(
-                        R.dimen.notification_right_icon_size);
-                int iconSize = backgroundSize - res.getDimensionPixelSize(
-                        R.dimen.notification_small_icon_background_padding) * 2;
-                if (Build.VERSION.SDK_INT >= 21) {
-                    Bitmap smallBit = createIconWithBackground(context,
-                            smallIcon,
-                            backgroundSize,
-                            iconSize,
-                            color);
-                    contentView.setImageViewBitmap(R.id.right_icon, smallBit);
-                } else {
-                    contentView.setImageViewBitmap(R.id.right_icon,
-                            createColoredBitmap(context, smallIcon, Color.WHITE));
-                }
-                contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
-            }
-        } else if (smallIcon != 0) { // small icon at left
-            contentView.setViewVisibility(R.id.icon, View.VISIBLE);
-            if (Build.VERSION.SDK_INT >= 21) {
-                int backgroundSize = res.getDimensionPixelSize(
-                        R.dimen.notification_large_icon_width)
-                        - res.getDimensionPixelSize(R.dimen.notification_big_circle_margin);
-                int iconSize = res.getDimensionPixelSize(
-                        R.dimen.notification_small_icon_size_as_large);
-                Bitmap smallBit = createIconWithBackground(context,
-                        smallIcon,
-                        backgroundSize,
-                        iconSize,
-                        color);
-                contentView.setImageViewBitmap(R.id.icon, smallBit);
-            } else {
-                contentView.setImageViewBitmap(R.id.icon,
-                        createColoredBitmap(context, smallIcon, Color.WHITE));
-            }
-        }
-        if (contentTitle != null) {
-            contentView.setTextViewText(R.id.title, contentTitle);
-        }
-        if (contentText != null) {
-            contentView.setTextViewText(R.id.text, contentText);
-            showLine3 = true;
-        }
-        // If there is a large icon we have a right side
-        boolean hasRightSide = !(Build.VERSION.SDK_INT >= 21) && largeIcon != null;
-        if (contentInfo != null) {
-            contentView.setTextViewText(R.id.info, contentInfo);
-            contentView.setViewVisibility(R.id.info, View.VISIBLE);
-            showLine3 = true;
-            hasRightSide = true;
-        } else if (number > 0) {
-            final int tooBig = res.getInteger(
-                    R.integer.status_bar_notification_info_maxnum);
-            if (number > tooBig) {
-                contentView.setTextViewText(R.id.info, ((Resources) res).getString(
-                        R.string.status_bar_notification_info_overflow));
-            } else {
-                NumberFormat f = NumberFormat.getIntegerInstance();
-                contentView.setTextViewText(R.id.info, f.format(number));
-            }
-            contentView.setViewVisibility(R.id.info, View.VISIBLE);
-            showLine3 = true;
-            hasRightSide = true;
-        } else {
-            contentView.setViewVisibility(R.id.info, View.GONE);
-        }
-
-        // Need to show three lines? Only allow on Jellybean+
-        if (subText != null && Build.VERSION.SDK_INT >= 16) {
-            contentView.setTextViewText(R.id.text, subText);
-            if (contentText != null) {
-                contentView.setTextViewText(R.id.text2, contentText);
-                contentView.setViewVisibility(R.id.text2, View.VISIBLE);
-                showLine2 = true;
-            } else {
-                contentView.setViewVisibility(R.id.text2, View.GONE);
-            }
-        }
-
-        // RemoteViews.setViewPadding and RemoteViews.setTextViewTextSize is not available on ICS-
-        if (showLine2 && Build.VERSION.SDK_INT >= 16) {
-            if (fitIn1U) {
-                // need to shrink all the type to make sure everything fits
-                final float subTextSize = res.getDimensionPixelSize(
-                        R.dimen.notification_subtext_size);
-                contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
-            }
-            // vertical centering
-            contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
-        }
-
-        if (when != 0) {
-            if (useChronometer && Build.VERSION.SDK_INT >= 16) {
-                contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
-                contentView.setLong(R.id.chronometer, "setBase",
-                        when + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
-                contentView.setBoolean(R.id.chronometer, "setStarted", true);
-            } else {
-                contentView.setViewVisibility(R.id.time, View.VISIBLE);
-                contentView.setLong(R.id.time, "setTime", when);
-            }
-            hasRightSide = true;
-        }
-        contentView.setViewVisibility(R.id.right_side, hasRightSide ? View.VISIBLE : View.GONE);
-        contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
-        return contentView;
-    }
-
-    public static Bitmap createIconWithBackground(Context ctx, int iconId, int size, int iconSize,
-            int color) {
-        Bitmap coloredBitmap = createColoredBitmap(ctx, R.drawable.notification_icon_background,
-                        color == NotificationCompat.COLOR_DEFAULT ? 0 : color, size);
-        Canvas canvas = new Canvas(coloredBitmap);
-        Drawable icon = ctx.getResources().getDrawable(iconId).mutate();
-        icon.setFilterBitmap(true);
-        int inset = (size - iconSize) / 2;
-        icon.setBounds(inset, inset, iconSize + inset, iconSize + inset);
-        icon.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP));
-        icon.draw(canvas);
-        return coloredBitmap;
-    }
-
-    public static void buildIntoRemoteViews(Context ctx, RemoteViews outerView,
-            RemoteViews innerView) {
-        // this needs to be done fore the other calls, since otherwise we might hide the wrong
-        // things if our ids collide.
-        hideNormalContent(outerView);
-        outerView.removeAllViews(R.id.notification_main_column);
-        outerView.addView(R.id.notification_main_column, innerView.clone());
-        outerView.setViewVisibility(R.id.notification_main_column, View.VISIBLE);
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
-            // Adjust padding depending on font size.
-            outerView.setViewPadding(R.id.notification_main_column_container,
-                    0, calculateTopPadding(ctx), 0, 0);
-        }
-    }
-
-    private static void hideNormalContent(RemoteViews outerView) {
-        outerView.setViewVisibility(R.id.title, View.GONE);
-        outerView.setViewVisibility(R.id.text2, View.GONE);
-        outerView.setViewVisibility(R.id.text, View.GONE);
-    }
-
-    public static int calculateTopPadding(Context ctx) {
-        int padding = ctx.getResources().getDimensionPixelSize(R.dimen.notification_top_pad);
-        int largePadding = ctx.getResources().getDimensionPixelSize(
-                R.dimen.notification_top_pad_large_text);
-        float fontScale = ctx.getResources().getConfiguration().fontScale;
-        float largeFactor = (constrain(fontScale, 1.0f, 1.3f) - 1f) / (1.3f - 1f);
-
-        // Linearly interpolate the padding between large and normal with the font scale ranging
-        // from 1f to LARGE_TEXT_SCALE
-        return Math.round((1 - largeFactor) * padding + largeFactor * largePadding);
-    }
-
-    public static float constrain(float amount, float low, float high) {
-        return amount < low ? low : (amount > high ? high : amount);
-    }
-}
diff --git a/v7/appcompat/src/android/support/v7/app/NotificationCompatImplJellybean.java b/v7/appcompat/src/android/support/v7/app/NotificationCompatImplJellybean.java
deleted file mode 100644
index 2fca0f0..0000000
--- a/v7/appcompat/src/android/support/v7/app/NotificationCompatImplJellybean.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.support.v7.app;
-
-import android.app.Notification;
-import android.support.annotation.RequiresApi;
-import android.support.v4.app.NotificationBuilderWithBuilderAccessor;
-
-@RequiresApi(16)
-class NotificationCompatImplJellybean {
-
-    public static void addBigTextStyle(NotificationBuilderWithBuilderAccessor b,
-            CharSequence bigText) {
-        Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle(b.getBuilder());
-        bigTextStyle.bigText(bigText);
-    }
-}
diff --git a/v7/appcompat/src/android/support/v7/view/menu/CascadingMenuPopup.java b/v7/appcompat/src/android/support/v7/view/menu/CascadingMenuPopup.java
index fda1a97..73499cf 100644
--- a/v7/appcompat/src/android/support/v7/view/menu/CascadingMenuPopup.java
+++ b/v7/appcompat/src/android/support/v7/view/menu/CascadingMenuPopup.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Rect;
+import android.os.Build;
 import android.os.Handler;
 import android.os.Parcelable;
 import android.os.SystemClock;
@@ -28,7 +29,6 @@
 import android.support.annotation.Nullable;
 import android.support.annotation.StyleRes;
 import android.support.v4.internal.view.SupportMenu;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.view.ViewCompat;
 import android.support.v7.appcompat.R;
@@ -406,7 +406,7 @@
 
             final int parentOffsetLeft;
             final int parentOffsetTop;
-            if (BuildCompat.isAtLeastO()) {
+            if (Build.VERSION.SDK_INT >= 26) {
                 // Anchor the submenu directly to the parent menu item view. This allows for
                 // accurate submenu positioning when the parent menu is being moved.
                 popupWindow.setAnchorView(parentView);
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatAutoCompleteTextView.java b/v7/appcompat/src/android/support/v7/widget/AppCompatAutoCompleteTextView.java
index 96a481e..5b0a2f8 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatAutoCompleteTextView.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatAutoCompleteTextView.java
@@ -32,18 +32,18 @@
 import android.widget.AutoCompleteTextView;
 
 /**
- * A {@link AutoCompleteTextView} which supports compatible features on older version of the
+ * A {@link AutoCompleteTextView} which supports compatible features on older versions of the
  * platform, including:
  * <ul>
- *     <li>Supports {@link R.attr#textAllCaps} style attribute which works back to
- *     {@link android.os.Build.VERSION_CODES#GINGERBREAD Gingerbread}.</li>
  *     <li>Allows dynamic tint of its background via the background tint methods in
  *     {@link android.support.v4.view.ViewCompat}.</li>
  *     <li>Allows setting of the background tint using {@link R.attr#backgroundTint} and
  *     {@link R.attr#backgroundTintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link AutoCompleteTextView} in your layouts.
+ * <p>This will automatically be used when you use {@link AutoCompleteTextView} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatAutoCompleteTextView extends AutoCompleteTextView implements
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatButton.java b/v7/appcompat/src/android/support/v7/widget/AppCompatButton.java
index 6fb6223..2156dce 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatButton.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatButton.java
@@ -22,33 +22,39 @@
 import android.content.res.ColorStateList;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.Drawable;
+import android.os.Build;
 import android.support.annotation.DrawableRes;
+import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
 import android.support.v4.view.TintableBackgroundView;
+import android.support.v4.widget.AutoSizeableTextView;
+import android.support.v4.widget.TextViewCompat;
 import android.support.v7.appcompat.R;
 import android.util.AttributeSet;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.widget.Button;
+import android.widget.TextView;
 
 /**
- * A {@link Button} which supports compatible features on older version of the platform,
+ * A {@link Button} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
- *     <li>Supports {@link R.attr#textAllCaps} style attribute which works back to
- *     {@link android.os.Build.VERSION_CODES#GINGERBREAD Gingerbread}.</li>
  *     <li>Allows dynamic tint of its background via the background tint methods in
  *     {@link android.support.v4.view.ViewCompat}.</li>
  *     <li>Allows setting of the background tint using {@link R.attr#backgroundTint} and
  *     {@link R.attr#backgroundTintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link android.widget.Button} in your
- * layouts. You should only need to manually use this class when writing custom views.</p>
+ * <p>This will automatically be used when you use {@link Button} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
+ * You should only need to manually use this class when writing custom views.</p>
  */
-public class AppCompatButton extends Button implements TintableBackgroundView {
+public class AppCompatButton extends Button implements TintableBackgroundView,
+        AutoSizeableTextView {
 
     private final AppCompatBackgroundHelper mBackgroundTintHelper;
     private final AppCompatTextHelper mTextHelper;
@@ -176,6 +182,169 @@
         info.setClassName(Button.class.getName());
     }
 
+    @Override
+    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+        super.onLayout(changed, left, top, right, bottom);
+        if (mTextHelper != null) {
+            mTextHelper.onLayout(changed, left, top, right, bottom);
+        }
+    }
+
+    @Override
+    public void setTextSize(int unit, float size) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            super.setTextSize(unit, size);
+        } else {
+            if (mTextHelper != null) {
+                mTextHelper.setTextSize(unit, size);
+            }
+        }
+    }
+
+    @Override
+    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
+        super.onTextChanged(text, start, lengthBefore, lengthAfter);
+        if (mTextHelper != null && Build.VERSION.SDK_INT < 26 && mTextHelper.isAutoSizeEnabled()) {
+            mTextHelper.autoSizeText();
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public void setAutoSizeTextTypeWithDefaults(
+            @TextViewCompat.AutoSizeTextType int autoSizeTextType) {
+        if (Build.VERSION.SDK_INT >= 26) {
+            super.setAutoSizeTextTypeWithDefaults(autoSizeTextType);
+        } else {
+            if (mTextHelper != null) {
+                mTextHelper.setAutoSizeTextTypeWithDefaults(autoSizeTextType);
+            }
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public void setAutoSizeTextTypeUniformWithConfiguration(
+            int autoSizeMinTextSize,
+            int autoSizeMaxTextSize,
+            int autoSizeStepGranularity,
+            int unit) throws IllegalArgumentException {
+        if (Build.VERSION.SDK_INT >= 26) {
+            super.setAutoSizeTextTypeUniformWithConfiguration(
+                    autoSizeMinTextSize, autoSizeMaxTextSize, autoSizeStepGranularity, unit);
+        } else {
+            if (mTextHelper != null) {
+                mTextHelper.setAutoSizeTextTypeUniformWithConfiguration(
+                        autoSizeMinTextSize, autoSizeMaxTextSize, autoSizeStepGranularity, unit);
+            }
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public void setAutoSizeTextTypeUniformWithPresetSizes(@NonNull int[] presetSizes, int unit)
+            throws IllegalArgumentException {
+        if (Build.VERSION.SDK_INT >= 26) {
+            super.setAutoSizeTextTypeUniformWithPresetSizes(presetSizes, unit);
+        } else {
+            if (mTextHelper != null) {
+                mTextHelper.setAutoSizeTextTypeUniformWithPresetSizes(presetSizes, unit);
+            }
+        }
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    @TextViewCompat.AutoSizeTextType
+    public int getAutoSizeTextType() {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return super.getAutoSizeTextType() == TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM
+                    ? TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM
+                    : TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
+        } else {
+            if (mTextHelper != null) {
+                return mTextHelper.getAutoSizeTextType();
+            }
+        }
+        return TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public int getAutoSizeStepGranularity() {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return super.getAutoSizeStepGranularity();
+        } else {
+            if (mTextHelper != null) {
+                return mTextHelper.getAutoSizeStepGranularity();
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public int getAutoSizeMinTextSize() {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return super.getAutoSizeMinTextSize();
+        } else {
+            if (mTextHelper != null) {
+                return mTextHelper.getAutoSizeMinTextSize();
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public int getAutoSizeMaxTextSize() {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return super.getAutoSizeMaxTextSize();
+        } else {
+            if (mTextHelper != null) {
+                return mTextHelper.getAutoSizeMaxTextSize();
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * @hide
+     */
+    @RestrictTo(LIBRARY_GROUP)
+    @Override
+    public int[] getAutoSizeTextAvailableSizes() {
+        if (Build.VERSION.SDK_INT >= 26) {
+            return super.getAutoSizeTextAvailableSizes();
+        } else {
+            if (mTextHelper != null) {
+                return mTextHelper.getAutoSizeTextAvailableSizes();
+            }
+        }
+        return new int[0];
+    }
+
     /**
      * Sets the properties of this field to transform input to ALL CAPS
      * display. This may use a "small caps" formatting if available.
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatCheckBox.java b/v7/appcompat/src/android/support/v7/widget/AppCompatCheckBox.java
index 5809d25..0d4f4cb 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatCheckBox.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatCheckBox.java
@@ -32,7 +32,7 @@
 import android.widget.CheckBox;
 
 /**
- * A {@link CheckBox} which supports compatible features on older version of the platform,
+ * A {@link CheckBox} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
  *     <li>Allows dynamic tint of its background via the background tint methods in
@@ -41,7 +41,9 @@
  *     {@link R.attr#buttonTintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link CheckBox} in your layouts.
+ * <p>This will automatically be used when you use {@link CheckBox} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatCheckBox extends CheckBox implements TintableCompoundButton {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatCheckedTextView.java b/v7/appcompat/src/android/support/v7/widget/AppCompatCheckedTextView.java
index 1725c24..921f0a2 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatCheckedTextView.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatCheckedTextView.java
@@ -23,9 +23,11 @@
 import android.widget.CheckedTextView;
 
 /**
- * A {@link CheckedTextView} which supports compatible features on older version of the platform.
+ * A {@link CheckedTextView} which supports compatible features on older versions of the platform.
  *
- * <p>This will automatically be used when you use {@link CheckedTextView} in your layouts.
+ * <p>This will automatically be used when you use {@link CheckedTextView} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatCheckedTextView extends CheckedTextView {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatEditText.java b/v7/appcompat/src/android/support/v7/widget/AppCompatEditText.java
index d93f399..406e364 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatEditText.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatEditText.java
@@ -31,19 +31,19 @@
 import android.widget.EditText;
 
 /**
- * A {@link EditText} which supports compatible features on older version of the platform,
+ * A {@link EditText} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
- *     <li>Supports {@link R.attr#textAllCaps} style attribute which works back to
- *     {@link android.os.Build.VERSION_CODES#GINGERBREAD Gingerbread}.</li>
  *     <li>Allows dynamic tint of its background via the background tint methods in
  *     {@link android.support.v4.view.ViewCompat}.</li>
  *     <li>Allows setting of the background tint using {@link R.attr#backgroundTint} and
  *     {@link R.attr#backgroundTintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link android.widget.EditText} in your
- * layouts. You should only need to manually use this class when writing custom views.</p>
+ * <p>This will automatically be used when you use {@link EditText} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
+ * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatEditText extends EditText implements TintableBackgroundView {
 
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatImageButton.java b/v7/appcompat/src/android/support/v7/widget/AppCompatImageButton.java
index ff09c08..90e6aa9 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatImageButton.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatImageButton.java
@@ -37,7 +37,7 @@
 import android.widget.ImageView;
 
 /**
- * A {@link ImageButton} which supports compatible features on older version of the platform,
+ * A {@link ImageButton} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
  *     <li>Allows dynamic tint of its background via the background tint methods in
@@ -50,8 +50,10 @@
  *     {@link R.attr#tintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link android.widget.ImageButton} in your
- * layouts. You should only need to manually use this class when writing custom views.</p>
+ * <p>This will automatically be used when you use {@link ImageButton} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
+ * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatImageButton extends ImageButton implements TintableBackgroundView,
         TintableImageSourceView {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatImageView.java b/v7/appcompat/src/android/support/v7/widget/AppCompatImageView.java
index a0eb9ee..0844f9a 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatImageView.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatImageView.java
@@ -36,7 +36,7 @@
 import android.widget.ImageView;
 
 /**
- * A {@link ImageView} which supports compatible features on older version of the platform,
+ * A {@link ImageView} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
  *     <li>Allows dynamic tint of its background via the background tint methods in
@@ -49,8 +49,10 @@
  *     {@link R.attr#tintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link android.widget.ImageView} in your
- * layouts. You should only need to manually use this class when writing custom views.</p>
+ * <p>This will automatically be used when you use {@link ImageView} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
+ * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatImageView extends ImageView implements TintableBackgroundView,
         TintableImageSourceView {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatRadioButton.java b/v7/appcompat/src/android/support/v7/widget/AppCompatRadioButton.java
index 8aa22f3..2a6bac0 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatRadioButton.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatRadioButton.java
@@ -32,7 +32,7 @@
 import android.widget.RadioButton;
 
 /**
- * A {@link RadioButton} which supports compatible features on older version of the platform,
+ * A {@link RadioButton} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
  *     <li>Allows dynamic tint of its background via the background tint methods in
@@ -41,7 +41,9 @@
  *     {@link R.attr#buttonTintMode}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link RadioButton} in your layouts.
+ * <p>This will automatically be used when you use {@link RadioButton} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatRadioButton extends RadioButton implements TintableCompoundButton {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatRatingBar.java b/v7/appcompat/src/android/support/v7/widget/AppCompatRatingBar.java
index d8bac12..b03b842 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatRatingBar.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatRatingBar.java
@@ -24,9 +24,11 @@
 import android.widget.RatingBar;
 
 /**
- * A {@link RatingBar} which supports compatible features on older version of the platform.
+ * A {@link RatingBar} which supports compatible features on older versions of the platform.
  *
- * <p>This will automatically be used when you use {@link RatingBar} in your layouts.
+ * <p>This will automatically be used when you use {@link RatingBar} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatRatingBar extends RatingBar {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatSeekBar.java b/v7/appcompat/src/android/support/v7/widget/AppCompatSeekBar.java
index bf05f4d..674e46b 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatSeekBar.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatSeekBar.java
@@ -24,9 +24,11 @@
 import android.widget.SeekBar;
 
 /**
- * A {@link SeekBar} which supports compatible features on older version of the platform.
+ * A {@link SeekBar} which supports compatible features on older versions of the platform.
  *
- * <p>This will automatically be used when you use {@link SeekBar} in your layouts.
+ * <p>This will automatically be used when you use {@link SeekBar} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatSeekBar extends SeekBar {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatTextHelper.java b/v7/appcompat/src/android/support/v7/widget/AppCompatTextHelper.java
index c5f6e17..afd59bd 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatTextHelper.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatTextHelper.java
@@ -27,7 +27,6 @@
 import android.support.annotation.NonNull;
 import android.support.annotation.RequiresApi;
 import android.support.annotation.RestrictTo;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.widget.TextViewCompat;
 import android.support.v7.appcompat.R;
 import android.text.method.PasswordTransformationMethod;
@@ -171,7 +170,7 @@
 
         mAutoSizeTextHelper.loadFromAttributes(attrs, defStyleAttr);
 
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             // Delegate auto-size functionality to the framework implementation.
             if (mAutoSizeTextHelper.getAutoSizeTextType()
                     != TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE) {
@@ -200,6 +199,7 @@
 
         if (a.hasValue(R.styleable.TextAppearance_android_fontFamily)
                 || a.hasValue(R.styleable.TextAppearance_fontFamily)) {
+            mFontTypeface = null;
             int fontFamilyId = a.hasValue(R.styleable.TextAppearance_android_fontFamily)
                     ? R.styleable.TextAppearance_android_fontFamily
                     : R.styleable.TextAppearance_fontFamily;
@@ -283,45 +283,33 @@
     @RestrictTo(LIBRARY_GROUP)
     void onLayout(boolean changed, int left, int top, int right, int bottom) {
         // Auto-size is supported by the framework starting from Android O.
-        if (!BuildCompat.isAtLeastO()) {
-            if (isAutoSizeEnabled()) {
-                if (getNeedsAutoSizeText()) {
-                    // Call auto-size after the width and height have been calculated.
-                    autoSizeText();
-                }
-                // Always try to auto-size if enabled. Functions that do not want to trigger
-                // auto-sizing after the next layout round should set this to false.
-                setNeedsAutoSizeText(true);
-            }
+        if (!(Build.VERSION.SDK_INT >= 26)) {
+            autoSizeText();
         }
     }
 
     /** @hide */
     @RestrictTo(LIBRARY_GROUP)
     void setTextSize(int unit, float size) {
-        if (!BuildCompat.isAtLeastO()) {
+        if (!(Build.VERSION.SDK_INT >= 26)) {
             if (!isAutoSizeEnabled()) {
                 setTextSizeInternal(unit, size);
             }
         }
     }
 
-    private boolean isAutoSizeEnabled() {
-        return mAutoSizeTextHelper.isAutoSizeEnabled();
-    }
-
-    private boolean getNeedsAutoSizeText() {
-        return mAutoSizeTextHelper.getNeedsAutoSizeText();
-    }
-
-    private void setNeedsAutoSizeText(boolean needsAutoSizeText) {
-        mAutoSizeTextHelper.setNeedsAutoSizeText(needsAutoSizeText);
-    }
-
-    private void autoSizeText() {
+    /** @hide */
+    @RestrictTo(LIBRARY_GROUP)
+    void autoSizeText() {
         mAutoSizeTextHelper.autoSizeText();
     }
 
+    /** @hide */
+    @RestrictTo(LIBRARY_GROUP)
+    boolean isAutoSizeEnabled() {
+        return mAutoSizeTextHelper.isAutoSizeEnabled();
+    }
+
     private void setTextSizeInternal(int unit, float size) {
         mAutoSizeTextHelper.setTextSizeInternal(unit, size);
     }
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatTextView.java b/v7/appcompat/src/android/support/v7/widget/AppCompatTextView.java
index 992ddc6..12d0ff9 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatTextView.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatTextView.java
@@ -22,11 +22,11 @@
 import android.content.res.ColorStateList;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.Drawable;
+import android.os.Build;
 import android.support.annotation.DrawableRes;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RestrictTo;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.view.TintableBackgroundView;
 import android.support.v4.widget.AutoSizeableTextView;
 import android.support.v4.widget.TextViewCompat;
@@ -35,11 +35,9 @@
 import android.widget.TextView;
 
 /**
- * A {@link TextView} which supports compatible features on older version of the platform,
+ * A {@link TextView} which supports compatible features on older versions of the platform,
  * including:
  * <ul>
- *     <li>Supports {@link R.attr#textAllCaps} style attribute which works back to
- *     {@link android.os.Build.VERSION_CODES#GINGERBREAD Gingerbread}.</li>
  *     <li>Allows dynamic tint of its background via the background tint methods in
  *     {@link android.support.v4.view.ViewCompat}.</li>
  *     <li>Allows setting of the background tint using {@link R.attr#backgroundTint} and
@@ -54,7 +52,9 @@
  *     {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH Ice Cream Sandwich}.</li>
  * </ul>
  *
- * <p>This will automatically be used when you use {@link TextView} in your layouts.
+ * <p>This will automatically be used when you use {@link TextView} in your layouts
+ * and the top-level activity / dialog is provided by
+ * <a href="{@docRoot}topic/libraries/support-library/packages.html#v7-appcompat">appcompat</a>.
  * You should only need to manually use this class when writing custom views.</p>
  */
 public class AppCompatTextView extends TextView implements TintableBackgroundView,
@@ -183,7 +183,7 @@
 
     @Override
     public void setTextSize(int unit, float size) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             super.setTextSize(unit, size);
         } else {
             if (mTextHelper != null) {
@@ -192,6 +192,14 @@
         }
     }
 
+    @Override
+    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
+        super.onTextChanged(text, start, lengthBefore, lengthAfter);
+        if (mTextHelper != null && Build.VERSION.SDK_INT < 26 && mTextHelper.isAutoSizeEnabled()) {
+            mTextHelper.autoSizeText();
+        }
+    }
+
     /**
      * This should be accessed via
      * {@link android.support.v4.widget.TextViewCompat#setAutoSizeTextTypeWithDefaults(
@@ -203,7 +211,7 @@
     @Override
     public void setAutoSizeTextTypeWithDefaults(
             @TextViewCompat.AutoSizeTextType int autoSizeTextType) {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             super.setAutoSizeTextTypeWithDefaults(autoSizeTextType);
         } else {
             if (mTextHelper != null) {
@@ -226,7 +234,7 @@
             int autoSizeMaxTextSize,
             int autoSizeStepGranularity,
             int unit) throws IllegalArgumentException {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             super.setAutoSizeTextTypeUniformWithConfiguration(
                     autoSizeMinTextSize, autoSizeMaxTextSize, autoSizeStepGranularity, unit);
         } else {
@@ -248,7 +256,7 @@
     @Override
     public void setAutoSizeTextTypeUniformWithPresetSizes(@NonNull int[] presetSizes, int unit)
             throws IllegalArgumentException {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             super.setAutoSizeTextTypeUniformWithPresetSizes(presetSizes, unit);
         } else {
             if (mTextHelper != null) {
@@ -267,7 +275,7 @@
     @Override
     @TextViewCompat.AutoSizeTextType
     public int getAutoSizeTextType() {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return super.getAutoSizeTextType() == TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM
                     ? TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM
                     : TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
@@ -288,7 +296,7 @@
     @RestrictTo(LIBRARY_GROUP)
     @Override
     public int getAutoSizeStepGranularity() {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return super.getAutoSizeStepGranularity();
         } else {
             if (mTextHelper != null) {
@@ -307,7 +315,7 @@
     @RestrictTo(LIBRARY_GROUP)
     @Override
     public int getAutoSizeMinTextSize() {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return super.getAutoSizeMinTextSize();
         } else {
             if (mTextHelper != null) {
@@ -326,7 +334,7 @@
     @RestrictTo(LIBRARY_GROUP)
     @Override
     public int getAutoSizeMaxTextSize() {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return super.getAutoSizeMaxTextSize();
         } else {
             if (mTextHelper != null) {
@@ -345,7 +353,7 @@
     @RestrictTo(LIBRARY_GROUP)
     @Override
     public int[] getAutoSizeTextAvailableSizes() {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             return super.getAutoSizeTextAvailableSizes();
         } else {
             if (mTextHelper != null) {
diff --git a/v7/appcompat/src/android/support/v7/widget/AppCompatTextViewAutoSizeHelper.java b/v7/appcompat/src/android/support/v7/widget/AppCompatTextViewAutoSizeHelper.java
index 068366a..29449f5 100644
--- a/v7/appcompat/src/android/support/v7/widget/AppCompatTextViewAutoSizeHelper.java
+++ b/v7/appcompat/src/android/support/v7/widget/AppCompatTextViewAutoSizeHelper.java
@@ -25,8 +25,8 @@
 import android.graphics.RectF;
 import android.os.Build;
 import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.support.annotation.RestrictTo;
-import android.support.v4.os.BuildCompat;
 import android.support.v4.widget.TextViewCompat;
 import android.support.v7.appcompat.R;
 import android.text.Layout;
@@ -36,6 +36,7 @@
 import android.text.TextPaint;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
+import android.util.Log;
 import android.util.TypedValue;
 import android.widget.TextView;
 
@@ -54,6 +55,7 @@
  * fill its layout based on the TextView's characteristics and boundaries.
  */
 class AppCompatTextViewAutoSizeHelper {
+    private static final String TAG = "ACTVAutoSizeHelper";
     private static final RectF TEMP_RECTF = new RectF();
     // Default minimum size for auto-sizing text in scaled pixels.
     private static final int DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP = 12;
@@ -61,6 +63,9 @@
     private static final int DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP = 112;
     // Default value for the step size in pixels.
     private static final int DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX = 1;
+    // Cache of TextView methods used via reflection; the key is the method name and the value is
+    // the method itself or null if it can not be found.
+    private static Hashtable<String, Method> sTextViewMethodByNameCache = new Hashtable<>();
     // Use this to specify that any of the auto-size configuration int values have not been set.
     static final float UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE = -1f;
     // Ported from TextView#VERY_WIDE. Represents a maximum width in pixels the TextView takes when
@@ -83,9 +88,7 @@
     // build the steps set using mAutoSizeMinTextSizeInPx, mAutoSizeMaxTextSizeInPx and
     // mAutoSizeStepGranularityInPx.
     private boolean mHasPresetAutoSizeValues = false;
-
     private TextPaint mTempTextPaint;
-    private Hashtable<String, Method> mMethodByNameCache = new Hashtable<>();
 
     private final TextView mTextView;
     private final Context mContext;
@@ -210,7 +213,9 @@
                             autoSizeMinTextSizeInPx,
                             autoSizeMaxTextSizeInPx,
                             DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX);
-                    setupAutoSizeText();
+                    if (setupAutoSizeText()) {
+                        autoSizeText();
+                    }
                     break;
                 default:
                     throw new IllegalArgumentException(
@@ -266,7 +271,9 @@
             validateAndSetAutoSizeTextTypeUniformConfiguration(autoSizeMinTextSizeInPx,
                     autoSizeMaxTextSizeInPx,
                     autoSizeStepGranularityInPx);
-            setupAutoSizeText();
+            if (setupAutoSizeText()) {
+                autoSizeText();
+            }
         }
     }
 
@@ -320,7 +327,10 @@
             } else {
                 mHasPresetAutoSizeValues = false;
             }
-            setupAutoSizeText();
+
+            if (setupAutoSizeText()) {
+                autoSizeText();
+            }
         }
     }
 
@@ -493,20 +503,19 @@
         mHasPresetAutoSizeValues = false;
     }
 
-    private void setupAutoSizeText() {
+    private boolean setupAutoSizeText() {
         if (supportsAutoSizeText()
                 && mAutoSizeTextType == TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM) {
             // Calculate the sizes set based on minimum size, maximum size and step size if we do
             // not have a predefined set of sizes or if the current sizes array is empty.
             if (!mHasPresetAutoSizeValues || mAutoSizeTextSizesInPx.length == 0) {
                 // Calculate sizes to choose from based on the current auto-size configuration.
-                int autoSizeValuesLength = (int) Math.ceil(
-                        (mAutoSizeMaxTextSizeInPx - mAutoSizeMinTextSizeInPx)
-                                / mAutoSizeStepGranularityInPx);
-                // Also reserve a slot for the max size if it fits.
-                if ((mAutoSizeMaxTextSizeInPx - mAutoSizeMinTextSizeInPx)
-                        % mAutoSizeStepGranularityInPx == 0) {
+                int autoSizeValuesLength = 1;
+                float currentSize = Math.round(mAutoSizeMinTextSizeInPx);
+                while (Math.round(currentSize + mAutoSizeStepGranularityInPx)
+                        <= Math.round(mAutoSizeMaxTextSizeInPx)) {
                     autoSizeValuesLength++;
+                    currentSize += mAutoSizeStepGranularityInPx;
                 }
                 int[] autoSizeTextSizesInPx = new int[autoSizeValuesLength];
                 float sizeToAdd = mAutoSizeMinTextSizeInPx;
@@ -518,17 +527,11 @@
             }
 
             mNeedsAutoSizeText = true;
-
-            // If the build version is at least 26 there is no need to auto-size using this
-            // helper because the job has been delegated to the actual TextView but the
-            // configuration still needs to be done for the case where this function is called
-            // from {@link #loadFromAttributes}, in which case the auto-size configuration
-            // attributes set up in this function will be read by {@link AppCompatTextHelper}
-            // and after passed on to the actual TextView which will take care of auto-sizing.
-            if (!BuildCompat.isAtLeastO()) {
-                autoSizeText();
-            }
+        } else {
+            mNeedsAutoSizeText = false;
         }
+
+        return mNeedsAutoSizeText;
     }
 
     /**
@@ -538,31 +541,41 @@
      */
     @RestrictTo(LIBRARY_GROUP)
     void autoSizeText() {
-        if (mTextView.getMeasuredHeight() <= 0 || mTextView.getMeasuredWidth() <= 0) {
+        if (!isAutoSizeEnabled()) {
             return;
         }
 
-        final int maxWidth = mTextView.getWidth() - mTextView.getTotalPaddingLeft()
-                - mTextView.getTotalPaddingRight();
-        final int maxHeight = Build.VERSION.SDK_INT >= 21
-                ? mTextView.getHeight() - mTextView.getExtendedPaddingBottom()
-                        - mTextView.getExtendedPaddingBottom()
-                : mTextView.getHeight() - mTextView.getCompoundPaddingBottom()
-                        - mTextView.getCompoundPaddingTop();
+        if (mNeedsAutoSizeText) {
+            if (mTextView.getMeasuredHeight() <= 0 || mTextView.getMeasuredWidth() <= 0) {
+                return;
+            }
 
-        if (maxWidth <= 0 || maxHeight <= 0) {
-            return;
-        }
+            final boolean horizontallyScrolling = invokeAndReturnWithDefault(
+                    mTextView, "getHorizontallyScrolling", false);
+            final int availableWidth = horizontallyScrolling
+                    ? VERY_WIDE
+                    : mTextView.getMeasuredWidth() - mTextView.getTotalPaddingLeft()
+                            - mTextView.getTotalPaddingRight();
+            final int availableHeight = mTextView.getHeight() - mTextView.getCompoundPaddingBottom()
+                    - mTextView.getCompoundPaddingTop();
 
-        synchronized (TEMP_RECTF) {
-            TEMP_RECTF.setEmpty();
-            TEMP_RECTF.right = maxWidth;
-            TEMP_RECTF.bottom = maxHeight;
-            final float optimalTextSize = findLargestTextSizeWhichFits(TEMP_RECTF);
-            if (optimalTextSize != mTextView.getTextSize()) {
-                setTextSizeInternal(TypedValue.COMPLEX_UNIT_PX, optimalTextSize);
+            if (availableWidth <= 0 || availableHeight <= 0) {
+                return;
+            }
+
+            synchronized (TEMP_RECTF) {
+                TEMP_RECTF.setEmpty();
+                TEMP_RECTF.right = availableWidth;
+                TEMP_RECTF.bottom = availableHeight;
+                final float optimalTextSize = findLargestTextSizeWhichFits(TEMP_RECTF);
+                if (optimalTextSize != mTextView.getTextSize()) {
+                    setTextSizeInternal(TypedValue.COMPLEX_UNIT_PX, optimalTextSize);
+                }
             }
         }
+        // Always try to auto-size if enabled. Functions that do not want to trigger auto-sizing
+        // after the next layout pass should set this to false.
+        mNeedsAutoSizeText = true;
     }
 
     private void clearAutoSizeConfiguration() {
@@ -588,30 +601,31 @@
         if (size != mTextView.getPaint().getTextSize()) {
             mTextView.getPaint().setTextSize(size);
 
+            boolean isInLayout = false;
+            if (Build.VERSION.SDK_INT >= 18) {
+                isInLayout = mTextView.isInLayout();
+            }
+
             if (mTextView.getLayout() != null) {
                 // Do not auto-size right after setting the text size.
                 mNeedsAutoSizeText = false;
 
+                final String methodName = "nullLayouts";
                 try {
-                    final String methodName = "nullLayouts";
-                    Method method = mMethodByNameCache.get(methodName);
-                    if (method == null) {
-                        method = TextView.class.getDeclaredMethod(methodName);
-                        if (method != null) {
-                            method.setAccessible(true);
-                            // Cache update.
-                            mMethodByNameCache.put(methodName, method);
-                        }
-                    }
-
+                    Method method = getTextViewMethod(methodName);
                     if (method != null) {
                         method.invoke(mTextView);
                     }
                 } catch (Exception ex) {
-                    // Nothing to do.
+                    Log.w(TAG, "Failed to invoke TextView#" + methodName + "() method", ex);
                 }
 
-                mTextView.requestLayout();
+                if (!isInLayout) {
+                    mTextView.requestLayout();
+                } else {
+                    mTextView.forceLayout();
+                }
+
                 mTextView.invalidate();
             }
         }
@@ -648,12 +662,6 @@
     private boolean suggestedSizeFitsInSpace(int suggestedSizeInPx, RectF availableSpace) {
         final CharSequence text = mTextView.getText();
         final int maxLines = Build.VERSION.SDK_INT >= 16 ? mTextView.getMaxLines() : -1;
-        final boolean horizontallyScrolling = invokeAndReturnWithDefault(
-                mTextView, "getHorizontallyScrolling", false);
-        final int availableWidth = horizontallyScrolling
-                ? VERY_WIDE
-                : mTextView.getMeasuredWidth() - mTextView.getTotalPaddingLeft()
-                        - mTextView.getTotalPaddingRight();
         if (mTempTextPaint == null) {
             mTempTextPaint = new TextPaint();
         } else {
@@ -666,11 +674,13 @@
         Layout.Alignment alignment = invokeAndReturnWithDefault(
                 mTextView, "getLayoutAlignment", Layout.Alignment.ALIGN_NORMAL);
         final StaticLayout layout = Build.VERSION.SDK_INT >= 23
-                ? createStaticLayoutForMeasuring(text, alignment, availableWidth, maxLines)
-                : createStaticLayoutForMeasuringPre23(text, alignment, availableWidth);
-
+                ? createStaticLayoutForMeasuring(
+                        text, alignment, Math.round(availableSpace.right), maxLines)
+                : createStaticLayoutForMeasuringPre23(
+                        text, alignment, Math.round(availableSpace.right));
         // Lines overflow.
-        if (maxLines != -1 && layout.getLineCount() > maxLines) {
+        if (maxLines != -1 && (layout.getLineCount() > maxLines
+                || (layout.getLineEnd(layout.getLineCount() - 1)) != text.length())) {
             return false;
         }
 
@@ -739,25 +749,18 @@
                 includePad);
     }
 
-    private <T> T invokeAndReturnWithDefault(@NonNull Object object, @NonNull String methodName,
-            @NonNull T defaultValue) {
+    private <T> T invokeAndReturnWithDefault(@NonNull Object object,
+            @NonNull final String methodName, @NonNull final T defaultValue) {
         T result = null;
         boolean exceptionThrown = false;
 
         try {
             // Cache lookup.
-            Method method = mMethodByNameCache.get(methodName);
-            if (method == null) {
-                method = TextView.class.getDeclaredMethod(methodName);
-                if (method != null) {
-                    method.setAccessible(true);
-                    // Cache update.
-                    mMethodByNameCache.put(methodName, method);
-                }
-            }
+            Method method = getTextViewMethod(methodName);
             result = (T) method.invoke(object);
-        } catch (Exception e) {
+        } catch (Exception ex) {
             exceptionThrown = true;
+            Log.w(TAG, "Failed to invoke TextView#" + methodName + "() method", ex);
         } finally {
             if (result == null && exceptionThrown) {
                 result = defaultValue;
@@ -767,6 +770,26 @@
         return result;
     }
 
+    @Nullable
+    private Method getTextViewMethod(@NonNull final String methodName) {
+        try {
+            Method method = sTextViewMethodByNameCache.get(methodName);
+            if (method == null) {
+                method = TextView.class.getDeclaredMethod(methodName);
+                if (method != null) {
+                    method.setAccessible(true);
+                    // Cache update.
+                    sTextViewMethodByNameCache.put(methodName, method);
+                }
+            }
+
+            return method;
+        } catch (Exception ex) {
+            Log.w(TAG, "Failed to retrieve TextView#" + methodName + "() method", ex);
+            return null;
+        }
+    }
+
     /**
      * @return {@code true} if this widget supports auto-sizing text and has been configured to
      * auto-size.
@@ -779,18 +802,6 @@
                 && mAutoSizeTextType != TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
     }
 
-    /** @hide */
-    @RestrictTo(LIBRARY_GROUP)
-    boolean getNeedsAutoSizeText() {
-        return mNeedsAutoSizeText;
-    }
-
-    /** @hide */
-    @RestrictTo(LIBRARY_GROUP)
-    void setNeedsAutoSizeText(boolean needsAutoSizeText) {
-        mNeedsAutoSizeText = needsAutoSizeText;
-    }
-
     /**
      * @return {@code true} if this TextView supports auto-sizing text to fit within its container.
      */
diff --git a/v7/appcompat/src/android/support/v7/widget/LinearLayoutCompat.java b/v7/appcompat/src/android/support/v7/widget/LinearLayoutCompat.java
index 6abdb75..bb400f1 100644
--- a/v7/appcompat/src/android/support/v7/widget/LinearLayoutCompat.java
+++ b/v7/appcompat/src/android/support/v7/widget/LinearLayoutCompat.java
@@ -1054,8 +1054,7 @@
 
             final int margin = lp.topMargin + lp.bottomMargin;
             final int childHeight = child.getMeasuredHeight() + margin;
-            childState = ViewUtils.combineMeasuredStates(childState,
-                    child.getMeasuredState());
+            childState = View.combineMeasuredStates(childState, child.getMeasuredState());
 
             if (baselineAligned) {
                 final int childBaseline = child.getBaseline();
diff --git a/v7/appcompat/src/android/support/v7/widget/SuggestionsAdapter.java b/v7/appcompat/src/android/support/v7/widget/SuggestionsAdapter.java
index 24dafb3..d6f0099 100644
--- a/v7/appcompat/src/android/support/v7/widget/SuggestionsAdapter.java
+++ b/v7/appcompat/src/android/support/v7/widget/SuggestionsAdapter.java
@@ -503,7 +503,7 @@
      * @return a Drawable, or null if none found
      */
     private Drawable getDrawableFromResourceValue(String drawableId) {
-        if (drawableId == null || drawableId.length() == 0 || "0".equals(drawableId)) {
+        if (drawableId == null || drawableId.isEmpty() || "0".equals(drawableId)) {
             return null;
         }
         try {
diff --git a/v7/appcompat/src/android/support/v7/widget/TintTypedArray.java b/v7/appcompat/src/android/support/v7/widget/TintTypedArray.java
index b920505..2213dd3 100644
--- a/v7/appcompat/src/android/support/v7/widget/TintTypedArray.java
+++ b/v7/appcompat/src/android/support/v7/widget/TintTypedArray.java
@@ -31,7 +31,6 @@
 import android.support.annotation.RestrictTo;
 import android.support.annotation.StyleableRes;
 import android.support.v4.content.res.ResourcesCompat;
-import android.support.v4.os.BuildCompat;
 import android.support.v7.content.res.AppCompatResources;
 import android.util.AttributeSet;
 import android.util.TypedValue;
@@ -110,9 +109,6 @@
      */
     @Nullable
     public Typeface getFont(@StyleableRes int index, int style, @NonNull TextView targetView) {
-        if (BuildCompat.isAtLeastO()) {
-            return mWrapped.getFont(index);
-        }
         final int resourceId = mWrapped.getResourceId(index, 0);
         if (resourceId == 0) {
             return null;
diff --git a/v7/appcompat/src/android/support/v7/widget/TooltipCompat.java b/v7/appcompat/src/android/support/v7/widget/TooltipCompat.java
index f7466bc..470c3b2 100644
--- a/v7/appcompat/src/android/support/v7/widget/TooltipCompat.java
+++ b/v7/appcompat/src/android/support/v7/widget/TooltipCompat.java
@@ -17,9 +17,9 @@
 package android.support.v7.widget;
 
 import android.annotation.TargetApi;
+import android.os.Build;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
-import android.support.v4.os.BuildCompat;
 import android.view.View;
 
 /**
@@ -49,7 +49,7 @@
 
     private static final ViewCompatImpl IMPL;
     static {
-        if (BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT >= 26) {
             IMPL = new Api26ViewCompatImpl();
         } else {
             IMPL = new BaseViewCompatImpl();
diff --git a/v7/appcompat/src/android/support/v7/widget/TooltipCompatHandler.java b/v7/appcompat/src/android/support/v7/widget/TooltipCompatHandler.java
index 4670534..5ce1f8b 100644
--- a/v7/appcompat/src/android/support/v7/widget/TooltipCompatHandler.java
+++ b/v7/appcompat/src/android/support/v7/widget/TooltipCompatHandler.java
@@ -22,7 +22,6 @@
 import android.content.Context;
 import android.support.annotation.RestrictTo;
 import android.support.v4.view.ViewCompat;
-import android.support.v4.view.accessibility.AccessibilityManagerCompat;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.MotionEvent;
@@ -85,11 +84,7 @@
             view.setLongClickable(false);
             view.setOnHoverListener(null);
         } else {
-            if (sActiveHandler != null && sActiveHandler.mAnchor == view) {
-                sActiveHandler.update(tooltipText);
-            } else {
-                new TooltipCompatHandler(view, tooltipText);
-            }
+            new TooltipCompatHandler(view, tooltipText);
         }
     }
 
@@ -116,8 +111,7 @@
         }
         AccessibilityManager manager = (AccessibilityManager)
                 mAnchor.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
-        if (manager.isEnabled()
-                && AccessibilityManagerCompat.isTouchExplorationEnabled(manager)) {
+        if (manager.isEnabled() && manager.isTouchExplorationEnabled()) {
             return false;
         }
         switch (event.getAction()) {
@@ -189,8 +183,4 @@
         mAnchor.removeCallbacks(mShowRunnable);
         mAnchor.removeCallbacks(mHideRunnable);
     }
-
-    private void update(CharSequence tooltipText) {
-        mPopup.updateContent(tooltipText);
-    }
 }
diff --git a/v7/appcompat/src/android/support/v7/widget/TooltipPopup.java b/v7/appcompat/src/android/support/v7/widget/TooltipPopup.java
index 6f78a79..f707c8f 100644
--- a/v7/appcompat/src/android/support/v7/widget/TooltipPopup.java
+++ b/v7/appcompat/src/android/support/v7/widget/TooltipPopup.java
@@ -97,10 +97,6 @@
         return mContentView.getParent() != null;
     }
 
-    void updateContent(CharSequence tooltipText) {
-        mMessageView.setText(tooltipText);
-    }
-
     private void computePosition(View anchorView, int anchorX, int anchorY, boolean fromTouch,
             WindowManager.LayoutParams outParams) {
         final int tooltipPreciseAnchorThreshold = mContext.getResources().getDimensionPixelOffset(
diff --git a/v7/appcompat/src/android/support/v7/widget/ViewUtils.java b/v7/appcompat/src/android/support/v7/widget/ViewUtils.java
index 58acb03..0f910c3 100644
--- a/v7/appcompat/src/android/support/v7/widget/ViewUtils.java
+++ b/v7/appcompat/src/android/support/v7/widget/ViewUtils.java
@@ -58,21 +58,6 @@
     }
 
     /**
-     * Merge two states as returned by {@link View#getMeasuredState()} ()}.
-     * @param curState The current state as returned from a view or the result
-     * of combining multiple views.
-     * @param newState The new view state to combine.
-     * @return Returns a new integer reflecting the combination of the two
-     * states.
-     *
-     * @deprecated Use {@link View#combineMeasuredStates(int, int)} directly.
-     */
-    @Deprecated
-    public static int combineMeasuredStates(int curState, int newState) {
-        return View.combineMeasuredStates(curState, newState);
-    }
-
-    /**
      * Allow calling the hidden method {@code computeFitSystemWindows(Rect, Rect)} through
      * reflection on {@code view}.
      */
diff --git a/v7/appcompat/tests/AndroidManifest.xml b/v7/appcompat/tests/AndroidManifest.xml
index 647d153..abad7d6 100644
--- a/v7/appcompat/tests/AndroidManifest.xml
+++ b/v7/appcompat/tests/AndroidManifest.xml
@@ -15,20 +15,14 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.v7.appcompat.test">
-
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application
-        android:theme="@style/Theme.AppCompat"
-        android:supportsRtl="true">
+        android:supportsRtl="true"
+        android:theme="@style/Theme.AppCompat">
         <activity
-                android:name="android.support.v7.app.AppCompatActivity"/>
+            android:name="android.support.v7.app.AppCompatActivity"/>
 
         <activity android:name="android.support.v7.app.AppCompatMenuItemShortcutsTestActivity"/>
 
@@ -37,82 +31,87 @@
             android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:name="android.support.v7.app.WindowDecorAppCompatActivity"/>
+            android:name="android.support.v7.app.WindowDecorAppCompatActivity"/>
         <activity
-                android:name="android.support.v7.app.ToolbarAppCompatActivity"
-                android:theme="@style/Theme.AppCompat.NoActionBar"/>
+            android:name="android.support.v7.app.ToolbarAppCompatActivity"
+            android:theme="@style/Theme.AppCompat.NoActionBar"/>
 
         <activity
-                android:name="android.support.v7.app.DrawerLayoutActivity"
-                android:label="@string/drawer_layout_activity"
-                android:theme="@style/Theme.SampleDrawerLayout" />
+            android:name="android.support.v7.app.DrawerLayoutActivity"
+            android:label="@string/drawer_layout_activity"
+            android:theme="@style/Theme.SampleDrawerLayout"/>
 
         <activity
-                android:name="android.support.v7.app.DrawerLayoutDoubleActivity"
-                android:label="@string/drawer_layout_activity"
-                android:theme="@style/Theme.SampleDrawerLayout" />
+            android:name="android.support.v7.app.DrawerLayoutDoubleActivity"
+            android:label="@string/drawer_layout_activity"
+            android:theme="@style/Theme.SampleDrawerLayout"/>
 
         <activity
-                android:name="android.support.v7.app.DrawerDynamicLayoutActivity"
-                android:label="@string/drawer_layout_activity"
-                android:theme="@style/Theme.SampleDrawerLayout" />
+            android:name="android.support.v7.app.DrawerDynamicLayoutActivity"
+            android:label="@string/drawer_layout_activity"
+            android:theme="@style/Theme.SampleDrawerLayout"/>
 
         <activity
-                android:name="android.support.v7.app.AlertDialogTestActivity"
-                android:label="@string/alert_dialog_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.app.AlertDialogTestActivity"
+            android:label="@string/alert_dialog_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
-        <activity android:name="android.support.v7.view.SupportMenuInflaterTestActivity" />
+        <activity android:name="android.support.v7.view.SupportMenuInflaterTestActivity"/>
 
         <activity
-                android:name="android.support.v7.widget.PopupTestActivity"
-                android:label="@string/popup_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.PopupTestActivity"
+            android:label="@string/popup_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatSpinnerActivity"
-                android:label="@string/app_compat_spinner_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatSpinnerActivity"
+            android:label="@string/app_compat_spinner_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatTextViewActivity"
-                android:label="@string/app_compat_text_view_activity"
-                android:theme="@style/Theme.TextColors" />
+            android:name="android.support.v7.widget.AppCompatTextViewActivity"
+            android:label="@string/app_compat_text_view_activity"
+            android:theme="@style/Theme.TextColors"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatTextViewAutoSizeActivity"
-                android:label="@string/app_compat_text_view_auto_size_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatTextViewAutoSizeActivity"
+            android:label="@string/app_compat_text_view_auto_size_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatImageButtonActivity"
-                android:label="@string/app_compat_image_button_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatButtonAutoSizeActivity"
+            android:label="@string/app_compat_button_auto_size_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatImageViewActivity"
-                android:label="@string/app_compat_image_view_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatImageButtonActivity"
+            android:label="@string/app_compat_image_button_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.AppCompatButtonActivity"
-                android:label="@string/app_compat_button_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatImageViewActivity"
+            android:label="@string/app_compat_image_view_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.widget.SearchViewTestActivity"
-                android:label="@string/search_view_activity"
-                android:theme="@style/Theme.AppCompat.Light" />
+            android:name="android.support.v7.widget.AppCompatButtonActivity"
+            android:label="@string/app_compat_button_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.app.LayoutInflaterFactoryTestActivity"/>
+            android:name="android.support.v7.widget.SearchViewTestActivity"
+            android:label="@string/search_view_activity"
+            android:theme="@style/Theme.AppCompat.Light"/>
 
         <activity
-                android:name="android.support.v7.app.FragmentContentIdActivity"/>
+            android:name="android.support.v7.app.LayoutInflaterFactoryTestActivity"/>
 
         <activity
-                android:name="android.support.v7.app.NightModeActivity"
-                android:theme="@style/Theme.AppCompat.DayNight"/>
+            android:name="android.support.v7.app.FragmentContentIdActivity"/>
+
+        <activity
+            android:name="android.support.v7.app.NightModeActivity"
+            android:theme="@style/Theme.AppCompat.DayNight"/>
 
         <activity
             android:name="android.support.v7.app.AppCompatVectorDrawableIntegrationActivity"/>
diff --git a/v7/appcompat/tests/res/font/samplexmldownloadedfont.xml b/v7/appcompat/tests/res/font/samplexmldownloadedfont.xml
index 59a0a05..659d196 100644
--- a/v7/appcompat/tests/res/font/samplexmldownloadedfont.xml
+++ b/v7/appcompat/tests/res/font/samplexmldownloadedfont.xml
@@ -1,10 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto"
-         android:fontProviderAuthority="com.example.test.fontprovider.authority"
-         android:fontProviderPackage="com.example.test.fontprovider.package"
-         android:fontProviderQuery="MyRequestedFont"
-         app:fontProviderAuthority="com.example.test.fontprovider.authority"
-         app:fontProviderPackage="com.example.test.fontprovider.package"
-         app:fontProviderQuery="MyRequestedFont">
-</font-family>
\ No newline at end of file
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
+    app:fontProviderAuthority="com.example.test.fontprovider.authority"
+    app:fontProviderPackage="com.example.test.fontprovider.package"
+    app:fontProviderQuery="MyRequestedFont">
+</font-family>
diff --git a/v7/appcompat/tests/res/font/samplexmlfont.xml b/v7/appcompat/tests/res/font/samplexmlfont.xml
index 3dba563..e225025 100644
--- a/v7/appcompat/tests/res/font/samplexmlfont.xml
+++ b/v7/appcompat/tests/res/font/samplexmlfont.xml
@@ -1,12 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
-<font-family xmlns:android="http://schemas.android.com/apk/res/android"
-             xmlns:app="http://schemas.android.com/apk/res-auto">
-    <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/samplefont"
-          app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
-    <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/samplefont2"
-          app:fontStyle="italic" app:fontWeight="400" app:font="@font/samplefont2" />
-    <font android:fontStyle="normal" android:fontWeight="800" android:font="@font/samplefont3"
-          app:fontStyle="normal" app:fontWeight="800" app:font="@font/samplefont3"/>
-    <font android:fontStyle="italic" android:fontWeight="800" android:font="@font/samplefont4"
-          app:fontStyle="italic" app:fontWeight="800" app:font="@font/samplefont4"/>
-</font-family>
\ No newline at end of file
+<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
+    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/samplefont" />
+    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/samplefont2" />
+    <font app:fontStyle="normal" app:fontWeight="800" app:font="@font/samplefont3"/>
+    <font app:fontStyle="italic" app:fontWeight="800" app:font="@font/samplefont4"/>
+</font-family>
diff --git a/v7/appcompat/tests/res/layout/appcompat_button_autosize_activity.xml b/v7/appcompat/tests/res/layout/appcompat_button_autosize_activity.xml
new file mode 100644
index 0000000..407154a
--- /dev/null
+++ b/v7/appcompat/tests/res/layout/appcompat_button_autosize_activity.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/container"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical">
+
+    <android.support.v7.widget.AppCompatButton
+        android:id="@+id/view_autosize_uniform"
+        android:layout_width="100dp"
+        android:layout_height="200dp"
+        android:text="@string/sample_text1"
+        app:autoSizeTextType="uniform"
+        app:autoSizeMinTextSize="2px"
+        app:autoSizeMaxTextSize="50dp"
+        app:autoSizeStepGranularity="1px" />
+
+    <android.support.v7.widget.AppCompatButton
+        android:id="@+id/view_autosize_uniform_predef_sizes"
+        android:layout_width="100dp"
+        android:layout_height="200dp"
+        android:text="@string/sample_text1"
+        app:autoSizeTextType="uniform"
+        app:autoSizePresetSizes="@array/auto_size_predefined_sizes" />
+
+    <android.support.v7.widget.AppCompatButton
+        android:id="@+id/view_autosize_uniform_predef_sizes_redundant_values"
+        android:layout_width="100dp"
+        android:layout_height="200dp"
+        android:text="@string/sample_text1"
+        app:autoSizeTextType="uniform"
+        app:autoSizePresetSizes="@array/auto_size_predefined_sizes_redundant_values" />
+
+    <android.support.v7.widget.AppCompatButton
+        android:id="@+id/view_text"
+        android:layout_width="100dp"
+        android:layout_height="200dp"
+        android:text="@string/sample_text1" />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/v7/appcompat/tests/res/layout/appcompat_textview_autosize_activity.xml b/v7/appcompat/tests/res/layout/appcompat_textview_autosize_activity.xml
index b9df4cc..f9aafcc 100644
--- a/v7/appcompat/tests/res/layout/appcompat_textview_autosize_activity.xml
+++ b/v7/appcompat/tests/res/layout/appcompat_textview_autosize_activity.xml
@@ -16,13 +16,13 @@
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
-    android:id="@+id/layout_textviewtest"
+    android:id="@+id/container"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
-    android:orientation="horizontal">
+    android:orientation="vertical">
 
     <android.support.v7.widget.AppCompatTextView
-        android:id="@+id/textview_autosize_uniform"
+        android:id="@+id/view_autosize_uniform"
         android:layout_width="100dp"
         android:layout_height="200dp"
         android:text="@string/sample_text1"
@@ -32,7 +32,7 @@
         app:autoSizeStepGranularity="1px" />
 
     <android.support.v7.widget.AppCompatTextView
-        android:id="@+id/textview_autosize_uniform_predef_sizes"
+        android:id="@+id/view_autosize_uniform_predef_sizes"
         android:layout_width="100dp"
         android:layout_height="200dp"
         android:text="@string/sample_text1"
@@ -40,7 +40,7 @@
         app:autoSizePresetSizes="@array/auto_size_predefined_sizes" />
 
     <android.support.v7.widget.AppCompatTextView
-        android:id="@+id/textview_autosize_uniform_predef_sizes_redundant_values"
+        android:id="@+id/view_autosize_uniform_predef_sizes_redundant_values"
         android:layout_width="100dp"
         android:layout_height="200dp"
         android:text="@string/sample_text1"
@@ -48,10 +48,10 @@
         app:autoSizePresetSizes="@array/auto_size_predefined_sizes_redundant_values" />
 
     <android.support.v7.widget.AppCompatTextView
-        android:id="@+id/textview_text"
-        android:text="@string/sample_text1"
+        android:id="@+id/view_text"
         android:layout_width="100dp"
-        android:layout_height="200dp"/>
+        android:layout_height="200dp"
+        android:text="@string/sample_text1" />
 
     <android.support.v7.widget.AppCompatEditText
         android:id="@+id/edittext_autosize_uniform"
diff --git a/v7/appcompat/tests/res/values/strings.xml b/v7/appcompat/tests/res/values/strings.xml
index 8a1746b..90be8b3 100644
--- a/v7/appcompat/tests/res/values/strings.xml
+++ b/v7/appcompat/tests/res/values/strings.xml
@@ -56,6 +56,7 @@
     <string name="app_compat_spinner_activity">AppCompat spinner</string>
     <string name="app_compat_text_view_activity">AppCompat text view</string>
     <string name="app_compat_text_view_auto_size_activity">AppCompat text view auto-size</string>
+    <string name="app_compat_button_auto_size_activity">AppCompat button auto-size</string>
     <string name="sample_text1">Sample text 1</string>
     <string name="sample_text2">Sample text 2</string>
     <string name="app_compat_image_button_activity">AppCompat image button</string>
@@ -95,4 +96,5 @@
     <string name="menu6">menu six</string>
 
     <string name="font_sans_serif">sans-serif</string>
+    <string name="font_serif">serif</string>
 </resources>
diff --git a/v7/appcompat/tests/res/values/styles.xml b/v7/appcompat/tests/res/values/styles.xml
index 81f8493..bdbedb8 100644
--- a/v7/appcompat/tests/res/values/styles.xml
+++ b/v7/appcompat/tests/res/values/styles.xml
@@ -70,4 +70,12 @@
         <item name="fontFamily">@font/samplexmlfont</item>
         <item name="android:textStyle">italic</item>
     </style>
+
+    <style name="TextView_SansSerif">
+        <item name="fontFamily">@string/font_sans_serif</item>
+    </style>
+
+    <style name="TextView_Serif">
+        <item name="fontFamily">@string/font_serif</item>
+    </style>
 </resources>
diff --git a/v7/appcompat/tests/src/android/support/v7/app/AlertDialogCursorTest.java b/v7/appcompat/tests/src/android/support/v7/app/AlertDialogCursorTest.java
index 8afd231..690cc26 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/AlertDialogCursorTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/AlertDialogCursorTest.java
@@ -45,6 +45,8 @@
 import android.database.sqlite.SQLiteDatabase;
 import android.support.test.espresso.DataInteraction;
 import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.TestUtilsMatchers;
 import android.view.View;
@@ -56,13 +58,17 @@
 import org.hamcrest.Matcher;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.io.File;
 
 @MediumTest
-public class AlertDialogCursorTest
-        extends BaseInstrumentationTestCase<AlertDialogTestActivity> {
+@RunWith(AndroidJUnit4.class)
+public class AlertDialogCursorTest {
+    @Rule
+    public final ActivityTestRule<AlertDialogTestActivity> mActivityTestRule;
 
     private Button mButton;
 
@@ -82,7 +88,7 @@
     private AlertDialog mAlertDialog;
 
     public AlertDialogCursorTest() {
-        super(AlertDialogTestActivity.class);
+        mActivityTestRule = new ActivityTestRule<>(AlertDialogTestActivity.class);
     }
 
     @Before
diff --git a/v7/appcompat/tests/src/android/support/v7/app/AlertDialogTest.java b/v7/appcompat/tests/src/android/support/v7/app/AlertDialogTest.java
index 1d4b244..a990a57 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/AlertDialogTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/AlertDialogTest.java
@@ -40,8 +40,8 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
@@ -60,6 +60,7 @@
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.TestUtilsMatchers;
 import android.text.TextUtils;
@@ -76,6 +77,7 @@
 import org.hamcrest.Matcher;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 
@@ -95,13 +97,16 @@
  *     is rendered by a single <code>CheckedTextView</code>.</li>
  * </ul>
  */
-public class AlertDialogTest extends BaseInstrumentationTestCase<AlertDialogTestActivity> {
+public class AlertDialogTest {
+    @Rule
+    public final ActivityTestRule<AlertDialogTestActivity> mActivityTestRule;
+
     private Button mButton;
 
     private AlertDialog mAlertDialog;
 
     public AlertDialogTest() {
-        super(AlertDialogTestActivity.class);
+        mActivityTestRule = new ActivityTestRule<>(AlertDialogTestActivity.class);
     }
 
     @Before
@@ -1009,7 +1014,7 @@
         // Verify that a Message with expected 'what' field has been posted on our mock handler
         ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
         verify(messageHandler, times(1)).sendMessageDelayed(
-                messageArgumentCaptor.capture(), anyInt());
+                messageArgumentCaptor.capture(), anyLong());
         assertEquals("Button clicked", whichButtonClicked, messageArgumentCaptor.getValue().what);
         // Verify that the dialog is no longer showing
         assertFalse("Dialog is not showing", mAlertDialog.isShowing());
diff --git a/v7/appcompat/tests/src/android/support/v7/app/AppCompatMenuItemShortcutsTest.java b/v7/appcompat/tests/src/android/support/v7/app/AppCompatMenuItemShortcutsTest.java
index bf55d69..b0a7fb7 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/AppCompatMenuItemShortcutsTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/AppCompatMenuItemShortcutsTest.java
@@ -19,15 +19,13 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import android.os.Build;
 import android.os.SystemClock;
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
-import android.support.v4.os.BuildCompat;
 import android.support.v7.appcompat.test.R;
 import android.view.KeyEvent;
-import android.view.Menu;
-import android.view.MenuInflater;
 
 import org.junit.Before;
 import org.junit.Rule;
@@ -42,8 +40,6 @@
 public class AppCompatMenuItemShortcutsTest {
 
     private AppCompatMenuItemShortcutsTestActivity mActivity;
-    private MenuInflater mMenuInflater;
-    private Menu mMenu;
 
     @Rule
     public ActivityTestRule<AppCompatMenuItemShortcutsTestActivity> mActivityTestRule =
@@ -57,7 +53,7 @@
     @Test
     public void testPerformShortcut() {
         // The support library is only needed for API 25 or lower.
-        if (!BuildCompat.isAtLeastO()) {
+        if (Build.VERSION.SDK_INT < 26) {
             final long downTime = SystemClock.uptimeMillis();
             int keyCodeToSend, metaState;
             KeyEvent keyEventToSend;
diff --git a/v7/appcompat/tests/src/android/support/v7/app/AppCompatVectorDrawableIntegrationTest.java b/v7/appcompat/tests/src/android/support/v7/app/AppCompatVectorDrawableIntegrationTest.java
index 905521d..84816ae 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/AppCompatVectorDrawableIntegrationTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/AppCompatVectorDrawableIntegrationTest.java
@@ -24,17 +24,23 @@
 import android.graphics.drawable.Drawable;
 import android.os.Build;
 import android.support.test.annotation.UiThreadTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.View;
 import android.widget.ImageView;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
-public class AppCompatVectorDrawableIntegrationTest
-        extends BaseInstrumentationTestCase<AppCompatVectorDrawableIntegrationActivity> {
+@RunWith(AndroidJUnit4.class)
+public class AppCompatVectorDrawableIntegrationTest {
+    @Rule
+    public final ActivityTestRule<AppCompatVectorDrawableIntegrationActivity> mActivityTestRule;
 
     private Bitmap mBitmap;
     private Canvas mCanvas;
@@ -46,7 +52,8 @@
     private static final int CENTER_Y = HEIGHT / 2;
 
     public AppCompatVectorDrawableIntegrationTest() {
-        super(AppCompatVectorDrawableIntegrationActivity.class);
+        mActivityTestRule =
+                new ActivityTestRule<>(AppCompatVectorDrawableIntegrationActivity.class);
     }
 
     @Before
diff --git a/v7/appcompat/tests/src/android/support/v7/app/BaseBasicsTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/BaseBasicsTestCase.java
index 6112d34..c634097 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/BaseBasicsTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/BaseBasicsTestCase.java
@@ -42,6 +42,8 @@
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SdkSuppress;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.custom.FitWindowsContentLayout;
 import android.support.v7.testutils.BaseTestActivity;
@@ -50,24 +52,31 @@
 import android.view.View;
 import android.view.WindowInsets;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
-public abstract class BaseBasicsTestCase<A extends BaseTestActivity>
-        extends BaseInstrumentationTestCase<A> {
+@RunWith(AndroidJUnit4.class)
+public abstract class BaseBasicsTestCase<A extends BaseTestActivity> {
+    @Rule
+    public final ActivityTestRule<A> mActivityTestRule;
+
 
     protected BaseBasicsTestCase(Class<A> activityClass) {
-        super(activityClass);
+        mActivityTestRule = new ActivityTestRule<>(activityClass);
     }
 
     @Test
     public void testActionBarExists() {
-        assertNotNull("ActionBar is not null", getActivity().getSupportActionBar());
+        assertNotNull("ActionBar is not null",
+                mActivityTestRule.getActivity().getSupportActionBar());
     }
 
     @Test
     public void testDefaultActionBarTitle() {
-        assertEquals(getActivity().getTitle(), getActivity().getSupportActionBar().getTitle());
+        assertEquals(mActivityTestRule.getActivity().getTitle(),
+                mActivityTestRule.getActivity().getSupportActionBar().getTitle());
     }
 
     @UiThreadTest
@@ -84,10 +93,10 @@
     @RequiresApi(16)
     public void testFitSystemWindowsReachesContent() {
         final FitWindowsContentLayout content =
-                (FitWindowsContentLayout) getActivity().findViewById(R.id.test_content);
+                mActivityTestRule.getActivity().findViewById(R.id.test_content);
         assertNotNull(content);
 
-        if (!canShowSystemUi(getActivity())) {
+        if (!canShowSystemUi(mActivityTestRule.getActivity())) {
             // Device cannot show system UI so setSystemUiVisibility will do nothing.
             return;
         }
@@ -103,10 +112,10 @@
     @SdkSuppress(minSdkVersion = 21)
     @RequiresApi(21)
     public void testOnApplyWindowInsetsReachesContent() {
-        final View content = getActivity().findViewById(R.id.test_content);
+        final View content = mActivityTestRule.getActivity().findViewById(R.id.test_content);
         assertNotNull(content);
 
-        if (!canShowSystemUi(getActivity())) {
+        if (!canShowSystemUi(mActivityTestRule.getActivity())) {
             // Device cannot show system UI so setSystemUiVisibility will do nothing.
             return;
         }
@@ -128,7 +137,7 @@
     @Test
     @UiThreadTest
     public void testSupportActionModeCallbacks() {
-        final A activity = getActivity();
+        final A activity = mActivityTestRule.getActivity();
 
         // Create a mock action mode callback which returns true from onCreateActionMode
         final ActionMode.Callback callback = mock(ActionMode.Callback.class);
@@ -152,7 +161,7 @@
     @Test
     @UiThreadTest
     public void testSupportActionModeCallbacksInvalidate() {
-        final A activity = getActivity();
+        final A activity = mActivityTestRule.getActivity();
 
         // Create a mock action mode callback which returns true from onCreateActionMode
         final ActionMode.Callback callback = mock(ActionMode.Callback.class);
@@ -176,7 +185,7 @@
     @Test
     @UiThreadTest
     public void testSupportActionModeCallbacksWithFalseOnCreate() {
-        final A activity = getActivity();
+        final A activity = mActivityTestRule.getActivity();
 
         // Create a mock action mode callback which returns true from onCreateActionMode
         final ActionMode.Callback callback = mock(ActionMode.Callback.class);
@@ -206,7 +215,7 @@
     }
 
     protected void testSupportActionModeAppCompatCallbacks(final boolean fromWindow) {
-        final A activity = getActivity();
+        final A activity = mActivityTestRule.getActivity();
 
         // Create a mock action mode callback which returns true from onCreateActionMode
         final ActionMode.Callback amCallback = mock(ActionMode.Callback.class);
diff --git a/v7/appcompat/tests/src/android/support/v7/app/BaseInstrumentationTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/BaseInstrumentationTestCase.java
deleted file mode 100644
index c98df27..0000000
--- a/v7/appcompat/tests/src/android/support/v7/app/BaseInstrumentationTestCase.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2015 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 android.support.v7.app;
-
-import android.app.Activity;
-import android.app.Instrumentation;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.rule.ActivityTestRule;
-import android.support.test.runner.AndroidJUnit4;
-
-import org.junit.Rule;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-public abstract class BaseInstrumentationTestCase<A extends Activity> {
-
-    @Rule
-    public final ActivityTestRule<A> mActivityTestRule;
-
-    protected BaseInstrumentationTestCase(Class<A> activityClass) {
-        mActivityTestRule = new ActivityTestRule<A>(activityClass);
-    }
-
-    @Deprecated
-    public A getActivity() {
-        return mActivityTestRule.getActivity();
-    }
-
-    @Deprecated
-    public Instrumentation getInstrumentation() {
-        return InstrumentationRegistry.getInstrumentation();
-    }
-}
diff --git a/v7/appcompat/tests/src/android/support/v7/app/BaseKeyEventsTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/BaseKeyEventsTestCase.java
index 5e10e97..135f65d 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/BaseKeyEventsTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/BaseKeyEventsTestCase.java
@@ -30,8 +30,12 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
+import android.app.Instrumentation;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.view.MenuItemCompat;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.BaseTestActivity;
@@ -41,15 +45,29 @@
 import android.view.MenuItem;
 
 import org.hamcrest.Matchers;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
-public abstract class BaseKeyEventsTestCase<A extends BaseTestActivity>
-        extends BaseInstrumentationTestCase<A> {
+@RunWith(AndroidJUnit4.class)
+public abstract class BaseKeyEventsTestCase<A extends BaseTestActivity> {
+    @Rule
+    public final ActivityTestRule<A> mActivityTestRule;
+
+    private Instrumentation mInstrumentation;
+    private A mActivity;
 
     protected BaseKeyEventsTestCase(Class<A> activityClass) {
-        super(activityClass);
+        mActivityTestRule = new ActivityTestRule<>(activityClass);
+    }
+
+    @Before
+    public void setup() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        mActivity = mActivityTestRule.getActivity();
     }
 
     @Test
@@ -57,10 +75,10 @@
     public void testBackDismissesActionMode() {
         final AtomicBoolean destroyed = new AtomicBoolean();
 
-        getActivity().runOnUiThread(new Runnable() {
+        mActivity.runOnUiThread(new Runnable() {
             @Override
             public void run() {
-                getActivity().startSupportActionMode(new ActionMode.Callback() {
+                mActivity.startSupportActionMode(new ActionMode.Callback() {
                     @Override
                     public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                         mode.getMenuInflater().inflate(R.menu.sample_actions, menu);
@@ -85,11 +103,11 @@
             }
         });
 
-        getInstrumentation().waitForIdleSync();
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        mInstrumentation.waitForIdleSync();
 
-        assertFalse("Activity was not finished", getActivity().isFinishing());
+        assertFalse("Activity was not finished", mActivity.isFinishing());
         assertTrue("ActionMode was destroyed", destroyed.get());
     }
 
@@ -103,14 +121,14 @@
                 .check(matches(isDisplayed()));
 
         // Let things settle
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.waitForIdleSync();
         // Now send a back event to collapse the custom action view
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        mInstrumentation.waitForIdleSync();
 
         // Check that the Activity is still running
-        assertFalse(getActivity().isFinishing());
-        assertFalse(getActivity().isDestroyed());
+        assertFalse(mActivity.isFinishing());
+        assertFalse(mActivity.isDestroyed());
         // ... and that our action view is not attached
         onView(withClassName(Matchers.is(CustomCollapsibleView.class.getName())))
                 .check(doesNotExist());
@@ -119,24 +137,24 @@
     @Test
     @SmallTest
     public void testMenuPressInvokesPanelCallbacks() throws InterruptedException {
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
-        assertTrue("onMenuOpened called", getActivity().wasOnMenuOpenedCalled());
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        mInstrumentation.waitForIdleSync();
+        assertTrue("onMenuOpened called", mActivity.wasOnMenuOpenedCalled());
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
-        assertTrue("onPanelClosed called", getActivity().wasOnPanelClosedCalled());
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        mInstrumentation.waitForIdleSync();
+        assertTrue("onPanelClosed called", mActivity.wasOnPanelClosedCalled());
     }
 
     @Test
     @SmallTest
     public void testBackPressWithMenuInvokesOnPanelClosed() throws InterruptedException {
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        mInstrumentation.waitForIdleSync();
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
-        getInstrumentation().waitForIdleSync();
-        assertTrue("onPanelClosed called", getActivity().wasOnPanelClosedCalled());
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        mInstrumentation.waitForIdleSync();
+        assertTrue("onPanelClosed called", mActivity.wasOnPanelClosedCalled());
     }
 
     @Test
@@ -144,25 +162,25 @@
     public void testBackPressWithEmptyMenuFinishesActivity() throws InterruptedException {
         repopulateWithEmptyMenu();
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        mInstrumentation.waitForIdleSync();
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
-        assertTrue(getActivity().isFinishing());
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        assertTrue(mActivity.isFinishing());
     }
 
     @Test
     @SmallTest
     public void testDelKeyEventReachesActivity() {
         // First send the event
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
+        mInstrumentation.waitForIdleSync();
 
-        KeyEvent downEvent = getActivity().getInvokedKeyDownEvent();
+        KeyEvent downEvent = mActivity.getInvokedKeyDownEvent();
         assertNotNull("onKeyDown called", downEvent);
         assertEquals("onKeyDown event matches", KeyEvent.KEYCODE_DEL, downEvent.getKeyCode());
 
-        KeyEvent upEvent = getActivity().getInvokedKeyUpEvent();
+        KeyEvent upEvent = mActivity.getInvokedKeyUpEvent();
         assertNotNull("onKeyUp called", upEvent);
         assertEquals("onKeyUp event matches", KeyEvent.KEYCODE_DEL, upEvent.getKeyCode());
     }
@@ -170,14 +188,14 @@
     @Test
     @SmallTest
     public void testMenuKeyEventReachesActivity() throws InterruptedException {
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        mInstrumentation.waitForIdleSync();
 
-        KeyEvent downEvent = getActivity().getInvokedKeyDownEvent();
+        KeyEvent downEvent = mActivity.getInvokedKeyDownEvent();
         assertNotNull("onKeyDown called", downEvent);
         assertEquals("onKeyDown event matches", KeyEvent.KEYCODE_MENU, downEvent.getKeyCode());
 
-        KeyEvent upEvent = getActivity().getInvokedKeyUpEvent();
+        KeyEvent upEvent = mActivity.getInvokedKeyUpEvent();
         assertNotNull("onKeyUp called", upEvent);
         assertEquals("onKeyDown event matches", KeyEvent.KEYCODE_MENU, upEvent.getKeyCode());
     }
@@ -193,7 +211,7 @@
                 .check(matches(isDisplayed()))
                 .check(matches(withContentDescription((String) null)));
 
-        Menu menu = getActivity().getMenu();
+        Menu menu = mActivity.getMenu();
         final MenuItem alphaItem = menu.findItem(R.id.action_alpha_shortcut);
         assertNotNull(alphaItem);
 
@@ -201,9 +219,9 @@
             @Override
             public void run() {
                 MenuItemCompat.setContentDescription(alphaItem,
-                        getActivity().getString(R.string.alpha_menu_description));
+                        mActivity.getString(R.string.alpha_menu_description));
                 MenuItemCompat.setTooltipText(alphaItem,
-                        getActivity().getString(R.string.alpha_menu_tooltip));
+                        mActivity.getString(R.string.alpha_menu_tooltip));
             }
         });
 
@@ -214,9 +232,9 @@
 
     private void repopulateWithEmptyMenu() throws InterruptedException {
         int count = 0;
-        getActivity().setShouldPopulateOptionsMenu(false);
+        mActivity.setShouldPopulateOptionsMenu(false);
         while (count++ < 10) {
-            Menu menu = getActivity().getMenu();
+            Menu menu = mActivity.getMenu();
             if (menu == null || menu.size() != 0) {
                 Thread.sleep(100);
             } else {
diff --git a/v7/appcompat/tests/src/android/support/v7/app/BaseKeyboardShortcutsTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/BaseKeyboardShortcutsTestCase.java
index cb21347..88216d1 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/BaseKeyboardShortcutsTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/BaseKeyboardShortcutsTestCase.java
@@ -19,21 +19,29 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
+import android.app.Instrumentation;
 import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.BaseTestActivity;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.MenuItem;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public abstract class BaseKeyboardShortcutsTestCase<A extends BaseTestActivity>
-        extends BaseInstrumentationTestCase<A> {
+@RunWith(AndroidJUnit4.class)
+public abstract class BaseKeyboardShortcutsTestCase<A extends BaseTestActivity> {
+    @Rule
+    public final ActivityTestRule<A> mActivityTestRule;
 
     protected BaseKeyboardShortcutsTestCase(Class<A> activityClass) {
-        super(activityClass);
+        mActivityTestRule = new ActivityTestRule<>(activityClass);
     }
 
     @Test
@@ -45,18 +53,19 @@
     }
 
     private void testKeyboardShortcut(final int keyCode, final int meta, final int expectedId) {
+        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
         final long downTime = SystemClock.uptimeMillis();
         final KeyEvent downEvent = new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN,
                 keyCode, 0, meta, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
-        getInstrumentation().sendKeySync(downEvent);
-        getInstrumentation().waitForIdleSync();
+        instrumentation.sendKeySync(downEvent);
+        instrumentation.waitForIdleSync();
 
         final KeyEvent upEvent = new KeyEvent(downTime, downTime + 500, KeyEvent.ACTION_UP,
                 keyCode, 0, meta, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
-        getInstrumentation().sendKeySync(upEvent);
-        getInstrumentation().waitForIdleSync();
+        instrumentation.sendKeySync(upEvent);
+        instrumentation.waitForIdleSync();
 
-        MenuItem selectedItem = getActivity().getOptionsItemSelected();
+        MenuItem selectedItem = mActivityTestRule.getActivity().getOptionsItemSelected();
         assertNotNull("Options item selected", selectedItem);
         assertEquals("Correct options item selected", selectedItem.getItemId(), expectedId);
     }
diff --git a/v7/appcompat/tests/src/android/support/v7/app/DialogTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/DialogTestCase.java
index 8230cbc..ce9c157 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/DialogTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/DialogTestCase.java
@@ -21,25 +21,30 @@
 
 import android.app.Dialog;
 import android.os.Bundle;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @MediumTest
-public class DialogTestCase extends BaseInstrumentationTestCase<WindowDecorAppCompatActivity> {
-
-    public DialogTestCase() {
-        super(WindowDecorAppCompatActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class DialogTestCase {
+    @Rule
+    public final ActivityTestRule<WindowDecorAppCompatActivity> mActivityTestRule =
+            new ActivityTestRule<>(WindowDecorAppCompatActivity.class);
 
     @Test
     public void testDialogFragmentShows() {
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         TestDialogFragment fragment = new TestDialogFragment();
-        fragment.show(getActivity().getSupportFragmentManager(), null);
+        fragment.show(mActivityTestRule.getActivity().getSupportFragmentManager(), null);
 
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         assertNotNull("Dialog was null", fragment.getDialog());
         assertTrue("Dialog was not being shown", fragment.getDialog().isShowing());
diff --git a/v7/appcompat/tests/src/android/support/v7/app/DrawerDynamicLayoutTest.java b/v7/appcompat/tests/src/android/support/v7/app/DrawerDynamicLayoutTest.java
index 198c63a..54597c0 100755
--- a/v7/appcompat/tests/src/android/support/v7/app/DrawerDynamicLayoutTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/DrawerDynamicLayoutTest.java
@@ -28,6 +28,8 @@
 import android.support.test.espresso.UiController;
 import android.support.test.espresso.ViewAction;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.widget.DrawerLayout;
 import android.support.v7.appcompat.test.R;
 import android.view.View;
@@ -37,18 +39,20 @@
 import org.hamcrest.Matcher;
 import org.hamcrest.TypeSafeMatcher;
 import org.junit.After;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test cases to verify that <code>DrawerLayout</code> only supports configurations
  * with at most one drawer child along each vertical (left / right) edge.
  */
 @SmallTest
-public class DrawerDynamicLayoutTest
-        extends BaseInstrumentationTestCase<DrawerDynamicLayoutActivity> {
-    public DrawerDynamicLayoutTest() {
-        super(DrawerDynamicLayoutActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class DrawerDynamicLayoutTest {
+    @Rule
+    public final ActivityTestRule<DrawerDynamicLayoutActivity> mActivityTestRule =
+            new ActivityTestRule<>(DrawerDynamicLayoutActivity.class);
 
     @UiThreadTest
     @After
diff --git a/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutDoubleTest.java b/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutDoubleTest.java
index 2f43430..8578798 100755
--- a/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutDoubleTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutDoubleTest.java
@@ -28,6 +28,8 @@
 
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.view.ViewCompat;
 import android.support.v4.widget.DrawerLayout;
 import android.support.v7.appcompat.test.R;
@@ -35,10 +37,16 @@
 import android.view.View;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class DrawerLayoutDoubleTest
-        extends BaseInstrumentationTestCase<DrawerLayoutDoubleActivity> {
+@RunWith(AndroidJUnit4.class)
+public class DrawerLayoutDoubleTest {
+    @Rule
+    public final ActivityTestRule<DrawerLayoutDoubleActivity> mActivityTestRule =
+            new ActivityTestRule<>(DrawerLayoutDoubleActivity.class);
+
     private CustomDrawerLayout mDrawerLayout;
 
     private View mStartDrawer;
@@ -47,10 +55,6 @@
 
     private View mContentView;
 
-    public DrawerLayoutDoubleTest() {
-        super(DrawerLayoutDoubleActivity.class);
-    }
-
     @Before
     public void setUp() {
         final DrawerLayoutDoubleActivity activity = mActivityTestRule.getActivity();
diff --git a/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutTest.java b/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutTest.java
index 34c5d64..f43c909 100755
--- a/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/DrawerLayoutTest.java
@@ -49,6 +49,8 @@
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.Suppress;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.widget.DrawerLayout;
 import android.support.v7.appcompat.test.R;
@@ -56,21 +58,24 @@
 import android.view.View;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
 
-public class DrawerLayoutTest extends BaseInstrumentationTestCase<DrawerLayoutActivity> {
+@RunWith(AndroidJUnit4.class)
+public class DrawerLayoutTest {
+    @Rule
+    public final ActivityTestRule<DrawerLayoutActivity> mActivityTestRule =
+            new ActivityTestRule<DrawerLayoutActivity>(DrawerLayoutActivity.class);
+
     private CustomDrawerLayout mDrawerLayout;
 
     private View mStartDrawer;
 
     private View mContentView;
 
-    public DrawerLayoutTest() {
-        super(DrawerLayoutActivity.class);
-    }
-
     @Before
     public void setUp() {
         final DrawerLayoutActivity activity = mActivityTestRule.getActivity();
diff --git a/v7/appcompat/tests/src/android/support/v7/app/FragmentContentIdTest.java b/v7/appcompat/tests/src/android/support/v7/app/FragmentContentIdTest.java
index c2e2d16..c316e29 100755
--- a/v7/appcompat/tests/src/android/support/v7/app/FragmentContentIdTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/FragmentContentIdTest.java
@@ -23,15 +23,19 @@
 import static android.support.test.espresso.matcher.ViewMatchers.withId;
 
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class FragmentContentIdTest extends BaseInstrumentationTestCase<FragmentContentIdActivity> {
-
-    public FragmentContentIdTest() {
-        super(FragmentContentIdActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class FragmentContentIdTest {
+    @Rule
+    public final ActivityTestRule<FragmentContentIdActivity> mActivityTestRule =
+            new ActivityTestRule<>(FragmentContentIdActivity.class);
 
     @SmallTest
     @Test
@@ -48,5 +52,4 @@
         // And that fragment_b is displayed
         onView(withId(R.id.fragment_b)).check(matches(isDisplayed()));
     }
-
 }
diff --git a/v7/appcompat/tests/src/android/support/v7/app/KeyEventsTestCaseWithToolbar.java b/v7/appcompat/tests/src/android/support/v7/app/KeyEventsTestCaseWithToolbar.java
index 80cfcaa..e7d485b 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/KeyEventsTestCaseWithToolbar.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/KeyEventsTestCaseWithToolbar.java
@@ -16,14 +16,15 @@
 
 package android.support.v7.app;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.v7.widget.Toolbar;
 import android.view.KeyEvent;
 import android.view.Window;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
 import org.junit.Test;
 
 public class KeyEventsTestCaseWithToolbar extends BaseKeyEventsTestCase<ToolbarAppCompatActivity> {
@@ -46,12 +47,12 @@
         Toolbar toolbar = mActivityTestRule.getActivity().getToolbar();
         assertFalse(toolbar.isOverflowMenuShowing());
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
         assertTrue(toolbar.isOverflowMenuShowing());
 
-        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
         assertFalse(toolbar.isOverflowMenuShowing());
     }
 
@@ -70,7 +71,7 @@
                 mActivityTestRule.getActivity().openOptionsMenu();
             }
         });
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
         assertTrue(toolbar.isOverflowMenuShowing());
 
         mActivityTestRule.runOnUiThread(new Runnable() {
@@ -79,7 +80,7 @@
                 mActivityTestRule.getActivity().closeOptionsMenu();
             }
         });
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
         assertFalse(toolbar.isOverflowMenuShowing());
     }
 }
diff --git a/v7/appcompat/tests/src/android/support/v7/app/KeyboardShortcutsTestCaseWithToolbar.java b/v7/appcompat/tests/src/android/support/v7/app/KeyboardShortcutsTestCaseWithToolbar.java
index fc2b2ae..4f450ff 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/KeyboardShortcutsTestCaseWithToolbar.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/KeyboardShortcutsTestCaseWithToolbar.java
@@ -22,7 +22,10 @@
 
 import android.os.Build;
 import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.testutils.BaseTestActivity;
 import android.support.v7.widget.Toolbar;
 import android.view.KeyEvent;
@@ -30,13 +33,15 @@
 import android.view.View;
 import android.view.Window;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class KeyboardShortcutsTestCaseWithToolbar
-        extends BaseKeyboardShortcutsTestCase<ToolbarAppCompatActivity> {
-    public KeyboardShortcutsTestCaseWithToolbar() {
-        super(ToolbarAppCompatActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class KeyboardShortcutsTestCaseWithToolbar {
+    @Rule
+    public final ActivityTestRule<ToolbarAppCompatActivity> mActivityTestRule =
+            new ActivityTestRule<>(ToolbarAppCompatActivity.class);
 
     @Test
     @SmallTest
@@ -45,7 +50,7 @@
         if (Build.VERSION.SDK_INT <= 25) {
             return;
         }
-        final BaseTestActivity activity = getActivity();
+        final BaseTestActivity activity = mActivityTestRule.getActivity();
 
         final View editText = activity.findViewById(android.support.v7.appcompat.test.R.id.editText);
         mActivityTestRule.runOnUiThread(new Runnable() {
@@ -55,9 +60,9 @@
             }
         });
 
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
         sendMetaKey(KeyEvent.KEYCODE_TAB);
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
@@ -71,7 +76,7 @@
         // navigation won't leaves it.
         sendMetaKey(KeyEvent.KEYCODE_TAB);
 
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         // Should jump to the first view again.
         mActivityTestRule.runOnUiThread(new Runnable() {
@@ -85,10 +90,10 @@
     @Test
     @SmallTest
     public void testKeyShortcuts() throws Throwable {
-        final ToolbarAppCompatActivity activity = getActivity();
+        final ToolbarAppCompatActivity activity = mActivityTestRule.getActivity();
 
         final Toolbar toolbar =
-                (Toolbar) activity.findViewById(android.support.v7.appcompat.test.R.id.toolbar);
+                activity.findViewById(android.support.v7.appcompat.test.R.id.toolbar);
 
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
@@ -135,7 +140,7 @@
         activity.resetCounters();
 
         // Make sure that unhandled shortcuts don't prepare menus (since toolbar is handling that).
-        getInstrumentation().sendKeySync(unhandledShortcutKey);
+        InstrumentationRegistry.getInstrumentation().sendKeySync(unhandledShortcutKey);
         assertEquals(1, activity.mKeyShortcutCount);
         assertEquals(0, activity.mPrepareMenuCount);
         assertEquals(0, activity.mCreateMenuCount);
@@ -145,10 +150,10 @@
         long time = SystemClock.uptimeMillis();
         KeyEvent keyDown = new KeyEvent(time, time, KeyEvent.ACTION_DOWN, keyCode,
                 0, KeyEvent.META_META_ON);
-        getInstrumentation().sendKeySync(keyDown);
+        InstrumentationRegistry.getInstrumentation().sendKeySync(keyDown);
         time = SystemClock.uptimeMillis();
         KeyEvent keyUp = new KeyEvent(time, time, KeyEvent.ACTION_UP, keyCode,
                 0, KeyEvent.META_META_ON);
-        getInstrumentation().sendKeySync(keyUp);
+        InstrumentationRegistry.getInstrumentation().sendKeySync(keyUp);
     }
 }
diff --git a/v7/appcompat/tests/src/android/support/v7/app/LayoutInflaterFactoryTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/LayoutInflaterFactoryTestCase.java
index 64c63a0..892a554 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/LayoutInflaterFactoryTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/LayoutInflaterFactoryTestCase.java
@@ -20,12 +20,14 @@
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
 
-import android.support.annotation.RequiresApi;
 import android.content.Context;
 import android.content.res.Resources;
+import android.support.annotation.RequiresApi;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SdkSuppress;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.custom.ContextWrapperFrameLayout;
 import android.support.v7.widget.AppCompatAutoCompleteTextView;
@@ -45,14 +47,15 @@
 import android.widget.LinearLayout;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class LayoutInflaterFactoryTestCase
-        extends BaseInstrumentationTestCase<LayoutInflaterFactoryTestActivity> {
-
-    public LayoutInflaterFactoryTestCase() {
-        super(LayoutInflaterFactoryTestActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class LayoutInflaterFactoryTestCase {
+    @Rule
+    public final ActivityTestRule<LayoutInflaterFactoryTestActivity> mActivityTestRule =
+            new ActivityTestRule<>(LayoutInflaterFactoryTestActivity.class);
 
     @Before
     public void setup() {
@@ -64,7 +67,7 @@
     @Test
     @SmallTest
     public void testAndroidThemeInflation() {
-        final LayoutInflater inflater = LayoutInflater.from(getActivity());
+        final LayoutInflater inflater = LayoutInflater.from(mActivityTestRule.getActivity());
         assertThemedContext(inflater.inflate(R.layout.layout_android_theme, null));
     }
 
@@ -72,7 +75,7 @@
     @Test
     @SmallTest
     public void testAppThemeInflation() {
-        final LayoutInflater inflater = LayoutInflater.from(getActivity());
+        final LayoutInflater inflater = LayoutInflater.from(mActivityTestRule.getActivity());
         assertThemedContext(inflater.inflate(R.layout.layout_app_theme, null));
     }
 
@@ -83,7 +86,7 @@
     @Test
     @SmallTest
     public void testAndroidThemeWithChildrenInflation() {
-        LayoutInflater inflater = LayoutInflater.from(getActivity());
+        LayoutInflater inflater = LayoutInflater.from(mActivityTestRule.getActivity());
         final ViewGroup root = (ViewGroup) inflater.inflate(
                 R.layout.layout_android_theme_children, null);
         assertThemedContext(root);
@@ -93,7 +96,7 @@
     @Test
     @SmallTest
     public void testThemedInflationWithUnattachedParent() {
-        final Context activity = getActivity();
+        final Context activity = mActivityTestRule.getActivity();
 
         // Create a parent but not attached
         final LinearLayout parent = new LinearLayout(activity);
@@ -195,15 +198,15 @@
     @Test
     @SmallTest
     public void testDeclarativeOnClickWithContextWrapper() {
-        LayoutInflater inflater = LayoutInflater.from(getActivity());
+        LayoutInflater inflater = LayoutInflater.from(mActivityTestRule.getActivity());
         View view = inflater.inflate(R.layout.layout_button_themed_onclick, null);
 
         assertTrue(view.performClick());
-        assertTrue(getActivity().wasDeclarativeOnClickCalled());
+        assertTrue(mActivityTestRule.getActivity().wasDeclarativeOnClickCalled());
     }
 
     private void verifyAppCompatWidgetInflation(final int layout, final Class<?> expectedClass) {
-        LayoutInflater inflater = LayoutInflater.from(getActivity());
+        LayoutInflater inflater = LayoutInflater.from(mActivityTestRule.getActivity());
         View view = inflater.inflate(layout, null);
         assertSame("View is " + expectedClass.getSimpleName(), expectedClass,
                 view.getClass());
diff --git a/v7/appcompat/tests/src/android/support/v7/app/NightModeTestCase.java b/v7/appcompat/tests/src/android/support/v7/app/NightModeTestCase.java
index 2168069..2981ad4 100644
--- a/v7/appcompat/tests/src/android/support/v7/app/NightModeTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/app/NightModeTestCase.java
@@ -28,22 +28,27 @@
 import android.app.Instrumentation;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.LargeTest;
-import android.support.test.filters.SdkSuppress;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.content.ContextCompat;
 import android.support.v7.appcompat.test.R;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @LargeTest
-@SdkSuppress(minSdkVersion = 14)
-public class NightModeTestCase extends BaseInstrumentationTestCase<NightModeActivity> {
+@RunWith(AndroidJUnit4.class)
+public class NightModeTestCase {
+    @Rule
+    public final ActivityTestRule<NightModeActivity> mActivityTestRule;
 
     private static final String STRING_DAY = "DAY";
     private static final String STRING_NIGHT = "NIGHT";
 
     public NightModeTestCase() {
-        super(NightModeActivity.class);
+        mActivityTestRule = new ActivityTestRule<>(NightModeActivity.class);
     }
 
     @Before
@@ -116,7 +121,7 @@
         });
 
         // Now wait for the recreate
-        getInstrumentation().waitForIdleSync();
+        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         // Now check that the text has changed, signifying that night resources are being used
         onView(withId(R.id.text_night_mode)).check(matches(withText(STRING_NIGHT)));
@@ -128,7 +133,7 @@
         final FakeTwilightManager twilightManager = new FakeTwilightManager();
         TwilightManager.setInstance(twilightManager);
 
-        final NightModeActivity activity = getActivity();
+        final NightModeActivity activity = mActivityTestRule.getActivity();
 
         // Set MODE_NIGHT_AUTO so that we will change to night mode automatically
         setLocalNightModeAndWaitForRecreate(activity, AppCompatDelegate.MODE_NIGHT_AUTO);
@@ -138,7 +143,8 @@
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
             public void run() {
-                final Instrumentation instrumentation = getInstrumentation();
+                final Instrumentation instrumentation =
+                        InstrumentationRegistry.getInstrumentation();
                 // Now fool the Activity into thinking that it has gone into the background
                 instrumentation.callActivityOnPause(activity);
                 instrumentation.callActivityOnStop(activity);
diff --git a/v7/appcompat/tests/src/android/support/v7/res/content/AppCompatResourcesTestCase.java b/v7/appcompat/tests/src/android/support/v7/res/content/AppCompatResourcesTestCase.java
index bfb456a..d6b9f83 100644
--- a/v7/appcompat/tests/src/android/support/v7/res/content/AppCompatResourcesTestCase.java
+++ b/v7/appcompat/tests/src/android/support/v7/res/content/AppCompatResourcesTestCase.java
@@ -23,25 +23,31 @@
 import android.content.res.ColorStateList;
 import android.graphics.Color;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.graphics.ColorUtils;
 import android.support.v7.app.AppCompatActivity;
-import android.support.v7.app.BaseInstrumentationTestCase;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.content.res.AppCompatResources;
 import android.support.v7.testutils.TestUtils;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
-public class AppCompatResourcesTestCase extends BaseInstrumentationTestCase<AppCompatActivity> {
+@RunWith(AndroidJUnit4.class)
+public class AppCompatResourcesTestCase {
+    @Rule
+    public final ActivityTestRule<AppCompatActivity> mActivityTestRule;
 
     public AppCompatResourcesTestCase() {
-        super(AppCompatActivity.class);
+        mActivityTestRule = new ActivityTestRule<>(AppCompatActivity.class);
     }
 
     @Test
     public void testGetColorStateListWithThemedAttributes() {
-        final Activity context = getActivity();
+        final Activity context = mActivityTestRule.getActivity();
 
         final int colorForegound = TestUtils.getThemeAttrColor(
                 context, android.R.attr.colorForeground);
@@ -65,7 +71,7 @@
 
     @Test
     public void testGetDrawableVectorResource() {
-        final Activity context = getActivity();
+        final Activity context = mActivityTestRule.getActivity();
         assertNotNull(AppCompatResources.getDrawable(context, R.drawable.test_vector_off));
     }
 
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseAutoSizeTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseAutoSizeTest.java
new file mode 100644
index 0000000..cc6f91b
--- /dev/null
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseAutoSizeTest.java
@@ -0,0 +1,1210 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.widget;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import android.app.Instrumentation;
+import android.graphics.Typeface;
+import android.graphics.drawable.Drawable;
+import android.os.Build;
+import android.support.annotation.IdRes;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.filters.SdkSuppress;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.v4.content.res.ResourcesCompat;
+import android.support.v4.widget.AutoSizeableTextView;
+import android.support.v4.widget.TextViewCompat;
+import android.support.v7.appcompat.test.R;
+import android.support.v7.testutils.BaseTestActivity;
+import android.text.TextUtils;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+/**
+ * Base class for testing auto-size-text enabled views in appcompat-v7 that implement the
+ * <code>AutoSizeableTextView</code> interface. Extensions of this class run all tests
+ * from here and can add test cases specific to the functionality they add to the relevant
+ * base view class.
+ */
+public abstract class AppCompatBaseAutoSizeTest<A extends BaseTestActivity,
+        T extends TextView & AutoSizeableTextView> {
+
+    @Rule
+    public final ActivityTestRule<A> mActivityTestRule;
+
+    protected A mActivity;
+    protected Instrumentation mInstrumentation;
+    protected ViewGroup mContainer;
+
+    public AppCompatBaseAutoSizeTest(Class clazz) {
+        mActivityTestRule = new ActivityTestRule<A>(clazz);
+    }
+
+    @Before
+    public void setup() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        mActivity = mActivityTestRule.getActivity();
+        mContainer = mActivity.findViewById(R.id.container);
+    }
+
+    @Test
+    @MediumTest
+    @SdkSuppress(minSdkVersion = 16)
+    // public TextView#getMaxLines only introduced in API 16.
+    public void testAutoSizeCallers_setMaxLines() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        // Configure layout params and auto-size both in pixels to dodge flakiness on different
+        // devices.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                500, 500);
+        final String text = "one two three four five six seven eight nine ten";
+        mActivity.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+                ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                        1 /* autoSizeMinTextSize */,
+                        5000 /* autoSizeMaxTextSize */,
+                        1 /* autoSizeStepGranularity */,
+                        TypedValue.COMPLEX_UNIT_PX);
+                autoSizeView.setText(text);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        float initialSize = 0;
+        for (int i = 1; i < 10; i++) {
+            final int maxLines = i;
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setMaxLines(maxLines);
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            float expectedSmallerSize = autoSizeView.getTextSize();
+            if (i == 1) {
+                initialSize = expectedSmallerSize;
+            }
+
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setMaxLines(maxLines + 1);
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            assertTrue(expectedSmallerSize <= autoSizeView.getTextSize());
+        }
+        assertTrue(initialSize < autoSizeView.getTextSize());
+
+        initialSize = 999999;
+        for (int i = 10; i > 1; i--) {
+            final int maxLines = i;
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setMaxLines(maxLines);
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            float expectedLargerSize = autoSizeView.getTextSize();
+            if (i == 10) {
+                initialSize = expectedLargerSize;
+            }
+
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setMaxLines(maxLines - 1);
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            assertTrue(expectedLargerSize >= autoSizeView.getTextSize());
+        }
+        assertTrue(initialSize > autoSizeView.getTextSize());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_autoSizeCalledWhenTypeChanged() throws Throwable {
+        final T view = mContainer.findViewById(R.id.view_text);
+
+        // Make sure we pick an already inflated non auto-sized text view.
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+        // Set the text size to a very low value in order to prepare for auto-size.
+        final int customTextSize = 3;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                view.setTextSize(TypedValue.COMPLEX_UNIT_PX, customTextSize);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertEquals(customTextSize, view.getTextSize(), 0f);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeWithDefaults(
+                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        // The size of the text should have changed.
+        assertNotEquals(customTextSize, view.getTextSize(), 0f);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setText() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+
+        // Configure layout params and auto-size both in pixels to dodge flakiness on different
+        // devices.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                500, 500);
+        mActivity.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+                ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                        1, 5000, 1, TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final String initialText = "13characters ";
+        final StringBuilder textToSet = new StringBuilder().append(initialText);
+        float initialSize = 0;
+
+        // As we add characters the text size shrinks.
+        for (int i = 0; i < 10; i++) {
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setText(textToSet.toString());
+                }
+            });
+
+            mInstrumentation.waitForIdleSync();
+            float expectedLargerSize = autoSizeView.getTextSize();
+            if (i == 0) {
+                initialSize = expectedLargerSize;
+            }
+
+            textToSet.append(initialText);
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setText(textToSet.toString());
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            assertTrue(expectedLargerSize >= autoSizeView.getTextSize());
+        }
+        assertTrue(initialSize > autoSizeView.getTextSize());
+
+        initialSize = 9999999;
+        // As we remove characters the text size expands.
+        for (int i = 9; i >= 0; i--) {
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setText(textToSet.toString());
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            float expectedSmallerSize = autoSizeView.getTextSize();
+            if (i == 0) {
+                initialSize = expectedSmallerSize;
+            }
+
+            textToSet.replace((textToSet.length() - initialText.length()),
+                    textToSet.length(), "");
+            mActivity.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    autoSizeView.setText(textToSet.toString());
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+
+            assertTrue(autoSizeView.getTextSize() >= expectedSmallerSize);
+        }
+        assertTrue(autoSizeView.getTextSize() > initialSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_equivalentConfigurations() throws Throwable {
+        final DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
+        final int minTextSize = 10;
+        final int maxTextSize = 20;
+        final int granularity = 2;
+        final int unit = TypedValue.COMPLEX_UNIT_SP;
+
+        final T granularityView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) granularityView).setAutoSizeTextTypeUniformWithConfiguration(
+                minTextSize, maxTextSize, granularity, unit);
+
+        final T presetView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) presetView).setAutoSizeTextTypeUniformWithPresetSizes(
+                new int[]{minTextSize, 12, 14, 16, 18, maxTextSize}, unit);
+
+        // The TextViews have been configured differently but the end result should be nearly
+        // identical.
+        final int expectedAutoSizeType = AppCompatTextView.AUTO_SIZE_TEXT_TYPE_UNIFORM;
+        assertEquals(expectedAutoSizeType,
+                ((AutoSizeableTextView) granularityView).getAutoSizeTextType());
+        assertEquals(expectedAutoSizeType,
+                ((AutoSizeableTextView) presetView).getAutoSizeTextType());
+
+        final int expectedMinTextSizeInPx = Math.round(
+                TypedValue.applyDimension(unit, minTextSize, dm));
+        assertEquals(expectedMinTextSizeInPx,
+                ((AutoSizeableTextView) granularityView).getAutoSizeMinTextSize());
+        assertEquals(expectedMinTextSizeInPx,
+                ((AutoSizeableTextView) presetView).getAutoSizeMinTextSize());
+
+        final int expectedMaxTextSizeInPx = Math.round(
+                TypedValue.applyDimension(unit, maxTextSize, dm));
+        assertEquals(expectedMaxTextSizeInPx,
+                ((AutoSizeableTextView) granularityView).getAutoSizeMaxTextSize());
+        assertEquals(expectedMaxTextSizeInPx,
+                ((AutoSizeableTextView) presetView).getAutoSizeMaxTextSize());
+
+        // Configured with granularity.
+        assertEquals(Math.round(TypedValue.applyDimension(unit, granularity, dm)),
+                ((AutoSizeableTextView) granularityView).getAutoSizeStepGranularity());
+        // Configured with preset values, there is no granularity.
+        assertEquals(-1,
+                ((AutoSizeableTextView) presetView).getAutoSizeStepGranularity());
+
+        // Both TextViews generate exactly the same sizes in pixels to choose from when auto-sizing.
+        assertArrayEquals(
+                ((AutoSizeableTextView) granularityView).getAutoSizeTextAvailableSizes(),
+                ((AutoSizeableTextView) presetView).getAutoSizeTextAvailableSizes());
+
+        final String someText = "This is a string";
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                500, 500);
+        // Configure identically and attach to layout.
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                granularityView.setLayoutParams(layoutParams);
+                presetView.setLayoutParams(layoutParams);
+
+                LinearLayout ll = mActivity.findViewById(R.id.container);
+                ll.removeAllViews();
+                ll.addView(granularityView);
+                ll.addView(presetView);
+
+                granularityView.setText(someText);
+                presetView.setText(someText);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(granularityView.getTextSize(), presetView.getTextSize(), 0f);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setHeight() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(
+                R.id.view_autosize_uniform, true);
+        // Do not force exact height only.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                200,
+                LinearLayout.LayoutParams.WRAP_CONTENT);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setHeight(autoSizeView.getHeight() / 4);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() < initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setCompoundDrawables() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        final float initialTextSize = autoSizeView.getTextSize();
+        final Drawable drawable = ResourcesCompat.getDrawable(mActivity.getResources(),
+                R.drawable.test_drawable_red, null);
+        drawable.setBounds(0, 0, autoSizeView.getWidth() / 3, autoSizeView.getHeight() / 3);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setCompoundDrawables(drawable, drawable, drawable, drawable);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() < initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setCompoundDrawablesRelative() throws Throwable {
+        if (Build.VERSION.SDK_INT >= 17) {
+            final T autoSizeView = prepareAndRetrieveAutoSizeTestData(
+                    R.id.view_autosize_uniform, false);
+            final float initialTextSize = autoSizeView.getTextSize();
+            final Drawable drawable = ResourcesCompat.getDrawable(mActivity.getResources(),
+                    R.drawable.test_drawable_red, null);
+            drawable.setBounds(0, 0, autoSizeView.getWidth() / 3,
+                    autoSizeView.getHeight() / 3);
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if (Build.VERSION.SDK_INT >= 17) {
+                        autoSizeView.setCompoundDrawablesRelative(
+                                drawable, drawable, drawable, drawable);
+                    }
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+
+            assertTrue(autoSizeView.getTextSize() < initialTextSize);
+        }
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setCompoundDrawablePadding() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        // Prepare a larger layout in order not to hit the min value easily.
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setWidth(autoSizeView.getWidth() * 2);
+                autoSizeView.setHeight(autoSizeView.getHeight() * 2);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        // Setup the drawables before setting their padding in order to modify the available
+        // space and trigger a resize.
+        final Drawable drawable = ResourcesCompat.getDrawable(mActivity.getResources(),
+                R.drawable.test_drawable_red, null);
+        drawable.setBounds(0, 0, autoSizeView.getWidth() / 4, autoSizeView.getHeight() / 4);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setCompoundDrawables(
+                        drawable, drawable, drawable, drawable);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setCompoundDrawablePadding(
+                        autoSizeView.getCompoundDrawablePadding() + 10);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() < initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setPadding() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setPadding(
+                        autoSizeView.getWidth() / 3, autoSizeView.getHeight() / 3,
+                        autoSizeView.getWidth() / 3, autoSizeView.getHeight() / 3);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() < initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setPaddingRelative() throws Throwable {
+        if (Build.VERSION.SDK_INT >= 16) {
+            final T autoSizeView = prepareAndRetrieveAutoSizeTestData(
+                    R.id.view_autosize_uniform, false);
+            final float initialTextSize = autoSizeView.getTextSize();
+
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if (Build.VERSION.SDK_INT > 16) {
+                        autoSizeView.setPaddingRelative(
+                                autoSizeView.getWidth() / 3, autoSizeView.getHeight() / 3,
+                                autoSizeView.getWidth() / 3, autoSizeView.getHeight() / 3);
+                    }
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+
+            assertTrue(autoSizeView.getTextSize() < initialTextSize);
+        }
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setTypeface() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setText("The typeface change needs a bit more text then "
+                        + "the default used for this batch of tests in order to get to resize text."
+                        + " The resize function is always called but even with different typefaces "
+                        + "there may not be a need to resize text because it just fits. The longer "
+                        + "the text, the higher the chance for a resize. And here is yet another "
+                        + "sentence to make sure this test is not flaky. Not flaky at all.");
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeView.getTextSize();
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                Typeface differentTypeface = Typeface.MONOSPACE;
+                if (autoSizeView.getTypeface() == Typeface.MONOSPACE) {
+                    differentTypeface = Typeface.SANS_SERIF;
+                }
+                autoSizeView.setTypeface(differentTypeface);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float changedTextSize = autoSizeView.getTextSize();
+
+        // Don't really know if it is larger or smaller (depends on the typeface chosen above),
+        // but it should definitely have changed.
+        assertNotEquals(initialTextSize, changedTextSize, 0f);
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setTypeface(autoSizeView.getTypeface());
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(changedTextSize, autoSizeView.getTextSize(), 0f);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setLetterSpacing() throws Throwable {
+        if (Build.VERSION.SDK_INT >= 21) {
+            final T autoSizeView = prepareAndRetrieveAutoSizeTestData(
+                    R.id.view_autosize_uniform, false);
+            final float initialTextSize = autoSizeView.getTextSize();
+
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if (Build.VERSION.SDK_INT >= 21) {
+                        autoSizeView.setLetterSpacing(
+                                autoSizeView.getLetterSpacing() * 1.5f + 4.5f);
+                    }
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+            final float changedTextSize = autoSizeView.getTextSize();
+
+            assertTrue(changedTextSize < initialTextSize);
+
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if (Build.VERSION.SDK_INT >= 21) {
+                        autoSizeView.setLetterSpacing(autoSizeView.getLetterSpacing());
+                    }
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+
+            assertEquals(changedTextSize, autoSizeView.getTextSize(), 0f);
+        }
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setMaxHeight() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                true);
+        // Do not force exact height only.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                200,
+                LinearLayout.LayoutParams.WRAP_CONTENT);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setMaxHeight(autoSizeView.getHeight() / 4);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() < initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setMaxWidth() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                true);
+        // Do not force exact width only.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                LinearLayout.LayoutParams.WRAP_CONTENT,
+                200);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setMaxWidth(autoSizeView.getWidth() / 4);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() != initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setWidth() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                true);
+        // Do not force exact width only.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                LinearLayout.LayoutParams.WRAP_CONTENT,
+                200);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setLayoutParams(layoutParams);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setWidth(autoSizeView.getWidth() / 4);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeView.getTextSize() != initialTextSize);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setTextSizeIsNoOp() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        final float initialTextSize = autoSizeView.getTextSize();
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setTextSize(initialTextSize + 123f);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(initialTextSize, autoSizeView.getTextSize(), 0f);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setHorizontallyScrolling() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        // Horizontal scrolling is expected to be deactivated for this test.
+        final float initialTextSize = autoSizeView.getTextSize();
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setHorizontallyScrolling(true);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertTrue(autoSizeView.getTextSize() > initialTextSize);
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setHorizontallyScrolling(false);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertEquals(initialTextSize, autoSizeView.getTextSize(), 0f);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSize_setEllipsize() throws Throwable {
+        final T autoSizeView = mActivity.findViewById(R.id.view_autosize_uniform_predef_sizes);
+        final int initialAutoSizeType = ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType();
+        final int initialMinTextSize =
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize();
+        final int initialMaxTextSize =
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize();
+        final int initialAutoSizeGranularity =
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity();
+        final int initialSizes =
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextAvailableSizes().length;
+
+        assertEquals(null, autoSizeView.getEllipsize());
+        // Verify styled attributes.
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM, initialAutoSizeType);
+        assertNotEquals(-1, initialMinTextSize);
+        assertNotEquals(-1, initialMaxTextSize);
+        // Because this TextView has been configured to use predefined sizes.
+        assertEquals(-1, initialAutoSizeGranularity);
+        assertNotEquals(0, initialSizes);
+
+        final TextUtils.TruncateAt newEllipsizeValue = TextUtils.TruncateAt.END;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setEllipsize(newEllipsizeValue);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertEquals(newEllipsizeValue, autoSizeView.getEllipsize());
+        // Beside the ellipsis no auto-size attribute has changed.
+        assertEquals(initialAutoSizeType,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        assertEquals(initialMinTextSize,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+        assertEquals(initialMaxTextSize,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+        assertEquals(initialAutoSizeGranularity,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+        assertEquals(initialSizes,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextAvailableSizes().length);
+    }
+
+    @Test
+    @MediumTest
+    public void testEllipsize_setAutoSize() throws Throwable {
+        final T view = mActivity.findViewById(R.id.view_text);
+        final TextUtils.TruncateAt newEllipsizeValue = TextUtils.TruncateAt.END;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                view.setEllipsize(newEllipsizeValue);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertEquals(newEllipsizeValue, view.getEllipsize());
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+        assertEquals(-1, ((AutoSizeableTextView) view).getAutoSizeMinTextSize());
+        assertEquals(-1, ((AutoSizeableTextView) view).getAutoSizeMaxTextSize());
+        assertEquals(-1, ((AutoSizeableTextView) view).getAutoSizeStepGranularity());
+        assertEquals(0,
+                ((AutoSizeableTextView) view).getAutoSizeTextAvailableSizes().length);
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeWithDefaults(
+                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertEquals(newEllipsizeValue, view.getEllipsize());
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+        // The auto-size defaults have been used.
+        assertNotEquals(-1, ((AutoSizeableTextView) view).getAutoSizeMinTextSize());
+        assertNotEquals(-1, ((AutoSizeableTextView) view).getAutoSizeMaxTextSize());
+        assertNotEquals(-1, ((AutoSizeableTextView) view).getAutoSizeStepGranularity());
+        assertNotEquals(0,
+                ((AutoSizeableTextView) view).getAutoSizeTextAvailableSizes().length);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_obtainStyledAttributesUsingPredefinedSizes() {
+        DisplayMetrics m = mActivity.getResources().getDisplayMetrics();
+        final T autoSizeViewUniform = mActivity.findViewById(
+                R.id.view_autosize_uniform_predef_sizes);
+
+        // In arrays.xml predefined the step sizes as: 5px, 11dip, 19sp, 29pt, 43mm and 53in.
+        // TypedValue can not use the math library and instead rounds the value by adding
+        // 0.5f when obtaining styled attributes. Check TypedValue#complexToDimensionPixelSize(...)
+        int[] expectedSizesInPx = new int[] {
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 5f, m)),
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 11f, m)),
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 19f, m)),
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 29f, m)),
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 43f, m)),
+                Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, 53f, m))};
+
+        boolean containsValueFromExpectedSizes = false;
+        final int textSize = (int) autoSizeViewUniform.getTextSize();
+        for (int i = 0; i < expectedSizesInPx.length; i++) {
+            if (expectedSizesInPx[i] == textSize) {
+                containsValueFromExpectedSizes = true;
+                break;
+            }
+        }
+        assertTrue(containsValueFromExpectedSizes);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_obtainStyledAttributesPredefinedSizesFiltering() {
+        T autoSizeViewUniform = mActivity.findViewById(
+                R.id.view_autosize_uniform_predef_sizes_redundant_values);
+
+        // In arrays.xml predefined the step sizes as: 40px, 10px, 10px, 10px, 0dp.
+        final int[] expectedSizes = new int[] {10, 40};
+        assertArrayEquals(expectedSizes,
+                ((AutoSizeableTextView) autoSizeViewUniform).getAutoSizeTextAvailableSizes());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_predefinedSizesFilteringAndSorting() throws Throwable {
+        final T view = mActivity.findViewById(R.id.view_text);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+
+        final int[] predefinedSizes = new int[] {400, 0, 10, 40, 10, 10, 0, 0};
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeUniformWithPresetSizes(
+                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertArrayEquals(new int[] {10, 40, 400},
+                ((AutoSizeableTextView) view).getAutoSizeTextAvailableSizes());
+    }
+
+    @Test(expected = NullPointerException.class)
+    @SmallTest
+    public void testAutoSizeUniform_predefinedSizesNullArray() throws Throwable {
+        final T view = mActivity.findViewById(R.id.view_text);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+
+        final int[] predefinedSizes = null;
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeUniformWithPresetSizes(
+                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_predefinedSizesEmptyArray() throws Throwable {
+        final T view = mActivity.findViewById(R.id.view_text);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) view).getAutoSizeTextType());
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeWithDefaults(
+                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final int[] defaultSizes = ((AutoSizeableTextView) view).getAutoSizeTextAvailableSizes();
+        assertNotNull(defaultSizes);
+        assertTrue(defaultSizes.length > 0);
+
+        final int[] predefinedSizes = new int[0];
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) view).setAutoSizeTextTypeUniformWithPresetSizes(
+                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final int[] newSizes = ((AutoSizeableTextView) view).getAutoSizeTextAvailableSizes();
+        assertNotNull(defaultSizes);
+        assertArrayEquals(defaultSizes, newSizes);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_buildsSizes() throws Throwable {
+        final T autoSizeViewUniform = mActivity.findViewById(R.id.view_autosize_uniform);
+
+        // Verify that the interval limits are both included.
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) autoSizeViewUniform)
+                        .setAutoSizeTextTypeUniformWithConfiguration(10, 20, 2,
+                                TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertArrayEquals(
+                new int[] {10, 12, 14, 16, 18, 20},
+                ((AutoSizeableTextView) autoSizeViewUniform).getAutoSizeTextAvailableSizes());
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) autoSizeViewUniform)
+                        .setAutoSizeTextTypeUniformWithConfiguration(
+                                ((AutoSizeableTextView) autoSizeViewUniform)
+                                        .getAutoSizeMinTextSize(),
+                                19,
+                                ((AutoSizeableTextView) autoSizeViewUniform)
+                                        .getAutoSizeStepGranularity(),
+                                TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertArrayEquals(
+                new int[] {10, 12, 14, 16, 18},
+                ((AutoSizeableTextView) autoSizeViewUniform).getAutoSizeTextAvailableSizes());
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) autoSizeViewUniform)
+                        .setAutoSizeTextTypeUniformWithConfiguration(
+                                ((AutoSizeableTextView) autoSizeViewUniform)
+                                        .getAutoSizeMinTextSize(),
+                                21,
+                                ((AutoSizeableTextView) autoSizeViewUniform)
+                                        .getAutoSizeStepGranularity(),
+                                TypedValue.COMPLEX_UNIT_PX);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        assertArrayEquals(
+                new int[] {10, 12, 14, 16, 18, 20},
+                ((AutoSizeableTextView) autoSizeViewUniform).getAutoSizeTextAvailableSizes());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_getSetAutoSizeTextDefaults() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        // Min/Max/Granularity values for auto-sizing are 0 because they are not used.
+        assertEquals(-1, ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+        assertEquals(-1, ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+        assertEquals(-1,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeWithDefaults(
+                TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        // Min/Max default values for auto-sizing XY have been loaded.
+        final int minSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize();
+        final int maxSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize();
+        assertTrue(0 < minSize);
+        assertTrue(minSize < maxSize);
+        assertNotEquals(0,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+
+        ((AutoSizeableTextView) autoSizeView)
+                .setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        // Min/Max values for auto-sizing XY have been cleared.
+        assertEquals(-1, ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+        assertEquals(-1, ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+        assertEquals(-1,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_getSetAutoSizeStepGranularity() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        final int initialValue = -1;
+        assertEquals(initialValue,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeWithDefaults(
+                TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        final int defaultValue = 1; // 1px.
+        // If the auto-size type is AUTO_SIZE_TEXT_TYPE_UNIFORM then it means autoSizeView went
+        // through the auto-size setup and given that 0 is an invalid value it changed it to the
+        // default.
+        assertEquals(defaultValue,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+
+        final int newValue = 33;
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize(),
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize(),
+                newValue,
+                TypedValue.COMPLEX_UNIT_PX);
+        assertEquals(newValue, ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_getSetAutoSizeMinTextSize() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeWithDefaults(
+                TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        final int minSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize();
+        assertNotEquals(0, minSize);
+        final int maxSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize();
+        assertNotEquals(0, maxSize);
+
+        // This is just a test check to verify the next assertions. If this fails it is a problem
+        // of this test setup (we need at least 2 units).
+        assertTrue((maxSize - minSize) > 1);
+        final int newMinSize = maxSize - 1;
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                newMinSize,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize(),
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity(),
+                TypedValue.COMPLEX_UNIT_PX);
+
+        assertEquals(newMinSize, ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+        // Max size has not changed.
+        assertEquals(maxSize, ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                newMinSize,
+                newMinSize + 10,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity(),
+                TypedValue.COMPLEX_UNIT_SP);
+
+        // It does not matter which unit has been used to set the min size, the getter always
+        // returns it in pixels.
+        assertEquals(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
+                newMinSize, mActivity.getResources().getDisplayMetrics())),
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    @SmallTest
+    public void testAutoSizeUniform_throwsException_whenMaxLessThanMin() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                10, 9, 1, TypedValue.COMPLEX_UNIT_SP);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    @SmallTest
+    public void testAutoSizeUniform_throwsException_minLessThanZero() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                -1, 9, 1, TypedValue.COMPLEX_UNIT_SP);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    @SmallTest
+    public void testAutoSizeUniform_throwsException_maxLessThanZero() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                10, -1, 1, TypedValue.COMPLEX_UNIT_SP);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    @SmallTest
+    public void testAutoSizeUniform_throwsException_granularityLessThanZero() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                10, 20, -1, TypedValue.COMPLEX_UNIT_SP);
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeUniform_getSetAutoSizeMaxTextSize() {
+        final T autoSizeView = getNewAutoSizeViewInstance();
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeWithDefaults(
+                TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeTextType());
+        final int minSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize();
+        assertNotEquals(0, minSize);
+        final int maxSize = ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize();
+        assertNotEquals(0, maxSize);
+
+        final int newMaxSize = maxSize + 11;
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize(),
+                newMaxSize,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity(),
+                TypedValue.COMPLEX_UNIT_PX);
+
+        assertEquals(newMaxSize, ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+        // Min size has not changed.
+        assertEquals(minSize, ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize());
+        ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeUniformWithConfiguration(
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMinTextSize(),
+                newMaxSize,
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeStepGranularity(),
+                TypedValue.COMPLEX_UNIT_SP);
+        // It does not matter which unit has been used to set the max size, the getter always
+        // returns it in pixels.
+        assertEquals(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
+                newMaxSize, mActivity.getResources().getDisplayMetrics())),
+                ((AutoSizeableTextView) autoSizeView).getAutoSizeMaxTextSize());
+    }
+
+    @Test
+    @MediumTest
+    public void testAutoSizeCallers_setTextSizeChangesSizeWhenAutoSizeDisabled() throws Throwable {
+        final T autoSizeView = prepareAndRetrieveAutoSizeTestData(R.id.view_autosize_uniform,
+                false);
+        // Disable auto-size.
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ((AutoSizeableTextView) autoSizeView).setAutoSizeTextTypeWithDefaults(
+                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+        final float newTextSizeInPx = 123f;
+        assertNotEquals(newTextSizeInPx, autoSizeView.getTextSize(), 0f);
+
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                autoSizeView.setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSizeInPx);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(newTextSizeInPx, autoSizeView.getTextSize(), 0f);
+    }
+
+    /**
+     * Some View attributes require non-fixed width and/or layout height. This function removes
+     * all other existing views from the layout leaving only one auto-size TextView (for exercising
+     * the auto-size behavior) which has been set up to suit the test needs.
+     *
+     * @param viewId The id of the view to prepare.
+     * @param shouldWrapLayoutContent Specifies if the layout params should wrap content
+     *
+     * @return a View configured for auto size tests.
+     */
+    private T prepareAndRetrieveAutoSizeTestData(final @IdRes int viewId,
+            final boolean shouldWrapLayoutContent) throws Throwable {
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                LinearLayout ll = mActivity.findViewById(R.id.container);
+                T targetedView = mActivity.findViewById(viewId);
+                ll.removeAllViews();
+                ll.addView(targetedView);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final T view = mActivity.findViewById(viewId);
+        if (shouldWrapLayoutContent) {
+            // Do not force exact width or height.
+            final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                    LinearLayout.LayoutParams.WRAP_CONTENT,
+                    LinearLayout.LayoutParams.WRAP_CONTENT);
+            mActivityTestRule.runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    view.setLayoutParams(layoutParams);
+                }
+            });
+            mInstrumentation.waitForIdleSync();
+        }
+
+        return view;
+    }
+
+    // Returns a new instance of the auto-sizable view for mActivity.
+    protected abstract T getNewAutoSizeViewInstance();
+}
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseImageViewTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseImageViewTest.java
index c8398ed..431dc0e 100755
--- a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseImageViewTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseImageViewTest.java
@@ -66,7 +66,7 @@
     @SmallTest
     public void testImageTintingAcrossStateChange() {
         final @IdRes int viewId = R.id.view_tinted_source;
-        final Resources res = getActivity().getResources();
+        final Resources res = mActivity.getResources();
         final T view = (T) mContainer.findViewById(viewId);
 
         @ColorInt int lilacDefault = ResourcesCompat.getColor(res, R.color.lilac_default, null);
@@ -144,7 +144,7 @@
     @SmallTest
     public void testImageTintingAcrossModeChange() {
         final @IdRes int viewId = R.id.view_untinted_source;
-        final Resources res = getActivity().getResources();
+        final Resources res = mActivity.getResources();
         final T view = (T) mContainer.findViewById(viewId);
 
         @ColorInt int emeraldDefault = ResourcesCompat.getColor(
@@ -216,7 +216,7 @@
     @SmallTest
     public void testImageOpaqueTintingAcrossImageChange() {
         final @IdRes int viewId = R.id.view_tinted_no_source;
-        final Resources res = getActivity().getResources();
+        final Resources res = mActivity.getResources();
         final T view = (T) mContainer.findViewById(viewId);
 
         @ColorInt int lilacDefault = ResourcesCompat.getColor(res, R.color.lilac_default, null);
@@ -271,7 +271,7 @@
     @SmallTest
     public void testImageTranslucentTintingAcrossImageChange() {
         final @IdRes int viewId = R.id.view_untinted_no_source;
-        final Resources res = getActivity().getResources();
+        final Resources res = mActivity.getResources();
         final T view = (T) mContainer.findViewById(viewId);
 
         @ColorInt int emeraldDefault = ResourcesCompat.getColor(
@@ -361,7 +361,7 @@
     @SmallTest
     public void testImageTintingAcrossBackgroundTintingChange() {
         final @IdRes int viewId = R.id.view_untinted_source;
-        final Resources res = getActivity().getResources();
+        final Resources res = mActivity.getResources();
         final T view = (T) mContainer.findViewById(viewId);
 
         @ColorInt int lilacDefault = ResourcesCompat.getColor(res, R.color.lilac_default, null);
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseViewTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseViewTest.java
index 74a73d3..cafe2cf 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseViewTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatBaseViewTest.java
@@ -36,9 +36,10 @@
 import android.support.annotation.IdRes;
 import android.support.annotation.NonNull;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.content.res.ResourcesCompat;
 import android.support.v4.graphics.ColorUtils;
-import android.support.v7.app.BaseInstrumentationTestCase;
 import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.AppCompatTintableViewActions;
 import android.support.v7.testutils.BaseTestActivity;
@@ -47,7 +48,9 @@
 import android.view.ViewGroup;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Base class for testing custom view extensions in appcompat-v7 that implement the
@@ -55,15 +58,18 @@
  * from here and add test cases specific to the functionality they add to the relevant
  * base view class (such as <code>AppCompatTextView</code>'s all-caps support).
  */
-public abstract class AppCompatBaseViewTest<A extends BaseTestActivity, T extends View>
-        extends BaseInstrumentationTestCase<A> {
+@RunWith(AndroidJUnit4.class)
+public abstract class AppCompatBaseViewTest<A extends BaseTestActivity, T extends View> {
+    @Rule
+    public final ActivityTestRule<A> mActivityTestRule;
+
     protected ViewGroup mContainer;
 
     protected A mActivity;
     protected Resources mResources;
 
     public AppCompatBaseViewTest(Class clazz) {
-        super(clazz);
+        mActivityTestRule = new ActivityTestRule<A>(clazz);
     }
 
     @Before
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeActivity.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeActivity.java
new file mode 100644
index 0000000..cd5c6a9
--- /dev/null
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.widget;
+
+import android.support.v7.appcompat.test.R;
+import android.support.v7.testutils.BaseTestActivity;
+
+/**
+ * This activity is used to test the auto-size feature of the {@link AppCompatButton}
+ * class.
+ */
+public class AppCompatButtonAutoSizeActivity extends BaseTestActivity {
+    @Override
+    protected int getContentViewLayoutResId() {
+        return R.layout.appcompat_button_autosize_activity;
+    }
+}
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeTest.java
new file mode 100644
index 0000000..cc54463
--- /dev/null
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatButtonAutoSizeTest.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.widget;
+
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.runner.RunWith;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class AppCompatButtonAutoSizeTest extends
+        AppCompatBaseAutoSizeTest<AppCompatButtonAutoSizeActivity, AppCompatButton> {
+
+    public AppCompatButtonAutoSizeTest() {
+        super(AppCompatButtonAutoSizeActivity.class);
+    }
+
+    @Override
+    protected AppCompatButton getNewAutoSizeViewInstance() {
+        return new AppCompatButton(mActivity);
+    }
+}
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeActivity.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeActivity.java
index 17ff6a2..5736dd9 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeActivity.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeActivity.java
@@ -15,6 +15,7 @@
  */
 package android.support.v7.widget;
 
+import android.support.v7.appcompat.test.R;
 import android.support.v7.testutils.BaseTestActivity;
 
 /**
@@ -24,6 +25,6 @@
 public class AppCompatTextViewAutoSizeActivity extends BaseTestActivity {
     @Override
     protected int getContentViewLayoutResId() {
-        return android.support.v7.appcompat.test.R.layout.appcompat_textview_autosize_activity;
+        return R.layout.appcompat_textview_autosize_activity;
     }
 }
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeTest.java
index b8f082e..45da1e4 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewAutoSizeTest.java
@@ -17,111 +17,39 @@
 
 import static junit.framework.TestCase.assertEquals;
 
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
 import android.content.Context;
-import android.graphics.Typeface;
-import android.graphics.drawable.Drawable;
 import android.os.Build;
 import android.support.annotation.Nullable;
 import android.support.test.filters.MediumTest;
-import android.support.v4.content.res.ResourcesCompat;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.widget.TextViewCompat;
-import android.support.v7.app.BaseInstrumentationTestCase;
 import android.support.v7.appcompat.test.R;
-import android.text.TextUtils;
 import android.text.method.SingleLineTransformationMethod;
 import android.util.AttributeSet;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
 import android.widget.LinearLayout;
-import android.widget.TextView;
 
-import org.junit.Assert;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @MediumTest
+@RunWith(AndroidJUnit4.class)
 public class AppCompatTextViewAutoSizeTest extends
-        BaseInstrumentationTestCase<AppCompatTextViewAutoSizeActivity> {
+        AppCompatBaseAutoSizeTest<AppCompatTextViewAutoSizeActivity, AppCompatTextView> {
 
     public AppCompatTextViewAutoSizeTest() {
         super(AppCompatTextViewAutoSizeActivity.class);
     }
 
-    @Test
-    public void testAutoSizeUniform_equivalentConfigurations() throws Throwable {
-        final DisplayMetrics dm = getActivity().getResources().getDisplayMetrics();
-        final int minTextSize = 10;
-        final int maxTextSize = 20;
-        final int granularity = 2;
-        final int unit = TypedValue.COMPLEX_UNIT_SP;
-
-        final AppCompatTextView granularityTextView = new AppCompatTextView(getActivity());
-        granularityTextView.setAutoSizeTextTypeUniformWithConfiguration(
-                minTextSize, maxTextSize, granularity, unit);
-
-        final AppCompatTextView presetTextView = new AppCompatTextView(getActivity());
-        presetTextView.setAutoSizeTextTypeUniformWithPresetSizes(
-                new int[]{minTextSize, 12, 14, 16, 18, maxTextSize}, unit);
-
-        // The TextViews have been configured differently but the end result should be nearly
-        // identical.
-        final int expectedAutoSizeType = AppCompatTextView.AUTO_SIZE_TEXT_TYPE_UNIFORM;
-        assertEquals(expectedAutoSizeType, granularityTextView.getAutoSizeTextType());
-        assertEquals(expectedAutoSizeType, presetTextView.getAutoSizeTextType());
-
-        final int expectedMinTextSizeInPx = Math.round(
-                TypedValue.applyDimension(unit, minTextSize, dm));
-        assertEquals(expectedMinTextSizeInPx, granularityTextView.getAutoSizeMinTextSize());
-        assertEquals(expectedMinTextSizeInPx, presetTextView.getAutoSizeMinTextSize());
-
-        final int expectedMaxTextSizeInPx = Math.round(
-                TypedValue.applyDimension(unit, maxTextSize, dm));
-        assertEquals(expectedMaxTextSizeInPx, granularityTextView.getAutoSizeMaxTextSize());
-        assertEquals(expectedMaxTextSizeInPx, presetTextView.getAutoSizeMaxTextSize());
-
-        // Configured with granularity.
-        assertEquals(Math.round(TypedValue.applyDimension(unit, granularity, dm)),
-                granularityTextView.getAutoSizeStepGranularity());
-        // Configured with preset values, there is no granularity.
-        assertEquals(-1, presetTextView.getAutoSizeStepGranularity());
-
-        // Both TextViews generate exactly the same sizes in pixels to choose from when auto-sizing.
-        assertArrayEquals(
-                granularityTextView.getAutoSizeTextAvailableSizes(),
-                presetTextView.getAutoSizeTextAvailableSizes());
-
-        final String someText = "This is a string";
-        final int widthHeight = 600;
-        // Configure identically and attach to layout.
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                LinearLayout ll = getActivity().findViewById(R.id.layout_textviewtest);
-                ll.removeAllViews();
-                ll.addView(granularityTextView);
-                ll.addView(presetTextView);
-
-                granularityTextView.setText(someText);
-                granularityTextView.setWidth(widthHeight);
-                granularityTextView.setHeight(widthHeight);
-
-                presetTextView.setText(someText);
-                presetTextView.setWidth(widthHeight);
-                presetTextView.setHeight(widthHeight);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertEquals(granularityTextView.getTextSize(), presetTextView.getTextSize(), 0f);
+    @Override
+    protected AppCompatTextView getNewAutoSizeViewInstance() {
+        return new AppCompatTextView(mActivity);
     }
 
     @Test
     public void testAutoSize_notSupportedByEditText() throws Throwable {
-        final AppCompatEditText autoSizeEditText = (AppCompatEditText) getActivity().findViewById(
+        final AppCompatEditText autoSizeEditText = mActivity.findViewById(
                 R.id.edittext_autosize_uniform);
         // Do not force exact height only.
         final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
@@ -133,7 +61,7 @@
                 autoSizeEditText.setLayoutParams(layoutParams);
             }
         });
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.waitForIdleSync();
         final float initialTextSize = autoSizeEditText.getTextSize();
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
@@ -141,870 +69,22 @@
                 autoSizeEditText.setHeight(autoSizeEditText.getHeight() / 4);
             }
         });
-        getInstrumentation().waitForIdleSync();
+        mInstrumentation.waitForIdleSync();
 
         assertEquals(initialTextSize, autoSizeEditText.getTextSize(), 0f);
     }
 
     @Test
-    public void testAutoSizeCallers_setHeight() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, true);
-        // Do not force exact height only.
-        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                200,
-                LinearLayout.LayoutParams.WRAP_CONTENT);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setLayoutParams(layoutParams);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setHeight(autoSizeTextView.getHeight() / 4);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setCompoundDrawables() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        final Drawable drawable = ResourcesCompat.getDrawable(getActivity().getResources(),
-                R.drawable.test_drawable_red, null);
-        drawable.setBounds(0, 0, autoSizeTextView.getWidth() / 3, autoSizeTextView.getHeight() / 3);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setCompoundDrawables(drawable, drawable, drawable, drawable);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setCompoundDrawablesRelative() throws Throwable {
-        if (Build.VERSION.SDK_INT >= 17) {
-            final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                    R.id.textview_autosize_uniform, false);
-            final float initialTextSize = autoSizeTextView.getTextSize();
-            final Drawable drawable = ResourcesCompat.getDrawable(getActivity().getResources(),
-                    R.drawable.test_drawable_red, null);
-            drawable.setBounds(0, 0, autoSizeTextView.getWidth() / 3,
-                    autoSizeTextView.getHeight() / 3);
-            mActivityTestRule.runOnUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    if (Build.VERSION.SDK_INT >= 17) {
-                        autoSizeTextView.setCompoundDrawablesRelative(
-                                drawable, drawable, drawable, drawable);
-                    }
-                }
-            });
-            getInstrumentation().waitForIdleSync();
-
-            assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-        }
-    }
-
-    @Test
-    public void testAutoSizeCallers_setCompoundDrawablePadding() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        // Prepare a larger layout in order not to hit the min value easily.
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setWidth(autoSizeTextView.getWidth() * 2);
-                autoSizeTextView.setHeight(autoSizeTextView.getHeight() * 2);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        // Setup the drawables before setting their padding in order to modify the available
-        // space and trigger a resize.
-        final Drawable drawable = ResourcesCompat.getDrawable(getActivity().getResources(),
-                R.drawable.test_drawable_red, null);
-        drawable.setBounds(0, 0, autoSizeTextView.getWidth() / 4, autoSizeTextView.getHeight() / 4);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setCompoundDrawables(
-                        drawable, drawable, drawable, drawable);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setCompoundDrawablePadding(
-                        autoSizeTextView.getCompoundDrawablePadding() + 10);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setPadding() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setPadding(
-                        autoSizeTextView.getWidth() / 3, autoSizeTextView.getHeight() / 3,
-                        autoSizeTextView.getWidth() / 3, autoSizeTextView.getHeight() / 3);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setPaddingRelative() throws Throwable {
-        if (Build.VERSION.SDK_INT >= 16) {
-            final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                    R.id.textview_autosize_uniform, false);
-            final float initialTextSize = autoSizeTextView.getTextSize();
-
-            mActivityTestRule.runOnUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    if (Build.VERSION.SDK_INT > 16) {
-                        autoSizeTextView.setPaddingRelative(
-                                autoSizeTextView.getWidth() / 3, autoSizeTextView.getHeight() / 3,
-                                autoSizeTextView.getWidth() / 3, autoSizeTextView.getHeight() / 3);
-                    }
-                }
-            });
-            getInstrumentation().waitForIdleSync();
-
-            assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-        }
-    }
-
-    @Test
-    public void testAutoSizeCallers_setTypeface() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setText("The typeface change needs a bit more text then "
-                        + "the default used for this batch of tests in order to get to resize text."
-                        + " The resize function is always called but even with different typefaces "
-                        + "there may not be a need to resize text because it just fits. The longer "
-                        + "the text, the higher the chance for a resize. And here is yet another "
-                        + "sentence to make sure this test is not flaky. Not flaky at all.");
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float initialTextSize = autoSizeTextView.getTextSize();
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                Typeface differentTypeface = Typeface.MONOSPACE;
-                if (autoSizeTextView.getTypeface() == Typeface.MONOSPACE) {
-                    differentTypeface = Typeface.SANS_SERIF;
-                }
-                autoSizeTextView.setTypeface(differentTypeface);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float changedTextSize = autoSizeTextView.getTextSize();
-
-        // Don't really know if it is larger or smaller (depends on the typeface chosen above),
-        // but it should definitely have changed.
-        assertNotEquals(initialTextSize, changedTextSize, 0f);
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setTypeface(autoSizeTextView.getTypeface());
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertEquals(changedTextSize, autoSizeTextView.getTextSize(), 0f);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setLetterSpacing() throws Throwable {
-        if (Build.VERSION.SDK_INT >= 21) {
-            final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                    R.id.textview_autosize_uniform, false);
-            final float initialTextSize = autoSizeTextView.getTextSize();
-
-            mActivityTestRule.runOnUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    if (Build.VERSION.SDK_INT >= 21) {
-                        autoSizeTextView.setLetterSpacing(
-                                autoSizeTextView.getLetterSpacing() * 1.5f + 4.5f);
-                    }
-                }
-            });
-            getInstrumentation().waitForIdleSync();
-            final float changedTextSize = autoSizeTextView.getTextSize();
-
-            assertTrue(changedTextSize < initialTextSize);
-
-            mActivityTestRule.runOnUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    if (Build.VERSION.SDK_INT >= 21) {
-                        autoSizeTextView.setLetterSpacing(autoSizeTextView.getLetterSpacing());
-                    }
-                }
-            });
-            getInstrumentation().waitForIdleSync();
-
-            assertEquals(changedTextSize, autoSizeTextView.getTextSize(), 0f);
-        }
-    }
-
-    @Test
-    public void testAutoSizeCallers_setMaxHeight() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, true);
-        // Do not force exact height only.
-        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                200,
-                LinearLayout.LayoutParams.WRAP_CONTENT);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setLayoutParams(layoutParams);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setMaxHeight(
-                        autoSizeTextView.getHeight() / 4);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setMaxWidth() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, true);
-        // Do not force exact width only.
-        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                LinearLayout.LayoutParams.WRAP_CONTENT,
-                200);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setLayoutParams(layoutParams);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setMaxWidth(
-                        autoSizeTextView.getWidth() / 4);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() != initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setWidth() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, true);
-        // Do not force exact width only.
-        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                LinearLayout.LayoutParams.WRAP_CONTENT,
-                200);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setLayoutParams(layoutParams);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setWidth(
-                        autoSizeTextView.getWidth() / 4);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertTrue(autoSizeTextView.getTextSize() != initialTextSize);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setTextSizeIsNoOp() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        final float initialTextSize = autoSizeTextView.getTextSize();
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setTextSize(initialTextSize + 123f);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertEquals(initialTextSize, autoSizeTextView.getTextSize(), 0f);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setHorizontallyScrolling() throws Throwable {
-        final AppCompatTextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        // Horizontal scrolling is expected to be deactivated for this test.
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setHorizontallyScrolling(true);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        assertTrue(autoSizeTextView.getTextSize() > initialTextSize);
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextView.setHorizontallyScrolling(false);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        Assert.assertEquals(initialTextSize, autoSizeTextView.getTextSize(), 0f);
-    }
-
-    @Test
-    public void testAutoSize_setEllipsize() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_autosize_uniform_predef_sizes);
-        final int initialAutoSizeType = textView.getAutoSizeTextType();
-        final int initialMinTextSize = textView.getAutoSizeMinTextSize();
-        final int initialMaxTextSize = textView.getAutoSizeMaxTextSize();
-        final int initialAutoSizeGranularity = textView.getAutoSizeStepGranularity();
-        final int initialSizes = textView.getAutoSizeTextAvailableSizes().length;
-
-        Assert.assertEquals(null, textView.getEllipsize());
-        // Verify styled attributes.
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM, initialAutoSizeType);
-        assertNotEquals(-1, initialMinTextSize);
-        assertNotEquals(-1, initialMaxTextSize);
-        // Because this TextView has been configured to use predefined sizes.
-        Assert.assertEquals(-1, initialAutoSizeGranularity);
-        assertNotEquals(0, initialSizes);
-
-        final TextUtils.TruncateAt newEllipsizeValue = TextUtils.TruncateAt.END;
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setEllipsize(newEllipsizeValue);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        Assert.assertEquals(newEllipsizeValue, textView.getEllipsize());
-        // Beside the ellipsis no auto-size attribute has changed.
-        Assert.assertEquals(initialAutoSizeType, textView.getAutoSizeTextType());
-        Assert.assertEquals(initialMinTextSize, textView.getAutoSizeMinTextSize());
-        Assert.assertEquals(initialMaxTextSize, textView.getAutoSizeMaxTextSize());
-        Assert.assertEquals(initialAutoSizeGranularity, textView.getAutoSizeStepGranularity());
-        Assert.assertEquals(initialSizes, textView.getAutoSizeTextAvailableSizes().length);
-    }
-
-    @Test
-    public void testEllipsize_setAutoSize() throws Throwable {
-        final AppCompatTextView textView =
-                (AppCompatTextView) getActivity().findViewById(R.id.textview_text);
-        final TextUtils.TruncateAt newEllipsizeValue = TextUtils.TruncateAt.END;
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setEllipsize(newEllipsizeValue);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        Assert.assertEquals(newEllipsizeValue, textView.getEllipsize());
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-        Assert.assertEquals(-1, textView.getAutoSizeMinTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeMaxTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeStepGranularity());
-        Assert.assertEquals(0, textView.getAutoSizeTextAvailableSizes().length);
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeWithDefaults(
-                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        Assert.assertEquals(newEllipsizeValue, textView.getEllipsize());
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
-                textView.getAutoSizeTextType());
-        // The auto-size defaults have been used.
-        assertNotEquals(-1, textView.getAutoSizeMinTextSize());
-        assertNotEquals(-1, textView.getAutoSizeMaxTextSize());
-        assertNotEquals(-1, textView.getAutoSizeStepGranularity());
-        assertNotEquals(0, textView.getAutoSizeTextAvailableSizes().length);
-    }
-
-    @Test
-    public void testAutoSizeUniform_obtainStyledAttributesUsingPredefinedSizes() {
-        DisplayMetrics m = getActivity().getResources().getDisplayMetrics();
-        final AppCompatTextView autoSizeTextViewUniform =
-                (AppCompatTextView) getActivity().findViewById(
-                        R.id.textview_autosize_uniform_predef_sizes);
-
-        // In arrays.xml predefined the step sizes as: 5px, 11dip, 19sp, 29pt, 43mm and 53in.
-        // TypedValue can not use the math library and instead rounds the value by adding
-        // 0.5f when obtaining styled attributes. Check TypedValue#complexToDimensionPixelSize(...)
-        int[] expectedSizesInPx = new int[] {
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 5f, m)),
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 11f, m)),
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 19f, m)),
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 29f, m)),
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 43f, m)),
-                (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, 53f, m))};
-
-        boolean containsValueFromExpectedSizes = false;
-        final int textSize = (int) autoSizeTextViewUniform.getTextSize();
-        for (int i = 0; i < expectedSizesInPx.length; i++) {
-            if (expectedSizesInPx[i] == textSize) {
-                containsValueFromExpectedSizes = true;
-                break;
-            }
-        }
-        assertTrue(containsValueFromExpectedSizes);
-    }
-
-    @Test
-    public void testAutoSizeUniform_obtainStyledAttributesPredefinedSizesFiltering() {
-        AppCompatTextView autoSizeTextViewUniform = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_autosize_uniform_predef_sizes_redundant_values);
-
-        // In arrays.xml predefined the step sizes as: 40px, 10px, 10px, 10px, 0dp.
-        final int[] expectedSizes = new int[] {10, 40};
-        assertArrayEquals(expectedSizes, autoSizeTextViewUniform.getAutoSizeTextAvailableSizes());
-    }
-
-    @Test
-    public void testAutoSizeUniform_predefinedSizesFilteringAndSorting() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_text);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-
-        final int[] predefinedSizes = new int[] {400, 0, 10, 40, 10, 10, 0, 0};
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeUniformWithPresetSizes(
-                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        assertArrayEquals(new int[] {10, 40, 400}, textView.getAutoSizeTextAvailableSizes());
-    }
-
-    @Test(expected = NullPointerException.class)
-    public void testAutoSizeUniform_predefinedSizesNullArray() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_text);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-
-        final int[] predefinedSizes = null;
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeUniformWithPresetSizes(
-                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-    }
-
-    @Test
-    public void testAutoSizeUniform_predefinedSizesEmptyArray() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_text);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeWithDefaults(
-                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        final int[] defaultSizes = textView.getAutoSizeTextAvailableSizes();
-        assertNotNull(defaultSizes);
-        assertTrue(defaultSizes.length > 0);
-
-        final int[] predefinedSizes = new int[0];
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeUniformWithPresetSizes(
-                        predefinedSizes, TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        final int[] newSizes = textView.getAutoSizeTextAvailableSizes();
-        assertNotNull(defaultSizes);
-        assertArrayEquals(defaultSizes, newSizes);
-    }
-
-    @Test
-    public void testAutoSizeUniform_buildsSizes() throws Throwable {
-        final AppCompatTextView autoSizeTextViewUniform =
-                (AppCompatTextView) getActivity().findViewById(
-                        R.id.textview_autosize_uniform);
-
-        // Verify that the interval limits are both included.
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextViewUniform
-                        .setAutoSizeTextTypeUniformWithConfiguration(10, 20, 2,
-                                TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        assertArrayEquals(
-                new int[] {10, 12, 14, 16, 18, 20},
-                autoSizeTextViewUniform.getAutoSizeTextAvailableSizes());
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextViewUniform
-                        .setAutoSizeTextTypeUniformWithConfiguration(
-                                autoSizeTextViewUniform.getAutoSizeMinTextSize(),
-                                19,
-                                autoSizeTextViewUniform.getAutoSizeStepGranularity(),
-                                TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        assertArrayEquals(
-                new int[] {10, 12, 14, 16, 18},
-                autoSizeTextViewUniform.getAutoSizeTextAvailableSizes());
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                autoSizeTextViewUniform
-                        .setAutoSizeTextTypeUniformWithConfiguration(
-                                autoSizeTextViewUniform.getAutoSizeMinTextSize(),
-                                21,
-                                autoSizeTextViewUniform.getAutoSizeStepGranularity(),
-                                TypedValue.COMPLEX_UNIT_PX);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        assertArrayEquals(
-                new int[] {10, 12, 14, 16, 18, 20},
-                autoSizeTextViewUniform.getAutoSizeTextAvailableSizes());
-    }
-
-    @Test
-    public void testAutoSizeUniform_getSetAutoSizeTextDefaults() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-        // Min/Max/Granularity values for auto-sizing are 0 because they are not used.
-        Assert.assertEquals(-1, textView.getAutoSizeMinTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeMaxTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeStepGranularity());
-
-        textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
-                textView.getAutoSizeTextType());
-        // Min/Max default values for auto-sizing XY have been loaded.
-        final int minSize = textView.getAutoSizeMinTextSize();
-        final int maxSize = textView.getAutoSizeMaxTextSize();
-        assertTrue(0 < minSize);
-        assertTrue(minSize < maxSize);
-        assertNotEquals(0, textView.getAutoSizeStepGranularity());
-
-        textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-        // Min/Max values for auto-sizing XY have been cleared.
-        Assert.assertEquals(-1, textView.getAutoSizeMinTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeMaxTextSize());
-        Assert.assertEquals(-1, textView.getAutoSizeStepGranularity());
-    }
-
-    @Test
-    public void testAutoSizeUniform_getSetAutoSizeStepGranularity() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-        final int initialValue = -1;
-        Assert.assertEquals(initialValue, textView.getAutoSizeStepGranularity());
-
-        textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
-                textView.getAutoSizeTextType());
-        final int defaultValue = 1; // 1px.
-        // If the auto-size type is AUTO_SIZE_TEXT_TYPE_UNIFORM then it means textView went through
-        // the auto-size setup and given that 0 is an invalid value it changed it to the default.
-        Assert.assertEquals(defaultValue, textView.getAutoSizeStepGranularity());
-
-        final int newValue = 33;
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                textView.getAutoSizeMinTextSize(),
-                textView.getAutoSizeMaxTextSize(),
-                newValue,
-                TypedValue.COMPLEX_UNIT_PX);
-        Assert.assertEquals(newValue, textView.getAutoSizeStepGranularity());
-    }
-
-    @Test
-    public void testAutoSizeUniform_getSetAutoSizeMinTextSize() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
-                textView.getAutoSizeTextType());
-        final int minSize = textView.getAutoSizeMinTextSize();
-        assertNotEquals(0, minSize);
-        final int maxSize = textView.getAutoSizeMaxTextSize();
-        assertNotEquals(0, maxSize);
-
-        // This is just a test check to verify the next assertions. If this fails it is a problem
-        // of this test setup (we need at least 2 units).
-        assertTrue((maxSize - minSize) > 1);
-        final int newMinSize = maxSize - 1;
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                newMinSize,
-                textView.getAutoSizeMaxTextSize(),
-                textView.getAutoSizeStepGranularity(),
-                TypedValue.COMPLEX_UNIT_PX);
-
-        Assert.assertEquals(newMinSize, textView.getAutoSizeMinTextSize());
-        // Max size has not changed.
-        Assert.assertEquals(maxSize, textView.getAutoSizeMaxTextSize());
-
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                newMinSize,
-                newMinSize + 10,
-                textView.getAutoSizeStepGranularity(),
-                TypedValue.COMPLEX_UNIT_SP);
-
-        // It does not matter which unit has been used to set the min size, the getter always
-        // returns it in pixels.
-        Assert.assertEquals(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
-                newMinSize, getActivity().getResources().getDisplayMetrics())),
-                        textView.getAutoSizeMinTextSize());
-    }
-
-    @Test(expected = IllegalArgumentException.class)
-    public void testAutoSizeUniform_throwsException_whenMaxLessThanMin() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                10, 9, 1, TypedValue.COMPLEX_UNIT_SP);
-    }
-
-    @Test(expected = IllegalArgumentException.class)
-    public void testAutoSizeUniform_throwsException_minLessThanZero() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                -1, 9, 1, TypedValue.COMPLEX_UNIT_SP);
-    }
-
-    @Test(expected = IllegalArgumentException.class)
-    public void testAutoSizeUniform_throwsException_maxLessThanZero() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                10, -1, 1, TypedValue.COMPLEX_UNIT_SP);
-    }
-
-    @Test(expected = IllegalArgumentException.class)
-    public void testAutoSizeUniform_throwsException_granularityLessThanZero() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                10, 20, -1, TypedValue.COMPLEX_UNIT_SP);
-    }
-
-    @Test
-    public void testAutoSizeUniform_getSetAutoSizeMaxTextSize() {
-        final AppCompatTextView textView = new AppCompatTextView(getActivity());
-        textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM,
-                textView.getAutoSizeTextType());
-        final int minSize = textView.getAutoSizeMinTextSize();
-        assertNotEquals(0, minSize);
-        final int maxSize = textView.getAutoSizeMaxTextSize();
-        assertNotEquals(0, maxSize);
-
-        final int newMaxSize = maxSize + 11;
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                textView.getAutoSizeMinTextSize(),
-                newMaxSize,
-                textView.getAutoSizeStepGranularity(),
-                TypedValue.COMPLEX_UNIT_PX);
-
-        Assert.assertEquals(newMaxSize, textView.getAutoSizeMaxTextSize());
-        // Min size has not changed.
-        Assert.assertEquals(minSize, textView.getAutoSizeMinTextSize());
-        textView.setAutoSizeTextTypeUniformWithConfiguration(
-                textView.getAutoSizeMinTextSize(),
-                newMaxSize,
-                textView.getAutoSizeStepGranularity(),
-                TypedValue.COMPLEX_UNIT_SP);
-        // It does not matter which unit has been used to set the max size, the getter always
-        // returns it in pixels.
-        Assert.assertEquals(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
-                newMaxSize, getActivity().getResources().getDisplayMetrics())),
-                        textView.getAutoSizeMaxTextSize());
-    }
-
-    @Test
-    public void testAutoSizeUniform_autoSizeCalledWhenTypeChanged() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) getActivity().findViewById(
-                R.id.textview_text);
-        // Make sure we pick an already inflated non auto-sized text view.
-        Assert.assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE,
-                textView.getAutoSizeTextType());
-        // Set the text size to a very low value in order to prepare for auto-size.
-        final int customTextSize = 3;
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, customTextSize);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        Assert.assertEquals(customTextSize, textView.getTextSize(), 0f);
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeWithDefaults(
-                        TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        // The size of the text should have changed.
-        assertNotEquals(customTextSize, textView.getTextSize(), 0f);
-    }
-
-    @Test
-    public void testAutoSizeCallers_setTextSizeChangesSizeWhenAutoSizeDisabled() throws Throwable {
-        final AppCompatTextView textView = (AppCompatTextView) prepareAndRetrieveAutoSizeTestData(
-                R.id.textview_autosize_uniform, false);
-        // Disable auto-size.
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setAutoSizeTextTypeWithDefaults(TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-        final float newTextSizeInPx = 123f;
-        assertNotEquals(newTextSizeInPx, textView.getTextSize(), 0f);
-
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSizeInPx);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        assertEquals(newTextSizeInPx, textView.getTextSize(), 0f);
-    }
-
-    /**
-     * Some TextView attributes require non-fixed width and/or layout height. This function removes
-     * all other existing views from the layout leaving only one auto-size TextView (for exercising
-     * the auto-size behavior) which has been set up to suit the test needs.
-     *
-     * @param viewId The id of the view to prepare.
-     * @param shouldWrapLayoutContent Specifies if the layout params should wrap content
-     *
-     * @return a TextView configured for auto size tests.
-     */
-    private AppCompatTextView prepareAndRetrieveAutoSizeTestData(final int viewId,
-            final boolean shouldWrapLayoutContent) throws Throwable {
-        mActivityTestRule.runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                LinearLayout ll = (LinearLayout) getActivity().findViewById(
-                        android.support.v7.appcompat.test.R.id.layout_textviewtest);
-                AppCompatTextView targetedTextView =
-                        (AppCompatTextView) getActivity().findViewById(viewId);
-                ll.removeAllViews();
-                ll.addView(targetedTextView);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        final AppCompatTextView textView = getActivity().findViewById(viewId);
-        if (shouldWrapLayoutContent) {
-            // Do not force exact width or height.
-            final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                    LinearLayout.LayoutParams.WRAP_CONTENT,
-                    LinearLayout.LayoutParams.WRAP_CONTENT);
-            mActivityTestRule.runOnUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    textView.setLayoutParams(layoutParams);
-                }
-            });
-            getInstrumentation().waitForIdleSync();
-        }
-
-        return textView;
-    }
-
-    @Test
     public void testAutoSizeWithMaxLines_shouldNotThrowException() throws Throwable {
         // the layout contains an instance of CustomTextViewWithTransformationMethod
-        final AppCompatTextView textView = (AppCompatTextView) mActivityTestRule.getActivity()
+        final AppCompatTextView textView = (AppCompatTextView) mActivity
                 .getLayoutInflater().inflate(R.layout.textview_autosize_maxlines, null);
         assertTrue(textView instanceof CustomTextViewWithTransformationMethod);
         // Method added in API 16.
         if (Build.VERSION.SDK_INT >= 16) {
             assertEquals(1, textView.getMaxLines());
         }
-        assertEquals(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM, textView.getAutoSizeTextType());
+        assertEquals(TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM, textView.getAutoSizeTextType());
         assertTrue(textView.getTransformationMethod() instanceof SingleLineTransformationMethod);
     }
 
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewTest.java b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewTest.java
index d1b00ad..dd0c146 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/AppCompatTextViewTest.java
@@ -24,6 +24,7 @@
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 
+import android.content.pm.PackageManager;
 import android.content.res.ColorStateList;
 import android.graphics.Color;
 import android.graphics.Typeface;
@@ -244,4 +245,19 @@
 
         assertNotEquals(Typeface.DEFAULT, textView.getTypeface());
     }
+
+    @Test
+    @UiThreadTest
+    public void testSetTextAppearance_resetTypeface() throws PackageManager.NameNotFoundException {
+        TextView textView = mContainer.findViewById(R.id.textview_simple);
+
+        TextViewCompat.setTextAppearance(textView, R.style.TextView_SansSerif);
+        Typeface firstTypeface = textView.getTypeface();
+
+        TextViewCompat.setTextAppearance(textView, R.style.TextView_Serif);
+        Typeface secondTypeface = textView.getTypeface();
+        assertNotNull(firstTypeface);
+        assertNotNull(secondTypeface);
+        assertNotEquals(firstTypeface, secondTypeface);
+    }
 }
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/ListPopupWindowTest.java b/v7/appcompat/tests/src/android/support/v7/widget/ListPopupWindowTest.java
index 907e653..2681d0f 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/ListPopupWindowTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/ListPopupWindowTest.java
@@ -29,6 +29,7 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doCallRealMethod;
 import static org.mockito.Mockito.eq;
@@ -46,7 +47,8 @@
 import android.support.test.filters.FlakyTest;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
-import android.support.v7.app.BaseInstrumentationTestCase;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.appcompat.test.R;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
@@ -60,9 +62,16 @@
 import android.widget.TextView;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class ListPopupWindowTest extends BaseInstrumentationTestCase<PopupTestActivity> {
+@RunWith(AndroidJUnit4.class)
+public class ListPopupWindowTest {
+    @Rule
+    public final ActivityTestRule<PopupTestActivity> mActivityTestRule =
+            new ActivityTestRule<>(PopupTestActivity.class);
+
     private FrameLayout mContainer;
 
     private Button mButton;
@@ -86,15 +95,11 @@
         }
     }
 
-    public ListPopupWindowTest() {
-        super(PopupTestActivity.class);
-    }
-
     @Before
     public void setUp() throws Exception {
         final PopupTestActivity activity = mActivityTestRule.getActivity();
-        mContainer = (FrameLayout) activity.findViewById(R.id.container);
-        mButton = (Button) mContainer.findViewById(R.id.test_button);
+        mContainer = activity.findViewById(R.id.container);
+        mButton = mContainer.findViewById(R.id.test_button);
         mItemClickListener = new PopupItemClickListener();
     }
 
@@ -177,9 +182,14 @@
         Builder popupBuilder = new Builder().setModal(setupAsModal).withDismissListener();
         popupBuilder.wireToActionButton();
 
+        final View.OnClickListener mockContainerClickListener = mock(View.OnClickListener.class);
         // Also register a click listener on the top-level container
-        View.OnClickListener mockContainerClickListener = mock(View.OnClickListener.class);
-        mContainer.setOnClickListener(mockContainerClickListener);
+        mActivityTestRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mContainer.setOnClickListener(mockContainerClickListener);
+            }
+        });
 
         onView(withId(R.id.test_button)).perform(click());
         assertTrue("Popup window showing", mListPopupWindow.isShowing());
@@ -262,7 +272,7 @@
 
         // Verify that our menu item click listener hasn't been called yet
         verify(popupBuilder.mOnItemClickListener, never()).onItemClick(
-                any(AdapterView.class), any(View.class), any(int.class), any(int.class));
+                any(AdapterView.class), any(View.class), any(int.class), anyLong());
 
         final View mainDecorView = mActivityTestRule.getActivity().getWindow().getDecorView();
         onView(withText("Charlie"))
@@ -272,7 +282,7 @@
         // position. Note that we use any() for other parameters, as we don't want to tie ourselves
         // to the specific implementation details of how ListPopupWindow displays its content.
         verify(popupBuilder.mOnItemClickListener, times(1)).onItemClick(
-                any(AdapterView.class), any(View.class), eq(2), any(int.class));
+                any(AdapterView.class), any(View.class), eq(2), anyLong());
 
         // Our item click listener also dismisses the popup
         assertFalse("Popup window not showing after click", mListPopupWindow.isShowing());
@@ -289,7 +299,7 @@
 
         // Verify that our menu item click listener hasn't been called yet
         verify(popupBuilder.mOnItemClickListener, never()).onItemClick(
-                any(AdapterView.class), any(View.class), any(int.class), any(int.class));
+                any(AdapterView.class), any(View.class), any(int.class), anyLong());
 
         mActivityTestRule.runOnUiThread(new Runnable() {
             @Override
@@ -302,7 +312,7 @@
         // position. Note that we use any() for other parameters, as we don't want to tie ourselves
         // to the specific implementation details of how ListPopupWindow displays its content.
         verify(popupBuilder.mOnItemClickListener, times(1)).onItemClick(
-                any(AdapterView.class), any(View.class), eq(1), any(int.class));
+                any(AdapterView.class), any(View.class), eq(1), anyLong());
         // Our item click listener also dismisses the popup
         assertFalse("Popup window not showing after click", mListPopupWindow.isShowing());
     }
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/PopupMenuTest.java b/v7/appcompat/tests/src/android/support/v7/widget/PopupMenuTest.java
index 8186e3a..7be67a6 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/PopupMenuTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/PopupMenuTest.java
@@ -51,8 +51,9 @@
 import android.support.test.filters.FlakyTest;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v4.view.MenuItemCompat;
-import android.support.v7.app.BaseInstrumentationTestCase;
 import android.support.v7.appcompat.test.R;
 import android.text.TextUtils;
 import android.view.MenuInflater;
@@ -69,9 +70,16 @@
 import org.hamcrest.TypeSafeMatcher;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
-public class PopupMenuTest extends BaseInstrumentationTestCase<PopupTestActivity> {
+@RunWith(AndroidJUnit4.class)
+public class PopupMenuTest {
+    @Rule
+    public final ActivityTestRule<PopupTestActivity> mActivityTestRule =
+            new ActivityTestRule<>(PopupTestActivity.class);
+
     // Since PopupMenu doesn't expose any access to the underlying
     // implementation (like ListPopupWindow.getListView), we're relying on the
     // class name of the list view from MenuPopupWindow that is being used
@@ -89,15 +97,11 @@
 
     private View mMainDecorView;
 
-    public PopupMenuTest() {
-        super(PopupTestActivity.class);
-    }
-
     @Before
     public void setUp() throws Exception {
         final PopupTestActivity activity = mActivityTestRule.getActivity();
-        mContainer = (FrameLayout) activity.findViewById(R.id.container);
-        mButton = (Button) mContainer.findViewById(R.id.test_button);
+        mContainer = activity.findViewById(R.id.container);
+        mButton = mContainer.findViewById(R.id.test_button);
         mResources = mActivityTestRule.getActivity().getResources();
         mMainDecorView = mActivityTestRule.getActivity().getWindow().getDecorView();
     }
diff --git a/v7/appcompat/tests/src/android/support/v7/widget/TintResourcesTest.java b/v7/appcompat/tests/src/android/support/v7/widget/TintResourcesTest.java
index eb2d462..700fe26 100644
--- a/v7/appcompat/tests/src/android/support/v7/widget/TintResourcesTest.java
+++ b/v7/appcompat/tests/src/android/support/v7/widget/TintResourcesTest.java
@@ -22,26 +22,31 @@
 import android.content.res.Resources;
 import android.graphics.drawable.Drawable;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.app.AppCompatActivity;
-import android.support.v7.app.BaseInstrumentationTestCase;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
-public class TintResourcesTest extends BaseInstrumentationTestCase<AppCompatActivity> {
-
-    public TintResourcesTest() {
-        super(AppCompatActivity.class);
-    }
+@RunWith(AndroidJUnit4.class)
+public class TintResourcesTest {
+    @Rule
+    public final ActivityTestRule<AppCompatActivity> mActivityTestRule =
+            new ActivityTestRule<>(AppCompatActivity.class);
 
     @Test
     public void testTintResourcesDelegateBackToOriginalResources() {
-        final TestResources testResources = new TestResources(getActivity().getResources());
+        final TestResources testResources =
+                new TestResources(mActivityTestRule.getActivity().getResources());
         // First make sure that the flag is false
         assertFalse(testResources.wasGetDrawableCalled());
 
         // Now wrap in a TintResources instance and get a Drawable
-        final Resources tintResources = new TintResources(getActivity(), testResources);
+        final Resources tintResources =
+                new TintResources(mActivityTestRule.getActivity(), testResources);
         tintResources.getDrawable(android.R.drawable.ic_delete);
 
         // ...and assert that the flag was flipped
diff --git a/v7/cardview/build.gradle b/v7/cardview/build.gradle
index b5a08ef..e839aee 100644
--- a/v7/cardview/build.gradle
+++ b/v7/cardview/build.gradle
@@ -2,7 +2,7 @@
 archivesBaseName = 'cardview-v7'
 
 dependencies {
-    compile project(':support-annotations')
+    api project(':support-annotations')
 }
 
 android {
diff --git a/v7/cardview/lint-baseline.xml b/v7/cardview/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v7/cardview/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v7/cardview/src/android/support/v7/widget/CardView.java b/v7/cardview/src/android/support/v7/widget/CardView.java
index fab9453..3df45d9 100644
--- a/v7/cardview/src/android/support/v7/widget/CardView.java
+++ b/v7/cardview/src/android/support/v7/widget/CardView.java
@@ -196,6 +196,9 @@
                     widthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minWidth,
                             MeasureSpec.getSize(widthMeasureSpec)), widthMode);
                     break;
+                case MeasureSpec.UNSPECIFIED:
+                    // Do nothing
+                    break;
             }
 
             final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
@@ -206,6 +209,9 @@
                     heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minHeight,
                             MeasureSpec.getSize(heightMeasureSpec)), heightMode);
                     break;
+                case MeasureSpec.UNSPECIFIED:
+                    // Do nothing
+                    break;
             }
             super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         } else {
diff --git a/v7/gridlayout/build.gradle b/v7/gridlayout/build.gradle
index 63d149f..c66848f 100644
--- a/v7/gridlayout/build.gradle
+++ b/v7/gridlayout/build.gradle
@@ -2,13 +2,13 @@
 archivesBaseName = 'gridlayout-v7'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-core-ui')
+    api project(':support-compat')
+    api project(':support-core-ui')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/v7/gridlayout/lint-baseline.xml b/v7/gridlayout/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v7/gridlayout/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v7/gridlayout/tests/AndroidManifest.xml b/v7/gridlayout/tests/AndroidManifest.xml
index 14946c9..e970897 100644
--- a/v7/gridlayout/tests/AndroidManifest.xml
+++ b/v7/gridlayout/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.v7.gridlayout.test">
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                  android.support.test.espresso, android.support.test.espresso.idling" />
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application>
         <activity android:name="android.support.v7.widget.GridLayoutTestActivity"/>
diff --git a/v7/mediarouter/build.gradle b/v7/mediarouter/build.gradle
index d0448dd..eabc5e3 100644
--- a/v7/mediarouter/build.gradle
+++ b/v7/mediarouter/build.gradle
@@ -2,10 +2,16 @@
 archivesBaseName = 'mediarouter-v7'
 
 dependencies {
-    compile project(":support-appcompat-v7")
-    compile project(":support-palette-v7")
+    api project(":support-appcompat-v7")
+    api project(":support-palette-v7")
 
-    androidTestCompile libs.test_runner
+    androidTestImplementation (libs.test_runner) {
+        exclude module: 'support-annotations'
+    }
+    androidTestImplementation (libs.espresso_core) {
+        exclude module: 'support-annotations'
+    }
+    androidTestImplementation libs.test_rules
 }
 
 android {
diff --git a/v7/mediarouter/lint-baseline.xml b/v7/mediarouter/lint-baseline.xml
new file mode 100644
index 0000000..9ea4e70
--- /dev/null
+++ b/v7/mediarouter/lint-baseline.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="MissingSuperCall"
+        message="Overriding method should call `super.jumpDrawablesToCurrentState`"
+        errorLine1="    public void jumpDrawablesToCurrentState() {"
+        errorLine2="                ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/v7/app/MediaRouteButton.java"
+            line="380"
+            column="17"/>
+    </issue>
+
+    <issue
+        id="LongLogTag"
+        message="The logging tag can be at most 23 characters, was 24 (MediaRouteActionProvider)"
+        errorLine1="            Log.e(TAG, &quot;onCreateActionView: this ActionProvider is already associated &quot; +"
+        errorLine2="                  ~~~">
+        <location
+            file="src/android/support/v7/app/MediaRouteActionProvider.java"
+            line="248"
+            column="19"/>
+    </issue>
+
+</issues>
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_dark.png
index c04e284..f6dd214 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_light.png
index da4c296..6b7bdcd 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_00_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_dark.png
index 9fd99dc..c7fe576 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_light.png
index 6be3008..0a5d6aa 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_01_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_dark.png
index a5946ab..0aadfa3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_light.png
index 1c8a4e1..125fe0b 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_02_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_dark.png
index 1ea1f71..05c48a7 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_light.png
index 3397f14..741e911 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_03_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_dark.png
index 0c211e5..ae4218a 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_light.png
index 620ec69..8b30fab 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_04_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_dark.png
index 4ac4f94..d7aa903 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_light.png
index aee1a31..f7e2f29 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_05_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_dark.png
index 5e99a48..e7871e2 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_light.png
index d357a9f..8c57f63 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_06_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_dark.png
index 7e23799..0041b01 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_light.png
index df0247d..6dbb694 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_07_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_dark.png
index d49c09b..08e1013 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_light.png
index 924212a..5c352c3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_08_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_dark.png
index 4df5079..70532e9 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_light.png
index dfaaef4..9c6ba30 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_09_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_dark.png
index 8b2499e..9ba3b5f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_light.png
index 47482ab..bd4bb22 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_10_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_dark.png
index 373aad0..2156127 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_light.png
index b8d035e..b417a9f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_11_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_dark.png
index f813902..9bf633e 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_light.png
index 0952676..ba51811 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_12_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_dark.png
index 3825e0a..756a53c 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_light.png
index c493860..4705dca 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_13_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_dark.png
index 12da4da..50e4ea3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_light.png
index 5420e91..bc6724f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_14_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_dark.png
index 8bb448e..9e3b410 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_light.png
index 6c7fb96..2f18abd 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_15_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_dark.png
index e000188..de81133 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_light.png
index 2afcf5b..b80b191 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_16_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_dark.png
index ead72cb..48aba3d 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_light.png
index 5e91f50..ca34d5b 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_17_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_dark.png
index 1939ceb..e9957b3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_light.png
index 3d6105c..a5d384f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_18_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_dark.png
index 4be02d4..ddc6297 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_light.png
index 1b18aad..28ab684 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_19_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_dark.png
index 25afe1a..51e7f75 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_light.png
index 219ac25..4aa3ca3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_20_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_dark.png
index 1ac72a3..9caecde 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_light.png
index 9b0645d..1b8d0b6 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_21_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_dark.png
index 62308f2..400be3c 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_light.png
index 6bab08f..c14f1bf 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_22_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_dark.png
new file mode 100644
index 0000000..4e18b46
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_light.png
new file mode 100644
index 0000000..c4c2c00
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_23_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_dark.png
new file mode 100644
index 0000000..98fae44
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_light.png
new file mode 100644
index 0000000..d64c289
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_24_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_dark.png
new file mode 100644
index 0000000..91f9327
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_light.png
new file mode 100644
index 0000000..f5e1f69
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_25_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_dark.png
new file mode 100644
index 0000000..3e6fafd
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_light.png
new file mode 100644
index 0000000..ae2bd87
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_26_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_dark.png
new file mode 100644
index 0000000..f73a1f8
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_light.png
new file mode 100644
index 0000000..78c1069
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_27_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_dark.png
new file mode 100644
index 0000000..562b803
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_light.png
new file mode 100644
index 0000000..ddfba02
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_28_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_dark.png
new file mode 100644
index 0000000..257f2d2
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_light.png
new file mode 100644
index 0000000..38f5478
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_29_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_dark.png
new file mode 100644
index 0000000..f995af0
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_light.png
new file mode 100644
index 0000000..c50b7f0
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connected_30_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_dark.png
index 7c8b5bc..f6dd214 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_light.png
index 85fe39c..6b7bdcd 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_00_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_dark.png
index b904ed1..c7fe576 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_light.png
index 94bcad9..0a5d6aa 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_01_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_dark.png
index 9c8f73d..0aadfa3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_light.png
index 70ecc18..125fe0b 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_02_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_dark.png
index 9cc01b3..05c48a7 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_light.png
index 6dc67ec..741e911 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_03_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_dark.png
index 8692da8..ae4218a 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_light.png
index 92061ac..8b30fab 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_04_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_dark.png
index 93af29a..d7aa903 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_light.png
index 3535d6f..f7e2f29 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_05_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_dark.png
index 7a17cdb..e7871e2 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_light.png
index 101207f..8c57f63 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_06_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_dark.png
index 186133e..0041b01 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_light.png
index 1e3afe1..6dbb694 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_07_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_dark.png
index 34cb511..08e1013 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_light.png
index 79f84ca..5c352c3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_08_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_dark.png
index 736bad8..70532e9 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_light.png
index 0fe61a4..9c6ba30 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_09_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_dark.png
index 22862e3..9ba3b5f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_light.png
index 6a310bd..bd4bb22 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_10_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_dark.png
index 3eb3fb4..f3570f4 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_light.png
index 3bc4947..65a403e 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_11_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_dark.png
index 58a6f9e..f644bfd 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_light.png
index f017cc6..c7d6048 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_12_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_dark.png
index ef3f046..6e0d558 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_light.png
index cf52855..f3bc48d 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_13_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_dark.png
index f701696..14d8f8e 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_light.png
index 26587e1..98b90e5 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_14_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_dark.png
index 7d3342c..83234a7 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_light.png
index e6ea555..47d452f 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_15_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_dark.png
index aa1f673..b81cf5a 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_light.png
index 5ad2aa3..20d08b4 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_16_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_dark.png
index 4c412a8..6feb3f1 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_light.png
index b919359..e6ae8b3 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_17_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_dark.png
index a27e3d7..0b0fc08 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_light.png
index efe5264..c2a16ac 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_18_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_dark.png
index a048045..a3598cc 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_light.png
index 8c31541..846d16d 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_19_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_dark.png
index fbb59c5..2070455 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_light.png
index 0bf03e2..ae6db13 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_20_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_dark.png
index 6cfa4c4..7f3828a 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_light.png
index 49f0f63..aaccc73 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_21_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_dark.png
index 6fdd92f..5c8ced9 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_dark.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_light.png
index 63fd45f..ad01b9e 100644
--- a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_light.png
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_22_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_dark.png
new file mode 100644
index 0000000..ce31dd3
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_light.png
new file mode 100644
index 0000000..9ef78e4
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_23_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_dark.png
new file mode 100644
index 0000000..a7c2cdb
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_light.png
new file mode 100644
index 0000000..e7c5bea
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_24_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_dark.png
new file mode 100644
index 0000000..ecad0d4
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_light.png
new file mode 100644
index 0000000..5fa5923
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_25_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_dark.png
new file mode 100644
index 0000000..f687e25
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_light.png
new file mode 100644
index 0000000..9c06db8
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_26_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_dark.png
new file mode 100644
index 0000000..90225ba
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_light.png
new file mode 100644
index 0000000..19697de
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_27_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_dark.png
new file mode 100644
index 0000000..d37ec21
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_light.png
new file mode 100644
index 0000000..21840bf
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_28_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_dark.png
new file mode 100644
index 0000000..5445e3a
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_light.png
new file mode 100644
index 0000000..2337c65
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_29_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_dark.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_dark.png
new file mode 100644
index 0000000..f6dd214
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_light.png b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_light.png
new file mode 100644
index 0000000..6b7bdcd
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xhdpi/ic_mr_button_connecting_30_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_dark.png
index e3fcc5a..0db679e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_light.png
index 8915e73..51c6051 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_00_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_dark.png
index 1f7c6a7..c083914 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_light.png
index e2f859a..c3c3caf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_01_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_dark.png
index 5d7377d..fc444cf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_light.png
index e87e963..abd6377 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_02_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_dark.png
index 5d98ca9..6dbd1da 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_light.png
index 5dd1728..d2e7108 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_03_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_dark.png
index 5768bf6..d9f596b 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_light.png
index 33dcad3..4f32e1a 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_04_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_dark.png
index 03b6d06..c568e04 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_light.png
index 04de404..ed20dd9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_05_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_dark.png
index b145e78..bbe39e7 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_light.png
index 7f6b343..1edc15f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_06_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_dark.png
index f553b98..78aebaf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_light.png
index 3c6d7ec..b5a6a4f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_07_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_dark.png
index bc96ec5..44b91ce 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_light.png
index 78d7707..85f66f9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_08_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_dark.png
index 1fc99d3..51ea34b 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_light.png
index cecbb05..952de04 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_09_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_dark.png
index 85c3404..8b1aa21 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_light.png
index 9504282..534bcc0 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_10_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_dark.png
index de5411f..f666b35 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_light.png
index 75ac2b5..145a8fb 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_11_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_dark.png
index bc5016f..edeb132 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_light.png
index e80a01a..9da2b60 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_12_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_dark.png
index d3bc15e..ab80aa9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_light.png
index 2aec231..115efe4 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_13_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_dark.png
index 0dc7afa..8c0cc31 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_light.png
index f6b8124..e6ae6fc 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_14_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_dark.png
index 428f2a5..b8816c9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_light.png
index 9b07aee..bd42931 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_15_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_dark.png
index 92b87f3..10d5b7f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_light.png
index d3aa0ec..303a0fe 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_16_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_dark.png
index c8f47f3..3c2a655 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_light.png
index 0ffd70c..90debc2 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_17_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_dark.png
index bd6b74d..d3e78a7 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_light.png
index 5a5644a..3a3f991 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_18_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_dark.png
index b9fcf3a..63fad9e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_light.png
index 41904df..d6dd8d4 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_19_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_dark.png
index 7d765c3..890fd5f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_light.png
index 1b38bd1..6b0b5c1 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_20_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_dark.png
index 1947769..9ce1ef1 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_light.png
index 6c01a5f..81710d4 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_21_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_dark.png
index 5d84106..861c080 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_light.png
index c03c7f6..1c4aa21 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_22_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_dark.png
new file mode 100644
index 0000000..59a6b30
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_light.png
new file mode 100644
index 0000000..c6e8fe0
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_23_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_dark.png
new file mode 100644
index 0000000..57b840e
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_light.png
new file mode 100644
index 0000000..bf24050
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_24_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_dark.png
new file mode 100644
index 0000000..01c18c1
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_light.png
new file mode 100644
index 0000000..be9753e
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_25_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_dark.png
new file mode 100644
index 0000000..3f291b1
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_light.png
new file mode 100644
index 0000000..dc1c619
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_26_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_dark.png
new file mode 100644
index 0000000..6504a70
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_light.png
new file mode 100644
index 0000000..a7e0a60
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_27_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_dark.png
new file mode 100644
index 0000000..57b1f3e
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_light.png
new file mode 100644
index 0000000..5c551ec
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_28_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_dark.png
new file mode 100644
index 0000000..238667e
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_light.png
new file mode 100644
index 0000000..ffb8183
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_29_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_dark.png
new file mode 100644
index 0000000..4893f18
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_light.png
new file mode 100644
index 0000000..ac5e156
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connected_30_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_dark.png
index 5e481fb..0db679e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_light.png
index c1ebe58..51c6051 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_00_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_dark.png
index f3c8f71..c083914 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_light.png
index 9a16dda..c3c3caf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_01_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_dark.png
index 17d29bb..fc444cf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_light.png
index 8e17432..abd6377 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_02_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_dark.png
index 72aec70..6dbd1da 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_light.png
index b41b474..d2e7108 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_03_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_dark.png
index 5a9aa0d..d9f596b 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_light.png
index 9b7a3c7..4f32e1a 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_04_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_dark.png
index b0bd59e..c568e04 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_light.png
index f9544ee..ed20dd9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_05_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_dark.png
index 3543c84..bbe39e7 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_light.png
index 9ecc2e4..1edc15f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_06_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_dark.png
index 63a5a16..78aebaf 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_light.png
index 8ae025a..b5a6a4f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_07_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_dark.png
index 2e506e8..44b91ce 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_light.png
index 7c96cc5..85f66f9 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_08_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_dark.png
index aeb7151..51ea34b 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_light.png
index deb6756..952de04 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_09_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_dark.png
index 4f679de..8b1aa21 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_light.png
index 54dbd70..534bcc0 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_10_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_dark.png
index e971a46..1fffa01 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_light.png
index 7bb99d5..0ff7e57 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_11_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_dark.png
index c7dd030..06ac4dc 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_light.png
index 1f081a0..42a86f5 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_12_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_dark.png
index 9da3f8f..0301090 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_light.png
index 38b45ab..4396f0e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_13_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_dark.png
index 6c05acb..e19001b 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_light.png
index 0294d12..2271581 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_14_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_dark.png
index 043096d..5e96208 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_light.png
index 9d9672a..0f69500 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_15_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_dark.png
index 321e868..07e1bd6 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_light.png
index 7d8f491..cde8f19 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_16_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_dark.png
index ecd6c23..b632e95 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_light.png
index 0eb016b..11d5d2e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_17_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_dark.png
index b6d08aa..660d527 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_light.png
index 4df7118..2761ae1 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_18_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_dark.png
index 653754a..0aa3f84 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_light.png
index cf62d75..27d166f 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_19_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_dark.png
index 4fa3be0..ebe527e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_light.png
index ca82881..aeb2a8e 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_20_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_dark.png
index 86b20be..7337af5 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_light.png
index 74521d0..f3f31ef 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_21_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_dark.png
index a646b60..20d9f57 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_dark.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_light.png
index be0b12a..bf8eb77 100644
--- a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_light.png
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_22_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_dark.png
new file mode 100644
index 0000000..56a0e14
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_light.png
new file mode 100644
index 0000000..67425e1
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_23_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_dark.png
new file mode 100644
index 0000000..7c76e19
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_light.png
new file mode 100644
index 0000000..e02f1ed
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_24_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_dark.png
new file mode 100644
index 0000000..f5fdcdd
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_light.png
new file mode 100644
index 0000000..8ce9b81
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_25_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_dark.png
new file mode 100644
index 0000000..a29e443
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_light.png
new file mode 100644
index 0000000..349ca89
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_26_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_dark.png
new file mode 100644
index 0000000..0fc75d5
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_light.png
new file mode 100644
index 0000000..5cbd27c
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_27_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_dark.png
new file mode 100644
index 0000000..0ebb0ac
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_light.png
new file mode 100644
index 0000000..5b514aa
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_28_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_dark.png
new file mode 100644
index 0000000..8e7fe5c
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_light.png
new file mode 100644
index 0000000..efb2c10
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_29_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_dark.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_dark.png
new file mode 100644
index 0000000..0db679e
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_dark.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_light.png b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_light.png
new file mode 100644
index 0000000..51c6051
--- /dev/null
+++ b/v7/mediarouter/res/drawable-xxhdpi/ic_mr_button_connecting_30_light.png
Binary files differ
diff --git a/v7/mediarouter/res/drawable/mr_button_connected_dark.xml b/v7/mediarouter/res/drawable/mr_button_connected_dark.xml
index ddf8c91..c69ba33 100644
--- a/v7/mediarouter/res/drawable/mr_button_connected_dark.xml
+++ b/v7/mediarouter/res/drawable/mr_button_connected_dark.xml
@@ -40,4 +40,12 @@
     <item android:drawable="@drawable/ic_mr_button_connected_20_dark" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connected_21_dark" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connected_22_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_23_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_24_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_25_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_26_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_27_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_28_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_29_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_30_dark" android:duration="42" />
 </animation-list>
diff --git a/v7/mediarouter/res/drawable/mr_button_connected_light.xml b/v7/mediarouter/res/drawable/mr_button_connected_light.xml
index ba0434a..af7224b 100644
--- a/v7/mediarouter/res/drawable/mr_button_connected_light.xml
+++ b/v7/mediarouter/res/drawable/mr_button_connected_light.xml
@@ -40,4 +40,12 @@
     <item android:drawable="@drawable/ic_mr_button_connected_20_light" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connected_21_light" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connected_22_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_23_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_24_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_25_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_26_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_27_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_28_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_29_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connected_30_light" android:duration="42" />
 </animation-list>
diff --git a/v7/mediarouter/res/drawable/mr_button_connecting_dark.xml b/v7/mediarouter/res/drawable/mr_button_connecting_dark.xml
index ba3a673..697f17d 100644
--- a/v7/mediarouter/res/drawable/mr_button_connecting_dark.xml
+++ b/v7/mediarouter/res/drawable/mr_button_connecting_dark.xml
@@ -40,4 +40,12 @@
     <item android:drawable="@drawable/ic_mr_button_connecting_20_dark" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connecting_21_dark" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connecting_22_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_23_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_24_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_25_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_26_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_27_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_28_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_29_dark" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_30_dark" android:duration="42" />
 </animation-list>
diff --git a/v7/mediarouter/res/drawable/mr_button_connecting_light.xml b/v7/mediarouter/res/drawable/mr_button_connecting_light.xml
index c511782..07a135d 100644
--- a/v7/mediarouter/res/drawable/mr_button_connecting_light.xml
+++ b/v7/mediarouter/res/drawable/mr_button_connecting_light.xml
@@ -40,4 +40,12 @@
     <item android:drawable="@drawable/ic_mr_button_connecting_20_light" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connecting_21_light" android:duration="42" />
     <item android:drawable="@drawable/ic_mr_button_connecting_22_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_23_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_24_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_25_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_26_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_27_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_28_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_29_light" android:duration="42" />
+    <item android:drawable="@drawable/ic_mr_button_connecting_30_light" android:duration="42" />
 </animation-list>
diff --git a/v7/mediarouter/res/drawable/mr_button_dark_static.xml b/v7/mediarouter/res/drawable/mr_button_dark_static.xml
deleted file mode 100644
index 20cb447..0000000
--- a/v7/mediarouter/res/drawable/mr_button_dark_static.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:state_enabled="true"
-        android:drawable="@drawable/ic_mr_button_disconnected_dark" />
-    <item android:drawable="@drawable/ic_mr_button_disabled_dark" />
-</selector>
diff --git a/v7/mediarouter/res/drawable/mr_button_light_static.xml b/v7/mediarouter/res/drawable/mr_button_light_static.xml
deleted file mode 100644
index 9d805d1..0000000
--- a/v7/mediarouter/res/drawable/mr_button_light_static.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:state_enabled="true"
-        android:drawable="@drawable/ic_mr_button_disconnected_light" />
-    <item android:drawable="@drawable/ic_mr_button_disabled_light" />
-</selector>
diff --git a/v7/mediarouter/res/values/attrs.xml b/v7/mediarouter/res/values/attrs.xml
index abd5815..e9f20a5 100644
--- a/v7/mediarouter/res/values/attrs.xml
+++ b/v7/mediarouter/res/values/attrs.xml
@@ -21,10 +21,6 @@
              and non-checked / non-checkable indicates
              that media is playing to the local device only. -->
         <attr name="externalRouteEnabledDrawable" format="reference" />
-        <!-- This drawable is a static version of the above animation drawable.
-             In order to speed up inflation, the static drawable is loaded first and
-             the animation drawable will be loaded in a worker thread separately. -->
-        <attr name="externalRouteEnabledDrawableStatic" format="reference" />
         <!-- Tint to apply to the media route button -->
         <attr name="mediaRouteButtonTint" format="color" />
 
diff --git a/v7/mediarouter/res/values/styles.xml b/v7/mediarouter/res/values/styles.xml
index 2611804..e8e00e7 100644
--- a/v7/mediarouter/res/values/styles.xml
+++ b/v7/mediarouter/res/values/styles.xml
@@ -17,13 +17,11 @@
 <resources>
     <style name="Widget.MediaRouter.MediaRouteButton"
             parent="Widget.AppCompat.ActionButton">
-        <item name="externalRouteEnabledDrawableStatic">@drawable/mr_button_dark_static</item>
         <item name="externalRouteEnabledDrawable">@drawable/mr_button_dark</item>
     </style>
 
     <style name="Widget.MediaRouter.Light.MediaRouteButton"
             parent="Widget.AppCompat.Light.ActionButton">
-        <item name="externalRouteEnabledDrawableStatic">@drawable/mr_button_light_static</item>
         <item name="externalRouteEnabledDrawable">@drawable/mr_button_light</item>
     </style>
 
diff --git a/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java b/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java
index 00d15c9..d3f7020 100644
--- a/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java
+++ b/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java
@@ -35,7 +35,7 @@
 import android.support.v7.widget.TooltipCompat;
 import android.util.AttributeSet;
 import android.util.Log;
-import android.util.TypedValue;
+import android.util.SparseArray;
 import android.view.SoundEffectConstants;
 import android.view.View;
 
@@ -91,6 +91,9 @@
 
     private boolean mAttachedToWindow;
 
+    private static final SparseArray<Drawable.ConstantState> sRemoteIndicatorCache =
+            new SparseArray<>(2);
+    private RemoteIndicatorLoader mRemoteIndicatorLoader;
     private Drawable mRemoteIndicator;
     private boolean mRemoteActive;
     private boolean mIsConnecting;
@@ -128,29 +131,25 @@
         TypedArray a = context.obtainStyledAttributes(attrs,
                 R.styleable.MediaRouteButton, defStyleAttr, 0);
         mButtonTint = a.getColorStateList(R.styleable.MediaRouteButton_mediaRouteButtonTint);
-        setRemoteIndicatorDrawable(a.getDrawable(
-                R.styleable.MediaRouteButton_externalRouteEnabledDrawableStatic));
-        final TypedValue value = new TypedValue();
-        a.getValue(R.styleable.MediaRouteButton_externalRouteEnabledDrawable, value);
-        new AsyncTask<Void, Void, Drawable>() {
-            @Override
-            protected Drawable doInBackground(Void... params) {
-                return getContext().getResources().getDrawable(value.resourceId);
-            }
-
-            @Override
-            protected void onPostExecute(Drawable result) {
-                if (result != null) {
-                    setRemoteIndicatorDrawable(result);
-                }
-            }
-        }.execute();
         mMinWidth = a.getDimensionPixelSize(
                 R.styleable.MediaRouteButton_android_minWidth, 0);
         mMinHeight = a.getDimensionPixelSize(
                 R.styleable.MediaRouteButton_android_minHeight, 0);
+        int remoteIndicatorResId = a.getResourceId(
+                R.styleable.MediaRouteButton_externalRouteEnabledDrawable, 0);
         a.recycle();
 
+        if (remoteIndicatorResId != 0) {
+            Drawable.ConstantState remoteIndicatorState =
+                    sRemoteIndicatorCache.get(remoteIndicatorResId);
+            if (remoteIndicatorState != null) {
+                setRemoteIndicatorDrawable(remoteIndicatorState.newDrawable());
+            } else {
+                mRemoteIndicatorLoader = new RemoteIndicatorLoader(remoteIndicatorResId);
+                mRemoteIndicatorLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+            }
+        }
+
         updateContentDescription();
         setClickable(true);
     }
@@ -336,22 +335,40 @@
      * Sets a drawable to use as the remote route indicator.
      */
     public void setRemoteIndicatorDrawable(Drawable d) {
+        if (mRemoteIndicatorLoader != null) {
+            mRemoteIndicatorLoader.cancel(false);
+        }
+
         if (mRemoteIndicator != null) {
             mRemoteIndicator.setCallback(null);
             unscheduleDrawable(mRemoteIndicator);
         }
-        if (mButtonTint != null) {
-            d = DrawableCompat.wrap(d.mutate());
-            DrawableCompat.setTintList(d, mButtonTint);
-        }
-        mRemoteIndicator = d;
         if (d != null) {
+            if (mButtonTint != null) {
+                d = DrawableCompat.wrap(d.mutate());
+                DrawableCompat.setTintList(d, mButtonTint);
+            }
             d.setCallback(this);
             d.setState(getDrawableState());
             d.setVisible(getVisibility() == VISIBLE, false);
         }
+        mRemoteIndicator = d;
 
         refreshDrawableState();
+        if (mAttachedToWindow && mRemoteIndicator != null
+                && mRemoteIndicator.getCurrent() instanceof AnimationDrawable) {
+            AnimationDrawable curDrawable = (AnimationDrawable) mRemoteIndicator.getCurrent();
+            if (mIsConnecting) {
+                if (!curDrawable.isRunning()) {
+                    curDrawable.start();
+                }
+            } else if (mRemoteActive) {
+                if (curDrawable.isRunning()) {
+                    curDrawable.stop();
+                }
+                curDrawable.selectDrawable(curDrawable.getNumberOfFrames() - 1);
+            }
+        }
     }
 
     @Override
@@ -563,4 +580,35 @@
             refreshRoute();
         }
     }
+
+    private final class RemoteIndicatorLoader extends AsyncTask<Void, Void, Drawable> {
+        private final int mResId;
+
+        RemoteIndicatorLoader(int resId) {
+            mResId = resId;
+        }
+
+        @Override
+        protected Drawable doInBackground(Void... params) {
+            return getContext().getResources().getDrawable(mResId);
+        }
+
+        @Override
+        protected void onPostExecute(Drawable remoteIndicator) {
+            cacheAndReset(remoteIndicator);
+            setRemoteIndicatorDrawable(remoteIndicator);
+        }
+
+        @Override
+        protected void onCancelled(Drawable remoteIndicator) {
+            cacheAndReset(remoteIndicator);
+        }
+
+        private void cacheAndReset(Drawable remoteIndicator) {
+            if (remoteIndicator != null) {
+                sRemoteIndicatorCache.put(mResId, remoteIndicator.getConstantState());
+            }
+            mRemoteIndicatorLoader = null;
+        }
+    }
 }
diff --git a/v7/mediarouter/src/android/support/v7/app/MediaRouteChooserDialog.java b/v7/mediarouter/src/android/support/v7/app/MediaRouteChooserDialog.java
index 9f2d396..0ab2eb1 100644
--- a/v7/mediarouter/src/android/support/v7/app/MediaRouteChooserDialog.java
+++ b/v7/mediarouter/src/android/support/v7/app/MediaRouteChooserDialog.java
@@ -92,7 +92,10 @@
     }
 
     public MediaRouteChooserDialog(Context context, int theme) {
-        super(MediaRouterThemeHelper.createThemedContext(context, theme), theme);
+        // If we pass theme ID of 0 to AppCompatDialog, it will apply dialogTheme on the context,
+        // which may override our style settings. Passes our uppermost theme ID to prevent this.
+        super(MediaRouterThemeHelper.createThemedContext(context, theme),
+                theme == 0 ? MediaRouterThemeHelper.createThemeForDialog(context, theme) : theme);
         context = getContext();
 
         mRouter = MediaRouter.getInstance(context);
diff --git a/v7/mediarouter/src/android/support/v7/app/MediaRouteControllerDialog.java b/v7/mediarouter/src/android/support/v7/app/MediaRouteControllerDialog.java
index a7bceec..4b9a17a 100644
--- a/v7/mediarouter/src/android/support/v7/app/MediaRouteControllerDialog.java
+++ b/v7/mediarouter/src/android/support/v7/app/MediaRouteControllerDialog.java
@@ -20,7 +20,6 @@
 import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY;
 import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY_PAUSE;
 import static android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP;
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 
 import android.app.PendingIntent;
 import android.content.ContentResolver;
@@ -40,6 +39,7 @@
 import android.support.v4.media.session.MediaControllerCompat;
 import android.support.v4.media.session.MediaSessionCompat;
 import android.support.v4.media.session.PlaybackStateCompat;
+import android.support.v4.util.ObjectsCompat;
 import android.support.v4.view.accessibility.AccessibilityEventCompat;
 import android.support.v7.app.OverlayListView.OverlayObject;
 import android.support.v7.graphics.Palette;
@@ -201,8 +201,12 @@
     }
 
     public MediaRouteControllerDialog(Context context, int theme) {
+        // If we pass theme ID of 0 to AppCompatDialog, it will apply dialogTheme on the context,
+        // which may override our style settings. Passes our uppermost theme ID to prevent this.
         super(MediaRouterThemeHelper.createThemedContext(context,
-                MediaRouterThemeHelper.getAlertDialogResolvedTheme(context, theme)), theme);
+                MediaRouterThemeHelper.getAlertDialogResolvedTheme(context, theme)), theme == 0
+                ? MediaRouterThemeHelper.createThemeForDialog(context, MediaRouterThemeHelper
+                        .getAlertDialogResolvedTheme(context, theme)) : theme);
         mContext = getContext();
 
         mControllerCallback = new MediaControllerCallback();
@@ -1280,6 +1284,11 @@
         }
 
         @Override
+        public boolean isEnabled(int position) {
+            return false;
+        }
+
+        @Override
         public View getView(final int position, View convertView, ViewGroup parent) {
             View v = convertView;
             if (v == null) {
@@ -1440,8 +1449,8 @@
         @Override
         protected void onPostExecute(Bitmap art) {
             mFetchArtTask = null;
-            if (!objectEquals(mArtIconBitmap, mIconBitmap)
-                    || !objectEquals(mArtIconUri, mIconUri)) {
+            if (!ObjectsCompat.equals(mArtIconBitmap, mIconBitmap)
+                    || !ObjectsCompat.equals(mArtIconUri, mIconUri)) {
                 mArtIconBitmap = mIconBitmap;
                 mArtIconLoadedBitmap = art;
                 mArtIconUri = mIconUri;
diff --git a/v7/mediarouter/src/android/support/v7/app/MediaRouterThemeHelper.java b/v7/mediarouter/src/android/support/v7/app/MediaRouterThemeHelper.java
index 23f3bad..9ef218e 100644
--- a/v7/mediarouter/src/android/support/v7/app/MediaRouterThemeHelper.java
+++ b/v7/mediarouter/src/android/support/v7/app/MediaRouterThemeHelper.java
@@ -54,29 +54,21 @@
      *              {@code 0} to use the parent {@code context}'s default theme.
      * @return The themed context.
      */
-    public static Context createThemedContext(Context context, int style) {
+    static Context createThemedContext(Context context, int style) {
         // First, apply dialog property overlay.
+        Context themedContext =
+                new ContextThemeWrapper(context, getStyledRouterThemeId(context, style));
+        int customizedThemeId = getThemeResource(context, R.attr.mediaRouteTheme);
+        return customizedThemeId == 0 ? themedContext
+                : new ContextThemeWrapper(themedContext, customizedThemeId);
+    }
 
-        int theme;
-        if (isLightTheme(context)) {
-            if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
-                theme = R.style.Theme_MediaRouter_Light;
-            } else {
-                theme = R.style.Theme_MediaRouter_Light_DarkControlPanel;
-            }
-        } else {
-            if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
-                theme = R.style.Theme_MediaRouter_LightControlPanel;
-            } else {
-                theme = R.style.Theme_MediaRouter;
-            }
-        }
-        int mediaRouteThemeResId = getThemeResource(context, R.attr.mediaRouteTheme);
-        Context themedContext = new ContextThemeWrapper(context, theme);
-        if (mediaRouteThemeResId != 0) {
-            themedContext = new ContextThemeWrapper(themedContext, mediaRouteThemeResId);
-        }
-        return themedContext;
+    /**
+     * Creates the theme resource ID intended to be used by dialogs.
+     */
+    static int createThemeForDialog(Context context, int style) {
+        int customizedThemeId = getThemeResource(context, R.attr.mediaRouteTheme);
+        return customizedThemeId != 0 ? customizedThemeId : getStyledRouterThemeId(context, style);
     }
 
     public static int getThemeResource(Context context, int attr) {
@@ -180,4 +172,22 @@
         }
         return value.data;
     }
+
+    private static int getStyledRouterThemeId(Context context, int style) {
+        int themeId;
+        if (isLightTheme(context)) {
+            if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
+                themeId = R.style.Theme_MediaRouter_Light;
+            } else {
+                themeId = R.style.Theme_MediaRouter_Light_DarkControlPanel;
+            }
+        } else {
+            if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
+                themeId = R.style.Theme_MediaRouter_LightControlPanel;
+            } else {
+                themeId = R.style.Theme_MediaRouter;
+            }
+        }
+        return themeId;
+    }
 }
diff --git a/v7/mediarouter/src/android/support/v7/media/MediaRouteProvider.java b/v7/mediarouter/src/android/support/v7/media/MediaRouteProvider.java
index 5467c40..99bcf21 100644
--- a/v7/mediarouter/src/android/support/v7/media/MediaRouteProvider.java
+++ b/v7/mediarouter/src/android/support/v7/media/MediaRouteProvider.java
@@ -17,7 +17,6 @@
 package android.support.v7.media;
 
 import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 
 import android.content.ComponentName;
 import android.content.Context;
@@ -27,6 +26,7 @@
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.RestrictTo;
+import android.support.v4.util.ObjectsCompat;
 import android.support.v7.media.MediaRouter.ControlRequestCallback;
 
 /**
@@ -151,7 +151,7 @@
     public final void setDiscoveryRequest(MediaRouteDiscoveryRequest request) {
         MediaRouter.checkCallingThread();
 
-        if (objectEquals(mDiscoveryRequest, request)) {
+        if (ObjectsCompat.equals(mDiscoveryRequest, request)) {
             return;
         }
 
diff --git a/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderDescriptor.java b/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderDescriptor.java
index f6daeff..ac3ae5a 100644
--- a/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderDescriptor.java
+++ b/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderDescriptor.java
@@ -30,13 +30,12 @@
  * </p>
  */
 public final class MediaRouteProviderDescriptor {
-    static final String KEY_ROUTES = "routes";
+    private static final String KEY_ROUTES = "routes";
 
-    final Bundle mBundle;
-    List<MediaRouteDescriptor> mRoutes;
+    private final Bundle mBundle;
+    private List<MediaRouteDescriptor> mRoutes;
 
-    MediaRouteProviderDescriptor(Bundle bundle,
-            List<MediaRouteDescriptor> routes) {
+    private MediaRouteProviderDescriptor(Bundle bundle, List<MediaRouteDescriptor> routes) {
         mBundle = bundle;
         mRoutes = routes;
     }
@@ -49,7 +48,7 @@
         return mRoutes;
     }
 
-    void ensureRoutes() {
+    private void ensureRoutes() {
         if (mRoutes == null) {
             ArrayList<Bundle> routeBundles = mBundle.<Bundle>getParcelableArrayList(KEY_ROUTES);
             if (routeBundles == null || routeBundles.isEmpty()) {
@@ -179,6 +178,19 @@
         }
 
         /**
+         * Sets the list of routes.
+         */
+        Builder setRoutes(Collection<MediaRouteDescriptor> routes) {
+            if (routes == null || routes.isEmpty()) {
+                mRoutes = null;
+                mBundle.remove(KEY_ROUTES);
+            } else {
+                mRoutes = new ArrayList<>(routes);
+            }
+            return this;
+        }
+
+        /**
          * Builds the {@link MediaRouteProviderDescriptor media route provider descriptor}.
          */
         public MediaRouteProviderDescriptor build() {
diff --git a/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderService.java b/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderService.java
index 0d9c396..faa211d 100644
--- a/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderService.java
+++ b/v7/mediarouter/src/android/support/v7/media/MediaRouteProviderService.java
@@ -16,7 +16,6 @@
 
 package android.support.v7.media;
 
-import static android.support.v4.utils.ObjectUtils.objectEquals;
 import static android.support.v7.media.MediaRouteProviderProtocol.CLIENT_DATA_ROUTE_ID;
 import static android.support.v7.media.MediaRouteProviderProtocol.CLIENT_DATA_ROUTE_LIBRARY_GROUP;
 import static android.support.v7.media.MediaRouteProviderProtocol.CLIENT_DATA_UNSELECT_REASON;
@@ -56,12 +55,13 @@
 import android.os.Message;
 import android.os.Messenger;
 import android.os.RemoteException;
+import android.support.annotation.VisibleForTesting;
+import android.support.v4.util.ObjectsCompat;
 import android.util.Log;
 import android.util.SparseArray;
 
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
-import java.util.List;
 
 /**
  * Base class for media route provider services.
@@ -192,7 +192,8 @@
                         MediaRouteProviderDescriptor descriptor = mProvider.getDescriptor();
                         sendReply(messenger, SERVICE_MSG_REGISTERED,
                                 requestId, SERVICE_VERSION_CURRENT,
-                                createDescriptorBundleForClient(descriptor, client), null);
+                                createDescriptorBundleForClientVersion(descriptor,
+                                        client.mVersion), null);
                     }
                     return true;
                 }
@@ -413,32 +414,29 @@
         for (int i = 0; i < count; i++) {
             ClientRecord client = mClients.get(i);
             sendReply(client.mMessenger, SERVICE_MSG_DESCRIPTOR_CHANGED, 0, 0,
-                    createDescriptorBundleForClient(descriptor, client), null);
+                    createDescriptorBundleForClientVersion(descriptor, client.mVersion), null);
             if (DEBUG) {
                 Log.d(TAG, client + ": Sent descriptor change event, descriptor=" + descriptor);
             }
         }
     }
 
-    private Bundle createDescriptorBundleForClient(MediaRouteProviderDescriptor descriptor,
-            ClientRecord client) {
+    @VisibleForTesting
+    static Bundle createDescriptorBundleForClientVersion(MediaRouteProviderDescriptor descriptor,
+            int clientVersion) {
         if (descriptor == null) {
             return null;
         }
-        List<MediaRouteDescriptor> routes = descriptor.getRoutes();
-        for (int i = routes.size() - 1; i >= 0; i--) {
-            if (client.mVersion < routes.get(i).getMinClientVersion()
-                    || client.mVersion > routes.get(i).getMaxClientVersion()) {
-                routes.remove(i);
+        MediaRouteProviderDescriptor.Builder builder =
+                new MediaRouteProviderDescriptor.Builder(descriptor);
+        builder.setRoutes(null);
+        for (MediaRouteDescriptor route : descriptor.getRoutes()) {
+            if (clientVersion >= route.getMinClientVersion()
+                    && clientVersion <= route.getMaxClientVersion()) {
+                builder.addRoute(route);
             }
         }
-
-        // Keep the values of the bundle from descriptor excepts routes values.
-        Bundle bundle = descriptor.asBundle();
-        bundle.remove(MediaRouteProviderDescriptor.KEY_ROUTES);
-        return new MediaRouteProviderDescriptor.Builder(
-                MediaRouteProviderDescriptor.fromBundle(bundle))
-                .addRoutes(routes).build().asBundle();
+        return builder.build().asBundle();
     }
 
     boolean updateCompositeDiscoveryRequest() {
@@ -464,7 +462,7 @@
         if (selectorBuilder != null) {
             composite = new MediaRouteDiscoveryRequest(selectorBuilder.build(), activeScan);
         }
-        if (!objectEquals(mCompositeDiscoveryRequest, composite)) {
+        if (!ObjectsCompat.equals(mCompositeDiscoveryRequest, composite)) {
             mCompositeDiscoveryRequest = composite;
             mProvider.setDiscoveryRequest(composite);
             return true;
@@ -614,7 +612,7 @@
         }
 
         public boolean setDiscoveryRequest(MediaRouteDiscoveryRequest request) {
-            if (!objectEquals(mDiscoveryRequest, request)) {
+            if (!ObjectsCompat.equals(mDiscoveryRequest, request)) {
                 mDiscoveryRequest = request;
                 return updateCompositeDiscoveryRequest();
             }
diff --git a/v7/mediarouter/src/android/support/v7/media/MediaRouter.java b/v7/mediarouter/src/android/support/v7/media/MediaRouter.java
index e2c9b87..5bc0bb4 100644
--- a/v7/mediarouter/src/android/support/v7/media/MediaRouter.java
+++ b/v7/mediarouter/src/android/support/v7/media/MediaRouter.java
@@ -229,7 +229,7 @@
      */
     public static final int AVAILABILITY_FLAG_REQUIRE_MATCH = 1 << 1;
 
-    MediaRouter(Context context) {
+    private MediaRouter(Context context) {
         mContext = context;
     }
 
@@ -1294,6 +1294,15 @@
                     && !supportsControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO);
         }
 
+        /**
+         * Returns {@code true} if the route is selectable.
+         */
+        boolean isSelectable() {
+            // This tests whether the route is still valid and enabled.
+            // The route descriptor field is set to null when the route is removed.
+            return mDescriptor != null && mEnabled;
+        }
+
         private static boolean isSystemMediaRouteProvider(MediaRouter.RouteInfo route) {
             return TextUtils.equals(route.getProviderInstance().getMetadata().getPackageName(),
                     SYSTEM_MEDIA_ROUTE_PROVIDER_PACKAGE_NAME);
@@ -1973,10 +1982,11 @@
             // the framework media router.  This one is special and receives
             // synchronization messages from the media router.
             mSystemProvider = SystemMediaRouteProvider.obtain(applicationContext, this);
-            addProvider(mSystemProvider);
         }
 
         public void start() {
+            addProvider(mSystemProvider);
+
             // Start watching for routes published by registered media route
             // provider services.
             mRegisteredProviderWatcher = new RegisteredMediaRouteProviderWatcher(
@@ -2061,11 +2071,11 @@
             return mRoutes;
         }
 
-        public List<ProviderInfo> getProviders() {
+        List<ProviderInfo> getProviders() {
             return mProviders;
         }
 
-        public RouteInfo getDefaultRoute() {
+        @NonNull RouteInfo getDefaultRoute() {
             if (mDefaultRoute == null) {
                 // This should never happen once the media router has been fully
                 // initialized but it is good to check for the error in case there
@@ -2076,11 +2086,11 @@
             return mDefaultRoute;
         }
 
-        public RouteInfo getBluetoothRoute() {
+        RouteInfo getBluetoothRoute() {
             return mBluetoothRoute;
         }
 
-        public RouteInfo getSelectedRoute() {
+        @NonNull RouteInfo getSelectedRoute() {
             if (mSelectedRoute == null) {
                 // This should never happen once the media router has been fully
                 // initialized but it is good to check for the error in case there
@@ -2091,11 +2101,11 @@
             return mSelectedRoute;
         }
 
-        public void selectRoute(RouteInfo route) {
+        void selectRoute(@NonNull RouteInfo route) {
             selectRoute(route, MediaRouter.UNSELECT_REASON_ROUTE_CHANGED);
         }
 
-        public void selectRoute(RouteInfo route, int unselectReason) {
+        void selectRoute(@NonNull RouteInfo route, int unselectReason) {
             if (!mRoutes.contains(route)) {
                 Log.w(TAG, "Ignoring attempt to select removed route: " + route);
                 return;
@@ -2444,14 +2454,14 @@
 
         private void updateSelectedRouteIfNeeded(boolean selectedRouteDescriptorChanged) {
             // Update default route.
-            if (mDefaultRoute != null && !isRouteSelectable(mDefaultRoute)) {
+            if (mDefaultRoute != null && !mDefaultRoute.isSelectable()) {
                 Log.i(TAG, "Clearing the default route because it "
                         + "is no longer selectable: " + mDefaultRoute);
                 mDefaultRoute = null;
             }
             if (mDefaultRoute == null && !mRoutes.isEmpty()) {
                 for (RouteInfo route : mRoutes) {
-                    if (isSystemDefaultRoute(route) && isRouteSelectable(route)) {
+                    if (isSystemDefaultRoute(route) && route.isSelectable()) {
                         mDefaultRoute = route;
                         Log.i(TAG, "Found default route: " + mDefaultRoute);
                         break;
@@ -2460,14 +2470,14 @@
             }
 
             // Update bluetooth route.
-            if (mBluetoothRoute != null && !isRouteSelectable(mBluetoothRoute)) {
+            if (mBluetoothRoute != null && !mBluetoothRoute.isSelectable()) {
                 Log.i(TAG, "Clearing the bluetooth route because it "
                         + "is no longer selectable: " + mBluetoothRoute);
                 mBluetoothRoute = null;
             }
             if (mBluetoothRoute == null && !mRoutes.isEmpty()) {
                 for (RouteInfo route : mRoutes) {
-                    if (isSystemLiveAudioOnlyRoute(route) && isRouteSelectable(route)) {
+                    if (isSystemLiveAudioOnlyRoute(route) && route.isSelectable()) {
                         mBluetoothRoute = route;
                         Log.i(TAG, "Found bluetooth route: " + mBluetoothRoute);
                         break;
@@ -2476,16 +2486,9 @@
             }
 
             // Update selected route.
-            if (mSelectedRoute != null && !isRouteSelectable(mSelectedRoute)) {
+            if (mSelectedRoute == null || !mSelectedRoute.isSelectable()) {
                 Log.i(TAG, "Unselecting the current route because it "
                         + "is no longer selectable: " + mSelectedRoute);
-                setSelectedRouteInternal(null,
-                        MediaRouter.UNSELECT_REASON_UNKNOWN);
-            }
-            if (mSelectedRoute == null) {
-                // Choose a new route.
-                // This will have the side-effect of updating the playback info when
-                // the new route is selected.
                 setSelectedRouteInternal(chooseFallbackRoute(),
                         MediaRouter.UNSELECT_REASON_UNKNOWN);
             } else if (selectedRouteDescriptorChanged) {
@@ -2534,7 +2537,7 @@
             for (RouteInfo route : mRoutes) {
                 if (route != mDefaultRoute
                         && isSystemLiveAudioOnlyRoute(route)
-                        && isRouteSelectable(route)) {
+                        && route.isSelectable()) {
                     return route;
                 }
             }
@@ -2547,19 +2550,32 @@
                     && !route.supportsControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO);
         }
 
-        private boolean isRouteSelectable(RouteInfo route) {
-            // This tests whether the route is still valid and enabled.
-            // The route descriptor field is set to null when the route is removed.
-            return route.mDescriptor != null && route.mEnabled;
-        }
-
         private boolean isSystemDefaultRoute(RouteInfo route) {
             return route.getProviderInstance() == mSystemProvider
                     && route.mDescriptorId.equals(
                             SystemMediaRouteProvider.DEFAULT_ROUTE_ID);
         }
 
-        private void setSelectedRouteInternal(RouteInfo route, int unselectReason) {
+        private void setSelectedRouteInternal(@NonNull RouteInfo route, int unselectReason) {
+            // TODO: Remove the following logging when no longer needed.
+            if (sGlobal == null || mBluetoothRoute != null && route.isDefault()) {
+                final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
+                StringBuffer sb = new StringBuffer();
+                // callStack[3] is the caller of this method.
+                for (int i = 3; i < callStack.length; i++) {
+                    StackTraceElement caller = callStack[i];
+                    sb.append(caller.getClassName() + "." + caller.getMethodName()
+                            + ":" + caller.getLineNumber()).append("  ");
+                }
+                if (sGlobal == null) {
+                    Log.w(TAG, "setSelectedRouteInternal is called while sGlobal is null: pkgName="
+                            + mApplicationContext.getPackageName() + ", callers=" + sb.toString());
+                } else {
+                    Log.w(TAG, "Default route is selected while a BT route is available: pkgName="
+                            + mApplicationContext.getPackageName() + ", callers=" + sb.toString());
+                }
+            }
+
             if (mSelectedRoute != route) {
                 if (mSelectedRoute != null) {
                     if (DEBUG) {
@@ -2583,28 +2599,25 @@
                 }
 
                 mSelectedRoute = route;
+                mSelectedRouteController = route.getProviderInstance().onCreateRouteController(
+                        route.mDescriptorId);
+                if (mSelectedRouteController != null) {
+                    mSelectedRouteController.onSelect();
+                }
+                if (DEBUG) {
+                    Log.d(TAG, "Route selected: " + mSelectedRoute);
+                }
+                mCallbackHandler.post(CallbackHandler.MSG_ROUTE_SELECTED, mSelectedRoute);
 
-                if (mSelectedRoute != null) {
-                    mSelectedRouteController = route.getProviderInstance().onCreateRouteController(
-                            route.mDescriptorId);
-                    if (mSelectedRouteController != null) {
-                        mSelectedRouteController.onSelect();
-                    }
-                    if (DEBUG) {
-                        Log.d(TAG, "Route selected: " + mSelectedRoute);
-                    }
-                    mCallbackHandler.post(CallbackHandler.MSG_ROUTE_SELECTED, mSelectedRoute);
-
-                    if (mSelectedRoute instanceof RouteGroup) {
-                        List<RouteInfo> routes = ((RouteGroup) mSelectedRoute).getRoutes();
-                        mRouteControllerMap.clear();
-                        for (RouteInfo r : routes) {
-                            RouteController controller =
-                                    r.getProviderInstance().onCreateRouteController(
-                                            r.mDescriptorId, mSelectedRoute.mDescriptorId);
-                            controller.onSelect();
-                            mRouteControllerMap.put(r.mDescriptorId, controller);
-                        }
+                if (mSelectedRoute instanceof RouteGroup) {
+                    List<RouteInfo> routes = ((RouteGroup) mSelectedRoute).getRoutes();
+                    mRouteControllerMap.clear();
+                    for (RouteInfo r : routes) {
+                        RouteController controller =
+                                r.getProviderInstance().onCreateRouteController(
+                                        r.mDescriptorId, mSelectedRoute.mDescriptorId);
+                        controller.onSelect();
+                        mRouteControllerMap.put(r.mDescriptorId, controller);
                     }
                 }
 
diff --git a/v7/mediarouter/src/android/support/v7/media/RemotePlaybackClient.java b/v7/mediarouter/src/android/support/v7/media/RemotePlaybackClient.java
index 045b69b..fb05ac7 100644
--- a/v7/mediarouter/src/android/support/v7/media/RemotePlaybackClient.java
+++ b/v7/mediarouter/src/android/support/v7/media/RemotePlaybackClient.java
@@ -15,8 +15,6 @@
  */
 package android.support.v7.media;
 
-import static android.support.v4.utils.ObjectUtils.objectEquals;
-
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -24,6 +22,7 @@
 import android.content.IntentFilter;
 import android.net.Uri;
 import android.os.Bundle;
+import android.support.v4.util.ObjectsCompat;
 import android.util.Log;
 
 /**
@@ -204,7 +203,7 @@
      * @param sessionId The new session id, or null if none.
      */
     public void setSessionId(String sessionId) {
-        if (!objectEquals(mSessionId, sessionId)) {
+        if (!ObjectsCompat.equals(mSessionId, sessionId)) {
             if (DEBUG) {
                 Log.d(TAG, "Session id is now: " + sessionId);
             }
diff --git a/v7/mediarouter/tests/AndroidManifest.xml b/v7/mediarouter/tests/AndroidManifest.xml
index 576c652..e1c6443 100644
--- a/v7/mediarouter/tests/AndroidManifest.xml
+++ b/v7/mediarouter/tests/AndroidManifest.xml
@@ -15,19 +15,18 @@
    limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.v7.mediarouter.test">
-
-    <uses-sdk
-            android:minSdkVersion="14"
-            android:targetSdkVersion="23"
-            tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application android:supportsRtl="true">
+        <activity
+            android:name="android.support.v7.app.MediaRouteChooserDialogTestActivity"
+            android:label="MediaRouteChooserDialogTestActivity"
+            android:theme="@style/Theme.AppCompat" />
+
         <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
             <intent-filter>
-                <action android:name="android.intent.action.MEDIA_BUTTON" />
+                <action android:name="android.intent.action.MEDIA_BUTTON"/>
             </intent-filter>
         </receiver>
     </application>
diff --git a/v7/mediarouter/tests/res/layout/mr_chooser_dialog_activity.xml b/v7/mediarouter/tests/res/layout/mr_chooser_dialog_activity.xml
new file mode 100644
index 0000000..484bd23
--- /dev/null
+++ b/v7/mediarouter/tests/res/layout/mr_chooser_dialog_activity.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/container"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+</FrameLayout>
+
diff --git a/v7/mediarouter/tests/res/values/themes.xml b/v7/mediarouter/tests/res/values/themes.xml
new file mode 100644
index 0000000..31ae4ce
--- /dev/null
+++ b/v7/mediarouter/tests/res/values/themes.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources>
+
+    <style name="HasWindowTitle">
+        <item name="windowNoTitle">false</item>
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTest.java b/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTest.java
index 7a21cdb..415ec1f 100644
--- a/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTest.java
+++ b/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTest.java
@@ -16,28 +16,76 @@
 
 package android.support.v7.app;
 
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.media.MediaRouter.RouteInfo;
 import android.support.v7.media.TestUtils;
+import android.support.v7.mediarouter.test.R;
 
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 @RunWith(AndroidJUnit4.class)
-@SmallTest
 public class MediaRouteChooserDialogTest {
+
+    @Rule
+    public final ActivityTestRule<MediaRouteChooserDialogTestActivity> mActivityTestRule;
     private MediaRouteChooserDialog.RouteComparator mComparator;
 
+    public MediaRouteChooserDialogTest() {
+        mActivityTestRule = new ActivityTestRule<>(MediaRouteChooserDialogTestActivity.class);
+    }
+
     @Before
     public void setup() {
         mComparator = new MediaRouteChooserDialog.RouteComparator();
     }
 
     @Test
+    @SmallTest
+    @UiThreadTest
+    public void testWindowNoTitle() {
+        final Context context = mActivityTestRule.getActivity();
+        TypedArray typedArray;
+
+        // Without any base theme or customized theme
+        MediaRouteChooserDialog dialog = new MediaRouteChooserDialog(context);
+        typedArray = dialog.getContext().obtainStyledAttributes(R.styleable.AppCompatTheme);
+        assertTrue(typedArray.getBoolean(R.styleable.AppCompatTheme_windowNoTitle, false));
+        typedArray.recycle();
+
+        // No base theme, with a customized theme (has window title)
+        dialog = new MediaRouteChooserDialog(context, R.style.HasWindowTitle);
+        typedArray = dialog.getContext().obtainStyledAttributes(R.styleable.AppCompatTheme);
+        assertFalse(typedArray.getBoolean(R.styleable.AppCompatTheme_windowNoTitle, false));
+        typedArray.recycle();
+
+        // With base theme (has window title), no customized theme
+        context.setTheme(R.style.HasWindowTitle);
+        dialog = new MediaRouteChooserDialog(context);
+        typedArray = dialog.getContext().obtainStyledAttributes(R.styleable.AppCompatTheme);
+        assertTrue(typedArray.getBoolean(R.styleable.AppCompatTheme_windowNoTitle, false));
+        typedArray.recycle();
+
+        // With base theme and a customized theme (both has window title)
+        dialog = new MediaRouteChooserDialog(context, R.style.HasWindowTitle);
+        typedArray = dialog.getContext().obtainStyledAttributes(R.styleable.AppCompatTheme);
+        assertFalse(typedArray.getBoolean(R.styleable.AppCompatTheme_windowNoTitle, false));
+        typedArray.recycle();
+
+        context.setTheme(0);
+    }
+
+    @Test
     public void testRouteComparatorWithSameRouteName() {
         RouteInfo routeInfo1 = TestUtils.createRouteInfo("ROUTE_ID_1", "ROUTE_NAME_1");
         RouteInfo routeInfo2 = TestUtils.createRouteInfo("ROUTE_ID_2", "ROUTE_NAME_1");
diff --git a/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTestActivity.java b/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTestActivity.java
new file mode 100644
index 0000000..39e4d7c
--- /dev/null
+++ b/v7/mediarouter/tests/src/android/support/v7/app/MediaRouteChooserDialogTestActivity.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.app;
+
+import android.os.Bundle;
+import android.support.v7.mediarouter.test.R;
+
+public class MediaRouteChooserDialogTestActivity extends AppCompatActivity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.mr_chooser_dialog_activity);
+    }
+}
diff --git a/v7/mediarouter/tests/src/android/support/v7/media/MediaRouteProviderTest.java b/v7/mediarouter/tests/src/android/support/v7/media/MediaRouteProviderTest.java
new file mode 100644
index 0000000..ff4409a
--- /dev/null
+++ b/v7/mediarouter/tests/src/android/support/v7/media/MediaRouteProviderTest.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.media;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.os.Bundle;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Test {@link MediaRouteProvider} and its related classes.
+ */
+@RunWith(AndroidJUnit4.class)
+public class MediaRouteProviderTest {
+    private static final String FAKE_MEDIA_ROUTE_ID_1 = "fakeMediaRouteId1";
+    private static final String FAKE_MEDIA_ROUTE_ID_2 = "fakeMediaRouteId2";
+    private static final String FAKE_MEDIA_ROUTE_ID_3 = "fakeMediaRouteId3";
+    private static final String FAKE_MEDIA_ROUTE_ID_4 = "fakeMediaRouteId4";
+    private static final String FAKE_MEDIA_ROUTE_NAME_1 = "fakeMediaRouteName1";
+    private static final String FAKE_MEDIA_ROUTE_NAME_2 = "fakeMediaRouteName2";
+    private static final String FAKE_MEDIA_ROUTE_NAME_3 = "fakeMediaRouteName3";
+    private static final String FAKE_MEDIA_ROUTE_NAME_4 = "fakeMediaRouteName4";
+
+    @Test
+    @SmallTest
+    public void testDescriptorBuilder() {
+        // Tests for empty descriptor
+        MediaRouteProviderDescriptor.Builder builder = new MediaRouteProviderDescriptor.Builder();
+        MediaRouteProviderDescriptor descriptor = builder.build();
+        assertTrue(descriptor.getRoutes().isEmpty());
+
+        // Tests for addRoute()
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_1,
+                FAKE_MEDIA_ROUTE_NAME_1).build());
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_2,
+                FAKE_MEDIA_ROUTE_NAME_2).build());
+        descriptor = builder.build();
+        List<MediaRouteDescriptor> routes = descriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_1, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_1, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_2, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_2, routes.get(1).getName());
+
+        // Tests for addRoutes()
+        List<MediaRouteDescriptor> otherRoutes = new ArrayList<>();
+        otherRoutes.add(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_3,
+                FAKE_MEDIA_ROUTE_NAME_3).build());
+        otherRoutes.add(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_4,
+                FAKE_MEDIA_ROUTE_NAME_4).build());
+        builder.addRoutes(otherRoutes);
+        descriptor = builder.build();
+        routes = descriptor.getRoutes();
+        assertEquals(4, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_1, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_1, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_2, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_2, routes.get(1).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_3, routes.get(2).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_3, routes.get(2).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(3).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(3).getName());
+
+        // Tests for setRoutes()
+        builder.setRoutes(otherRoutes);
+        descriptor = builder.build();
+        routes = descriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_3, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_3, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(1).getName());
+
+        // Tests setRoutes() for side effects
+        otherRoutes.add(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_1,
+                FAKE_MEDIA_ROUTE_NAME_1).build());
+        descriptor = builder.build();
+        routes = descriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_3, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_3, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(1).getName());
+
+        // Tests setRoutes against null
+        builder.setRoutes(null);
+        descriptor = builder.build();
+        assertTrue(descriptor.getRoutes().isEmpty());
+    }
+
+    @Test
+    @SmallTest
+    public void testCreateDescriptorBundleForClient() {
+        MediaRouteProviderDescriptor.Builder builder = new MediaRouteProviderDescriptor.Builder();
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_1,
+                FAKE_MEDIA_ROUTE_NAME_1).setMaxClientVersion(15).setMinClientVersion(10).build());
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_2,
+                FAKE_MEDIA_ROUTE_NAME_2).setMaxClientVersion(18).setMinClientVersion(11).build());
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_3,
+                FAKE_MEDIA_ROUTE_NAME_3).setMaxClientVersion(25).setMinClientVersion(16).build());
+        builder.addRoute(new MediaRouteDescriptor.Builder(FAKE_MEDIA_ROUTE_ID_4,
+                FAKE_MEDIA_ROUTE_NAME_4).setMaxClientVersion(12).setMinClientVersion(4).build());
+        MediaRouteProviderDescriptor descriptor = builder.build();
+
+        Bundle bundle = MediaRouteProviderService
+                .createDescriptorBundleForClientVersion(descriptor, 3);
+        MediaRouteProviderDescriptor resultDescriptor =
+                MediaRouteProviderDescriptor.fromBundle(bundle);
+        assertTrue(resultDescriptor.getRoutes().isEmpty());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 4);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        List<MediaRouteDescriptor> routes = resultDescriptor.getRoutes();
+        assertEquals(1, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(0).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 10);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        routes = resultDescriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_1, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_1, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(1).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 12);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        routes = resultDescriptor.getRoutes();
+        assertEquals(3, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_1, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_1, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_2, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_2, routes.get(1).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_4, routes.get(2).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_4, routes.get(2).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 15);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        routes = resultDescriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_1, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_1, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_2, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_2, routes.get(1).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 16);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        routes = resultDescriptor.getRoutes();
+        assertEquals(2, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_2, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_2, routes.get(0).getName());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_3, routes.get(1).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_3, routes.get(1).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 19);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        routes = resultDescriptor.getRoutes();
+        assertEquals(1, routes.size());
+        assertEquals(FAKE_MEDIA_ROUTE_ID_3, routes.get(0).getId());
+        assertEquals(FAKE_MEDIA_ROUTE_NAME_3, routes.get(0).getName());
+
+        bundle = MediaRouteProviderService.createDescriptorBundleForClientVersion(descriptor, 26);
+        resultDescriptor = MediaRouteProviderDescriptor.fromBundle(bundle);
+        assertTrue(resultDescriptor.getRoutes().isEmpty());
+    }
+}
diff --git a/v7/palette/build.gradle b/v7/palette/build.gradle
index 6ab7995..915ef13 100644
--- a/v7/palette/build.gradle
+++ b/v7/palette/build.gradle
@@ -2,10 +2,10 @@
 archivesBaseName = 'palette-v7'
 
 dependencies {
-    compile project(':support-compat')
-    compile project(':support-core-utils')
+    api project(':support-compat')
+    api project(':support-core-utils')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
 }
diff --git a/v7/palette/lint-baseline.xml b/v7/palette/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v7/palette/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v7/palette/tests/AndroidManifest.xml b/v7/palette/tests/AndroidManifest.xml
index cc6e45a..ca9860a 100644
--- a/v7/palette/tests/AndroidManifest.xml
+++ b/v7/palette/tests/AndroidManifest.xml
@@ -15,10 +15,6 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.v7.palette.test">
-
-    <uses-sdk android:minSdkVersion="14"
-              tools:overrideLibrary="android.support.test, android.app, android.support.test.rule"/>
-
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 </manifest>
diff --git a/v7/preference/build.gradle b/v7/preference/build.gradle
index a7ad709..3f81093 100644
--- a/v7/preference/build.gradle
+++ b/v7/preference/build.gradle
@@ -18,18 +18,18 @@
 archivesBaseName = 'preference-v7'
 
 dependencies {
-    compile project(':support-v4')
-    compile project(':support-appcompat-v7')
-    compile project(':support-recyclerview-v7')
+    api project(':support-v4')
+    api project(':support-appcompat-v7')
+    api project(':support-recyclerview-v7')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/v7/preference/lint-baseline.xml b/v7/preference/lint-baseline.xml
new file mode 100644
index 0000000..22b46d6
--- /dev/null
+++ b/v7/preference/lint-baseline.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        android:layout_width=&quot;0dp&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout/preference_dropdown.xml"
+            line="29"
+            column="9"/>
+    </issue>
+
+    <issue
+        id="Suspicious0dp"
+        message="Suspicious size: this will make the view invisible, should be used with `layout_weight`"
+        errorLine1="        android:layout_width=&quot;0dp&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/layout-v11/preference_dropdown.xml"
+            line="30"
+            column="9"/>
+    </issue>
+
+</issues>
diff --git a/v7/preference/src/android/support/v7/preference/Preference.java b/v7/preference/src/android/support/v7/preference/Preference.java
index 6b302fd..cfc4311 100644
--- a/v7/preference/src/android/support/v7/preference/Preference.java
+++ b/v7/preference/src/android/support/v7/preference/Preference.java
@@ -999,6 +999,7 @@
      * @attr ref R.styleable#Preference_android_singleLineTitle
      */
     public void setSingleLineTitle(boolean singleLineTitle) {
+        mHasSingleLineTitleAttr = true;
         mSingleLineTitle = singleLineTitle;
     }
 
diff --git a/v7/preference/tests/AndroidManifest.xml b/v7/preference/tests/AndroidManifest.xml
index 095212e..34b8a72 100644
--- a/v7/preference/tests/AndroidManifest.xml
+++ b/v7/preference/tests/AndroidManifest.xml
@@ -15,13 +15,6 @@
   -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    package="android.support.v7.preference.tests">
-
-    <uses-sdk
-        android:minSdkVersion="14"
-        android:targetSdkVersion="24"
-        tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                android.support.test.espresso, android.support.test.espresso.idling" />
-
+          package="android.support.v7.preference.tests">
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 </manifest>
diff --git a/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceDataStoreTest.java b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceDataStoreTest.java
index 5c0923f..8f9929e 100644
--- a/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceDataStoreTest.java
+++ b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceDataStoreTest.java
@@ -22,6 +22,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.AdditionalMatchers.or;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyBoolean;
 import static org.mockito.Matchers.anyFloat;
@@ -212,7 +213,7 @@
     private void putStringTestCommon() {
         mPreference.putString(TEST_STR);
 
-        verify(mDataStore, atLeast(0)).getString(eq(KEY), anyString());
+        verify(mDataStore, atLeast(0)).getString(eq(KEY), nullable(String.class));
         verify(mDataStore, atLeastOnce()).putString(eq(KEY), anyString());
         verifyNoMoreInteractions(mDataStore);
 
diff --git a/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceIconSpaceTest.java b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceIconSpaceTest.java
index a891d36..c03f411 100644
--- a/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceIconSpaceTest.java
+++ b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceIconSpaceTest.java
@@ -24,7 +24,6 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.LargeTest;
-import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.support.v7.preference.AndroidResources;
 import android.support.v7.preference.Preference;
@@ -40,7 +39,7 @@
 import org.mockito.MockitoAnnotations;
 
 @RunWith(AndroidJUnit4.class)
-@SmallTest
+@LargeTest
 public class PreferenceIconSpaceTest {
 
     private Preference mPreference;
diff --git a/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceSingleLineTitleTest.java b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceSingleLineTitleTest.java
new file mode 100644
index 0000000..6c1cf5f
--- /dev/null
+++ b/v7/preference/tests/src/android/support/v7/preference/tests/PreferenceSingleLineTitleTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.preference.tests;
+
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class PreferenceSingleLineTitleTest {
+
+    private Preference mPreference;
+
+    @Mock
+    private ViewGroup mViewGroup;
+    @Mock
+    private TextView mTitleView;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        when(mViewGroup.findViewById(android.R.id.title)).thenReturn(mTitleView);
+
+        mPreference = new Preference(InstrumentationRegistry.getTargetContext());
+        mPreference.setTitle("Test Title");
+    }
+
+    @Test
+    public void bindViewHolder_singleLineTitleNotSet_shouldNotSetSingleLine() {
+        PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(mViewGroup);
+        mPreference.onBindViewHolder(holder);
+
+        verify(mTitleView, never()).setSingleLine(anyBoolean());
+    }
+
+    @Test
+    public void bindViewHolder_singleLineTitleSetToTrue_shouldSetSingleLineToTrue() {
+        PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(mViewGroup);
+        mPreference.setSingleLineTitle(true);
+        mPreference.onBindViewHolder(holder);
+
+        verify(mTitleView).setSingleLine(true);
+    }
+
+    @Test
+    public void bindViewHolder_singleLineTitleSetToFalse_shouldSetSingleLineToFalse() {
+        PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(mViewGroup);
+        mPreference.setSingleLineTitle(false);
+        mPreference.onBindViewHolder(holder);
+
+        verify(mTitleView).setSingleLine(false);
+    }
+
+}
diff --git a/v7/recyclerview/build.gradle b/v7/recyclerview/build.gradle
index 274c91e..06cdc53 100644
--- a/v7/recyclerview/build.gradle
+++ b/v7/recyclerview/build.gradle
@@ -2,25 +2,24 @@
 archivesBaseName = 'recyclerview-v7'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-compat')
-    compile project(':support-core-ui')
+    api project(':support-annotations')
+    api project(':support-compat')
+    api project(':support-core-ui')
 
-    androidTestCompile (libs.test_runner) {
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.junit
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
-    androidTestCompile project(':support-testutils')
+    androidTestImplementation libs.junit
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
+    androidTestImplementation project(':support-testutils')
 
-    testCompile libs.junit
-    testCompile libs.mockito_core
-    testCompile ("$libs.test_runner") {
+    testImplementation libs.junit
+    testImplementation libs.mockito_core
+    testImplementation ("$libs.test_runner") {
         exclude module: 'support-annotations'
     }
 }
diff --git a/v7/recyclerview/lint-baseline.xml b/v7/recyclerview/lint-baseline.xml
new file mode 100644
index 0000000..e961253
--- /dev/null
+++ b/v7/recyclerview/lint-baseline.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+</issues>
diff --git a/v7/recyclerview/src/android/support/v7/widget/LinearLayoutManager.java b/v7/recyclerview/src/android/support/v7/widget/LinearLayoutManager.java
index a72975d..a12e9a8 100644
--- a/v7/recyclerview/src/android/support/v7/widget/LinearLayoutManager.java
+++ b/v7/recyclerview/src/android/support/v7/widget/LinearLayoutManager.java
@@ -491,6 +491,7 @@
         // resolve layout direction
         resolveShouldLayoutReverse();
 
+        final View focused = getFocusedChild();
         if (!mAnchorInfo.mValid || mPendingScrollPosition != NO_POSITION
                 || mPendingSavedState != null) {
             mAnchorInfo.reset();
@@ -498,6 +499,22 @@
             // calculate anchor position and coordinate
             updateAnchorInfoForLayout(recycler, state, mAnchorInfo);
             mAnchorInfo.mValid = true;
+        } else if (focused != null && (mOrientationHelper.getDecoratedStart(focused)
+                        >= mOrientationHelper.getEndAfterPadding()
+                || mOrientationHelper.getDecoratedEnd(focused)
+                <= mOrientationHelper.getStartAfterPadding())) {
+            // This case relates to when the anchor child is the focused view and due to layout
+            // shrinking the focused view fell outside the viewport, e.g. when soft keyboard shows
+            // up after tapping an EditText which shrinks RV causing the focused view (The tapped
+            // EditText which is the anchor child) to get kicked out of the screen. Will update the
+            // anchor coordinate in order to make sure that the focused view is laid out. Otherwise,
+            // the available space in layoutState will be calculated as negative preventing the
+            // focused view from being laid out in fill.
+            // Note that we won't update the anchor position between layout passes (refer to
+            // TestResizingRelayoutWithAutoMeasure), which happens if we were to call
+            // updateAnchorInfoForLayout for an anchor that's not the focused view (e.g. a reference
+            // child which can change between layout passes).
+            mAnchorInfo.assignFromViewAndKeepVisibleRect(focused);
         }
         if (DEBUG) {
             Log.d(TAG, "Anchor info:" + mAnchorInfo);
@@ -1293,6 +1310,7 @@
             return;
         }
 
+        ensureLayoutState();
         final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
         final int absDy = Math.abs(delta);
         updateLayoutState(layoutDirection, absDy, true, state);
diff --git a/v7/recyclerview/src/android/support/v7/widget/RecyclerView.java b/v7/recyclerview/src/android/support/v7/widget/RecyclerView.java
index e01cd83..ff8e0e6 100644
--- a/v7/recyclerview/src/android/support/v7/widget/RecyclerView.java
+++ b/v7/recyclerview/src/android/support/v7/widget/RecyclerView.java
@@ -636,20 +636,15 @@
         setNestedScrollingEnabled(nestedScrollingEnabled);
     }
 
-    @Override
-    public String toString() {
-        return super.toString()
-                + ", adapter:" + mAdapter
-                + ", layout:" + mLayout
-                + ", context:" + getContext();
-    }
-
     /**
      * Label appended to all public exception strings, used to help find which RV in an app is
      * hitting an exception.
      */
     String exceptionLabel() {
-        return " " + this;
+        return " " + super.toString()
+                + ", adapter:" + mAdapter
+                + ", layout:" + mLayout
+                + ", context:" + getContext();
     }
 
     /**
@@ -677,7 +672,7 @@
             int defStyleAttr, int defStyleRes) {
         if (className != null) {
             className = className.trim();
-            if (className.length() != 0) {  // Can't use isEmpty since it was added in API 9.
+            if (!className.isEmpty()) {
                 className = getFullClassName(context, className);
                 try {
                     ClassLoader classLoader;
@@ -1038,7 +1033,6 @@
         // bail out if layout is frozen
         setLayoutFrozen(false);
         setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
-        setDataSetChangedAfterLayout();
         requestLayout();
     }
     /**
@@ -1107,7 +1101,7 @@
         }
         mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
         mState.mStructureChanged = true;
-        markKnownViewsInvalid();
+        setDataSetChangedAfterLayout();
     }
 
     /**
@@ -3149,6 +3143,14 @@
                 }
                 mAdapterUpdateDuringMeasure = false;
                 resumeRequestLayout(false);
+            } else if (mState.mRunPredictiveAnimations) {
+                // If mAdapterUpdateDuringMeasure is false and mRunPredictiveAnimations is true:
+                // this means there is already an onMeasure() call performed to handle the pending
+                // adapter change, two onMeasure() calls can happen if RV is a child of LinearLayout
+                // with layout_width=MATCH_PARENT. RV cannot call LM.onMeasure() second time
+                // because getViewForPosition() will crash when LM uses a child to measure.
+                setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
+                return;
             }
 
             if (mAdapter != null) {
@@ -4234,8 +4236,8 @@
 
     /**
      * Call this method to signal that *all* adapter content has changed (generally, because of
-     * swapAdapter, or notifyDataSetChanged), and that once layout occurs, all attached items should
-     * be discarded or animated.
+     * setAdapter, swapAdapter, or notifyDataSetChanged), and that once layout occurs, all
+     * attached items should be discarded or animated.
      *
      * Attached items are labeled as invalid, and all cached items are discarded.
      *
diff --git a/v7/recyclerview/src/android/support/v7/widget/SnapHelper.java b/v7/recyclerview/src/android/support/v7/widget/SnapHelper.java
index d63045b..d85a27a 100644
--- a/v7/recyclerview/src/android/support/v7/widget/SnapHelper.java
+++ b/v7/recyclerview/src/android/support/v7/widget/SnapHelper.java
@@ -19,6 +19,7 @@
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.v7.widget.RecyclerView.LayoutManager;
+import android.support.v7.widget.RecyclerView.SmoothScroller;
 import android.support.v7.widget.RecyclerView.SmoothScroller.ScrollVectorProvider;
 import android.util.DisplayMetrics;
 import android.view.View;
@@ -159,7 +160,7 @@
             return false;
         }
 
-        RecyclerView.SmoothScroller smoothScroller = createSnapScroller(layoutManager);
+        SmoothScroller smoothScroller = createScroller(layoutManager);
         if (smoothScroller == null) {
             return false;
         }
@@ -203,9 +204,24 @@
      * @param layoutManager     The {@link RecyclerView.LayoutManager} associated with the attached
      *                          {@link RecyclerView}.
      *
-     * @return a {@link LinearSmoothScroller} which will handle the scrolling.
+     * @return a {@link SmoothScroller} which will handle the scrolling.
      */
     @Nullable
+    protected SmoothScroller createScroller(LayoutManager layoutManager) {
+        return createSnapScroller(layoutManager);
+    }
+
+    /**
+     * Creates a scroller to be used in the snapping implementation.
+     *
+     * @param layoutManager     The {@link RecyclerView.LayoutManager} associated with the attached
+     *                          {@link RecyclerView}.
+     *
+     * @return a {@link LinearSmoothScroller} which will handle the scrolling.
+     * @deprecated use {@link #createScroller(LayoutManager)} instead.
+     */
+    @Nullable
+    @Deprecated
     protected LinearSmoothScroller createSnapScroller(LayoutManager layoutManager) {
         if (!(layoutManager instanceof ScrollVectorProvider)) {
             return null;
@@ -281,4 +297,4 @@
      */
     public abstract int findTargetSnapPosition(LayoutManager layoutManager, int velocityX,
             int velocityY);
-}
\ No newline at end of file
+}
diff --git a/v7/recyclerview/src/android/support/v7/widget/StaggeredGridLayoutManager.java b/v7/recyclerview/src/android/support/v7/widget/StaggeredGridLayoutManager.java
index 679f483..f3ea045 100644
--- a/v7/recyclerview/src/android/support/v7/widget/StaggeredGridLayoutManager.java
+++ b/v7/recyclerview/src/android/support/v7/widget/StaggeredGridLayoutManager.java
@@ -55,7 +55,7 @@
 public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager implements
         RecyclerView.SmoothScroller.ScrollVectorProvider {
 
-    private static final String TAG = "StaggeredGridLayoutManager";
+    private static final String TAG = "StaggeredGridLManager";
 
     static final boolean DEBUG = false;
 
diff --git a/v7/recyclerview/src/android/support/v7/widget/ViewBoundsCheck.java b/v7/recyclerview/src/android/support/v7/widget/ViewBoundsCheck.java
index 8a4f89c..191a069 100644
--- a/v7/recyclerview/src/android/support/v7/widget/ViewBoundsCheck.java
+++ b/v7/recyclerview/src/android/support/v7/widget/ViewBoundsCheck.java
@@ -122,7 +122,7 @@
             FLAG_CVS_GT_PVS, FLAG_CVS_EQ_PVS, FLAG_CVS_LT_PVS,
             FLAG_CVS_GT_PVE, FLAG_CVS_EQ_PVE, FLAG_CVS_LT_PVE,
             FLAG_CVE_GT_PVS, FLAG_CVE_EQ_PVS, FLAG_CVE_LT_PVS,
-            FLAG_CVE_EQ_PVE, FLAG_CVE_EQ_PVE, FLAG_CVE_LT_PVE
+            FLAG_CVE_GT_PVE, FLAG_CVE_EQ_PVE, FLAG_CVE_LT_PVE
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ViewBounds {}
diff --git a/v7/recyclerview/tests/AndroidManifest.xml b/v7/recyclerview/tests/AndroidManifest.xml
index 22c2e32..3d10333 100644
--- a/v7/recyclerview/tests/AndroidManifest.xml
+++ b/v7/recyclerview/tests/AndroidManifest.xml
@@ -15,13 +15,8 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.v7.recyclerview.test">
-    <uses-sdk android:minSdkVersion="14"
-              android:targetSdkVersion="23"
-              tools:overrideLibrary="android.support.test,
-                      android.app, android.support.test.rule, android.support.test.espresso,
-                      android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
     <application android:supportsRtl="true">
         <activity android:name="android.support.v7.widget.test.RecyclerViewTestActivity"
diff --git a/v7/recyclerview/tests/src/android/support/v7/util/ImeCleanUpTestRule.java b/v7/recyclerview/tests/src/android/support/v7/util/ImeCleanUpTestRule.java
new file mode 100644
index 0000000..f4caad3
--- /dev/null
+++ b/v7/recyclerview/tests/src/android/support/v7/util/ImeCleanUpTestRule.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2017 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 android.support.v7.util;
+
+import android.graphics.Rect;
+import android.support.testutils.PollingCheck;
+import android.view.View;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+/**
+ * A JUnit rule that ensures that IME is closed after a test is finished (or exception thrown).
+ * A test that triggers IME open/close should call setContainerView with the activity's container
+ * view in order to trigger this cleanup at the end of the test. Otherwise, no cleanup happens.
+ */
+public class ImeCleanUpTestRule implements TestRule {
+
+    private View mContainerView;
+
+    @Override
+    public Statement apply(final Statement base, Description description) {
+        return new Statement() {
+            @Override
+            public void evaluate() throws Throwable {
+                try {
+                    base.evaluate();
+                } finally {
+                    closeImeIfOpen();
+                }
+            }
+        };
+    }
+
+    /**
+     * Sets the container view used to calculate the total screen height and the height available
+     * to the test activity.
+     */
+    public void setContainerView(View containerView) {
+        mContainerView = containerView;
+    }
+
+    private void closeImeIfOpen() {
+        if (mContainerView == null) {
+            return;
+        }
+        // Ensuring that IME is closed after starting each test.
+        final Rect r = new Rect();
+        mContainerView.getWindowVisibleDisplayFrame(r);
+        // This is the entire height of the screen available to both the view and IME
+        final int screenHeight = mContainerView.getRootView().getHeight();
+
+        // r.bottom is the position above IME if it's open or device button.
+        // if IME is shown, r.bottom is smaller than screenHeight.
+        int imeHeight = screenHeight - r.bottom;
+
+        // Picking a threshold to detect when IME is open
+        if (imeHeight > screenHeight * 0.15) {
+            // Soft keyboard is shown, will wait for it to close after running the test. Note that
+            // we don't press back button here as the IME should close by itself when a test
+            // finishes. If the wait isn't done here, the IME can mess up with the layout of the
+            // next test.
+            PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+                @Override
+                public boolean canProceed() {
+                    mContainerView.getWindowVisibleDisplayFrame(r);
+                    int imeHeight = screenHeight - r.bottom;
+                    return imeHeight < screenHeight * 0.15;
+                }
+            });
+        }
+    }
+}
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/BaseGridLayoutManagerTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/BaseGridLayoutManagerTest.java
index cc6bbe8..13dd1e4 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/BaseGridLayoutManagerTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/BaseGridLayoutManagerTest.java
@@ -325,6 +325,36 @@
         }
     }
 
+    class GridEditTextAdapter extends EditTextAdapter {
+
+        Set<Integer> mFullSpanItems = new HashSet<Integer>();
+        int mSpanPerItem = 1;
+
+        GridEditTextAdapter(int count) {
+            this(count, 1);
+        }
+
+        GridEditTextAdapter(int count, int spanPerItem) {
+            super(count);
+            mSpanPerItem = spanPerItem;
+        }
+
+        void setFullSpan(int... items) {
+            for (int i : items) {
+                mFullSpanItems.add(i);
+            }
+        }
+
+        void assignSpanSizeLookup(final GridLayoutManager glm) {
+            glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
+                @Override
+                public int getSpanSize(int position) {
+                    return mFullSpanItems.contains(position) ? glm.getSpanCount() : mSpanPerItem;
+                }
+            });
+        }
+    }
+
     class GridTestAdapter extends TestAdapter {
 
         Set<Integer> mFullSpanItems = new HashSet<Integer>();
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/BaseRecyclerViewInstrumentationTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/BaseRecyclerViewInstrumentationTest.java
index 8ca5f4e..2139497 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/BaseRecyclerViewInstrumentationTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/BaseRecyclerViewInstrumentationTest.java
@@ -38,10 +38,12 @@
 import android.support.v4.view.ViewCompat;
 import android.support.v7.recyclerview.test.R;
 import android.support.v7.recyclerview.test.SameActivityTestRule;
+import android.text.Editable;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
+import android.widget.EditText;
 import android.widget.FrameLayout;
 import android.widget.TextView;
 
@@ -793,6 +795,37 @@
         }
     }
 
+    public class EditTextAdapter extends RecyclerView.Adapter<TestViewHolder> {
+
+        final ArrayList<Editable> mEditables;
+        public EditTextAdapter(int count) {
+            mEditables = new ArrayList<>();
+            for (int i = 0; i < count; ++i) {
+                mEditables.add(Editable.Factory.getInstance().newEditable("Sample Text " + i));
+            }
+        }
+
+        @Override
+        public TestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+            final EditText editText = new EditText(parent.getContext());
+            editText.setLayoutParams(new ViewGroup.LayoutParams(
+                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+            final TestViewHolder viewHolder = new TestViewHolder(editText);
+            return viewHolder;
+        }
+
+        @Override
+        public void onBindViewHolder(TestViewHolder holder, int position) {
+            ((EditText) holder.itemView).setText(Editable.Factory.getInstance().newEditable(
+                    mEditables.get(position)));
+        }
+
+        @Override
+        public int getItemCount() {
+            return mEditables.size();
+        }
+    }
+
     public class TestAdapter extends RecyclerView.Adapter<TestViewHolder>
             implements AttachDetachCountingAdapter {
 
@@ -812,7 +845,7 @@
             mLayoutParams = layoutParams;
         }
 
-        private void addItems(int pos, int count, String prefix) {
+        void addItems(int pos, int count, String prefix) {
             for (int i = 0; i < count; i++, pos++) {
                 mItems.add(pos, new Item(pos, prefix));
             }
@@ -1197,6 +1230,27 @@
         }
     }
 
+
+    public static View findFirstFullyVisibleChild(RecyclerView parent) {
+        for (int i = 0; i < parent.getChildCount(); i++) {
+            View child = parent.getChildAt(i);
+            if (isViewFullyInBound(parent, child)) {
+                return child;
+            }
+        }
+        return null;
+    }
+
+    public static View findLastFullyVisibleChild(RecyclerView parent) {
+        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
+            View child = parent.getChildAt(i);
+            if (isViewFullyInBound(parent, child)) {
+                return child;
+            }
+        }
+        return null;
+    }
+
     /**
      * Returns whether a child of RecyclerView is partially in bound. A child is
      * partially in-bounds if it's either fully or partially visible on the screen.
@@ -1232,7 +1286,7 @@
      * @param child The child view to be checked whether is fully within RV's bounds.
      * @return True if the child view is fully visible; false otherwise.
      */
-    public boolean isViewFullyInBound(RecyclerView parent, View child) {
+    public static boolean isViewFullyInBound(RecyclerView parent, View child) {
         if (child == null) {
             return false;
         }
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/GridLayoutManagerTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/GridLayoutManagerTest.java
index 5ebebfe..23eaf52 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/GridLayoutManagerTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/GridLayoutManagerTest.java
@@ -18,6 +18,9 @@
 
 import static android.support.v7.widget.LinearLayoutManager.HORIZONTAL;
 import static android.support.v7.widget.LinearLayoutManager.VERTICAL;
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertEquals;
@@ -34,15 +37,20 @@
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.SdkSuppress;
 import android.support.test.runner.AndroidJUnit4;
+import android.support.testutils.PollingCheck;
 import android.support.v4.view.AccessibilityDelegateCompat;
 import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
+import android.support.v7.util.ImeCleanUpTestRule;
+import android.support.v7.util.TouchUtils;
 import android.test.UiThreadTest;
 import android.util.SparseIntArray;
 import android.util.StateSet;
+import android.view.KeyEvent;
 import android.view.View;
 import android.view.ViewGroup;
 
 import org.hamcrest.CoreMatchers;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -56,6 +64,9 @@
 @RunWith(AndroidJUnit4.class)
 public class GridLayoutManagerTest extends BaseGridLayoutManagerTest {
 
+    @Rule
+    public final ImeCleanUpTestRule imeCleanUp = new ImeCleanUpTestRule();
+
     @Test
     public void focusSearchFailureUp() throws Throwable {
         focusSearchFailure(false);
@@ -168,6 +179,101 @@
         }
     }
 
+    @Test
+    public void editTextVisibility() throws Throwable {
+        final int spanCount = 3;
+        final int itemCount = 100;
+
+        imeCleanUp.setContainerView(getActivity().getContainer());
+        RecyclerView recyclerView = new WrappedRecyclerView(getActivity());
+        GridEditTextAdapter editTextAdapter = new GridEditTextAdapter(itemCount) {
+            @Override
+            public TestViewHolder onCreateViewHolder(ViewGroup parent,
+                    int viewType) {
+                TestViewHolder testViewHolder = super.onCreateViewHolder(parent, viewType);
+                // Good to have colors for debugging
+                StateListDrawable stl = new StateListDrawable();
+                stl.addState(new int[]{android.R.attr.state_focused},
+                        new ColorDrawable(Color.RED));
+                stl.addState(StateSet.WILD_CARD, new ColorDrawable(Color.BLUE));
+                //noinspection deprecation using this for kitkat tests
+                testViewHolder.itemView.setBackgroundDrawable(stl);
+                return testViewHolder;
+            }
+        };
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mActivityRule.getActivity().getWindow().setSoftInputMode(SOFT_INPUT_ADJUST_RESIZE);
+            }
+        });
+
+        recyclerView.setLayoutParams(
+                new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
+
+        Config config = new Config(spanCount, itemCount);
+        mGlm = new WrappedGridLayoutManager(getActivity(), config.mSpanCount, config.mOrientation,
+                config.mReverseLayout);
+        editTextAdapter.assignSpanSizeLookup(mGlm);
+        recyclerView.setAdapter(editTextAdapter);
+        recyclerView.setLayoutManager(mGlm);
+        waitForFirstLayout(recyclerView);
+
+        // First focus on the last fully visible EditText located at span index #1.
+        View toFocus = findLastFullyVisibleChild(mRecyclerView);
+        int focusIndex = mRecyclerView.getChildAdapterPosition(toFocus);
+        focusIndex = (focusIndex / spanCount) * spanCount + 1;
+        toFocus = mRecyclerView.findViewHolderForAdapterPosition(focusIndex).itemView;
+        assertTrue(focusIndex >= 1 && focusIndex < itemCount);
+
+        final int heightBeforeImeOpen = mRecyclerView.getHeight();
+        TouchUtils.tapView(getInstrumentation(), mRecyclerView, toFocus);
+        getInstrumentation().waitForIdleSync();
+        // Wait for IME to pop up.
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() < heightBeforeImeOpen;
+            }
+        });
+
+        assertThat("Child at position " + focusIndex + " should be focused",
+                toFocus.hasFocus(), is(true));
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+
+        // Close IME
+        final int heightBeforeImeClose = mRecyclerView.getHeight();
+        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        getInstrumentation().waitForIdleSync();
+        // Wait for IME to close
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() > heightBeforeImeClose;
+            }
+        });
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+
+        // Now focus on the first fully visible EditText located at the last span index.
+        toFocus = findFirstFullyVisibleChild(mRecyclerView);
+        focusIndex = mRecyclerView.getChildAdapterPosition(toFocus);
+        focusIndex = (focusIndex / spanCount) * spanCount + (spanCount - 1);
+        toFocus = mRecyclerView.findViewHolderForAdapterPosition(focusIndex).itemView;
+        final int heightBeforeImeOpen2 = mRecyclerView.getHeight();
+        TouchUtils.tapView(getInstrumentation(), mRecyclerView, toFocus);
+        getInstrumentation().waitForIdleSync();
+        // Wait for IME to pop up
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() < heightBeforeImeOpen2;
+            }
+        });
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+    }
 
     @Test
     public void topUnfocusableViewsVisibility() throws Throwable {
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/LinearLayoutManagerTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/LinearLayoutManagerTest.java
index a2db640..91d0dbf 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/LinearLayoutManagerTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/LinearLayoutManagerTest.java
@@ -18,6 +18,9 @@
 
 import static android.support.v7.widget.LinearLayoutManager.HORIZONTAL;
 import static android.support.v7.widget.LinearLayoutManager.VERTICAL;
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertEquals;
@@ -34,13 +37,19 @@
 import android.os.Build;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.SdkSuppress;
+import android.support.testutils.PollingCheck;
 import android.support.v4.view.AccessibilityDelegateCompat;
+import android.support.v7.util.ImeCleanUpTestRule;
+import android.support.v7.util.TouchUtils;
 import android.util.Log;
 import android.util.StateSet;
+import android.view.KeyEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.accessibility.AccessibilityEvent;
+import android.widget.LinearLayout;
 
+import org.junit.Rule;
 import org.junit.Test;
 
 import java.util.ArrayList;
@@ -60,6 +69,111 @@
 @LargeTest
 public class LinearLayoutManagerTest extends BaseLinearLayoutManagerTest {
 
+    @Rule
+    public final ImeCleanUpTestRule imeCleanUp = new ImeCleanUpTestRule();
+
+    @Test
+    public void editTextVisibility() throws Throwable {
+
+        // Simulating a scenario where an EditText is tapped (which will receive focus).
+        // The soft keyboard that's opened overlaps the focused EditText which will shrink RV's
+        // padded bounded area. LLM should still lay out the focused EditText so that it becomes
+        // visible above the soft keyboard.
+        // The condition for this test is setting RV's height to a non-exact height, so that measure
+        // is called twice (once with the larger height and another time with smaller height when
+        // the keyboard shows up). To ensure this resizing of RV, SOFT_INPUT_ADJUST_RESIZE is set.
+        imeCleanUp.setContainerView(getActivity().getContainer());
+        final LinearLayout container = new LinearLayout(getActivity());
+        container.setOrientation(LinearLayout.VERTICAL);
+        container.setLayoutParams(
+                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
+                        .LayoutParams.MATCH_PARENT));
+
+        final EditTextAdapter editTextAdapter = new EditTextAdapter(50);
+
+        mRecyclerView = inflateWrappedRV();
+        ViewGroup.LayoutParams lp = mRecyclerView.getLayoutParams();
+        lp.height = WRAP_CONTENT;
+        lp.width = MATCH_PARENT;
+
+        mRecyclerView.setHasFixedSize(true);
+        mRecyclerView.setAdapter(editTextAdapter);
+        mLayoutManager = new WrappedLinearLayoutManager(getActivity(), VERTICAL, false);
+        mRecyclerView.setLayoutManager(mLayoutManager);
+
+        container.addView(mRecyclerView);
+
+        mLayoutManager.expectLayouts(1);
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                getActivity().getContainer().addView(container);
+            }
+        });
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mActivityRule.getActivity().getWindow().setSoftInputMode(SOFT_INPUT_ADJUST_RESIZE);
+            }
+        });
+
+        // First focus on the last fully visible EditText.
+        View toFocus = findLastFullyVisibleChild(mRecyclerView);
+        int focusIndex = mRecyclerView.getChildAdapterPosition(toFocus);
+
+        final int heightBeforeImeOpen = mRecyclerView.getHeight();
+        TouchUtils.tapView(getInstrumentation(), mRecyclerView, toFocus);
+        getInstrumentation().waitForIdleSync();
+       // Wait for IME to pop up.
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() < heightBeforeImeOpen;
+            }
+        });
+
+        assertThat("Child at position " + focusIndex + " should be focused",
+                toFocus.hasFocus(), is(true));
+        // Testing for partial visibility instead of full visibility since TextView calls
+        // requestRectangleOnScreen (inside bringPointIntoView) for the focused view with a rect
+        // containing the content area. This rect is guaranteed to be fully visible whereas a
+        // portion of TextView could be out of bounds.
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+
+        // Close IME
+        final int heightBeforeImeClose = mRecyclerView.getHeight();
+        getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
+        getInstrumentation().waitForIdleSync();
+        // Wait for IME to close
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() > heightBeforeImeClose;
+            }
+        });
+        assertThat("Child at position " + focusIndex + " should be focused",
+                toFocus.hasFocus(), is(true));
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+
+        // Now focus on the first fully visible EditText.
+        toFocus = findFirstFullyVisibleChild(mRecyclerView);
+        focusIndex = mRecyclerView.getChildAdapterPosition(toFocus);
+        final int heightBeforeImeOpen2 = mRecyclerView.getHeight();
+        TouchUtils.tapView(getInstrumentation(), mRecyclerView, toFocus);
+        getInstrumentation().waitForIdleSync();
+        // Wait for IME to pop up
+        PollingCheck.waitFor(new PollingCheck.PollingCheckCondition() {
+            @Override
+            public boolean canProceed() {
+                return mRecyclerView.getHeight() < heightBeforeImeOpen2;
+            }
+        });
+        assertTrue("Child view at adapter pos " + focusIndex + " should be fully visible.",
+                isViewPartiallyInBound(mRecyclerView, toFocus));
+    }
+
     @Test
     public void topUnfocusableViewsVisibility() throws Throwable {
         // The maximum number of child views that can be visible at any time.
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewBasicTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewBasicTest.java
index a7530d1..5a13f52 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewBasicTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewBasicTest.java
@@ -460,32 +460,23 @@
     }
 
     @Test
-    public void toStringContainsClasses() {
-        RecyclerView recyclerView = new RecyclerView(getContext());
-        recyclerView.setAdapter(new MockAdapter(10));
-        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
-
-        String string = recyclerView.toString();
-        assertTrue("must contain RV class", string.contains(RecyclerView.class.getName()));
-        assertTrue("must contain Adapter class", string.contains(MockAdapter.class.getName()));
-        assertTrue("must contain LM class", string.contains(LinearLayoutManager.class.getName()));
-        assertTrue("must contain ctx class", string.contains(getContext().getClass().getName()));
-    }
-
-    @Test
     public void exceptionContainsClasses() {
-        RecyclerView recyclerView = new RecyclerView(getContext());
-        recyclerView.setAdapter(new MockAdapter(10));
+        RecyclerView first = new RecyclerView(getContext());
+        first.setLayoutManager(new LinearLayoutManager(getContext()));
+        first.setAdapter(new MockAdapter(10));
 
+        RecyclerView second = new RecyclerView(getContext());
         try {
-            recyclerView.generateDefaultLayoutParams();
+            second.setLayoutManager(first.getLayoutManager());
             fail("exception expected");
-        } catch (IllegalStateException e) {
-            String message = e.getMessage();
-            assertTrue("must contain RV class",
-                    message.contains(RecyclerView.class.getName()));
-            assertTrue("must contain Adapter class",
-                    message.contains(MockAdapter.class.getName()));
+        } catch (IllegalArgumentException e) {
+            // Note: exception contains first RV
+            String m = e.getMessage();
+            assertTrue("must contain RV class", m.contains(RecyclerView.class.getName()));
+            assertTrue("must contain Adapter class", m.contains(MockAdapter.class.getName()));
+            assertTrue("must contain LM class", m.contains(LinearLayoutManager.class.getName()));
+            assertTrue("must contain ctx class", m.contains(getContext().getClass().getName()));
+
         }
     }
 
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewCacheTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewCacheTest.java
index 1006e1b..1267fdb 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewCacheTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewCacheTest.java
@@ -44,12 +44,11 @@
 import android.view.ViewGroup;
 import android.widget.FrameLayout;
 
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatcher;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -299,6 +298,41 @@
     }
 
     @Test
+    public void prefetchAfterOrientationChange() {
+        LinearLayoutManager layout = new LinearLayoutManager(getContext(),
+                LinearLayoutManager.VERTICAL, false);
+        mRecyclerView.setLayoutManager(layout);
+
+        // 100x100 pixel views
+        mRecyclerView.setAdapter(new RecyclerView.Adapter() {
+            @Override
+            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+                View view = new View(getContext());
+                view.setMinimumWidth(100);
+                view.setMinimumHeight(100);
+                assertTrue(mRecyclerView.isComputingLayout());
+                return new RecyclerView.ViewHolder(view) {};
+            }
+
+            @Override
+            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {}
+
+            @Override
+            public int getItemCount() {
+                return 100;
+            }
+        });
+
+        layout(100, 100);
+
+        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
+
+        // Prefetch an item after changing orientation, before layout - shouldn't crash
+        mRecyclerView.mPrefetchRegistry.setPrefetchVector(1, 1);
+        mRecyclerView.mGapWorker.prefetch(RecyclerView.FOREVER_NS);
+    }
+
+    @Test
     public void prefetchDrag() {
         // event dispatch requires a parent
         ViewGroup parent = new FrameLayout(getContext());
@@ -687,15 +721,11 @@
 
         verify(mockAdapter, times(2)).onCreateViewHolder(any(ViewGroup.class), anyInt());
         verify(mockAdapter, times(2)).onBindViewHolder(
-                argThat(new BaseMatcher<RecyclerView.ViewHolder>() {
+                argThat(new ArgumentMatcher<RecyclerView.ViewHolder>() {
                     @Override
-                    public boolean matches(Object item) {
-                        RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder) item;
+                    public boolean matches(RecyclerView.ViewHolder holder) {
                         return holder.itemView == holder.mNestedRecyclerView.get();
                     }
-
-                    @Override
-                    public void describeTo(Description description) { }
                 }),
                 anyInt(),
                 any(List.class));
diff --git a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewLayoutTest.java b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewLayoutTest.java
index be687c3..42fde85 100644
--- a/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewLayoutTest.java
+++ b/v7/recyclerview/tests/src/android/support/v7/widget/RecyclerViewLayoutTest.java
@@ -252,6 +252,112 @@
     }
 
     @Test
+    public void setAdapterNotifyItemRangeInsertedCrashTest() throws Throwable {
+        final RecyclerView rv = new RecyclerView(getActivity());
+        final TestLayoutManager lm = new LayoutAllLayoutManager(true);
+        lm.setSupportsPredictive(true);
+        rv.setLayoutManager(lm);
+        setRecyclerView(rv);
+        lm.expectLayouts(1);
+        setAdapter(new TestAdapter(1));
+        lm.waitForLayout(2);
+        lm.expectLayouts(1);
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                final TestAdapter adapter2 = new TestAdapter(0);
+                rv.setAdapter(adapter2);
+                adapter2.addItems(0, 1, "1");
+                adapter2.notifyItemRangeInserted(0, 1);
+            }
+        });
+        lm.waitForLayout(2);
+    }
+
+    @Test
+    public void swapAdapterNotifyItemRangeInsertedCrashTest() throws Throwable {
+        final RecyclerView rv = new RecyclerView(getActivity());
+        final TestLayoutManager lm = new LayoutAllLayoutManager(true);
+        lm.setSupportsPredictive(true);
+        rv.setLayoutManager(lm);
+        setRecyclerView(rv);
+        lm.expectLayouts(1);
+        setAdapter(new TestAdapter(1));
+        lm.waitForLayout(2);
+        lm.expectLayouts(1);
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                final TestAdapter adapter2 = new TestAdapter(0);
+                rv.swapAdapter(adapter2, true);
+                adapter2.addItems(0, 1, "1");
+                adapter2.notifyItemRangeInserted(0, 1);
+            }
+        });
+        lm.waitForLayout(2);
+    }
+
+    @Test
+    public void predictiveMeasuredCrashTest() throws Throwable {
+        final RecyclerView rv = new RecyclerView(getActivity());
+        final LayoutAllLayoutManager lm = new LayoutAllLayoutManager(true) {
+            @Override
+            public void onAttachedToWindow(RecyclerView view) {
+                super.onAttachedToWindow(view);
+                assertThat(view.mLayout, is((RecyclerView.LayoutManager) this));
+            }
+
+            @Override
+            public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
+                super.onDetachedFromWindow(view, recycler);
+                assertThat(view.mLayout, is((RecyclerView.LayoutManager) this));
+            }
+
+            @Override
+            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
+                    int widthSpec,
+                    int heightSpec) {
+                if (state.getItemCount() > 0) {
+                    // A typical LayoutManager will use a child view to measure the size.
+                    View v = recycler.getViewForPosition(0);
+                }
+                super.onMeasure(recycler, state, widthSpec, heightSpec);
+            }
+        };
+        lm.setSupportsPredictive(true);
+        lm.setAutoMeasureEnabled(false);
+        rv.setHasFixedSize(false);
+        final TestAdapter adapter = new TestAdapter(0);
+        rv.setAdapter(adapter);
+        rv.setLayoutManager(lm);
+        lm.expectLayouts(1);
+        setRecyclerView(rv);
+        lm.waitForLayout(2);
+        mActivityRule.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                ViewGroup parent = (ViewGroup) rv.getParent();
+                parent.removeView(rv);
+                // setting RV as child of LinearLayout using MATCH_PARENT will cause
+                // RV.onMeasure() being called twice before layout(). This may cause crash.
+                LinearLayout linearLayout = new LinearLayout(parent.getContext());
+                linearLayout.setOrientation(LinearLayout.VERTICAL);
+                parent.addView(linearLayout,
+                        ViewGroup.LayoutParams.WRAP_CONTENT,
+                        ViewGroup.LayoutParams.WRAP_CONTENT);
+                linearLayout.addView(rv, ViewGroup.LayoutParams.MATCH_PARENT,
+                        ViewGroup.LayoutParams.WRAP_CONTENT);
+
+            }
+        });
+
+        lm.expectLayouts(1);
+        adapter.addAndNotify(1);
+        lm.waitForLayout(2);
+        checkForMainThreadException();
+    }
+
+    @Test
     public void detachRvAndLayoutManagerProperly() throws Throwable {
         final RecyclerView rv = new RecyclerView(getActivity());
         final LayoutAllLayoutManager lm = new LayoutAllLayoutManager(true) {
diff --git a/wear/AndroidManifest.xml b/wear/AndroidManifest.xml
index fda54e2..5fa5a83 100644
--- a/wear/AndroidManifest.xml
+++ b/wear/AndroidManifest.xml
@@ -15,7 +15,6 @@
 -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.support.wear">
-    <uses-sdk android:minSdkVersion="22"/>
     <application>
         <meta-data android:name="android.support.VERSION" android:value="${support-version}" />
     </application>
diff --git a/wear/build.gradle b/wear/build.gradle
index b320ab7..1e39dfc 100644
--- a/wear/build.gradle
+++ b/wear/build.gradle
@@ -2,19 +2,19 @@
 archivesBaseName = 'wear'
 
 dependencies {
-    compile project(':support-annotations')
-    compile project(':support-core-ui')
-    compile project(':support-percent')
-    compile project(':support-recyclerview-v7')
-    androidTestCompile (libs.test_runner) {
+    api project(':support-annotations')
+    api project(':support-core-ui')
+    api project(':support-percent')
+    api project(':support-recyclerview-v7')
+
+    androidTestImplementation (libs.test_runner) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile (libs.espresso_core) {
+    androidTestImplementation (libs.espresso_core) {
         exclude module: 'support-annotations'
     }
-    androidTestCompile libs.mockito_core
-    androidTestCompile libs.dexmaker
-    androidTestCompile libs.dexmaker_mockito
+    androidTestImplementation libs.mockito_core
+    androidTestImplementation libs.dexmaker_mockito
 }
 
 android {
diff --git a/wear/lint-baseline.xml b/wear/lint-baseline.xml
new file mode 100644
index 0000000..81531cf
--- /dev/null
+++ b/wear/lint-baseline.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="4" by="lint 3.0.0-alpha7">
+
+    <issue
+        id="DuplicateIds"
+        message="Duplicate id `@+id/off`, already defined earlier in this layout"
+        errorLine1="        android:id=&quot;@+id/off&quot;"
+        errorLine2="        ~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="res/drawable-v21/ws_switch_thumb_material_anim.xml"
+            line="27"
+            column="9"/>
+        <location
+            file="res/drawable-v21/ws_switch_thumb_material_anim.xml"
+            line="19"
+            column="9"/>
+    </issue>
+
+    <issue
+        id="ResourceAsColor"
+        message="Should pass resolved color instead of resource id here: `getResources().getColor(android.R.color.darker_gray)`"
+        errorLine1="            mCircleColor = ColorStateList.valueOf(android.R.color.darker_gray);"
+        errorLine2="                                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+        <location
+            file="src/android/support/wear/widget/CircledImageView.java"
+            line="148"
+            column="51"/>
+    </issue>
+
+</issues>
diff --git a/wear/res-public/values-v24/public_styles.xml b/wear/res-public/values-v24/public_styles.xml
new file mode 100644
index 0000000..d4575e4
--- /dev/null
+++ b/wear/res-public/values-v24/public_styles.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<!-- Definitions of styles to be exposed as public -->
+<resources>
+    <public type="style" name="Widget.Wear.RoundSwitch"/>
+</resources>
diff --git a/wear/res-public/values/public_attrs.xml b/wear/res-public/values/public_attrs.xml
index 285c3dc..b4b35db 100644
--- a/wear/res-public/values/public_attrs.xml
+++ b/wear/res-public/values/public_attrs.xml
@@ -36,4 +36,10 @@
 
     <!-- WearableNavigationDrawerView -->
     <public type="attr" name="navigationStyle" />
+
+    <!-- CircularProgressLayout -->
+    <public type="attr" name="backgroundColor" />
+    <public type="attr" name="colorSchemeColors" />
+    <public type="attr" name="strokeWidth" />
+    <public type="attr" name="indeterminate" />
 </resources>
diff --git a/wear/res/color/ws_switch_thumb_color_material.xml b/wear/res/color/ws_switch_thumb_color_material.xml
new file mode 100644
index 0000000..0707d69
--- /dev/null
+++ b/wear/res/color/ws_switch_thumb_color_material.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="?android:attr/colorButtonNormal"
+            android:alpha="?android:attr/disabledAlpha" android:state_enabled="false" />
+    <item android:color="?android:attr/colorControlActivated" android:state_checked="true" />
+    <item android:color="?android:attr/colorButtonNormal" />
+</selector>
diff --git a/wear/res/color/ws_switch_track_color_material.xml b/wear/res/color/ws_switch_track_color_material.xml
new file mode 100644
index 0000000..214bf4a
--- /dev/null
+++ b/wear/res/color/ws_switch_track_color_material.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:state_enabled="false"
+          android:alpha="?android:attr/disabledAlpha"
+          android:color="?android:attr/colorPrimary" />
+    <item android:color="?android:attr/colorPrimary" />
+</selector>
diff --git a/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_14w.png b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_14w.png
new file mode 100644
index 0000000..035e901
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_14w.png
Binary files differ
diff --git a/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_15w.png b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_15w.png
new file mode 100644
index 0000000..6688631
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_15w.png
Binary files differ
diff --git a/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_16w.png b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_16w.png
new file mode 100644
index 0000000..0dd9fce
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_16w.png
Binary files differ
diff --git a/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_17w.png b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_17w.png
new file mode 100644
index 0000000..a15b133
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_17w.png
Binary files differ
diff --git a/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_18w.png b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_18w.png
new file mode 100644
index 0000000..1cd259e
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_thumb_mtrl_18w.png
Binary files differ
diff --git a/wear/res/drawable-hdpi/ws_switch_track_mtrl.png b/wear/res/drawable-hdpi/ws_switch_track_mtrl.png
new file mode 100644
index 0000000..8ed1c97
--- /dev/null
+++ b/wear/res/drawable-hdpi/ws_switch_track_mtrl.png
Binary files differ
diff --git a/wear/res/drawable-v21/ic_expand_more_white_22.xml b/wear/res/drawable-v21/ws_ic_expand_more_white_22.xml
similarity index 100%
rename from wear/res/drawable-v21/ic_expand_more_white_22.xml
rename to wear/res/drawable-v21/ws_ic_expand_more_white_22.xml
diff --git a/wear/res/drawable-v21/ws_switch_thumb_material_anim.xml b/wear/res/drawable-v21/ws_switch_thumb_material_anim.xml
new file mode 100644
index 0000000..15423e5
--- /dev/null
+++ b/wear/res/drawable-v21/ws_switch_thumb_material_anim.xml
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<animated-selector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:constantSize="true">
+    <item
+        android:id="@+id/off"
+        android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+        android:state_enabled="false" />
+    <item
+        android:id="@+id/on"
+        android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+        android:state_checked="true" />
+    <item
+        android:id="@+id/off"
+        android:drawable="@drawable/ws_switch_thumb_mtrl_14w" />
+    <transition
+        android:fromId="@id/off"
+        android:toId="@id/on">
+        <animation-list>
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+                android:duration="30" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_15w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_16w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_17w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_18w"
+                android:duration="75" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_17w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_16w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_15w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+                android:duration="30" />
+        </animation-list>
+    </transition>
+    <transition
+        android:fromId="@id/on"
+        android:toId="@id/off">
+        <animation-list>
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+                android:duration="30" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_15w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_16w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_17w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_18w"
+                android:duration="75" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_17w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_16w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_15w"
+                android:duration="15" />
+            <item
+                android:drawable="@drawable/ws_switch_thumb_mtrl_14w"
+                android:duration="30" />
+        </animation-list>
+    </transition>
+</animated-selector>
diff --git a/wear/res/drawable-v23/action_item_background.xml b/wear/res/drawable-v23/ws_action_item_background.xml
similarity index 100%
rename from wear/res/drawable-v23/action_item_background.xml
rename to wear/res/drawable-v23/ws_action_item_background.xml
diff --git a/wear/res/drawable-v23/action_item_icon_background.xml b/wear/res/drawable-v23/ws_action_item_icon_background.xml
similarity index 100%
rename from wear/res/drawable-v23/action_item_icon_background.xml
rename to wear/res/drawable-v23/ws_action_item_icon_background.xml
diff --git a/wear/res/drawable-v23/ic_expand_less_white_22.xml b/wear/res/drawable-v23/ws_ic_expand_less_white_22.xml
similarity index 100%
rename from wear/res/drawable-v23/ic_expand_less_white_22.xml
rename to wear/res/drawable-v23/ws_ic_expand_less_white_22.xml
diff --git a/wear/res/drawable-v23/ic_more_horiz_24dp_wht.xml b/wear/res/drawable-v23/ws_ic_more_horiz_24dp_wht.xml
similarity index 100%
rename from wear/res/drawable-v23/ic_more_horiz_24dp_wht.xml
rename to wear/res/drawable-v23/ws_ic_more_horiz_24dp_wht.xml
diff --git a/wear/res/drawable-v23/ic_more_vert_24dp_wht.xml b/wear/res/drawable-v23/ws_ic_more_vert_24dp_wht.xml
similarity index 100%
rename from wear/res/drawable-v23/ic_more_vert_24dp_wht.xml
rename to wear/res/drawable-v23/ws_ic_more_vert_24dp_wht.xml
diff --git a/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_14w.png b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_14w.png
new file mode 100644
index 0000000..119207b
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_14w.png
Binary files differ
diff --git a/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_15w.png b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_15w.png
new file mode 100644
index 0000000..b89c86a
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_15w.png
Binary files differ
diff --git a/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_16w.png b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_16w.png
new file mode 100644
index 0000000..7528731
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_16w.png
Binary files differ
diff --git a/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_17w.png b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_17w.png
new file mode 100644
index 0000000..dba351f
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_17w.png
Binary files differ
diff --git a/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_18w.png b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_18w.png
new file mode 100644
index 0000000..ab7b1df
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_thumb_mtrl_18w.png
Binary files differ
diff --git a/wear/res/drawable-xhdpi/ws_switch_track_mtrl.png b/wear/res/drawable-xhdpi/ws_switch_track_mtrl.png
new file mode 100644
index 0000000..1769795
--- /dev/null
+++ b/wear/res/drawable-xhdpi/ws_switch_track_mtrl.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_14w.png b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_14w.png
new file mode 100644
index 0000000..8a00760
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_14w.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_15w.png b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_15w.png
new file mode 100644
index 0000000..64a0cab
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_15w.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_16w.png b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_16w.png
new file mode 100644
index 0000000..ce7369e
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_16w.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_17w.png b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_17w.png
new file mode 100644
index 0000000..398e3f2
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_17w.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_18w.png b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_18w.png
new file mode 100644
index 0000000..1cf40e2
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_thumb_mtrl_18w.png
Binary files differ
diff --git a/wear/res/drawable-xxhdpi/ws_switch_track_mtrl.png b/wear/res/drawable-xxhdpi/ws_switch_track_mtrl.png
new file mode 100644
index 0000000..a329817
--- /dev/null
+++ b/wear/res/drawable-xxhdpi/ws_switch_track_mtrl.png
Binary files differ
diff --git a/wear/res/layout-v23/action_drawer_item_view.xml b/wear/res/layout-v23/action_drawer_item_view.xml
deleted file mode 100644
index 068e364..0000000
--- a/wear/res/layout-v23/action_drawer_item_view.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<LinearLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:background="@drawable/action_item_background"
-    android:orientation="horizontal">
-
-    <ImageView
-        android:id="@+id/wearable_support_action_drawer_item_icon"
-        android:layout_width="@dimen/action_drawer_item_icon_size"
-        android:layout_height="@dimen/action_drawer_item_icon_size"
-        android:layout_gravity="center_vertical"
-        android:background="@drawable/action_item_icon_background"
-        android:tint="?android:attr/colorBackground"
-        android:padding="@dimen/action_drawer_item_icon_padding"
-        android:scaleType="fitCenter"
-        tools:ignore="ContentDescription" />
-
-    <TextView
-        android:id="@+id/wearable_support_action_drawer_item_text"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        style="@style/WearableActionDrawerItemText"/>
-
-</LinearLayout>
diff --git a/wear/res/layout-v23/action_drawer_peek_view.xml b/wear/res/layout-v23/action_drawer_peek_view.xml
deleted file mode 100644
index 88946cb..0000000
--- a/wear/res/layout-v23/action_drawer_peek_view.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<LinearLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="wrap_content"
-    android:layout_height="@dimen/action_drawer_peek_view_height"
-    android:layout_gravity="center"
-    android:gravity="center_vertical"
-    android:orientation="vertical"
-    android:paddingTop="@dimen/action_drawer_peek_top_padding">
-
-    <ImageView
-        android:id="@+id/wearable_support_action_drawer_peek_action_icon"
-        android:layout_width="@dimen/peek_view_icon_size"
-        android:layout_height="@dimen/peek_view_icon_size"
-        android:tint="?android:attr/colorForeground"
-        tools:ignore="ContentDescription" />
-
-    <ImageView
-        android:id="@+id/wearable_support_action_drawer_expand_icon"
-        android:layout_width="@dimen/peek_view_icon_size"
-        android:layout_height="@dimen/peek_view_icon_size"
-        android:layout_marginTop="@dimen/action_drawer_expand_icon_top_margin"
-        android:src="@drawable/ic_expand_less_white_22"
-        android:alpha="0.5"
-        android:tint="?android:attr/colorForeground"
-        tools:ignore="NegativeMargin,ContentDescription" />
-
-</LinearLayout>
diff --git a/wear/res/layout-v23/action_drawer_title_view.xml b/wear/res/layout-v23/action_drawer_title_view.xml
deleted file mode 100644
index a2be3e1..0000000
--- a/wear/res/layout-v23/action_drawer_title_view.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<TextView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/wearable_support_action_drawer_title"
-    android:layout_width="wrap_content"
-    android:layout_height="@dimen/action_drawer_item_icon_size"
-    android:layout_gravity="center"
-    android:gravity="center"
-    style="@style/WearableActionDrawerTitleText" />
diff --git a/wear/res/layout-v23/wearable_drawer_view.xml b/wear/res/layout-v23/wearable_drawer_view.xml
deleted file mode 100644
index 8659aac..0000000
--- a/wear/res/layout-v23/wearable_drawer_view.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<merge
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools">
-
-    <!-- Layout gravity for peek is set in code by WearableDrawerView. -->
-    <FrameLayout
-        android:id="@+id/wearable_support_drawer_view_peek_container"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content">
-
-        <ImageView
-            android:id="@+id/wearable_support_drawer_view_peek_icon"
-            android:layout_width="@dimen/peek_view_icon_size"
-            android:layout_height="@dimen/peek_view_icon_size"
-            android:layout_marginTop="@dimen/peek_view_top_padding"
-            android:layout_marginBottom="@dimen/peek_view_bottom_padding"
-            android:layout_gravity="center"
-            android:tint="?android:attr/colorForeground"
-            tools:ignore="ContentDescription" />
-
-    </FrameLayout>
-</merge>
diff --git a/wear/res/layout-v23/ws_action_drawer_item_view.xml b/wear/res/layout-v23/ws_action_drawer_item_view.xml
new file mode 100644
index 0000000..fc84862
--- /dev/null
+++ b/wear/res/layout-v23/ws_action_drawer_item_view.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:background="@drawable/ws_action_item_background"
+    android:orientation="horizontal">
+
+    <ImageView
+        android:id="@+id/ws_action_drawer_item_icon"
+        android:layout_width="@dimen/ws_action_drawer_item_icon_size"
+        android:layout_height="@dimen/ws_action_drawer_item_icon_size"
+        android:layout_gravity="center_vertical"
+        android:background="@drawable/ws_action_item_icon_background"
+        android:tint="?android:attr/colorBackground"
+        android:padding="@dimen/ws_action_drawer_item_icon_padding"
+        android:scaleType="fitCenter"
+        tools:ignore="ContentDescription" />
+
+    <TextView
+        android:id="@+id/ws_action_drawer_item_text"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        style="@style/WsWearableActionDrawerItemText"/>
+
+</LinearLayout>
diff --git a/wear/res/layout-v23/ws_action_drawer_peek_view.xml b/wear/res/layout-v23/ws_action_drawer_peek_view.xml
new file mode 100644
index 0000000..ce66d73
--- /dev/null
+++ b/wear/res/layout-v23/ws_action_drawer_peek_view.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="wrap_content"
+    android:layout_height="@dimen/ws_action_drawer_peek_view_height"
+    android:layout_gravity="center"
+    android:gravity="center_vertical"
+    android:orientation="vertical"
+    android:paddingTop="@dimen/ws_action_drawer_peek_top_padding">
+
+    <ImageView
+        android:id="@+id/ws_action_drawer_peek_action_icon"
+        android:layout_width="@dimen/ws_peek_view_icon_size"
+        android:layout_height="@dimen/ws_peek_view_icon_size"
+        android:tint="?android:attr/colorForeground"
+        tools:ignore="ContentDescription" />
+
+    <ImageView
+        android:id="@+id/ws_action_drawer_expand_icon"
+        android:layout_width="@dimen/ws_peek_view_icon_size"
+        android:layout_height="@dimen/ws_peek_view_icon_size"
+        android:layout_marginTop="@dimen/ws_action_drawer_expand_icon_top_margin"
+        android:src="@drawable/ws_ic_expand_less_white_22"
+        android:alpha="0.5"
+        android:tint="?android:attr/colorForeground"
+        tools:ignore="NegativeMargin,ContentDescription" />
+
+</LinearLayout>
diff --git a/wear/res/layout-v23/ws_action_drawer_title_view.xml b/wear/res/layout-v23/ws_action_drawer_title_view.xml
new file mode 100644
index 0000000..e5535c4
--- /dev/null
+++ b/wear/res/layout-v23/ws_action_drawer_title_view.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<TextView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/ws_action_drawer_title"
+    android:layout_width="wrap_content"
+    android:layout_height="@dimen/ws_action_drawer_item_icon_size"
+    android:layout_gravity="center"
+    android:gravity="center"
+    style="@style/WsWearableActionDrawerTitleText" />
diff --git a/wear/res/layout-v23/ws_wearable_drawer_view.xml b/wear/res/layout-v23/ws_wearable_drawer_view.xml
new file mode 100644
index 0000000..c7c5907
--- /dev/null
+++ b/wear/res/layout-v23/ws_wearable_drawer_view.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<merge
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools">
+
+    <!-- Layout gravity for peek is set in code by WearableDrawerView. -->
+    <FrameLayout
+        android:id="@+id/ws_drawer_view_peek_container"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content">
+
+        <ImageView
+            android:id="@+id/ws_drawer_view_peek_icon"
+            android:layout_width="@dimen/ws_peek_view_icon_size"
+            android:layout_height="@dimen/ws_peek_view_icon_size"
+            android:layout_marginTop="@dimen/ws_peek_view_top_padding"
+            android:layout_marginBottom="@dimen/ws_peek_view_bottom_padding"
+            android:layout_gravity="center"
+            android:tint="?android:attr/colorForeground"
+            tools:ignore="ContentDescription" />
+
+    </FrameLayout>
+</merge>
diff --git a/wear/res/layout/navigation_drawer_item_view.xml b/wear/res/layout/navigation_drawer_item_view.xml
deleted file mode 100644
index 9e4d86a..0000000
--- a/wear/res/layout/navigation_drawer_item_view.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<RelativeLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent">
-    <ImageView
-        android:id="@+id/wearable_support_navigation_drawer_item_icon"
-        android:layout_width="48dp"
-        android:layout_height="48dp"
-        android:layout_centerInParent="true"
-        android:scaleType="fitCenter"
-        tools:ignore="ContentDescription" />
-    <TextView
-        android:id="@+id/wearable_support_navigation_drawer_item_text"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:layout_below="@id/wearable_support_navigation_drawer_item_icon"
-        android:layout_marginTop="6dp"
-        android:gravity="center_horizontal"
-        android:textColor="?android:attr/textColorPrimary"/>
-</RelativeLayout>
diff --git a/wear/res/layout/navigation_drawer_view.xml b/wear/res/layout/navigation_drawer_view.xml
deleted file mode 100644
index 9824bbf..0000000
--- a/wear/res/layout/navigation_drawer_view.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent" >
-
-    <android.support.v4.view.ViewPager
-        android:id="@+id/wearable_support_navigation_drawer_view_pager"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent" />
-    <android.support.wear.widget.drawer.PageIndicatorView
-        android:id="@+id/wearable_support_navigation_drawer_page_indicator"
-        android:layout_width="wrap_content"
-        android:layout_height="@dimen/peek_view_icon_size"
-        android:layout_marginBottom="@dimen/peek_view_bottom_padding"
-        android:layout_gravity="bottom|center_horizontal"
-        app:pageIndicatorDotFadeWhenIdle="false" />
-
-</FrameLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_1_item.xml b/wear/res/layout/single_page_nav_drawer_1_item.xml
deleted file mode 100644
index 2911f43..0000000
--- a/wear/res/layout/single_page_nav_drawer_1_item.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_centerInParent="true"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <TextView
-        android:id="@+id/wearable_support_nav_drawer_text"
-        android:layout_below="@id/wearable_support_nav_drawer_icon_0"
-        style="@style/SinglePageNavDrawerTextStyle"/>
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_2_item.xml b/wear/res/layout/single_page_nav_drawer_2_item.xml
deleted file mode 100644
index cbdbb24..0000000
--- a/wear/res/layout/single_page_nav_drawer_2_item.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentStart="true"
-        android:layout_centerVertical="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_2_items"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_alignParentEnd="true"
-        android:layout_centerVertical="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_2_items"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <TextView
-        android:id="@+id/wearable_support_nav_drawer_text"
-        android:layout_below="@id/wearable_support_nav_drawer_icon_1"
-        style="@style/SinglePageNavDrawerTextStyle"/>
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_3_item.xml b/wear/res/layout/single_page_nav_drawer_3_item.xml
deleted file mode 100644
index 5e4fc52..0000000
--- a/wear/res/layout/single_page_nav_drawer_3_item.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentStart="true"
-        android:layout_centerVertical="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_3_items"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_centerInParent="true"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_2"
-        android:layout_alignParentEnd="true"
-        android:layout_centerVertical="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_3_items"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <TextView
-        android:id="@+id/wearable_support_nav_drawer_text"
-        android:layout_below="@id/wearable_support_nav_drawer_icon_2"
-        style="@style/SinglePageNavDrawerTextStyle"/>
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_4_item.xml b/wear/res/layout/single_page_nav_drawer_4_item.xml
deleted file mode 100644
index 4acfdab..0000000
--- a/wear/res/layout/single_page_nav_drawer_4_item.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentTop="true"
-        android:layout_centerHorizontal="true"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_4_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_alignParentStart="true"
-        android:layout_centerVertical="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_4_items_horizontal"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_2"
-        android:layout_centerInParent="true"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_3"
-        android:layout_alignParentEnd="true"
-        android:layout_centerVertical="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_4_items_horizontal"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <TextView
-        android:id="@+id/wearable_support_nav_drawer_text"
-        android:layout_below="@id/wearable_support_nav_drawer_icon_3"
-        style="@style/SinglePageNavDrawerTextStyle"/>
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_5_item.xml b/wear/res/layout/single_page_nav_drawer_5_item.xml
deleted file mode 100644
index 2a8c3af..0000000
--- a/wear/res/layout/single_page_nav_drawer_5_item.xml
+++ /dev/null
@@ -1,68 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentStart="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_5_items_horizontal_outer_rows"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_5_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle"/>
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_5_items_horizontal_outer_rows"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_5_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_2"
-        android:layout_alignParentStart="true"
-        android:layout_centerVertical="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_5_items_horizontal_middle_row"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_3"
-        android:layout_centerInParent="true"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_4"
-        android:layout_alignParentEnd="true"
-        android:layout_centerVertical="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_5_items_horizontal_middle_row"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <TextView
-        android:id="@+id/wearable_support_nav_drawer_text"
-        android:layout_below="@id/wearable_support_nav_drawer_icon_4"
-        style="@style/SinglePageNavDrawerTextStyle"/>
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_6_item.xml b/wear/res/layout/single_page_nav_drawer_6_item.xml
deleted file mode 100644
index fd6cd65..0000000
--- a/wear/res/layout/single_page_nav_drawer_6_item.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentStart="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_6_items_horizontal"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_centerHorizontal="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_2"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_6_items_horizontal"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_3"
-        android:layout_alignParentStart="true"
-        android:layout_alignParentBottom="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_6_items_horizontal"
-        app:layout_marginBottomPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_4"
-        android:layout_centerHorizontal="true"
-        android:layout_alignParentBottom="true"
-        app:layout_marginBottomPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_5"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentBottom="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_6_items_horizontal"
-        app:layout_marginBottomPercent="@fraction/nav_drawer_margin_6_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_7_item.xml b/wear/res/layout/single_page_nav_drawer_7_item.xml
deleted file mode 100644
index 45e0c24..0000000
--- a/wear/res/layout/single_page_nav_drawer_7_item.xml
+++ /dev/null
@@ -1,81 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:clipChildren="false">
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_0"
-        android:layout_alignParentStart="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_7_items_horizontal_outer_rows"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_7_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_1"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentTop="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_7_items_horizontal_outer_rows"
-        app:layout_marginTopPercent="@fraction/nav_drawer_margin_7_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_2"
-        android:layout_alignParentStart="true"
-        android:layout_centerVertical="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_7_items_horizontal_middle_row"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_3"
-        android:layout_centerInParent="true"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_4"
-        android:layout_alignParentEnd="true"
-        android:layout_centerVertical="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_7_items_horizontal_middle_row"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_5"
-        android:layout_alignParentStart="true"
-        android:layout_alignParentBottom="true"
-        app:layout_marginStartPercent="@fraction/nav_drawer_margin_7_items_horizontal_outer_rows"
-        app:layout_marginBottomPercent="@fraction/nav_drawer_margin_7_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-    <android.support.wear.widget.CircledImageView
-        android:id="@+id/wearable_support_nav_drawer_icon_6"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentBottom="true"
-        app:layout_marginEndPercent="@fraction/nav_drawer_margin_7_items_horizontal_outer_rows"
-        app:layout_marginBottomPercent="@fraction/nav_drawer_margin_7_items_vertical"
-        tools:ignore="ContentDescription"
-        style="@style/SinglePageNavDrawerIconStyle" />
-
-</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/single_page_nav_drawer_peek_view.xml b/wear/res/layout/single_page_nav_drawer_peek_view.xml
deleted file mode 100644
index e0ed880..0000000
--- a/wear/res/layout/single_page_nav_drawer_peek_view.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<LinearLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:gravity="center"
-    android:orientation="vertical"
-    android:paddingTop="@dimen/peek_view_top_padding"
-    android:paddingBottom="@dimen/peek_view_bottom_padding">
-
-    <ImageView
-        android:layout_width="@dimen/peek_view_icon_size"
-        android:layout_height="@dimen/peek_view_icon_size"
-        android:src="@drawable/ic_expand_more_white_22"
-        android:tint="?android:attr/colorForeground"
-        tools:ignore="ContentDescription"/>
-
-</LinearLayout>
diff --git a/wear/res/layout/ws_navigation_drawer_item_view.xml b/wear/res/layout/ws_navigation_drawer_item_view.xml
new file mode 100644
index 0000000..dcd5e41
--- /dev/null
+++ b/wear/res/layout/ws_navigation_drawer_item_view.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+    <ImageView
+        android:id="@+id/ws_navigation_drawer_item_icon"
+        android:layout_width="48dp"
+        android:layout_height="48dp"
+        android:layout_centerInParent="true"
+        android:scaleType="fitCenter"
+        tools:ignore="ContentDescription" />
+    <TextView
+        android:id="@+id/ws_navigation_drawer_item_text"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_below="@id/ws_navigation_drawer_item_icon"
+        android:layout_marginTop="6dp"
+        android:gravity="center_horizontal"
+        android:textColor="?android:attr/textColorPrimary"/>
+</RelativeLayout>
diff --git a/wear/res/layout/ws_navigation_drawer_view.xml b/wear/res/layout/ws_navigation_drawer_view.xml
new file mode 100644
index 0000000..ea4eced
--- /dev/null
+++ b/wear/res/layout/ws_navigation_drawer_view.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" >
+
+    <android.support.v4.view.ViewPager
+        android:id="@+id/ws_navigation_drawer_view_pager"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent" />
+    <android.support.wear.widget.drawer.PageIndicatorView
+        android:id="@+id/ws_navigation_drawer_page_indicator"
+        android:layout_width="wrap_content"
+        android:layout_height="@dimen/ws_peek_view_icon_size"
+        android:layout_marginBottom="@dimen/ws_peek_view_bottom_padding"
+        android:layout_gravity="bottom|center_horizontal"
+        app:wsPageIndicatorDotFadeWhenIdle="false" />
+
+</FrameLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_1_item.xml b/wear/res/layout/ws_single_page_nav_drawer_1_item.xml
new file mode 100644
index 0000000..550d737
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_1_item.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_centerInParent="true"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <TextView
+        android:id="@+id/ws_nav_drawer_text"
+        android:layout_below="@id/ws_nav_drawer_icon_0"
+        style="@style/WsSinglePageNavDrawerTextStyle"/>
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_2_item.xml b/wear/res/layout/ws_single_page_nav_drawer_2_item.xml
new file mode 100644
index 0000000..63dbbe6
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_2_item.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentStart="true"
+        android:layout_centerVertical="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_2_items"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_alignParentEnd="true"
+        android:layout_centerVertical="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_2_items"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <TextView
+        android:id="@+id/ws_nav_drawer_text"
+        android:layout_below="@id/ws_nav_drawer_icon_1"
+        style="@style/WsSinglePageNavDrawerTextStyle"/>
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_3_item.xml b/wear/res/layout/ws_single_page_nav_drawer_3_item.xml
new file mode 100644
index 0000000..209ec16
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_3_item.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentStart="true"
+        android:layout_centerVertical="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_3_items"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_centerInParent="true"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_2"
+        android:layout_alignParentEnd="true"
+        android:layout_centerVertical="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_3_items"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <TextView
+        android:id="@+id/ws_nav_drawer_text"
+        android:layout_below="@id/ws_nav_drawer_icon_2"
+        style="@style/WsSinglePageNavDrawerTextStyle"/>
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_4_item.xml b/wear/res/layout/ws_single_page_nav_drawer_4_item.xml
new file mode 100644
index 0000000..1b2c163
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_4_item.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentTop="true"
+        android:layout_centerHorizontal="true"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_4_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_alignParentStart="true"
+        android:layout_centerVertical="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_4_items_horizontal"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_2"
+        android:layout_centerInParent="true"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_3"
+        android:layout_alignParentEnd="true"
+        android:layout_centerVertical="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_4_items_horizontal"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <TextView
+        android:id="@+id/ws_nav_drawer_text"
+        android:layout_below="@id/ws_nav_drawer_icon_3"
+        style="@style/WsSinglePageNavDrawerTextStyle"/>
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_5_item.xml b/wear/res/layout/ws_single_page_nav_drawer_5_item.xml
new file mode 100644
index 0000000..699533d
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_5_item.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_5_items_horizontal_outer_rows"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_5_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle"/>
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_5_items_horizontal_outer_rows"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_5_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_2"
+        android:layout_alignParentStart="true"
+        android:layout_centerVertical="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_5_items_horizontal_middle_row"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_3"
+        android:layout_centerInParent="true"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_4"
+        android:layout_alignParentEnd="true"
+        android:layout_centerVertical="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_5_items_horizontal_middle_row"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <TextView
+        android:id="@+id/ws_nav_drawer_text"
+        android:layout_below="@id/ws_nav_drawer_icon_4"
+        style="@style/WsSinglePageNavDrawerTextStyle"/>
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_6_item.xml b/wear/res/layout/ws_single_page_nav_drawer_6_item.xml
new file mode 100644
index 0000000..00625a1
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_6_item.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_6_items_horizontal"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_centerHorizontal="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_2"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_6_items_horizontal"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_3"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentBottom="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_6_items_horizontal"
+        app:layout_marginBottomPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_4"
+        android:layout_centerHorizontal="true"
+        android:layout_alignParentBottom="true"
+        app:layout_marginBottomPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_5"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentBottom="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_6_items_horizontal"
+        app:layout_marginBottomPercent="@fraction/ws_nav_drawer_margin_6_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_7_item.xml b/wear/res/layout/ws_single_page_nav_drawer_7_item.xml
new file mode 100644
index 0000000..5daef22
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_7_item.xml
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipChildren="false">
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_0"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_outer_rows"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_7_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_1"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentTop="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_outer_rows"
+        app:layout_marginTopPercent="@fraction/ws_nav_drawer_margin_7_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_2"
+        android:layout_alignParentStart="true"
+        android:layout_centerVertical="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_middle_row"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_3"
+        android:layout_centerInParent="true"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_4"
+        android:layout_alignParentEnd="true"
+        android:layout_centerVertical="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_middle_row"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_5"
+        android:layout_alignParentStart="true"
+        android:layout_alignParentBottom="true"
+        app:layout_marginStartPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_outer_rows"
+        app:layout_marginBottomPercent="@fraction/ws_nav_drawer_margin_7_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+    <android.support.wear.widget.CircledImageView
+        android:id="@+id/ws_nav_drawer_icon_6"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentBottom="true"
+        app:layout_marginEndPercent="@fraction/ws_nav_drawer_margin_7_items_horizontal_outer_rows"
+        app:layout_marginBottomPercent="@fraction/ws_nav_drawer_margin_7_items_vertical"
+        tools:ignore="ContentDescription"
+        style="@style/WsSinglePageNavDrawerIconStyle" />
+
+</android.support.percent.PercentRelativeLayout>
diff --git a/wear/res/layout/ws_single_page_nav_drawer_peek_view.xml b/wear/res/layout/ws_single_page_nav_drawer_peek_view.xml
new file mode 100644
index 0000000..8b11554
--- /dev/null
+++ b/wear/res/layout/ws_single_page_nav_drawer_peek_view.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:gravity="center"
+    android:orientation="vertical"
+    android:paddingTop="@dimen/ws_peek_view_top_padding"
+    android:paddingBottom="@dimen/ws_peek_view_bottom_padding">
+
+    <ImageView
+        android:layout_width="@dimen/ws_peek_view_icon_size"
+        android:layout_height="@dimen/ws_peek_view_icon_size"
+        android:src="@drawable/ws_ic_expand_more_white_22"
+        android:tint="?android:attr/colorForeground"
+        tools:ignore="ContentDescription"/>
+
+</LinearLayout>
diff --git a/wear/res/values-sw180dp-notround/dimens.xml b/wear/res/values-sw180dp-notround/dimens.xml
index 87938e5..f6395d3 100644
--- a/wear/res/values-sw180dp-notround/dimens.xml
+++ b/wear/res/values-sw180dp-notround/dimens.xml
@@ -15,11 +15,11 @@
 -->
 <resources>
 
-    <dimen name="action_drawer_item_top_padding">10dp</dimen>
-    <dimen name="action_drawer_item_bottom_padding">10dp</dimen>
-    <dimen name="action_drawer_item_icon_right_margin">12dp</dimen>
-    <dimen name="action_drawer_item_icon_size">40dp</dimen>
-    <dimen name="action_drawer_item_icon_padding">8dp</dimen>
-    <dimen name="action_drawer_item_text_size">16sp</dimen>
+    <dimen name="ws_action_drawer_item_top_padding">10dp</dimen>
+    <dimen name="ws_action_drawer_item_bottom_padding">10dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_right_margin">12dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_size">40dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_padding">8dp</dimen>
+    <dimen name="ws_action_drawer_item_text_size">16sp</dimen>
 
 </resources>
diff --git a/wear/res/values-sw210dp-round/dimens.xml b/wear/res/values-sw210dp-round/dimens.xml
index d6d4ed0..1a2581e 100644
--- a/wear/res/values-sw210dp-round/dimens.xml
+++ b/wear/res/values-sw210dp-round/dimens.xml
@@ -14,10 +14,10 @@
      limitations under the License.
 -->
 <resources>
-    <dimen name="action_drawer_item_top_padding">10dp</dimen>
-    <dimen name="action_drawer_item_bottom_padding">10dp</dimen>
-    <dimen name="action_drawer_item_icon_right_margin">12dp</dimen>
-    <dimen name="action_drawer_item_icon_size">40dp</dimen>
-    <dimen name="action_drawer_item_icon_padding">8dp</dimen>
-    <dimen name="action_drawer_item_text_size">16sp</dimen>
+    <dimen name="ws_action_drawer_item_top_padding">10dp</dimen>
+    <dimen name="ws_action_drawer_item_bottom_padding">10dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_right_margin">12dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_size">40dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_padding">8dp</dimen>
+    <dimen name="ws_action_drawer_item_text_size">16sp</dimen>
 </resources>
diff --git a/wear/res/values-sw210dp/dimens.xml b/wear/res/values-sw210dp/dimens.xml
index e8d7afc..8f69e0b 100644
--- a/wear/res/values-sw210dp/dimens.xml
+++ b/wear/res/values-sw210dp/dimens.xml
@@ -15,8 +15,8 @@
 -->
 <resources>
 
-    <dimen name="nav_drawer_text_size">14sp</dimen>
-    <dimen name="nav_drawer_single_page_icon_size">32dp</dimen>
-    <dimen name="nav_drawer_single_page_circle_radius">27dp</dimen>
+    <dimen name="ws_nav_drawer_text_size">14sp</dimen>
+    <dimen name="ws_nav_drawer_single_page_icon_size">32dp</dimen>
+    <dimen name="ws_nav_drawer_single_page_circle_radius">27dp</dimen>
 
 </resources>
diff --git a/wear/res/values-v20/styles.xml b/wear/res/values-v20/styles.xml
index aa442f7..92613f2 100644
--- a/wear/res/values-v20/styles.xml
+++ b/wear/res/values-v20/styles.xml
@@ -15,20 +15,20 @@
 -->
 <resources>
 
-    <style name="PageIndicatorViewStyle">
-        <item name="pageIndicatorDotSpacing">7.8dp</item>
-        <item name="pageIndicatorDotRadius">2.1dp</item>
-        <item name="pageIndicatorDotRadiusSelected">3.1dp</item>
-        <item name="pageIndicatorDotColor">?android:attr/colorForeground</item>
-        <item name="pageIndicatorDotColorSelected">?android:attr/colorForeground</item>
-        <item name="pageIndicatorDotFadeOutDelay">1000</item>
-        <item name="pageIndicatorDotFadeOutDuration">250</item>
-        <item name="pageIndicatorDotFadeInDuration">100</item>
-        <item name="pageIndicatorDotFadeWhenIdle">true</item>
-        <item name="pageIndicatorDotShadowColor">#66000000</item>
-        <item name="pageIndicatorDotShadowRadius">1dp</item>
-        <item name="pageIndicatorDotShadowDx">0.5dp</item>
-        <item name="pageIndicatorDotShadowDy">0.5dp</item>
+    <style name="WsPageIndicatorViewStyle">
+        <item name="wsPageIndicatorDotSpacing">7.8dp</item>
+        <item name="wsPageIndicatorDotRadius">2.1dp</item>
+        <item name="wsPageIndicatorDotRadiusSelected">3.1dp</item>
+        <item name="wsPageIndicatorDotColor">?android:attr/colorForeground</item>
+        <item name="wsPageIndicatorDotColorSelected">?android:attr/colorForeground</item>
+        <item name="wsPageIndicatorDotFadeOutDelay">1000</item>
+        <item name="wsPageIndicatorDotFadeOutDuration">250</item>
+        <item name="wsPageIndicatorDotFadeInDuration">100</item>
+        <item name="wsPageIndicatorDotFadeWhenIdle">true</item>
+        <item name="wsPageIndicatorDotShadowColor">#66000000</item>
+        <item name="wsPageIndicatorDotShadowRadius">1dp</item>
+        <item name="wsPageIndicatorDotShadowDx">0.5dp</item>
+        <item name="wsPageIndicatorDotShadowDy">0.5dp</item>
     </style>
 
 </resources>
diff --git a/wear/res/values-v23/styles.xml b/wear/res/values-v23/styles.xml
index 49a94eb..6bb1a51 100644
--- a/wear/res/values-v23/styles.xml
+++ b/wear/res/values-v23/styles.xml
@@ -14,15 +14,15 @@
      limitations under the License.
 -->
 <resources>
-    <style name="WearableActionDrawerItemText">
+    <style name="WsWearableActionDrawerItemText">
         <item name="android:layout_gravity">center_vertical</item>
         <item name="android:ellipsize">end</item>
         <item name="android:fontFamily">sans-serif-condensed-light</item>
         <item name="android:maxLines">3</item>
         <item name="android:textColor">?android:attr/textColorPrimary</item>
-        <item name="android:textSize">@dimen/action_drawer_item_text_size</item>
+        <item name="android:textSize">@dimen/ws_action_drawer_item_text_size</item>
     </style>
-    <style name="WearableActionDrawerTitleText" parent="android:TextAppearance.Material.Subhead">
+    <style name="WsWearableActionDrawerTitleText" parent="android:TextAppearance.Material.Subhead">
         <item name="android:alpha">0.7</item>
     </style>
 </resources>
diff --git a/wear/res/values-v24/styles.xml b/wear/res/values-v24/styles.xml
new file mode 100644
index 0000000..a7f50fa
--- /dev/null
+++ b/wear/res/values-v24/styles.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<resources>
+    <style name="Widget.Wear.RoundSwitch"
+            parent="@android:style/Widget.Material.CompoundButton.Switch">
+        <item name="android:layout_width">@dimen/ws_switch_size</item>
+        <item name="android:layout_height">@dimen/ws_switch_size</item>
+        <item name="android:switchMinWidth">@dimen/ws_switch_size</item>
+        <item name="android:layout_gravity">center</item>
+        <item name="android:thumb">@drawable/ws_switch_thumb_material_anim</item>
+        <item name="android:thumbTint">@color/ws_switch_thumb_color_material</item>
+        <item name="android:thumbTintMode">multiply</item>
+        <item name="android:track">@drawable/ws_switch_track_mtrl</item>
+        <item name="android:trackTint">@color/ws_switch_track_color_material</item>
+        <item name="android:background">@empty</item>
+        <item name="android:showText">false</item>
+    </style>
+</resources>
diff --git a/wear/res/values/arrays.xml b/wear/res/values/arrays.xml
new file mode 100644
index 0000000..3d7740d
--- /dev/null
+++ b/wear/res/values/arrays.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <!-- Default color scheme colors for CircularProgressLayout -->
+    <array name="circular_progress_layout_color_scheme_colors">
+        <item>@color/circular_progress_layout_red</item>
+        <item>@color/circular_progress_layout_yellow</item>
+        <item>@color/circular_progress_layout_green</item>
+        <item>@color/circular_progress_layout_blue</item>
+    </array>
+</resources>
\ No newline at end of file
diff --git a/wear/res/values/attrs.xml b/wear/res/values/attrs.xml
index 673fda5..c8b47c7 100644
--- a/wear/res/values/attrs.xml
+++ b/wear/res/values/attrs.xml
@@ -101,74 +101,86 @@
 
     <declare-styleable name="PageIndicatorView">
         <!-- Sets the distance between dots. -->
-        <attr name="pageIndicatorDotSpacing" format="dimension" />
+        <attr name="wsPageIndicatorDotSpacing" format="dimension" />
         <!-- Sets the radius of a dot when it is not selected. -->
-        <attr name="pageIndicatorDotRadius" format="dimension" />
+        <attr name="wsPageIndicatorDotRadius" format="dimension" />
         <!-- Sets the radius of a dot when it is selected. -->
-        <attr name="pageIndicatorDotRadiusSelected" format="dimension" />
+        <attr name="wsPageIndicatorDotRadiusSelected" format="dimension" />
         <!-- Sets the color of a dot when it is not selected. -->
-        <attr name="pageIndicatorDotColor" format="color" />
+        <attr name="wsPageIndicatorDotColor" format="color" />
         <!-- Sets the color of a dot when it is selected. -->
-        <attr name="pageIndicatorDotColorSelected" format="color" />
+        <attr name="wsPageIndicatorDotColorSelected" format="color" />
         <!-- Sets whether the dots should fade out after inactivity. -->
-        <attr name="pageIndicatorDotFadeWhenIdle" format="boolean" />
+        <attr name="wsPageIndicatorDotFadeWhenIdle" format="boolean" />
         <!-- Sets the delay between the pager arriving at an idle state, and the fade out animation
              beginning, in milliseconds. -->
-        <attr name="pageIndicatorDotFadeOutDelay" format="integer" />
+        <attr name="wsPageIndicatorDotFadeOutDelay" format="integer" />
         <!-- Sets the duration of the fade out animation. -->
-        <attr name="pageIndicatorDotFadeOutDuration" format="integer" />
+        <attr name="wsPageIndicatorDotFadeOutDuration" format="integer" />
         <!-- Sets the duration of the fade in animation. -->
-        <attr name="pageIndicatorDotFadeInDuration" format="integer" />
+        <attr name="wsPageIndicatorDotFadeInDuration" format="integer" />
         <!-- Sets the shadow color. -->
-        <attr name="pageIndicatorDotShadowColor" format="color" />
+        <attr name="wsPageIndicatorDotShadowColor" format="color" />
         <!-- Sets the shadow radius. -->
-        <attr name="pageIndicatorDotShadowRadius" format="dimension" />
+        <attr name="wsPageIndicatorDotShadowRadius" format="dimension" />
         <!-- Sets the horizontal shadow offset. -->
-        <attr name="pageIndicatorDotShadowDx" format="dimension" />
+        <attr name="wsPageIndicatorDotShadowDx" format="dimension" />
         <!-- Sets the vertical shadow offset. -->
-        <attr name="pageIndicatorDotShadowDy" format="dimension" />
+        <attr name="wsPageIndicatorDotShadowDy" format="dimension" />
     </declare-styleable>
 
     <declare-styleable name="CircledImageView">
         <attr name="android:src" />
         <!-- Sets the color of the circle. -->
-        <attr name="circle_color" format="color" />
+        <attr name="background_color" format="color" />
         <!-- Sets the radius of the circle. -->
-        <attr name="circle_radius" format="dimension" />
+        <attr name="background_radius" format="dimension" />
         <!-- Sets the radius of the circle while the circle is being pressed. -->
-        <attr name="circle_radius_pressed" format="dimension" />
+        <attr name="background_radius_pressed" format="dimension" />
         <!-- Sets the width of the border. -->
-        <attr name="circle_border_width" format="dimension" />
+        <attr name="background_border_width" format="dimension" />
         <!-- Sets the color of the border. -->
-        <attr name="circle_border_color" format="color" />
+        <attr name="background_border_color" format="color" />
         <!-- Sets the stroke cap for the border around the circle. -->
-        <attr name="circle_border_cap" format="enum">
+        <attr name="background_border_cap" format="enum">
             <enum name="butt" value="0" />
             <enum name="round" value="1" />
             <enum name="square" value="2" />
         </attr>
         <!-- Sets the padding between the edge of the circle and the start of the image. -->
-        <attr name="circle_padding" format="dimension" />
+        <attr name="img_padding" format="dimension" />
         <!-- Sets the width of the shadow. -->
-        <attr name="shadow_width" format="dimension" />
+        <attr name="background_shadow_width" format="dimension" />
         <!-- Sets the percentage of the circle which the image should occupy. -->
-        <attr name="image_circle_percentage" format="dimension" />
+        <attr name="img_circle_percentage" format="dimension" />
         <!-- Sets the percentage of the circle which the image should should be offset
              horizontally. -->
-        <attr name="image_horizontal_offcenter_percentage" format="dimension" />
+        <attr name="img_horizontal_offset_percentage" format="dimension" />
         <!-- Sets the tint color of the image. -->
-        <attr name="image_tint" format="color" />
+        <attr name="img_tint" format="color" />
         <!-- Sets the radius of the circle to be a percentage of the largest dimension of the
              view. -->
-        <attr name="circle_radius_percent" format="fraction" />
+        <attr name="background_radius_percent" format="fraction" />
         <!-- Sets the circle radius when pressed. -->
-        <attr name="circle_radius_pressed_percent" format="fraction" />
+        <attr name="background_radius_pressed_percent" format="fraction" />
         <!-- Sets which dimension to use if the image isn't square. -->
-        <attr name="square_dimen" format="enum">
+        <attr name="clip_dimen" format="enum">
             <enum name="none" value="0" />
             <enum name="height" value="1" />
             <enum name="width" value="2" />
         </attr>
     </declare-styleable>
 
+    <declare-styleable name="CircularProgressLayout">
+        <!-- Sets the color of the background circle. -->
+        <attr name="backgroundColor" format="color" />
+        <!-- Sets the stroke width of the progress indicator. -->
+        <attr name="strokeWidth" format="dimension" />
+        <!-- Sets the color scheme used by the progress indicator. This may be an array of colors or
+        a single color. If an array of colors is used, first color will be used for determinate
+        progress indicator, while the rest will be shown in order during indeterminate spinner. -->
+        <attr name="colorSchemeColors" format="reference|color" />
+        <!-- Sets if the progress should be shown as an indeterminate spinner. -->
+        <attr name="indeterminate" format="boolean" />
+    </declare-styleable>
 </resources>
diff --git a/wear/res/values/colors.xml b/wear/res/values/colors.xml
new file mode 100644
index 0000000..a44c7a0
--- /dev/null
+++ b/wear/res/values/colors.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<resources>
+    <!-- From material color palette -->
+    <color name="circular_progress_layout_red">#FFF44336</color>
+    <color name="circular_progress_layout_yellow">#FFFFEB3B</color>
+    <color name="circular_progress_layout_green">#FF4CAF50</color>
+    <color name="circular_progress_layout_blue">#FF2196F3</color>
+
+    <!-- Default background color for CircularProgressLayout -->
+    <color name="circular_progress_layout_background_color">#00000000</color>
+</resources>
\ No newline at end of file
diff --git a/wear/res/values/dimens.xml b/wear/res/values/dimens.xml
index c39fc77..26d6c0a 100644
--- a/wear/res/values/dimens.xml
+++ b/wear/res/values/dimens.xml
@@ -15,50 +15,55 @@
 -->
 <resources>
     <!-- Values for the WearableRecyclerView. -->
-    <dimen name="wrv_curve_default_x_offset">24dp</dimen>
+    <dimen name="ws_wrv_curve_default_x_offset">24dp</dimen>
 
     <!-- Values for WearableDrawerView. -->
-    <dimen name="wearable_drawer_view_elevation">12dp</dimen>
+    <dimen name="ws_wearable_drawer_view_elevation">12dp</dimen>
 
     <!-- Values for WearableActionDrawerView. -->
-    <item name="action_drawer_item_first_item_top_padding" type="fraction">15%</item>
-    <item name="action_drawer_item_last_item_bottom_padding" type="fraction">15%</item>
-    <item name="action_drawer_item_left_padding" type="fraction">15%</item>
-    <item name="action_drawer_item_right_padding" type="fraction">10%</item>
-    <dimen name="action_drawer_item_top_padding">8dp</dimen>
-    <dimen name="action_drawer_item_bottom_padding">8dp</dimen>
-    <dimen name="action_drawer_item_icon_right_margin">8dp</dimen>
-    <dimen name="action_drawer_item_icon_size">36dp</dimen>
-    <dimen name="action_drawer_item_icon_padding">7dp</dimen>
-    <dimen name="action_drawer_item_text_size">14sp</dimen>
-    <dimen name="action_drawer_peek_view_height">43dp</dimen>
-    <dimen name="action_drawer_peek_top_padding">2dp</dimen>
-    <dimen name="action_drawer_expand_icon_top_margin">-3dp</dimen>
+    <item name="ws_action_drawer_item_first_item_top_padding" type="fraction">15%</item>
+    <item name="ws_action_drawer_item_last_item_bottom_padding" type="fraction">15%</item>
+    <item name="ws_action_drawer_item_left_padding" type="fraction">15%</item>
+    <item name="ws_action_drawer_item_right_padding" type="fraction">10%</item>
+    <dimen name="ws_action_drawer_item_top_padding">8dp</dimen>
+    <dimen name="ws_action_drawer_item_bottom_padding">8dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_right_margin">8dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_size">36dp</dimen>
+    <dimen name="ws_action_drawer_item_icon_padding">7dp</dimen>
+    <dimen name="ws_action_drawer_item_text_size">14sp</dimen>
+    <dimen name="ws_action_drawer_peek_view_height">43dp</dimen>
+    <dimen name="ws_action_drawer_peek_top_padding">2dp</dimen>
+    <dimen name="ws_action_drawer_expand_icon_top_margin">-3dp</dimen>
 
     <!-- Dimensions for the single page WearableNavigationDrawerView. -->
-    <dimen name="nav_drawer_single_page_icon_size">28dp</dimen>
-    <dimen name="nav_drawer_single_page_icon_padding">6dp</dimen>
-    <dimen name="nav_drawer_single_page_circle_radius">24dp</dimen>
-    <dimen name="nav_drawer_text_size">12sp</dimen>
-    <fraction name="nav_drawer_text_margin">13%</fraction>
-    <fraction name="nav_drawer_margin_2_items">20%</fraction>
-    <fraction name="nav_drawer_margin_3_items">16%</fraction>
-    <fraction name="nav_drawer_margin_4_items_vertical">16.9%</fraction>
-    <fraction name="nav_drawer_margin_4_items_horizontal">13%</fraction>
-    <fraction name="nav_drawer_margin_5_items_horizontal_outer_rows">27.4%</fraction>
-    <fraction name="nav_drawer_margin_5_items_horizontal_middle_row">13%</fraction>
-    <fraction name="nav_drawer_margin_5_items_vertical">16.9%</fraction>
-    <fraction name="nav_drawer_margin_6_items_horizontal">16%</fraction>
-    <fraction name="nav_drawer_margin_6_items_vertical">26.8%</fraction>
-    <fraction name="nav_drawer_margin_7_items_horizontal_outer_rows">27.4%</fraction>
-    <fraction name="nav_drawer_margin_7_items_horizontal_middle_row">13%</fraction>
-    <fraction name="nav_drawer_margin_7_items_vertical">16.9%</fraction>
+    <dimen name="ws_nav_drawer_single_page_icon_size">28dp</dimen>
+    <dimen name="ws_nav_drawer_single_page_icon_padding">6dp</dimen>
+    <dimen name="ws_nav_drawer_single_page_circle_radius">24dp</dimen>
+    <dimen name="ws_nav_drawer_text_size">12sp</dimen>
+    <fraction name="ws_nav_drawer_text_margin">13%</fraction>
+    <fraction name="ws_nav_drawer_margin_2_items">20%</fraction>
+    <fraction name="ws_nav_drawer_margin_3_items">16%</fraction>
+    <fraction name="ws_nav_drawer_margin_4_items_vertical">16.9%</fraction>
+    <fraction name="ws_nav_drawer_margin_4_items_horizontal">13%</fraction>
+    <fraction name="ws_nav_drawer_margin_5_items_horizontal_outer_rows">27.4%</fraction>
+    <fraction name="ws_nav_drawer_margin_5_items_horizontal_middle_row">13%</fraction>
+    <fraction name="ws_nav_drawer_margin_5_items_vertical">16.9%</fraction>
+    <fraction name="ws_nav_drawer_margin_6_items_horizontal">16%</fraction>
+    <fraction name="ws_nav_drawer_margin_6_items_vertical">26.8%</fraction>
+    <fraction name="ws_nav_drawer_margin_7_items_horizontal_outer_rows">27.4%</fraction>
+    <fraction name="ws_nav_drawer_margin_7_items_horizontal_middle_row">13%</fraction>
+    <fraction name="ws_nav_drawer_margin_7_items_vertical">16.9%</fraction>
 
-    <dimen name="peek_view_top_padding">8dp</dimen>
-    <dimen name="peek_view_bottom_padding">8dp</dimen>
-    <dimen name="peek_view_icon_size">22dp</dimen>
+    <dimen name="ws_peek_view_top_padding">8dp</dimen>
+    <dimen name="ws_peek_view_bottom_padding">8dp</dimen>
+    <dimen name="ws_peek_view_icon_size">22dp</dimen>
 
     <!-- Maximum distance from edge to consider an edge drag. This should be the sum of the peek
          view's top padding, bottom padding, and icon size. -->
-    <dimen name="drawer_view_edge_size">38dp</dimen>
+    <dimen name="ws_drawer_view_edge_size">38dp</dimen>
+    <!-- Dimensions for the wearable switch. -->
+    <dimen name="ws_switch_size">40dp</dimen>
+
+    <!-- Default stroke width for CircularProgressLayout -->
+    <dimen name="circular_progress_layout_stroke_width">4dp</dimen>
 </resources>
diff --git a/wear/res/values/ids.xml b/wear/res/values/ids.xml
index 881e52a..8a7324e 100644
--- a/wear/res/values/ids.xml
+++ b/wear/res/values/ids.xml
@@ -14,5 +14,5 @@
      limitations under the License.
 -->
 <resources>
-    <item name="wearable_support_navigation_drawer_view_pager" type="id" />
+    <item name="ws_navigation_drawer_view_pager" type="id" />
 </resources>
diff --git a/wear/res/values/strings.xml b/wear/res/values/strings.xml
index 4d50ddf..3bbb78c 100644
--- a/wear/res/values/strings.xml
+++ b/wear/res/values/strings.xml
@@ -15,8 +15,8 @@
 -->
 <resources>
     <!-- String describing the navigation drawer which is read aloud when focused using accessibility gestures [CHAR LIMIT=35] -->
-    <string name="navigation_drawer_content_description">Navigation drawer</string>
+    <string name="ws_navigation_drawer_content_description">Navigation drawer</string>
 
     <!-- String describing the action drawer which is read aloud when focused using accessibility gestures [CHAR LIMIT=35] -->
-    <string name="action_drawer_content_description">Action drawer</string>
+    <string name="ws_action_drawer_content_description">Action drawer</string>
 </resources>
diff --git a/wear/res/values/styles.xml b/wear/res/values/styles.xml
index 706df13..44ab0b0 100644
--- a/wear/res/values/styles.xml
+++ b/wear/res/values/styles.xml
@@ -14,27 +14,27 @@
      limitations under the License.
 -->
 <resources>
-    <style name="SinglePageNavDrawerIconStyle">
-        <item name="android:layout_height">@dimen/nav_drawer_single_page_icon_size</item>
-        <item name="android:layout_width">@dimen/nav_drawer_single_page_icon_size</item>
-        <item name="android:padding">@dimen/nav_drawer_single_page_icon_padding</item>
+    <style name="WsSinglePageNavDrawerIconStyle">
+        <item name="android:layout_height">@dimen/ws_nav_drawer_single_page_icon_size</item>
+        <item name="android:layout_width">@dimen/ws_nav_drawer_single_page_icon_size</item>
+        <item name="android:padding">@dimen/ws_nav_drawer_single_page_icon_padding</item>
         <item name="android:clipToPadding">false</item>
-        <item name="circle_radius">@dimen/nav_drawer_single_page_circle_radius</item>
-        <item name="circle_color">#33ffffff</item>
+        <item name="background_radius">@dimen/ws_nav_drawer_single_page_circle_radius</item>
+        <item name="background_color">#33ffffff</item>
     </style>
-    <style name="SinglePageNavDrawerTextStyle">
+    <style name="WsSinglePageNavDrawerTextStyle">
         <item name="android:layout_height">wrap_content</item>
         <item name="android:layout_width">match_parent</item>
         <item name="android:fontFamily">sans-serif-condensed</item>
-        <item name="android:textSize">@dimen/nav_drawer_text_size</item>
+        <item name="android:textSize">@dimen/ws_nav_drawer_text_size</item>
         <item name="android:gravity">center</item>
         <item name="android:maxLines">2</item>
-        <item name="layout_marginTopPercent">@fraction/nav_drawer_text_margin</item>
-        <item name="layout_marginStartPercent">@fraction/nav_drawer_text_margin</item>
-        <item name="layout_marginEndPercent">@fraction/nav_drawer_text_margin</item>
+        <item name="layout_marginTopPercent">@fraction/ws_nav_drawer_text_margin</item>
+        <item name="layout_marginStartPercent">@fraction/ws_nav_drawer_text_margin</item>
+        <item name="layout_marginEndPercent">@fraction/ws_nav_drawer_text_margin</item>
     </style>
-    <style name="Widget.Wearable.WearableDrawerView" parent="">
-        <item name="android:elevation">@dimen/wearable_drawer_view_elevation</item>
+    <style name="Widget.Wear.WearableDrawerView" parent="">
+        <item name="android:elevation">@dimen/ws_wearable_drawer_view_elevation</item>
         <item name="android:background">?android:attr/colorBackgroundFloating</item>
     </style>
 </resources>
diff --git a/wear/src/android/support/wear/internal/widget/drawer/MultiPageUi.java b/wear/src/android/support/wear/internal/widget/drawer/MultiPageUi.java
index 8a65b57..9056845 100644
--- a/wear/src/android/support/wear/internal/widget/drawer/MultiPageUi.java
+++ b/wear/src/android/support/wear/internal/widget/drawer/MultiPageUi.java
@@ -59,16 +59,16 @@
         mPresenter = presenter;
 
         LayoutInflater inflater = LayoutInflater.from(drawer.getContext());
-        final View content =
-                inflater.inflate(R.layout.navigation_drawer_view, drawer, false /* attachToRoot */);
+        final View content = inflater.inflate(R.layout.ws_navigation_drawer_view, drawer,
+                false /* attachToRoot */);
 
         mNavigationPager =
                 (ViewPager) content
-                        .findViewById(R.id.wearable_support_navigation_drawer_view_pager);
+                        .findViewById(R.id.ws_navigation_drawer_view_pager);
         mPageIndicatorView =
                 (PageIndicatorView)
                         content.findViewById(
-                                R.id.wearable_support_navigation_drawer_page_indicator);
+                                R.id.ws_navigation_drawer_page_indicator);
 
         drawer.setDrawerContent(content);
     }
@@ -138,13 +138,13 @@
             // of this method. Attaching to root will cause view to point to container instead.
             final View view =
                     LayoutInflater.from(container.getContext())
-                            .inflate(R.layout.navigation_drawer_item_view, container, false);
+                            .inflate(R.layout.ws_navigation_drawer_item_view, container, false);
             container.addView(view);
             final ImageView iconView =
                     (ImageView) view
-                            .findViewById(R.id.wearable_support_navigation_drawer_item_icon);
+                            .findViewById(R.id.ws_navigation_drawer_item_icon);
             final TextView textView =
-                    (TextView) view.findViewById(R.id.wearable_support_navigation_drawer_item_text);
+                    (TextView) view.findViewById(R.id.ws_navigation_drawer_item_text);
             iconView.setImageDrawable(mAdapter.getItemDrawable(position));
             textView.setText(mAdapter.getItemText(position));
             return view;
diff --git a/wear/src/android/support/wear/internal/widget/drawer/SinglePageUi.java b/wear/src/android/support/wear/internal/widget/drawer/SinglePageUi.java
index 9a834eb..f3a4290 100644
--- a/wear/src/android/support/wear/internal/widget/drawer/SinglePageUi.java
+++ b/wear/src/android/support/wear/internal/widget/drawer/SinglePageUi.java
@@ -44,26 +44,26 @@
     @IdRes
     private static final int[] SINGLE_PAGE_BUTTON_IDS =
             new int[]{
-                    R.id.wearable_support_nav_drawer_icon_0,
-                    R.id.wearable_support_nav_drawer_icon_1,
-                    R.id.wearable_support_nav_drawer_icon_2,
-                    R.id.wearable_support_nav_drawer_icon_3,
-                    R.id.wearable_support_nav_drawer_icon_4,
-                    R.id.wearable_support_nav_drawer_icon_5,
-                    R.id.wearable_support_nav_drawer_icon_6,
+                    R.id.ws_nav_drawer_icon_0,
+                    R.id.ws_nav_drawer_icon_1,
+                    R.id.ws_nav_drawer_icon_2,
+                    R.id.ws_nav_drawer_icon_3,
+                    R.id.ws_nav_drawer_icon_4,
+                    R.id.ws_nav_drawer_icon_5,
+                    R.id.ws_nav_drawer_icon_6,
             };
 
     @LayoutRes
     private static final int[] SINGLE_PAGE_LAYOUT_RES =
             new int[]{
                     0,
-                    R.layout.single_page_nav_drawer_1_item,
-                    R.layout.single_page_nav_drawer_2_item,
-                    R.layout.single_page_nav_drawer_3_item,
-                    R.layout.single_page_nav_drawer_4_item,
-                    R.layout.single_page_nav_drawer_5_item,
-                    R.layout.single_page_nav_drawer_6_item,
-                    R.layout.single_page_nav_drawer_7_item,
+                    R.layout.ws_single_page_nav_drawer_1_item,
+                    R.layout.ws_single_page_nav_drawer_2_item,
+                    R.layout.ws_single_page_nav_drawer_3_item,
+                    R.layout.ws_single_page_nav_drawer_4_item,
+                    R.layout.ws_single_page_nav_drawer_5_item,
+                    R.layout.ws_single_page_nav_drawer_6_item,
+                    R.layout.ws_single_page_nav_drawer_7_item,
             };
 
     private final WearableNavigationDrawerView mDrawer;
@@ -108,10 +108,10 @@
         View content = inflater.inflate(layoutRes, mDrawer, false /* attachToRoot */);
         final View peek =
                 inflater.inflate(
-                        R.layout.single_page_nav_drawer_peek_view, mDrawer,
+                        R.layout.ws_single_page_nav_drawer_peek_view, mDrawer,
                         false /* attachToRoot */);
 
-        mTextView = (TextView) content.findViewById(R.id.wearable_support_nav_drawer_text);
+        mTextView = (TextView) content.findViewById(R.id.ws_nav_drawer_text);
         mSinglePageImageViews = new CircledImageView[count];
         for (int i = 0; i < count; i++) {
             mSinglePageImageViews[i] = (CircledImageView) content
diff --git a/wear/src/android/support/wear/widget/CircledImageView.java b/wear/src/android/support/wear/widget/CircledImageView.java
index 413b913..e21a1ab 100644
--- a/wear/src/android/support/wear/widget/CircledImageView.java
+++ b/wear/src/android/support/wear/widget/CircledImageView.java
@@ -143,54 +143,55 @@
             mDrawable = mDrawable.mutate();
         }
 
-        mCircleColor = a.getColorStateList(R.styleable.CircledImageView_circle_color);
+        mCircleColor = a.getColorStateList(R.styleable.CircledImageView_background_color);
         if (mCircleColor == null) {
             mCircleColor = ColorStateList.valueOf(android.R.color.darker_gray);
         }
 
-        mCircleRadius = a.getDimension(R.styleable.CircledImageView_circle_radius, 0);
+        mCircleRadius = a.getDimension(R.styleable.CircledImageView_background_radius, 0);
         mInitialCircleRadius = mCircleRadius;
-        mCircleRadiusPressed =
-                a.getDimension(R.styleable.CircledImageView_circle_radius_pressed, mCircleRadius);
+        mCircleRadiusPressed = a.getDimension(
+                R.styleable.CircledImageView_background_radius_pressed, mCircleRadius);
         mCircleBorderColor = a
-                .getColor(R.styleable.CircledImageView_circle_border_color, Color.BLACK);
+                .getColor(R.styleable.CircledImageView_background_border_color, Color.BLACK);
         mCircleBorderCap =
-                Paint.Cap.values()[a.getInt(R.styleable.CircledImageView_circle_border_cap, 0)];
-        mCircleBorderWidth = a.getDimension(R.styleable.CircledImageView_circle_border_width, 0);
+                Paint.Cap.values()[a.getInt(R.styleable.CircledImageView_background_border_cap, 0)];
+        mCircleBorderWidth = a.getDimension(
+                R.styleable.CircledImageView_background_border_width, 0);
 
         if (mCircleBorderWidth > 0) {
             // The border arc is drawn from the middle of the arc - take that into account.
             mRadiusInset += mCircleBorderWidth / 2;
         }
 
-        float circlePadding = a.getDimension(R.styleable.CircledImageView_circle_padding, 0);
+        float circlePadding = a.getDimension(R.styleable.CircledImageView_img_padding, 0);
         if (circlePadding > 0) {
             mRadiusInset += circlePadding;
         }
 
         mImageCirclePercentage = a
-                .getFloat(R.styleable.CircledImageView_image_circle_percentage, 0f);
+                .getFloat(R.styleable.CircledImageView_img_circle_percentage, 0f);
 
         mImageHorizontalOffcenterPercentage =
-                a.getFloat(R.styleable.CircledImageView_image_horizontal_offcenter_percentage, 0f);
+                a.getFloat(R.styleable.CircledImageView_img_horizontal_offset_percentage, 0f);
 
-        if (a.hasValue(R.styleable.CircledImageView_image_tint)) {
-            mImageTint = a.getColor(R.styleable.CircledImageView_image_tint, 0);
+        if (a.hasValue(R.styleable.CircledImageView_img_tint)) {
+            mImageTint = a.getColor(R.styleable.CircledImageView_img_tint, 0);
         }
 
-        if (a.hasValue(R.styleable.CircledImageView_square_dimen)) {
-            mSquareDimen = a.getInt(R.styleable.CircledImageView_square_dimen, SQUARE_DIMEN_NONE);
+        if (a.hasValue(R.styleable.CircledImageView_clip_dimen)) {
+            mSquareDimen = a.getInt(R.styleable.CircledImageView_clip_dimen, SQUARE_DIMEN_NONE);
         }
 
         mCircleRadiusPercent =
-                a.getFraction(R.styleable.CircledImageView_circle_radius_percent, 1, 1, 0f);
+                a.getFraction(R.styleable.CircledImageView_background_radius_percent, 1, 1, 0f);
 
         mCircleRadiusPressedPercent =
                 a.getFraction(
-                        R.styleable.CircledImageView_circle_radius_pressed_percent, 1, 1,
+                        R.styleable.CircledImageView_background_radius_pressed_percent, 1, 1,
                         mCircleRadiusPercent);
 
-        float shadowWidth = a.getDimension(R.styleable.CircledImageView_shadow_width, 0);
+        float shadowWidth = a.getDimension(R.styleable.CircledImageView_background_shadow_width, 0);
 
         a.recycle();
 
diff --git a/wear/src/android/support/wear/widget/CircularProgressLayout.java b/wear/src/android/support/wear/widget/CircularProgressLayout.java
new file mode 100644
index 0000000..c317f28
--- /dev/null
+++ b/wear/src/android/support/wear/widget/CircularProgressLayout.java
@@ -0,0 +1,372 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.os.Build;
+import android.support.annotation.ColorInt;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.RequiresApi;
+import android.support.v4.content.ContextCompat;
+import android.support.v4.widget.CircularProgressDrawable;
+import android.support.wear.R;
+import android.util.AttributeSet;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.View;
+import android.widget.FrameLayout;
+
+/**
+ * {@link CircularProgressLayout} adds a circular countdown timer behind the view it contains,
+ * typically used to automatically confirm an operation after a short delay has elapsed.
+ *
+ * <p>The developer can specify a countdown interval via {@link #setTotalTime(long)} and a listener
+ * via {@link #setOnTimerFinishedListener(OnTimerFinishedListener)} to be called when the time has
+ * elapsed after {@link #startTimer()} has been called. Tap action can be received via {@link
+ * #setOnClickListener(OnClickListener)} and can be used to cancel the timer via {@link
+ * #stopTimer()} method.
+ *
+ * <p>Alternatively, this layout can be used to show indeterminate progress by calling {@link
+ * #setIndeterminate(boolean)} method.
+ */
+@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
+public class CircularProgressLayout extends FrameLayout {
+
+    /**
+     * Update interval for 60 fps.
+     */
+    private static final long DEFAULT_UPDATE_INTERVAL = 1000 / 60;
+
+    /**
+     * Starting rotation for the progress indicator. Geometric clockwise [0..360] degree range
+     * correspond to [0..1] range. 0.75 corresponds to 12 o'clock direction on a watch.
+     */
+    private static final float DEFAULT_ROTATION = 0.75f;
+
+    /**
+     * Used as background of this layout.
+     */
+    private CircularProgressDrawable mProgressDrawable;
+
+    /**
+     * Used to control this layout.
+     */
+    private CircularProgressLayoutController mController;
+
+    /**
+     * Angle for the progress to start from.
+     */
+    private float mStartingRotation = DEFAULT_ROTATION;
+
+    /**
+     * Duration of the timer in milliseconds.
+     */
+    private long mTotalTime;
+
+
+    /**
+     * Interface to implement for listening to {@link
+     * OnTimerFinishedListener#onTimerFinished(CircularProgressLayout)} event.
+     */
+    public interface OnTimerFinishedListener {
+
+        /**
+         * Called when the timer started by {@link #startTimer()} method finishes.
+         *
+         * @param layout {@link CircularProgressLayout} that calls this method.
+         */
+        void onTimerFinished(CircularProgressLayout layout);
+    }
+
+    public CircularProgressLayout(Context context) {
+        this(context, null);
+    }
+
+    public CircularProgressLayout(Context context, AttributeSet attrs) {
+        this(context, attrs, 0);
+    }
+
+    public CircularProgressLayout(Context context, AttributeSet attrs, int defStyleAttr) {
+        this(context, attrs, defStyleAttr, 0);
+    }
+
+    public CircularProgressLayout(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+
+        mProgressDrawable = new CircularProgressDrawable(context);
+        mProgressDrawable.setProgressRotation(DEFAULT_ROTATION);
+        mProgressDrawable.setStrokeCap(Paint.Cap.BUTT);
+        setBackground(mProgressDrawable);
+
+        // If a child view is added, make it center aligned so it fits in the progress drawable.
+        setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
+            @Override
+            public void onChildViewAdded(View parent, View child) {
+                // Ensure that child view is aligned in center
+                LayoutParams params = (LayoutParams) child.getLayoutParams();
+                params.gravity = Gravity.CENTER;
+                child.setLayoutParams(params);
+            }
+
+            @Override
+            public void onChildViewRemoved(View parent, View child) {
+
+            }
+        });
+
+        mController = new CircularProgressLayoutController(this);
+
+        Resources r = context.getResources();
+        TypedArray a = r.obtainAttributes(attrs, R.styleable.CircularProgressLayout);
+
+        if (a.getType(R.styleable.CircularProgressLayout_colorSchemeColors) == TypedValue
+                .TYPE_REFERENCE || !a.hasValue(
+                R.styleable.CircularProgressLayout_colorSchemeColors)) {
+            int arrayResId = a.getResourceId(R.styleable.CircularProgressLayout_colorSchemeColors,
+                    R.array.circular_progress_layout_color_scheme_colors);
+            setColorSchemeColors(getColorListFromResources(r, arrayResId));
+        } else {
+            setColorSchemeColors(a.getColor(R.styleable.CircularProgressLayout_colorSchemeColors,
+                    Color.BLACK));
+        }
+
+        setStrokeWidth(a.getDimensionPixelSize(R.styleable.CircularProgressLayout_strokeWidth,
+                r.getDimensionPixelSize(
+                        R.dimen.circular_progress_layout_stroke_width)));
+
+        setBackgroundColor(a.getColor(R.styleable.CircularProgressLayout_backgroundColor,
+                ContextCompat.getColor(context,
+                        R.color.circular_progress_layout_background_color)));
+
+        setIndeterminate(a.getBoolean(R.styleable.CircularProgressLayout_indeterminate, false));
+
+        a.recycle();
+    }
+
+    private int[] getColorListFromResources(Resources resources, int arrayResId) {
+        TypedArray colorArray = resources.obtainTypedArray(arrayResId);
+        int[] colors = new int[colorArray.length()];
+        for (int i = 0; i < colorArray.length(); i++) {
+            colors[i] = colorArray.getColor(i, 0);
+        }
+        colorArray.recycle();
+        return colors;
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+        super.onLayout(changed, left, top, right, bottom);
+        if (getChildCount() != 0) {
+            View childView = getChildAt(0);
+            // Wrap the drawable around the child view
+            mProgressDrawable.setCenterRadius(
+                    Math.min(childView.getWidth(), childView.getHeight()) / 2f);
+        } else {
+            // Fill the bounds if no child view is present
+            mProgressDrawable.setCenterRadius(0f);
+        }
+    }
+
+    @Override
+    protected void onDetachedFromWindow() {
+        super.onDetachedFromWindow();
+        mController.reset();
+    }
+
+    /**
+     * Sets the background color of the {@link CircularProgressDrawable}, which is drawn as a circle
+     * inside the progress drawable. Colors are in ARGB format defined in {@link Color}.
+     *
+     * @param color an ARGB color
+     */
+    @Override
+    public void setBackgroundColor(@ColorInt int color) {
+        mProgressDrawable.setBackgroundColor(color);
+    }
+
+    /**
+     * Returns the background color of the {@link CircularProgressDrawable}.
+     *
+     * @return an ARGB color
+     */
+    @ColorInt
+    public int getBackgroundColor() {
+        return mProgressDrawable.getBackgroundColor();
+    }
+
+    /**
+     * Returns the {@link CircularProgressDrawable} used as background of this layout.
+     *
+     * @return {@link CircularProgressDrawable}
+     */
+    @NonNull
+    public CircularProgressDrawable getProgressDrawable() {
+        return mProgressDrawable;
+    }
+
+    /**
+     * Sets if progress should be shown as an indeterminate spinner.
+     *
+     * @param indeterminate {@code true} if indeterminate spinner should be shown, {@code false}
+     *                      otherwise.
+     */
+    public void setIndeterminate(boolean indeterminate) {
+        mController.setIndeterminate(indeterminate);
+    }
+
+    /**
+     * Returns if progress is showing as an indeterminate spinner.
+     *
+     * @return {@code true} if indeterminate spinner is shown, {@code false} otherwise.
+     */
+    public boolean isIndeterminate() {
+        return mController.isIndeterminate();
+    }
+
+    /**
+     * Sets the total time in milliseconds for the timer to countdown to. Calling this method while
+     * the timer is already running will not change the duration of the current timer.
+     *
+     * @param totalTime total time in milliseconds
+     */
+    public void setTotalTime(long totalTime) {
+        if (totalTime <= 0) {
+            throw new IllegalArgumentException("Total time should be greater than zero.");
+        }
+        mTotalTime = totalTime;
+    }
+
+    /**
+     * Returns the total time in milliseconds for the timer to countdown to.
+     *
+     * @return total time in milliseconds
+     */
+    public long getTotalTime() {
+        return mTotalTime;
+    }
+
+    /**
+     * Starts the timer countdown. Once the countdown is finished, if there is an {@link
+     * OnTimerFinishedListener} registered by {@link
+     * #setOnTimerFinishedListener(OnTimerFinishedListener)} method, its
+     * {@link OnTimerFinishedListener#onTimerFinished(CircularProgressLayout)} method is called. If
+     * this method is called while there is already a running timer, it will restart the timer.
+     */
+    public void startTimer() {
+        mController.startTimer(mTotalTime, DEFAULT_UPDATE_INTERVAL);
+        mProgressDrawable.setProgressRotation(mStartingRotation);
+    }
+
+    /**
+     * Stops the timer countdown. If there is no timer running, calling this method will not do
+     * anything.
+     */
+    public void stopTimer() {
+        mController.stopTimer();
+    }
+
+    /**
+     * Returns if the timer is running.
+     *
+     * @return {@code true} if the timer is running, {@code false} otherwise
+     */
+    public boolean isTimerRunning() {
+        return mController.isTimerRunning();
+    }
+
+    /**
+     * Sets the starting rotation for the progress drawable to start from. Default starting rotation
+     * is {@code 0.75} and it corresponds clockwise geometric 270 degrees (12 o'clock on a watch)
+     *
+     * @param rotation starting rotation from [0..1]
+     */
+    public void setStartingRotation(float rotation) {
+        mStartingRotation = rotation;
+    }
+
+    /**
+     * Returns the starting rotation of the progress drawable.
+     *
+     * @return starting rotation from [0..1]
+     */
+    public float getStartingRotation() {
+        return mStartingRotation;
+    }
+
+    /**
+     * Sets the stroke width of the progress drawable in pixels.
+     *
+     * @param strokeWidth stroke width in pixels
+     */
+    public void setStrokeWidth(float strokeWidth) {
+        mProgressDrawable.setStrokeWidth(strokeWidth);
+    }
+
+    /**
+     * Returns the stroke width of the progress drawable in pixels.
+     *
+     * @return stroke width in pixels
+     */
+    public float getStrokeWidth() {
+        return mProgressDrawable.getStrokeWidth();
+    }
+
+    /**
+     * Sets the color scheme colors of the progress drawable, which is equivalent to calling {@link
+     * CircularProgressDrawable#setColorSchemeColors(int...)} method on background drawable of this
+     * layout.
+     *
+     * @param colors list of ARGB colors
+     */
+    public void setColorSchemeColors(int... colors) {
+        mProgressDrawable.setColorSchemeColors(colors);
+    }
+
+    /**
+     * Returns the color scheme colors of the progress drawable
+     *
+     * @return list of ARGB colors
+     */
+    public int[] getColorSchemeColors() {
+        return mProgressDrawable.getColorSchemeColors();
+    }
+
+    /**
+     * Returns the {@link OnTimerFinishedListener} that is registered to this layout.
+     *
+     * @return registered {@link OnTimerFinishedListener}
+     */
+    @Nullable
+    public OnTimerFinishedListener getOnTimerFinishedListener() {
+        return mController.getOnTimerFinishedListener();
+    }
+
+    /**
+     * Sets the {@link OnTimerFinishedListener} to be notified when timer countdown is finished.
+     *
+     * @param listener {@link OnTimerFinishedListener} to be notified, or {@code null} to clear
+     */
+    public void setOnTimerFinishedListener(@Nullable OnTimerFinishedListener listener) {
+        mController.setOnTimerFinishedListener(listener);
+    }
+}
diff --git a/wear/src/android/support/wear/widget/CircularProgressLayoutController.java b/wear/src/android/support/wear/widget/CircularProgressLayoutController.java
new file mode 100644
index 0000000..4fd7156
--- /dev/null
+++ b/wear/src/android/support/wear/widget/CircularProgressLayoutController.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import android.os.CountDownTimer;
+import android.support.annotation.Nullable;
+import android.support.annotation.VisibleForTesting;
+
+/**
+ * Controller for {@link CircularProgressLayout}.
+ */
+class CircularProgressLayoutController {
+
+    private final CircularProgressLayout mLayout;
+    @VisibleForTesting CountDownTimer mTimer;
+    private boolean mIsIndeterminate;
+    private boolean mIsTimerRunning;
+
+    /**
+     * Called when the timer is finished.
+     */
+    @Nullable
+    private CircularProgressLayout.OnTimerFinishedListener mOnTimerFinishedListener;
+
+    CircularProgressLayoutController(CircularProgressLayout layout) {
+        mLayout = layout;
+    }
+
+    /**
+     * Returns the registered {@link CircularProgressLayout.OnTimerFinishedListener}.
+     */
+    @Nullable
+    public CircularProgressLayout.OnTimerFinishedListener getOnTimerFinishedListener() {
+        return mOnTimerFinishedListener;
+    }
+
+    /**
+     * Sets the {@link CircularProgressLayout.OnTimerFinishedListener} to be notified when timer
+     * countdown is finished.
+     */
+    public void setOnTimerFinishedListener(
+            @Nullable CircularProgressLayout.OnTimerFinishedListener listener) {
+        mOnTimerFinishedListener = listener;
+    }
+
+    /** Returns true if the progress is shown as an indeterminate spinner. */
+    boolean isIndeterminate() {
+        return mIsIndeterminate;
+    }
+
+    /** Returns true if timer is running. */
+    boolean isTimerRunning() {
+        return mIsTimerRunning;
+    }
+
+    /** Sets if the progress should be shown as an indeterminate spinner. */
+    void setIndeterminate(boolean indeterminate) {
+        if (mIsIndeterminate == indeterminate) {
+            return;
+        }
+        mIsIndeterminate = indeterminate;
+        if (mIsIndeterminate) {
+            if (mIsTimerRunning) {
+                stopTimer();
+            }
+            mLayout.getProgressDrawable().start();
+        } else {
+            mLayout.getProgressDrawable().stop();
+        }
+    }
+
+    void startTimer(long totalTime, long updateInterval) {
+        reset();
+        mIsTimerRunning = true;
+        mTimer = new CircularProgressTimer(totalTime, updateInterval);
+        mTimer.start();
+    }
+
+    void stopTimer() {
+        if (mIsTimerRunning) {
+            mTimer.cancel();
+            mIsTimerRunning = false;
+            mLayout.getProgressDrawable().setStartEndTrim(0f, 0f); // Reset the progress
+        }
+    }
+
+    /**
+     * Resets everything.
+     */
+    void reset() {
+        setIndeterminate(false); // If showing indeterminate progress, stop it
+        stopTimer(); // Stop the previous timer if there is one
+        mLayout.getProgressDrawable().setStartEndTrim(0f, 0f); // Reset the progress
+    }
+
+    /**
+     * Class to handle timing for {@link CircularProgressLayout}.
+     */
+    private class CircularProgressTimer extends CountDownTimer {
+
+        private final long mTotalTime;
+
+        CircularProgressTimer(long totalTime, long updateInterval) {
+            super(totalTime, updateInterval);
+            mTotalTime = totalTime;
+        }
+
+        @Override
+        public void onTick(long millisUntilFinished) {
+            mLayout.getProgressDrawable()
+                    .setStartEndTrim(0f, 1f - (float) millisUntilFinished / (float) mTotalTime);
+            mLayout.invalidate();
+        }
+
+        @Override
+        public void onFinish() {
+            mLayout.getProgressDrawable().setStartEndTrim(0f, 1f);
+            if (mOnTimerFinishedListener != null) {
+                mOnTimerFinishedListener.onTimerFinished(mLayout);
+            }
+            mIsTimerRunning = false;
+        }
+    }
+}
diff --git a/wear/src/android/support/wear/widget/CurvingLayoutCallback.java b/wear/src/android/support/wear/widget/CurvingLayoutCallback.java
index f6eed46..275f1f8 100644
--- a/wear/src/android/support/wear/widget/CurvingLayoutCallback.java
+++ b/wear/src/android/support/wear/widget/CurvingLayoutCallback.java
@@ -53,7 +53,7 @@
         mPathMeasure = new PathMeasure();
         mIsScreenRound = context.getResources().getConfiguration().isScreenRound();
         mXCurveOffset = context.getResources().getDimensionPixelSize(
-                R.dimen.wrv_curve_default_x_offset);
+                R.dimen.ws_wrv_curve_default_x_offset);
     }
 
     @Override
diff --git a/wear/src/android/support/wear/widget/RoundedDrawable.java b/wear/src/android/support/wear/widget/RoundedDrawable.java
new file mode 100644
index 0000000..e2d7611
--- /dev/null
+++ b/wear/src/android/support/wear/widget/RoundedDrawable.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import android.annotation.TargetApi;
+import android.graphics.Bitmap;
+import android.graphics.BitmapShader;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.ColorFilter;
+import android.graphics.Paint;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.Shader;
+import android.graphics.drawable.Drawable;
+import android.os.Build;
+import android.support.annotation.ColorInt;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.annotation.VisibleForTesting;
+
+import java.util.Objects;
+
+/**
+ * Maintains and draws a drawable inside rounded rectangular bounds.
+ *
+ * <p>The drawable set by the {@link #setDrawable(Drawable)} method will be drawn within the rounded
+ * bounds specified by {@link #setBounds(Rect)} and {@link #setRadius(int)} when the
+ * {@link #draw(Canvas)} method is called.
+ *
+ * <p>By default, RoundedDrawable will apply padding to the drawable inside to fit the drawable into
+ * the rounded rectangle. If clipping is enabled by the {@link #setClipEnabled(boolean)} method, it
+ * will clip the drawable to a rounded rectangle instead of resizing it.
+ *
+ * <p>The {@link #setRadius(int)} method is used to specify the amount of border radius applied to
+ * the corners of inner drawable, regardless of whether or not the clipping is enabled, border
+ * radius will be applied to prevent overflowing of the drawable from specified rounded rectangular
+ * area.
+ */
+@TargetApi(Build.VERSION_CODES.N)
+public class RoundedDrawable extends Drawable {
+
+    @VisibleForTesting
+    final Paint mPaint;
+    final Paint mBackgroundPaint;
+
+    @Nullable
+    private Drawable mDrawable;
+    private int mRadius; // Radius applied to corners in pixels
+    private boolean mIsClipEnabled;
+
+    // Used to avoid creating new Rect objects every time draw() is called
+    private final Rect mTmpBounds = new Rect();
+    private final RectF mTmpBoundsF = new RectF();
+
+    public RoundedDrawable() {
+        mPaint = new Paint();
+        mPaint.setAntiAlias(true);
+        mBackgroundPaint = new Paint();
+        mBackgroundPaint.setAntiAlias(true);
+        mBackgroundPaint.setColor(Color.TRANSPARENT);
+    }
+
+    /**
+     * Sets the drawable to be rendered.
+     *
+     * @param drawable {@link Drawable} to be rendered
+     */
+    public void setDrawable(@Nullable Drawable drawable) {
+        if (Objects.equals(mDrawable, drawable)) {
+            return;
+        }
+        mDrawable = drawable;
+        mPaint.setShader(null); // Clear the shader so it can be reinitialized
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the drawable that will be rendered.
+     *
+     * @return {@link Drawable} that will be rendered.
+     */
+    @Nullable
+    public Drawable getDrawable() {
+        return mDrawable;
+    }
+
+    /**
+     * Sets the background color of the rounded drawable.
+     *
+     * @param color an ARGB color
+     */
+    public void setBackgroundColor(@ColorInt int color) {
+        mBackgroundPaint.setColor(color);
+        invalidateSelf();
+    }
+
+    /**
+     * Returns the background color.
+     *
+     * @return an ARGB color
+     */
+    @ColorInt
+    public int getBackgroundColor() {
+        return mBackgroundPaint.getColor();
+    }
+
+    /**
+     * Sets whether the drawable inside should be clipped or resized to fit the rounded bounds. If
+     * the drawable is animated, don't set clipping to {@code true} as clipping on animated
+     * drawables is not supported.
+     *
+     * @param clipEnabled {@code true} if the drawable should be clipped, {@code false} if it
+     *                    should be resized.
+     */
+    public void setClipEnabled(boolean clipEnabled) {
+        mIsClipEnabled = clipEnabled;
+        if (!clipEnabled) {
+            mPaint.setShader(null); // Clear the shader so it's garbage collected
+        }
+        invalidateSelf();
+    }
+
+    /**
+     * Returns whether the drawable inside is clipped or resized to fit the rounded bounds.
+     *
+     * @return {@code true} if the drawable is clipped, {@code false} if it's resized.
+     */
+    public boolean isClipEnabled() {
+        return mIsClipEnabled;
+    }
+
+    @Override
+    protected void onBoundsChange(Rect bounds) {
+        mTmpBounds.right = bounds.width();
+        mTmpBounds.bottom = bounds.height();
+        mTmpBoundsF.right = bounds.width();
+        mTmpBoundsF.bottom = bounds.height();
+        mPaint.setShader(null); // Clear the shader so it can be reinitialized
+    }
+
+    @Override
+    public void draw(@NonNull Canvas canvas) {
+        Rect bounds = getBounds();
+        if (mDrawable == null || bounds.isEmpty()) {
+            return;
+        }
+        canvas.save();
+        canvas.translate(bounds.left, bounds.top);
+        // mTmpBoundsF is bounds translated to (0,0) and converted to RectF as drawRoundRect
+        // requires.
+        canvas.drawRoundRect(mTmpBoundsF, (float) mRadius, (float) mRadius,
+                mBackgroundPaint);
+        if (mIsClipEnabled) {
+            // Update the shader if it's not present.
+            if (mPaint.getShader() == null) {
+                updateBitmapShader();
+            }
+            // Clip to a rounded rectangle
+            canvas.drawRoundRect(mTmpBoundsF, (float) mRadius, (float) mRadius, mPaint);
+        } else {
+            // Scale to fit the rounded rectangle
+            int minEdge = Math.min(bounds.width(), bounds.height());
+            int padding = (int) Math.ceil(
+                    Math.min(mRadius, minEdge / 2) * (1 - 1 / (float) Math.sqrt(2.0)));
+            mTmpBounds.inset(padding, padding);
+            mDrawable.setBounds(mTmpBounds);
+            mDrawable.draw(canvas);
+            mTmpBounds.inset(-padding, -padding);
+        }
+        canvas.restore();
+    }
+
+    @Override
+    public int getOpacity() {
+        return PixelFormat.TRANSLUCENT;
+    }
+
+    @Override
+    public void setAlpha(int alpha) {
+        mPaint.setAlpha(alpha);
+        mBackgroundPaint.setAlpha(alpha);
+    }
+
+    @Override
+    public int getAlpha() {
+        return mPaint.getAlpha();
+    }
+
+    @Override
+    public void setColorFilter(ColorFilter cf) {
+        mPaint.setColorFilter(cf);
+    }
+
+    /**
+     * Sets the border radius to be applied when rendering the drawable in pixels.
+     *
+     * @param radius radius in pixels
+     */
+    public void setRadius(int radius) {
+        mRadius = radius;
+    }
+
+    /**
+     * Returns the border radius applied when rendering the drawable in pixels.
+     *
+     * @return radius in pixels
+     */
+    public int getRadius() {
+        return mRadius;
+    }
+
+    /**
+     * Updates the shader of the paint. To avoid scaling and creation of a BitmapShader every time,
+     * this method should be called only if the drawable or the bounds has changed.
+     */
+    private void updateBitmapShader() {
+        if (mDrawable == null) {
+            return;
+        }
+        Rect bounds = getBounds();
+        if (!bounds.isEmpty()) {
+            Bitmap bitmap = drawableToBitmap(mDrawable, bounds.width(), bounds.height());
+
+            Shader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
+            mPaint.setShader(shader);
+        }
+    }
+
+    /** Converts a drawable to a bitmap of specified width and height. */
+    private Bitmap drawableToBitmap(Drawable drawable, int width, int height) {
+        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
+
+        Canvas canvas = new Canvas(bitmap);
+        drawable.setBounds(0, 0, width, height);
+        drawable.draw(canvas);
+        return bitmap;
+    }
+}
diff --git a/wear/src/android/support/wear/widget/drawer/PageIndicatorView.java b/wear/src/android/support/wear/widget/drawer/PageIndicatorView.java
index 7317c21..99c7c09 100644
--- a/wear/src/android/support/wear/widget/drawer/PageIndicatorView.java
+++ b/wear/src/android/support/wear/widget/drawer/PageIndicatorView.java
@@ -96,28 +96,30 @@
                 getContext()
                         .obtainStyledAttributes(
                                 attrs, R.styleable.PageIndicatorView, defStyleAttr,
-                                R.style.PageIndicatorViewStyle);
+                                R.style.WsPageIndicatorViewStyle);
 
-        mDotSpacing =
-                a.getDimensionPixelOffset(R.styleable.PageIndicatorView_pageIndicatorDotSpacing, 0);
-        mDotRadius = a.getDimension(R.styleable.PageIndicatorView_pageIndicatorDotRadius, 0);
+        mDotSpacing = a.getDimensionPixelOffset(
+                R.styleable.PageIndicatorView_wsPageIndicatorDotSpacing, 0);
+        mDotRadius = a.getDimension(R.styleable.PageIndicatorView_wsPageIndicatorDotRadius, 0);
         mDotRadiusSelected =
-                a.getDimension(R.styleable.PageIndicatorView_pageIndicatorDotRadiusSelected, 0);
-        mDotColor = a.getColor(R.styleable.PageIndicatorView_pageIndicatorDotColor, 0);
+                a.getDimension(R.styleable.PageIndicatorView_wsPageIndicatorDotRadiusSelected, 0);
+        mDotColor = a.getColor(R.styleable.PageIndicatorView_wsPageIndicatorDotColor, 0);
         mDotColorSelected = a
-                .getColor(R.styleable.PageIndicatorView_pageIndicatorDotColorSelected, 0);
-        mDotFadeOutDelay = a.getInt(R.styleable.PageIndicatorView_pageIndicatorDotFadeOutDelay, 0);
+                .getColor(R.styleable.PageIndicatorView_wsPageIndicatorDotColorSelected, 0);
+        mDotFadeOutDelay =
+                a.getInt(R.styleable.PageIndicatorView_wsPageIndicatorDotFadeOutDelay, 0);
         mDotFadeOutDuration =
-                a.getInt(R.styleable.PageIndicatorView_pageIndicatorDotFadeOutDuration, 0);
-        mDotFadeInDuration = a
-                .getInt(R.styleable.PageIndicatorView_pageIndicatorDotFadeInDuration, 0);
+                a.getInt(R.styleable.PageIndicatorView_wsPageIndicatorDotFadeOutDuration, 0);
+        mDotFadeInDuration =
+                a.getInt(R.styleable.PageIndicatorView_wsPageIndicatorDotFadeInDuration, 0);
         mDotFadeWhenIdle =
-                a.getBoolean(R.styleable.PageIndicatorView_pageIndicatorDotFadeWhenIdle, false);
-        mDotShadowDx = a.getDimension(R.styleable.PageIndicatorView_pageIndicatorDotShadowDx, 0);
-        mDotShadowDy = a.getDimension(R.styleable.PageIndicatorView_pageIndicatorDotShadowDy, 0);
+                a.getBoolean(R.styleable.PageIndicatorView_wsPageIndicatorDotFadeWhenIdle, false);
+        mDotShadowDx = a.getDimension(R.styleable.PageIndicatorView_wsPageIndicatorDotShadowDx, 0);
+        mDotShadowDy = a.getDimension(R.styleable.PageIndicatorView_wsPageIndicatorDotShadowDy, 0);
         mDotShadowRadius =
-                a.getDimension(R.styleable.PageIndicatorView_pageIndicatorDotShadowRadius, 0);
-        mDotShadowColor = a.getColor(R.styleable.PageIndicatorView_pageIndicatorDotShadowColor, 0);
+                a.getDimension(R.styleable.PageIndicatorView_wsPageIndicatorDotShadowRadius, 0);
+        mDotShadowColor =
+                a.getColor(R.styleable.PageIndicatorView_wsPageIndicatorDotShadowColor, 0);
         a.recycle();
 
         mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
diff --git a/wear/src/android/support/wear/widget/drawer/WearableActionDrawerView.java b/wear/src/android/support/wear/widget/drawer/WearableActionDrawerView.java
index a663cc2..994b804 100644
--- a/wear/src/android/support/wear/widget/drawer/WearableActionDrawerView.java
+++ b/wear/src/android/support/wear/widget/drawer/WearableActionDrawerView.java
@@ -50,13 +50,13 @@
  * WearableDrawerLayout} to create a drawer for users to easily pull up contextual actions. These
  * contextual actions may be specified by using a {@link Menu}, which may be populated by either:
  *
- * <ul> <li>Specifying the {@code action_menu} attribute in the XML layout file. Example:
+ * <ul> <li>Specifying the {@code app:actionMenu} attribute in the XML layout file. Example:
  * <pre>
  * &lt;android.support.wear.widget.drawer.WearableActionDrawerView
  *     xmlns:app="http://schemas.android.com/apk/res-auto"
  *     android:layout_width=”match_parent”
  *     android:layout_height=”match_parent”
- *     app:action_menu="@menu/action_drawer" /&gt;</pre>
+ *     app:actionMenu="@menu/action_drawer" /&gt;</pre>
  *
  * <li>Getting the menu with {@link #getMenu}, and then inflating it with {@link
  * MenuInflater#inflate}. Example:
@@ -137,20 +137,20 @@
 
         if (!mShowOverflowInPeek) {
             LayoutInflater layoutInflater = LayoutInflater.from(context);
-            View peekView = layoutInflater.inflate(
-                    R.layout.action_drawer_peek_view, getPeekContainer(), false /* attachToRoot */);
+            View peekView = layoutInflater.inflate(R.layout.ws_action_drawer_peek_view,
+                    getPeekContainer(), false /* attachToRoot */);
             setPeekContent(peekView);
             mPeekActionIcon =
                     (ImageView) peekView
-                            .findViewById(R.id.wearable_support_action_drawer_peek_action_icon);
+                            .findViewById(R.id.ws_action_drawer_peek_action_icon);
             mPeekExpandIcon =
                     (ImageView) peekView
-                            .findViewById(R.id.wearable_support_action_drawer_expand_icon);
+                            .findViewById(R.id.ws_action_drawer_expand_icon);
         } else {
             mPeekActionIcon = null;
             mPeekExpandIcon = null;
             getPeekContainer().setContentDescription(
-                    context.getString(R.string.action_drawer_content_description));
+                    context.getString(R.string.ws_action_drawer_content_description));
         }
 
         if (menuRes != 0) {
@@ -164,26 +164,26 @@
         int screenHeightPx = ResourcesUtil.getScreenHeightPx(context);
 
         Resources res = getResources();
-        mTopPadding = res.getDimensionPixelOffset(R.dimen.action_drawer_item_top_padding);
-        mBottomPadding = res.getDimensionPixelOffset(R.dimen.action_drawer_item_bottom_padding);
+        mTopPadding = res.getDimensionPixelOffset(R.dimen.ws_action_drawer_item_top_padding);
+        mBottomPadding = res.getDimensionPixelOffset(R.dimen.ws_action_drawer_item_bottom_padding);
         mLeftPadding =
                 ResourcesUtil.getFractionOfScreenPx(
-                        context, screenWidthPx, R.fraction.action_drawer_item_left_padding);
+                        context, screenWidthPx, R.fraction.ws_action_drawer_item_left_padding);
         mRightPadding =
                 ResourcesUtil.getFractionOfScreenPx(
-                        context, screenWidthPx, R.fraction.action_drawer_item_right_padding);
+                        context, screenWidthPx, R.fraction.ws_action_drawer_item_right_padding);
 
         mFirstItemTopPadding =
                 ResourcesUtil.getFractionOfScreenPx(
                         context, screenHeightPx,
-                        R.fraction.action_drawer_item_first_item_top_padding);
+                        R.fraction.ws_action_drawer_item_first_item_top_padding);
         mLastItemBottomPadding =
                 ResourcesUtil.getFractionOfScreenPx(
                         context, screenHeightPx,
-                        R.fraction.action_drawer_item_last_item_bottom_padding);
+                        R.fraction.ws_action_drawer_item_last_item_bottom_padding);
 
         mIconRightMargin = res
-                .getDimensionPixelOffset(R.dimen.action_drawer_item_icon_right_margin);
+                .getDimensionPixelOffset(R.dimen.ws_action_drawer_item_icon_right_margin);
 
         mActionList = new RecyclerView(context);
         mActionList.setLayoutManager(new LinearLayoutManager(context));
@@ -359,7 +359,7 @@
         TitleViewHolder(View view) {
             super(view);
             this.view = view;
-            textView = (TextView) view.findViewById(R.id.wearable_support_action_drawer_title);
+            textView = (TextView) view.findViewById(R.id.ws_action_drawer_title);
         }
     }
 
@@ -425,14 +425,14 @@
                 case TYPE_TITLE:
                     View titleView =
                             LayoutInflater.from(parent.getContext())
-                                    .inflate(R.layout.action_drawer_title_view, parent, false);
+                                    .inflate(R.layout.ws_action_drawer_title_view, parent, false);
                     return new TitleViewHolder(titleView);
 
                 case TYPE_ACTION:
                 default:
                     View actionView =
                             LayoutInflater.from(parent.getContext())
-                                    .inflate(R.layout.action_drawer_item_view, parent, false);
+                                    .inflate(R.layout.ws_action_drawer_item_view, parent, false);
                     actionView.setOnClickListener(mItemClickListener);
                     return new ActionItemViewHolder(actionView);
             }
@@ -453,9 +453,9 @@
         ActionItemViewHolder(View view) {
             super(view);
             this.view = view;
-            iconView = (ImageView) view.findViewById(R.id.wearable_support_action_drawer_item_icon);
+            iconView = (ImageView) view.findViewById(R.id.ws_action_drawer_item_icon);
             ((LinearLayout.LayoutParams) iconView.getLayoutParams()).setMarginEnd(mIconRightMargin);
-            textView = (TextView) view.findViewById(R.id.wearable_support_action_drawer_item_text);
+            textView = (TextView) view.findViewById(R.id.ws_action_drawer_item_text);
         }
     }
 }
diff --git a/wear/src/android/support/wear/widget/drawer/WearableDrawerLayout.java b/wear/src/android/support/wear/widget/drawer/WearableDrawerLayout.java
index 9825692..6d27064 100644
--- a/wear/src/android/support/wear/widget/drawer/WearableDrawerLayout.java
+++ b/wear/src/android/support/wear/widget/drawer/WearableDrawerLayout.java
@@ -60,8 +60,7 @@
  *
  * <pre>
  * &lt;android.support.wear.widget.drawer.WearableDrawerLayout [...]&gt;
- *     &lt;FrameLayout
- *         android:id=”@+id/content” /&gt;
+ *     &lt;FrameLayout android:id=”@+id/content” /&gt;
  *
  *     &lt;android.support.wear.widget.drawer.WearableNavigationDrawerView
  *         android:layout_width=”match_parent”
@@ -76,25 +75,25 @@
  * <p>To use custom content in a drawer, place {@link WearableDrawerView} in a WearableDrawerLayout
  * and specify the layout_gravity to pick the drawer location (the following example is for a top
  * drawer). <b>Note:</b> You must either call {@link WearableDrawerView#setDrawerContent} and pass
- * in your drawer content view, or specify it in the {@code app:drawer_content} XML attribute.
+ * in your drawer content view, or specify it in the {@code app:drawerContent} XML attribute.
  *
  * <pre>
  * &lt;android.support.wear.widget.drawer.WearableDrawerLayout [...]&gt;
  *     &lt;FrameLayout
+ *         android:id=”@+id/content”
  *         android:layout_width=”match_parent”
- *         android:layout_height=”match_parent”
- *         android:id=”@+id/content” /&gt;
+ *         android:layout_height=”match_parent” /&gt;
  *
  *     &lt;android.support.wear.widget.drawer.WearableDrawerView
  *         android:layout_width=”match_parent”
  *         android:layout_height=”match_parent”
  *         android:layout_gravity=”top”
- *         app:drawer_content="@+id/top_drawer_content" &gt;
+ *         app:drawerContent="@+id/top_drawer_content" &gt;
  *
  *         &lt;FrameLayout
+ *             android:id=”@id/top_drawer_content”
  *             android:layout_width=”match_parent”
- *             android:layout_height=”match_parent”
- *             android:id=”@id/top_drawer_content” /&gt;
+ *             android:layout_height=”match_parent” /&gt;
  *
  *     &lt;/android.support.wear.widget.drawer.WearableDrawerView&gt;
  * &lt;/android.support.wear.widget.drawer.WearableDrawerLayout&gt;</pre>
diff --git a/wear/src/android/support/wear/widget/drawer/WearableDrawerView.java b/wear/src/android/support/wear/widget/drawer/WearableDrawerView.java
index 97aa9f5..dafac39 100644
--- a/wear/src/android/support/wear/widget/drawer/WearableDrawerView.java
+++ b/wear/src/android/support/wear/widget/drawer/WearableDrawerView.java
@@ -48,8 +48,8 @@
  * content must be provided.
  *
  * <p>There are two ways to specify the content and peek views: by invoking {@code setter} methods
- * on the {@code WearableDrawerView}, or by specifying the {@code drawer_content} and {@code
- * peek_view} attributes. Examples:
+ * on the {@code WearableDrawerView}, or by specifying the {@code app:drawerContent} and {@code
+ * app:peekView} attributes. Examples:
  *
  * <pre>
  * // From Java:
@@ -62,8 +62,8 @@
  *     android:layout_height="match_parent"
  *     android:layout_gravity="bottom"
  *     android:background="@color/red"
- *     app:drawer_content="@+id/drawer_content"
- *     app:peek_view="@+id/peek_view"&gt;
+ *     app:drawerContent="@+id/drawer_content"
+ *     app:peekView="@+id/peek_view"&gt;
  *
  *     &lt;FrameLayout
  *         android:id="@id/drawer_content"
@@ -149,13 +149,14 @@
     public WearableDrawerView(
             Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
-        LayoutInflater.from(context).inflate(R.layout.wearable_drawer_view, this, true);
+        LayoutInflater.from(context).inflate(R.layout.ws_wearable_drawer_view, this, true);
 
         setClickable(true);
-        setElevation(context.getResources().getDimension(R.dimen.wearable_drawer_view_elevation));
+        setElevation(context.getResources()
+                .getDimension(R.dimen.ws_wearable_drawer_view_elevation));
 
-        mPeekContainer = (ViewGroup) findViewById(R.id.wearable_support_drawer_view_peek_container);
-        mPeekIcon = (ImageView) findViewById(R.id.wearable_support_drawer_view_peek_icon);
+        mPeekContainer = (ViewGroup) findViewById(R.id.ws_drawer_view_peek_container);
+        mPeekIcon = (ImageView) findViewById(R.id.ws_drawer_view_peek_icon);
 
         mPeekContainer.setOnClickListener(
                 new OnClickListener() {
@@ -215,10 +216,10 @@
                             == Gravity.TOP;
             if (isTopDrawer) {
                 peekParams.gravity = Gravity.BOTTOM;
-                mPeekIcon.setImageResource(R.drawable.ic_more_horiz_24dp_wht);
+                mPeekIcon.setImageResource(R.drawable.ws_ic_more_horiz_24dp_wht);
             } else {
                 peekParams.gravity = Gravity.TOP;
-                mPeekIcon.setImageResource(R.drawable.ic_more_vert_24dp_wht);
+                mPeekIcon.setImageResource(R.drawable.ws_ic_more_vert_24dp_wht);
             }
             mPeekContainer.setLayoutParams(peekParams);
         }
@@ -466,7 +467,7 @@
         TypedArray typedArray =
                 context.obtainStyledAttributes(
                         attrs, R.styleable.WearableDrawerView, defStyleAttr,
-                        R.style.Widget_Wearable_WearableDrawerView);
+                        R.style.Widget_Wear_WearableDrawerView);
 
         Drawable background =
                 getDrawable(context, typedArray, R.styleable.WearableDrawerView_android_background);
diff --git a/wear/src/android/support/wear/widget/drawer/WearableNavigationDrawerView.java b/wear/src/android/support/wear/widget/drawer/WearableNavigationDrawerView.java
index 5a17c5c..480812b 100644
--- a/wear/src/android/support/wear/widget/drawer/WearableNavigationDrawerView.java
+++ b/wear/src/android/support/wear/widget/drawer/WearableNavigationDrawerView.java
@@ -55,8 +55,8 @@
  * navigation drawer will be displayed as empty. The multiple page navigation drawer will display 1
  * or more pages to the user, each representing different navigation verticals.
  *
- * <p>The developer may specify which style to use with the {@code app:navigation_style} custom
- * attribute. If not specified, {@link #SINGLE_PAGE} will be used as the default.
+ * <p>The developer may specify which style to use with the {@code app:navigationStyle} custom
+ * attribute. If not specified, {@link #SINGLE_PAGE singlePage} will be used as the default.
  */
 @TargetApi(Build.VERSION_CODES.M)
 public class WearableNavigationDrawerView extends WearableDrawerView {
@@ -163,7 +163,7 @@
 
         getPeekContainer()
                 .setContentDescription(
-                        context.getString(R.string.navigation_drawer_content_description));
+                        context.getString(R.string.ws_navigation_drawer_content_description));
 
         setOpenOnlyAtTopEnabled(true);
     }
diff --git a/wear/tests/AndroidManifest.xml b/wear/tests/AndroidManifest.xml
index 34a0f03..23d66f4 100644
--- a/wear/tests/AndroidManifest.xml
+++ b/wear/tests/AndroidManifest.xml
@@ -15,41 +15,37 @@
   ~ limitations under the License.
   -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
           package="android.support.wear.test">
-    <uses-sdk android:minSdkVersion="20"
-              android:targetSdkVersion="23"
-              tools:overrideLibrary="android.support.test, android.app, android.support.test.rule,
-                      android.support.test.espresso, android.support.test.espresso.idling"/>
+    <uses-sdk android:targetSdkVersion="${target-sdk-version}"/>
 
-    <uses-permission android:name="android.permission.WAKE_LOCK" />
+    <uses-permission android:name="android.permission.WAKE_LOCK"/>
 
     <application android:supportsRtl="true">
         <activity android:name="android.support.wear.widget.LayoutTestActivity">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
         <activity android:name="android.support.wear.widget.SwipeDismissFrameLayoutTestActivity"
-                  android:theme="@style/AppThemeNoSwipe" >
+                  android:theme="@style/AppThemeNoSwipe">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
 
         <activity android:name="android.support.wear.widget.WearableRecyclerViewTestActivity">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
 
         <activity android:name="android.support.wear.widget.drawer.DrawerTestActivity">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
     </application>
diff --git a/wear/tests/res/layout/circular_progress_layout.xml b/wear/tests/res/layout/circular_progress_layout.xml
new file mode 100644
index 0000000..cce69e6
--- /dev/null
+++ b/wear/tests/res/layout/circular_progress_layout.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+             android:layout_width="match_parent"
+             android:layout_height="match_parent"
+             xmlns:app="http://schemas.android.com/apk/res-auto"
+             android:orientation="vertical">
+    <android.support.wear.widget.CircularProgressLayout
+        android:id="@+id/circular_progress_layout"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:padding="10dp"
+        app:strokeWidth="10dp">
+        <View
+            android:id="@+id/child_view"
+            android:layout_width="40dp"
+            android:layout_height="40dp"/>
+    </android.support.wear.widget.CircularProgressLayout>
+</FrameLayout >
\ No newline at end of file
diff --git a/wear/tests/res/layout/rounded_drawable_layout.xml b/wear/tests/res/layout/rounded_drawable_layout.xml
new file mode 100644
index 0000000..6c83b58
--- /dev/null
+++ b/wear/tests/res/layout/rounded_drawable_layout.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent">
+
+</LinearLayout>
\ No newline at end of file
diff --git a/wear/tests/src/android/support/wear/widget/CircularProgressLayoutControllerTest.java b/wear/tests/src/android/support/wear/widget/CircularProgressLayoutControllerTest.java
new file mode 100644
index 0000000..8d5406d
--- /dev/null
+++ b/wear/tests/src/android/support/wear/widget/CircularProgressLayoutControllerTest.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v4.widget.CircularProgressDrawable;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+
+import java.util.concurrent.TimeUnit;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class CircularProgressLayoutControllerTest {
+
+    private static final long TOTAL_TIME = TimeUnit.SECONDS.toMillis(1);
+    private static final long UPDATE_INTERVAL = TimeUnit.MILLISECONDS.toMillis(30);
+
+    private CircularProgressLayoutController mControllerUnderTest;
+
+    @Mock
+    CircularProgressDrawable mMockDrawable;
+    @Mock
+    CircularProgressLayout mMockLayout;
+    @Mock
+    CircularProgressLayout.OnTimerFinishedListener mMockListener;
+
+    @Before
+    public void setUp() {
+        mMockDrawable = mock(CircularProgressDrawable.class);
+        mMockLayout = mock(CircularProgressLayout.class);
+        mMockListener = mock(CircularProgressLayout.OnTimerFinishedListener.class);
+        when(mMockLayout.getProgressDrawable()).thenReturn(mMockDrawable);
+        when(mMockLayout.getOnTimerFinishedListener()).thenReturn(mMockListener);
+        mControllerUnderTest = new CircularProgressLayoutController(mMockLayout);
+    }
+
+    @Test
+    public void testSetIndeterminate() {
+        mControllerUnderTest.setIndeterminate(true);
+
+        assertEquals(true, mControllerUnderTest.isIndeterminate());
+        verify(mMockDrawable).start();
+    }
+
+    @Test
+    public void testIsIndeterminateAfterSetToFalse() {
+        mControllerUnderTest.setIndeterminate(true);
+        mControllerUnderTest.setIndeterminate(false);
+
+        assertEquals(false, mControllerUnderTest.isIndeterminate());
+        verify(mMockDrawable).stop();
+    }
+
+    @Test
+    @UiThreadTest
+    public void testIsTimerRunningAfterStart() {
+        mControllerUnderTest.startTimer(TOTAL_TIME, UPDATE_INTERVAL);
+
+        assertEquals(true, mControllerUnderTest.isTimerRunning());
+    }
+
+    @Test
+    @UiThreadTest
+    public void testIsTimerRunningAfterStop() {
+        mControllerUnderTest.startTimer(TOTAL_TIME, UPDATE_INTERVAL);
+        mControllerUnderTest.stopTimer();
+
+        assertEquals(false, mControllerUnderTest.isTimerRunning());
+    }
+
+    @Test
+    @UiThreadTest
+    public void testSwitchFromIndeterminateToDeterminate() {
+        mControllerUnderTest.setIndeterminate(true);
+        mControllerUnderTest.startTimer(TOTAL_TIME, UPDATE_INTERVAL);
+
+        assertEquals(false, mControllerUnderTest.isIndeterminate());
+        assertEquals(true, mControllerUnderTest.isTimerRunning());
+        verify(mMockDrawable).stop();
+    }
+
+    @Test
+    @UiThreadTest
+    public void testSwitchFromDeterminateToIndeterminate() {
+        mControllerUnderTest.startTimer(TOTAL_TIME, UPDATE_INTERVAL);
+        mControllerUnderTest.setIndeterminate(true);
+
+        assertEquals(true, mControllerUnderTest.isIndeterminate());
+        assertEquals(false, mControllerUnderTest.isTimerRunning());
+        verify(mMockDrawable).start();
+    }
+}
diff --git a/wear/tests/src/android/support/wear/widget/CircularProgressLayoutTest.java b/wear/tests/src/android/support/wear/widget/CircularProgressLayoutTest.java
new file mode 100644
index 0000000..ff98c30
--- /dev/null
+++ b/wear/tests/src/android/support/wear/widget/CircularProgressLayoutTest.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Intent;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.wear.test.R;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.TimeUnit;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class CircularProgressLayoutTest {
+
+    private static final long TOTAL_TIME = TimeUnit.SECONDS.toMillis(1);
+
+    @Rule
+    public final ActivityTestRule<LayoutTestActivity> mActivityRule = new ActivityTestRule<>(
+            LayoutTestActivity.class, true, false);
+    private CircularProgressLayout mLayoutUnderTest;
+
+    @Before
+    public void setUp() {
+        mActivityRule.launchActivity(new Intent().putExtra(LayoutTestActivity
+                .EXTRA_LAYOUT_RESOURCE_ID, R.layout.circular_progress_layout));
+        mLayoutUnderTest = mActivityRule.getActivity().findViewById(R.id.circular_progress_layout);
+        mLayoutUnderTest.setOnTimerFinishedListener(new FakeListener());
+    }
+
+    @Test
+    public void testListenerIsNotified() {
+        mLayoutUnderTest.setTotalTime(TOTAL_TIME);
+        startTimerOnUiThread();
+        waitForTimer(TOTAL_TIME + 100);
+        assertNotNull(mLayoutUnderTest.getOnTimerFinishedListener());
+        assertTrue(((FakeListener) mLayoutUnderTest.getOnTimerFinishedListener()).mFinished);
+    }
+
+    @Test
+    public void testListenerIsNotNotifiedWhenStopped() {
+        mLayoutUnderTest.setTotalTime(TOTAL_TIME);
+        startTimerOnUiThread();
+        stopTimerOnUiThread();
+        waitForTimer(TOTAL_TIME + 100);
+        assertNotNull(mLayoutUnderTest.getOnTimerFinishedListener());
+        assertFalse(((FakeListener) mLayoutUnderTest.getOnTimerFinishedListener()).mFinished);
+    }
+
+    private class FakeListener implements CircularProgressLayout.OnTimerFinishedListener {
+
+        boolean mFinished;
+
+        @Override
+        public void onTimerFinished(CircularProgressLayout layout) {
+            mFinished = true;
+        }
+    }
+
+    private void startTimerOnUiThread() {
+        mActivityRule.getActivity().runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mLayoutUnderTest.startTimer();
+            }
+        });
+    }
+
+    private void stopTimerOnUiThread() {
+        mActivityRule.getActivity().runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                mLayoutUnderTest.stopTimer();
+            }
+        });
+    }
+
+    private void waitForTimer(long time) {
+        try {
+            Thread.sleep(time);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+}
diff --git a/wear/tests/src/android/support/wear/widget/RoundedDrawableTest.java b/wear/tests/src/android/support/wear/widget/RoundedDrawableTest.java
new file mode 100644
index 0000000..dbe575f
--- /dev/null
+++ b/wear/tests/src/android/support/wear/widget/RoundedDrawableTest.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2017 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 android.support.wear.widget;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.ColorFilter;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.drawable.BitmapDrawable;
+import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+
+/** Tests for {@link RoundedDrawable} */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class RoundedDrawableTest {
+
+    @Rule
+    public final ActivityTestRule<LayoutTestActivity> mActivityRule = new ActivityTestRule<>(
+            LayoutTestActivity.class, true, false);
+    private static final int BITMAP_WIDTH = 64;
+    private static final int BITMAP_HEIGHT = 32;
+
+    private RoundedDrawable mRoundedDrawable;
+    private BitmapDrawable mBitmapDrawable;
+
+    @Mock
+    Canvas mMockCanvas;
+
+    @Before
+    public void setUp() {
+        mMockCanvas = mock(Canvas.class);
+        mActivityRule.launchActivity(new Intent().putExtra(LayoutTestActivity
+                        .EXTRA_LAYOUT_RESOURCE_ID,
+                android.support.wear.test.R.layout.rounded_drawable_layout));
+        mRoundedDrawable = new RoundedDrawable();
+        mBitmapDrawable =
+                new BitmapDrawable(
+                        mActivityRule.getActivity().getResources(),
+                        Bitmap.createBitmap(BITMAP_WIDTH, BITMAP_HEIGHT, Bitmap.Config.ARGB_8888));
+    }
+
+    @Test
+    public void colorFilterIsAppliedCorrectly() {
+        ColorFilter cf = new ColorFilter();
+        mRoundedDrawable.setColorFilter(cf);
+        assertEquals(cf, mRoundedDrawable.mPaint.getColorFilter());
+    }
+
+    @Test
+    public void alphaIsAppliedCorrectly() {
+        int alpha = 128;
+        mRoundedDrawable.setAlpha(alpha);
+        assertEquals(alpha, mRoundedDrawable.mPaint.getAlpha());
+    }
+
+    @Test
+    public void radiusIsAppliedCorrectly() {
+        int radius = 10;
+        Rect bounds = new Rect(0, 0, BITMAP_WIDTH, BITMAP_HEIGHT);
+        mRoundedDrawable.setDrawable(mBitmapDrawable);
+        mRoundedDrawable.setClipEnabled(true);
+        mRoundedDrawable.setRadius(radius);
+        mRoundedDrawable.setBounds(bounds);
+        mRoundedDrawable.draw(mMockCanvas);
+        // One for background and one for the actual drawable, this should be called two times.
+        verify(mMockCanvas, times(2))
+                .drawRoundRect(
+                        eq(new RectF(0, 0, bounds.width(), bounds.height())),
+                        eq((float) radius),
+                        eq((float) radius),
+                        any(Paint.class));
+    }
+
+    @Test
+    public void scalingIsAppliedCorrectly() {
+        int radius = 14;
+        // 14 px radius should apply 5 px padding due to formula ceil(radius * 1 - 1 / sqrt(2))
+        Rect bounds = new Rect(0, 0, BITMAP_WIDTH, BITMAP_HEIGHT);
+        mRoundedDrawable.setDrawable(mBitmapDrawable);
+        mRoundedDrawable.setClipEnabled(false);
+        mRoundedDrawable.setRadius(radius);
+        mRoundedDrawable.setBounds(bounds);
+        mRoundedDrawable.draw(mMockCanvas);
+        assertEquals(BITMAP_WIDTH - 10, mBitmapDrawable.getBounds().width());
+        assertEquals(BITMAP_HEIGHT - 10, mBitmapDrawable.getBounds().height());
+        assertEquals(bounds.centerX(), mBitmapDrawable.getBounds().centerX());
+        assertEquals(bounds.centerY(), mBitmapDrawable.getBounds().centerY());
+        // Background should also be drawn
+        verify(mMockCanvas)
+                .drawRoundRect(
+                        eq(new RectF(0, 0, bounds.width(), bounds.height())),
+                        eq((float) radius),
+                        eq((float) radius),
+                        any(Paint.class));
+    }
+}
diff --git a/wear/tests/src/android/support/wear/widget/drawer/WearableDrawerLayoutEspressoTest.java b/wear/tests/src/android/support/wear/widget/drawer/WearableDrawerLayoutEspressoTest.java
index 88c89c7..07eaa87 100644
--- a/wear/tests/src/android/support/wear/widget/drawer/WearableDrawerLayoutEspressoTest.java
+++ b/wear/tests/src/android/support/wear/widget/drawer/WearableDrawerLayoutEspressoTest.java
@@ -136,7 +136,7 @@
                                 MAX_WAIT_MS));
 
         // THEN the text should display "0".
-        onView(withId(R.id.wearable_support_nav_drawer_text)).check(matches(withText("0")));
+        onView(withId(R.id.ws_nav_drawer_text)).check(matches(withText("0")));
     }
 
     @Test
@@ -151,13 +151,13 @@
                                 MAX_WAIT_MS));
 
         // WHEN the second item is selected
-        onView(withId(R.id.wearable_support_nav_drawer_icon_1)).perform(click());
+        onView(withId(R.id.ws_nav_drawer_icon_1)).perform(click());
 
         // THEN the text should display "1" and it should close.
-        onView(withId(R.id.wearable_support_nav_drawer_text))
+        onView(withId(R.id.ws_nav_drawer_text))
                 .perform(
                         waitForMatchingView(
-                                allOf(withId(R.id.wearable_support_nav_drawer_text), withText("1")),
+                                allOf(withId(R.id.ws_nav_drawer_text), withText("1")),
                                 MAX_WAIT_MS));
         onView(withId(R.id.navigation_drawer))
                 .perform(
@@ -181,7 +181,7 @@
         selectNavItem(navDrawer, 1);
 
         // THEN the text should display "1" and the listener should be notified.
-        onView(withId(R.id.wearable_support_nav_drawer_text))
+        onView(withId(R.id.ws_nav_drawer_text))
                 .check(matches(withText("1")));
         verify(mNavDrawerItemSelectedListener).onItemSelected(1);
     }
@@ -201,7 +201,7 @@
         selectNavItem(navDrawer, 1);
 
         // THEN the text should display "1" and the listener should be notified.
-        onView(allOf(withId(R.id.wearable_support_navigation_drawer_item_text), isDisplayed()))
+        onView(allOf(withId(R.id.ws_navigation_drawer_item_text), isDisplayed()))
                 .check(matches(withText("1")));
         verify(mNavDrawerItemSelectedListener).onItemSelected(1);
     }
@@ -319,7 +319,7 @@
         DrawerTestActivity activity = activityRule.getActivity();
         ImageView peekIconView =
                 (ImageView) activity
-                        .findViewById(R.id.wearable_support_action_drawer_peek_action_icon);
+                        .findViewById(R.id.ws_action_drawer_peek_action_icon);
         // THEN its peek icon should not be null
         assertNotNull(peekIconView.getDrawable());
     }
@@ -340,7 +340,7 @@
         onView(
                 allOf(
                         withParent(withId(R.id.action_drawer)),
-                        withId(R.id.wearable_support_drawer_view_peek_container)))
+                        withId(R.id.ws_drawer_view_peek_container)))
                 .perform(click());
         // THEN its click listener should be notified
         verify(mockClickListener).onMenuItemClick(any(MenuItem.class));