Merge "Grant access to ephemeral metadata"
diff --git a/api/current.txt b/api/current.txt
index 21ff81e..b3090cd 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -1378,7 +1378,7 @@
     field public static final int toYDelta = 16843209; // 0x10101c9
     field public static final int toYScale = 16843205; // 0x10101c5
     field public static final int toolbarStyle = 16843946; // 0x10104aa
-    field public static final int tooltip = 16844084; // 0x1010534
+    field public static final int tooltipText = 16844084; // 0x1010534
     field public static final int top = 16843182; // 0x10101ae
     field public static final int topBright = 16842955; // 0x10100cb
     field public static final int topDark = 16842951; // 0x10100c7
@@ -4837,11 +4837,13 @@
   public static class Instrumentation.ActivityMonitor {
     ctor public Instrumentation.ActivityMonitor(android.content.IntentFilter, android.app.Instrumentation.ActivityResult, boolean);
     ctor public Instrumentation.ActivityMonitor(java.lang.String, android.app.Instrumentation.ActivityResult, boolean);
+    ctor public Instrumentation.ActivityMonitor();
     method public final android.content.IntentFilter getFilter();
     method public final int getHits();
     method public final android.app.Activity getLastActivity();
     method public final android.app.Instrumentation.ActivityResult getResult();
     method public final boolean isBlocking();
+    method public android.app.Instrumentation.ActivityResult onMatchIntent(android.content.Intent);
     method public final android.app.Activity waitForActivity();
     method public final android.app.Activity waitForActivityWithTimeout(long);
   }
@@ -42905,7 +42907,7 @@
     method public abstract android.view.SubMenu getSubMenu();
     method public abstract java.lang.CharSequence getTitle();
     method public abstract java.lang.CharSequence getTitleCondensed();
-    method public default java.lang.CharSequence getTooltip();
+    method public default java.lang.CharSequence getTooltipText();
     method public abstract boolean hasSubMenu();
     method public abstract boolean isActionViewExpanded();
     method public abstract boolean isCheckable();
@@ -42932,7 +42934,7 @@
     method public abstract android.view.MenuItem setTitle(java.lang.CharSequence);
     method public abstract android.view.MenuItem setTitle(int);
     method public abstract android.view.MenuItem setTitleCondensed(java.lang.CharSequence);
-    method public default android.view.MenuItem setTooltip(java.lang.CharSequence);
+    method public default android.view.MenuItem setTooltipText(java.lang.CharSequence);
     method public abstract android.view.MenuItem setVisible(boolean);
     field public static final int SHOW_AS_ACTION_ALWAYS = 2; // 0x2
     field public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = 8; // 0x8
@@ -43626,7 +43628,8 @@
     method public java.lang.Object getTag(int);
     method public int getTextAlignment();
     method public int getTextDirection();
-    method public final java.lang.CharSequence getTooltip();
+    method public final deprecated java.lang.CharSequence getTooltip();
+    method public final java.lang.CharSequence getTooltipText();
     method public final int getTop();
     method protected float getTopFadingEdgeStrength();
     method protected int getTopPaddingOffset();
@@ -43927,7 +43930,8 @@
     method public void setTag(int, java.lang.Object);
     method public void setTextAlignment(int);
     method public void setTextDirection(int);
-    method public final void setTooltip(java.lang.CharSequence);
+    method public final deprecated void setTooltip(java.lang.CharSequence);
+    method public final void setTooltipText(java.lang.CharSequence);
     method public final void setTop(int);
     method public void setTouchDelegate(android.view.TouchDelegate);
     method public final void setTransitionName(java.lang.String);
diff --git a/api/system-current.txt b/api/system-current.txt
index 1f590dd..3bc7be5 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -1491,7 +1491,7 @@
     field public static final int toYDelta = 16843209; // 0x10101c9
     field public static final int toYScale = 16843205; // 0x10101c5
     field public static final int toolbarStyle = 16843946; // 0x10104aa
-    field public static final int tooltip = 16844084; // 0x1010534
+    field public static final int tooltipText = 16844084; // 0x1010534
     field public static final int top = 16843182; // 0x10101ae
     field public static final int topBright = 16842955; // 0x10100cb
     field public static final int topDark = 16842951; // 0x10100c7
@@ -4994,11 +4994,13 @@
   public static class Instrumentation.ActivityMonitor {
     ctor public Instrumentation.ActivityMonitor(android.content.IntentFilter, android.app.Instrumentation.ActivityResult, boolean);
     ctor public Instrumentation.ActivityMonitor(java.lang.String, android.app.Instrumentation.ActivityResult, boolean);
+    ctor public Instrumentation.ActivityMonitor();
     method public final android.content.IntentFilter getFilter();
     method public final int getHits();
     method public final android.app.Activity getLastActivity();
     method public final android.app.Instrumentation.ActivityResult getResult();
     method public final boolean isBlocking();
+    method public android.app.Instrumentation.ActivityResult onMatchIntent(android.content.Intent);
     method public final android.app.Activity waitForActivity();
     method public final android.app.Activity waitForActivityWithTimeout(long);
   }
@@ -6747,6 +6749,7 @@
     method public boolean isBackupEnabled();
     method public java.lang.String[] listAllTransports();
     method public int requestBackup(java.lang.String[], android.app.backup.BackupObserver);
+    method public int requestBackup(java.lang.String[], android.app.backup.BackupObserver, int);
     method public int requestRestore(android.app.backup.RestoreObserver);
     method public java.lang.String selectBackupTransport(java.lang.String);
     method public void setAutoRestore(boolean);
@@ -6757,6 +6760,8 @@
     field public static final int ERROR_TRANSPORT_ABORTED = -1000; // 0xfffffc18
     field public static final int ERROR_TRANSPORT_PACKAGE_REJECTED = -1002; // 0xfffffc16
     field public static final int ERROR_TRANSPORT_QUOTA_EXCEEDED = -1005; // 0xfffffc13
+    field public static final int FLAG_NON_INCREMENTAL_BACKUP = 1; // 0x1
+    field public static final java.lang.String PACKAGE_MANAGER_SENTINEL = "@pm@";
     field public static final int SUCCESS = 0; // 0x0
   }
 
@@ -46165,7 +46170,7 @@
     method public abstract android.view.SubMenu getSubMenu();
     method public abstract java.lang.CharSequence getTitle();
     method public abstract java.lang.CharSequence getTitleCondensed();
-    method public default java.lang.CharSequence getTooltip();
+    method public default java.lang.CharSequence getTooltipText();
     method public abstract boolean hasSubMenu();
     method public abstract boolean isActionViewExpanded();
     method public abstract boolean isCheckable();
@@ -46192,7 +46197,7 @@
     method public abstract android.view.MenuItem setTitle(java.lang.CharSequence);
     method public abstract android.view.MenuItem setTitle(int);
     method public abstract android.view.MenuItem setTitleCondensed(java.lang.CharSequence);
-    method public default android.view.MenuItem setTooltip(java.lang.CharSequence);
+    method public default android.view.MenuItem setTooltipText(java.lang.CharSequence);
     method public abstract android.view.MenuItem setVisible(boolean);
     field public static final int SHOW_AS_ACTION_ALWAYS = 2; // 0x2
     field public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = 8; // 0x8
@@ -46886,7 +46891,8 @@
     method public java.lang.Object getTag(int);
     method public int getTextAlignment();
     method public int getTextDirection();
-    method public final java.lang.CharSequence getTooltip();
+    method public final deprecated java.lang.CharSequence getTooltip();
+    method public final java.lang.CharSequence getTooltipText();
     method public final int getTop();
     method protected float getTopFadingEdgeStrength();
     method protected int getTopPaddingOffset();
@@ -47187,7 +47193,8 @@
     method public void setTag(int, java.lang.Object);
     method public void setTextAlignment(int);
     method public void setTextDirection(int);
-    method public final void setTooltip(java.lang.CharSequence);
+    method public final deprecated void setTooltip(java.lang.CharSequence);
+    method public final void setTooltipText(java.lang.CharSequence);
     method public final void setTop(int);
     method public void setTouchDelegate(android.view.TouchDelegate);
     method public final void setTransitionName(java.lang.String);
diff --git a/api/test-current.txt b/api/test-current.txt
index f4e71e3..22c5581 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -1378,7 +1378,7 @@
     field public static final int toYDelta = 16843209; // 0x10101c9
     field public static final int toYScale = 16843205; // 0x10101c5
     field public static final int toolbarStyle = 16843946; // 0x10104aa
-    field public static final int tooltip = 16844084; // 0x1010534
+    field public static final int tooltipText = 16844084; // 0x1010534
     field public static final int top = 16843182; // 0x10101ae
     field public static final int topBright = 16842955; // 0x10100cb
     field public static final int topDark = 16842951; // 0x10100c7
@@ -4847,11 +4847,13 @@
   public static class Instrumentation.ActivityMonitor {
     ctor public Instrumentation.ActivityMonitor(android.content.IntentFilter, android.app.Instrumentation.ActivityResult, boolean);
     ctor public Instrumentation.ActivityMonitor(java.lang.String, android.app.Instrumentation.ActivityResult, boolean);
+    ctor public Instrumentation.ActivityMonitor();
     method public final android.content.IntentFilter getFilter();
     method public final int getHits();
     method public final android.app.Activity getLastActivity();
     method public final android.app.Instrumentation.ActivityResult getResult();
     method public final boolean isBlocking();
+    method public android.app.Instrumentation.ActivityResult onMatchIntent(android.content.Intent);
     method public final android.app.Activity waitForActivity();
     method public final android.app.Activity waitForActivityWithTimeout(long);
   }
@@ -43194,7 +43196,7 @@
     method public abstract android.view.SubMenu getSubMenu();
     method public abstract java.lang.CharSequence getTitle();
     method public abstract java.lang.CharSequence getTitleCondensed();
-    method public default java.lang.CharSequence getTooltip();
+    method public default java.lang.CharSequence getTooltipText();
     method public abstract boolean hasSubMenu();
     method public abstract boolean isActionViewExpanded();
     method public abstract boolean isCheckable();
@@ -43221,7 +43223,7 @@
     method public abstract android.view.MenuItem setTitle(java.lang.CharSequence);
     method public abstract android.view.MenuItem setTitle(int);
     method public abstract android.view.MenuItem setTitleCondensed(java.lang.CharSequence);
-    method public default android.view.MenuItem setTooltip(java.lang.CharSequence);
+    method public default android.view.MenuItem setTooltipText(java.lang.CharSequence);
     method public abstract android.view.MenuItem setVisible(boolean);
     field public static final int SHOW_AS_ACTION_ALWAYS = 2; // 0x2
     field public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = 8; // 0x8
@@ -43917,7 +43919,8 @@
     method public java.lang.Object getTag(int);
     method public int getTextAlignment();
     method public int getTextDirection();
-    method public final java.lang.CharSequence getTooltip();
+    method public final deprecated java.lang.CharSequence getTooltip();
+    method public final java.lang.CharSequence getTooltipText();
     method public android.view.View getTooltipView();
     method public final int getTop();
     method protected float getTopFadingEdgeStrength();
@@ -44219,7 +44222,8 @@
     method public void setTag(int, java.lang.Object);
     method public void setTextAlignment(int);
     method public void setTextDirection(int);
-    method public final void setTooltip(java.lang.CharSequence);
+    method public final deprecated void setTooltip(java.lang.CharSequence);
+    method public final void setTooltipText(java.lang.CharSequence);
     method public final void setTop(int);
     method public void setTouchDelegate(android.view.TouchDelegate);
     method public final void setTransitionName(java.lang.String);
diff --git a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
index 5bf8076..780db5e 100644
--- a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
+++ b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
@@ -270,7 +270,7 @@
         }
     }
 
-    private void backupNowAllPackages() {
+    private void backupNowAllPackages(boolean nonIncrementalBackup) {
         int userId = UserHandle.USER_SYSTEM;
         IPackageManager mPm =
                 IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
@@ -297,14 +297,19 @@
                     System.err.println(BMGR_NOT_RUNNING_ERR);
                 }
             }
-            backupNowPackages(packages);
+            backupNowPackages(packages, nonIncrementalBackup);
         }
     }
 
-    private void backupNowPackages(List<String> packages) {
+    private void backupNowPackages(List<String> packages, boolean nonIncrementalBackup) {
+        int flags = 0;
+        if (nonIncrementalBackup) {
+            flags |= BackupManager.FLAG_NON_INCREMENTAL_BACKUP;
+        }
         try {
             BackupObserver observer = new BackupObserver();
-            int err = mBmgr.requestBackup(packages.toArray(new String[packages.size()]), observer);
+            int err = mBmgr.requestBackup(packages.toArray(new String[packages.size()]), observer,
+                    flags);
             if (err == 0) {
                 // Off and running -- wait for the backup to complete
                 observer.waitForCompletion();
@@ -320,24 +325,31 @@
     private void doBackupNow() {
         String pkg;
         boolean backupAll = false;
+        boolean nonIncrementalBackup = false;
         ArrayList<String> allPkgs = new ArrayList<String>();
         while ((pkg = nextArg()) != null) {
             if (pkg.equals("--all")) {
                 backupAll = true;
+            } else if (pkg.equals("--non-incremental")) {
+                nonIncrementalBackup = true;
+            } else if (pkg.equals("--incremental")) {
+                nonIncrementalBackup = false;
             } else {
                 allPkgs.add(pkg);
             }
         }
         if (backupAll) {
             if (allPkgs.size() == 0) {
-                System.out.println("Running backup for all packages.");
-                backupNowAllPackages();
+                System.out.println("Running " + (nonIncrementalBackup ? "non-" : "") +
+                        "incremental backup for all packages.");
+                backupNowAllPackages(nonIncrementalBackup);
             } else {
                 System.err.println("Provide only '--all' flag or list of packages.");
             }
         } else if (allPkgs.size() > 0) {
-            System.out.println("Running backup for " + allPkgs.size() +" requested packages.");
-            backupNowPackages(allPkgs);
+            System.out.println("Running " + (nonIncrementalBackup ? "non-" : "") +
+                    "incremental backup for " + allPkgs.size() +" requested packages.");
+            backupNowPackages(allPkgs, nonIncrementalBackup);
         } else {
             System.err.println("Provide '--all' flag or list of packages.");
         }
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index f3185a8..20f7e63 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -24,6 +24,7 @@
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.ContentResolver;
+import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.IntentSender;
@@ -1386,7 +1387,7 @@
         }
     }
 
-    ApplicationPackageManager(ContextImpl context,
+    protected ApplicationPackageManager(ContextImpl context,
                               IPackageManager pm) {
         mContext = context;
         mPM = pm;
@@ -1820,6 +1821,12 @@
     @Override
     public @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app) {
         final StorageManager storage = mContext.getSystemService(StorageManager.class);
+        return getPackageCurrentVolume(app, storage);
+    }
+
+    @VisibleForTesting
+    protected @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app,
+            StorageManager storage) {
         if (app.isInternal()) {
             return storage.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
         } else if (app.isExternalAsec()) {
@@ -1831,25 +1838,43 @@
 
     @Override
     public @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app) {
-        final StorageManager storage = mContext.getSystemService(StorageManager.class);
-        final VolumeInfo currentVol = getPackageCurrentVolume(app);
-        final List<VolumeInfo> vols = storage.getVolumes();
+        final StorageManager storageManager = mContext.getSystemService(StorageManager.class);
+        return getPackageCandidateVolumes(app, storageManager, mPM);
+    }
+
+    @VisibleForTesting
+    protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
+            StorageManager storageManager, IPackageManager pm) {
+        final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
+        final List<VolumeInfo> vols = storageManager.getVolumes();
         final List<VolumeInfo> candidates = new ArrayList<>();
         for (VolumeInfo vol : vols) {
-            if (Objects.equals(vol, currentVol) || isPackageCandidateVolume(mContext, app, vol)) {
+            if (Objects.equals(vol, currentVol)
+                    || isPackageCandidateVolume(mContext, app, vol, pm)) {
                 candidates.add(vol);
             }
         }
         return candidates;
     }
 
-    private boolean isPackageCandidateVolume(
-            ContextImpl context, ApplicationInfo app, VolumeInfo vol) {
-        final boolean forceAllowOnExternal = Settings.Global.getInt(
+    @VisibleForTesting
+    protected boolean isForceAllowOnExternal(Context context) {
+        return Settings.Global.getInt(
                 context.getContentResolver(), Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0;
-        // Private internal is always an option
+    }
+
+    @VisibleForTesting
+    protected boolean isAllow3rdPartyOnInternal(Context context) {
+        return context.getResources().getBoolean(
+                com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
+    }
+
+    private boolean isPackageCandidateVolume(
+            ContextImpl context, ApplicationInfo app, VolumeInfo vol, IPackageManager pm) {
+        final boolean forceAllowOnExternal = isForceAllowOnExternal(context);
+
         if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
-            return true;
+            return app.isSystemApp() || isAllow3rdPartyOnInternal(context);
         }
 
         // System apps and apps demanding internal storage can't be moved
@@ -1875,7 +1900,7 @@
 
         // Some apps can't be moved. (e.g. device admins)
         try {
-            if (mPM.isPackageDeviceAdminOnAnyUser(app.packageName)) {
+            if (pm.isPackageDeviceAdminOnAnyUser(app.packageName)) {
                 return false;
             }
         } catch (RemoteException e) {
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index cc7981c..b1bdea1 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -443,6 +443,7 @@
         private final String mClass;
         private final ActivityResult mResult;
         private final boolean mBlock;
+        private final boolean mIgnoreMatchingSpecificIntents;
 
 
         // This is protected by 'Instrumentation.this.mSync'.
@@ -454,7 +455,7 @@
         /**
          * Create a new ActivityMonitor that looks for a particular kind of 
          * intent to be started.
-         *  
+         *
          * @param which The set of intents this monitor is responsible for.
          * @param result A canned result to return if the monitor is hit; can 
          *               be null.
@@ -470,6 +471,7 @@
             mClass = null;
             mResult = result;
             mBlock = block;
+            mIgnoreMatchingSpecificIntents = false;
         }
 
         /**
@@ -491,6 +493,34 @@
             mClass = cls;
             mResult = result;
             mBlock = block;
+            mIgnoreMatchingSpecificIntents = false;
+        }
+
+        /**
+         * Create a new ActivityMonitor that can be used for intercepting any activity to be
+         * started.
+         *
+         * <p> When an activity is started, {@link #onMatchIntent(Intent)} will be called on
+         * instances created using this constructor to see if it is a hit.
+         *
+         * @see #onMatchIntent(Intent)
+         */
+        public ActivityMonitor() {
+            mWhich = null;
+            mClass = null;
+            mResult = null;
+            mBlock = false;
+            mIgnoreMatchingSpecificIntents = true;
+        }
+
+        /**
+         * @return true if this monitor is used for intercepting any started activity by calling
+         *         into {@link #onMatchIntent(Intent)}, false if this monitor is only used
+         *         for specific intents corresponding to the intent filter or activity class
+         *         passed in the constructor.
+         */
+        final boolean ignoreMatchingSpecificIntents() {
+            return mIgnoreMatchingSpecificIntents;
         }
 
         /**
@@ -577,10 +607,31 @@
                 }
             }
         }
-        
+
+        /**
+         * Used for intercepting any started activity.
+         *
+         * <p> A non-null return value here will be considered a hit for this monitor.
+         * By default this will return {@code null} and subclasses can override this to return
+         * a non-null value if the intent needs to be intercepted.
+         *
+         * <p> Whenever a new activity is started, this method will be called on instances created
+         * using {@link #Instrumentation.ActivityMonitor()} to check if there is a match. In case
+         * of a match, the activity start will be blocked and the returned result will be used.
+         *
+         * @param intent The intent used for starting the activity.
+         * @return The {@link ActivityResult} that needs to be used in case of a match.
+         */
+        public ActivityResult onMatchIntent(Intent intent) {
+            return null;
+        }
+
         final boolean match(Context who,
                             Activity activity,
                             Intent intent) {
+            if (mIgnoreMatchingSpecificIntents) {
+                return false;
+            }
             synchronized (this) {
                 if (mWhich != null
                     && mWhich.match(who.getContentResolver(), intent,
@@ -1492,7 +1543,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intent)) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intent);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return result;
+                    } else if (am.match(who, null, intent)) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return requestCode >= 0 ? am.getResult() : null;
@@ -1548,7 +1606,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intents[0])) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intents[0]);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return;
+                    } else if (am.match(who, null, intents[0])) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return;
@@ -1611,7 +1676,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intent)) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intent);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return result;
+                    } else if (am.match(who, null, intent)) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return requestCode >= 0 ? am.getResult() : null;
@@ -1671,7 +1743,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intent)) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intent);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return result;
+                    } else if (am.match(who, null, intent)) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return requestCode >= 0 ? am.getResult() : null;
@@ -1710,7 +1789,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intent)) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intent);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return result;
+                    } else if (am.match(who, null, intent)) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return requestCode >= 0 ? am.getResult() : null;
@@ -1748,7 +1834,14 @@
                 final int N = mActivityMonitors.size();
                 for (int i=0; i<N; i++) {
                     final ActivityMonitor am = mActivityMonitors.get(i);
-                    if (am.match(who, null, intent)) {
+                    ActivityResult result = null;
+                    if (am.ignoreMatchingSpecificIntents()) {
+                        result = am.onMatchIntent(intent);
+                    }
+                    if (result != null) {
+                        am.mHits++;
+                        return;
+                    } else if (am.match(who, null, intent)) {
                         am.mHits++;
                         if (am.isBlocking()) {
                             return;
diff --git a/core/java/android/app/MediaRouteButton.java b/core/java/android/app/MediaRouteButton.java
index 09e95df..d2d7b6d 100644
--- a/core/java/android/app/MediaRouteButton.java
+++ b/core/java/android/app/MediaRouteButton.java
@@ -174,7 +174,7 @@
     @Override
     public void setContentDescription(CharSequence contentDescription) {
         super.setContentDescription(contentDescription);
-        setTooltip(contentDescription);
+        setTooltipText(contentDescription);
     }
 
     @Override
diff --git a/core/java/android/app/backup/BackupManager.java b/core/java/android/app/backup/BackupManager.java
index 80bc136..540683d 100644
--- a/core/java/android/app/backup/BackupManager.java
+++ b/core/java/android/app/backup/BackupManager.java
@@ -136,6 +136,27 @@
      */
     public static final String EXTRA_BACKUP_SERVICES_AVAILABLE = "backup_services_available";
 
+    /**
+     * If this flag is passed to {@link #requestBackup(String[], BackupObserver, int)},
+     * BackupManager will pass a blank old state to BackupAgents of requested packages.
+     *
+     * @hide
+     */
+    @SystemApi
+    public static final int FLAG_NON_INCREMENTAL_BACKUP = 1;
+
+    /**
+     * Use with {@link #requestBackup} to force backup of
+     * package meta data. Typically you do not need to explicitly request this be backed up as it is
+     * handled internally by the BackupManager. If you are requesting backups with
+     * FLAG_NON_INCREMENTAL, this package won't automatically be backed up and you have to
+     * explicitly request for its backup.
+     *
+     * @hide
+     */
+    @SystemApi
+    public static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
+
     private Context mContext;
     private static IBackupManager sService;
 
@@ -484,13 +505,34 @@
      */
     @SystemApi
     public int requestBackup(String[] packages, BackupObserver observer) {
+        return requestBackup(packages, observer, 0);
+    }
+
+    /**
+     * Request an immediate backup, providing an observer to which results of the backup operation
+     * will be published. The Android backup system will decide for each package whether it will
+     * be full app data backup or key/value-pair-based backup.
+     *
+     * <p>If this method returns {@link BackupManager#SUCCESS}, the OS will attempt to backup all
+     * provided packages using the remote transport.
+     *
+     * @param packages List of package names to backup.
+     * @param observer The {@link BackupObserver} to receive callbacks during the backup
+     *                 operation. Could be {@code null}.
+     * @param flags    {@link #FLAG_NON_INCREMENTAL_BACKUP}.
+     * @return {@link BackupManager#SUCCESS} on success; nonzero on error.
+     * @throws IllegalArgumentException on null or empty {@code packages} param.
+     * @hide
+     */
+    @SystemApi
+    public int requestBackup(String[] packages, BackupObserver observer, int flags) {
         checkServiceBinder();
         if (sService != null) {
             try {
                 BackupObserverWrapper observerWrapper = observer == null
                         ? null
                         : new BackupObserverWrapper(mContext, observer);
-                return sService.requestBackup(packages, observerWrapper);
+                return sService.requestBackup(packages, observerWrapper, flags);
             } catch (RemoteException e) {
                 Log.e(TAG, "requestBackup() couldn't connect");
             }
diff --git a/core/java/android/app/backup/IBackupManager.aidl b/core/java/android/app/backup/IBackupManager.aidl
index a320bbf..fe23c28 100644
--- a/core/java/android/app/backup/IBackupManager.aidl
+++ b/core/java/android/app/backup/IBackupManager.aidl
@@ -357,7 +357,9 @@
      * @param observer The {@link BackupObserver} to receive callbacks during the backup
      * operation.
      *
+     * @param flags {@link BackupManager#FLAG_NON_INCREMENTAL_BACKUP}.
+     *
      * @return Zero on success; nonzero on error.
      */
-    int requestBackup(in String[] packages, IBackupObserver observer);
+    int requestBackup(in String[] packages, IBackupObserver observer, int flags);
 }
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 04e649c..c3fe182 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1360,6 +1360,14 @@
     public static final int MOVE_FAILED_DEVICE_ADMIN = -8;
 
     /**
+     * Error code that is passed to the {@link IPackageMoveObserver} if system does not allow
+     * non-system apps to be moved to internal storage.
+     *
+     * @hide
+     */
+    public static final int MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL = -9;
+
+    /**
      * Flag parameter for {@link #movePackage} to indicate that
      * the package should be moved to internal storage if its
      * been installed on external media.
diff --git a/core/java/android/view/MenuInflater.java b/core/java/android/view/MenuInflater.java
index f3f3d40..7a5c65f 100644
--- a/core/java/android/view/MenuInflater.java
+++ b/core/java/android/view/MenuInflater.java
@@ -335,7 +335,7 @@
         private ActionProvider itemActionProvider;
 
         private CharSequence itemContentDescription;
-        private CharSequence itemTooltip;
+        private CharSequence itemTooltipText;
 
         private static final int defaultGroupId = NO_ID;
         private static final int defaultItemId = NO_ID;
@@ -429,7 +429,7 @@
 
             itemContentDescription =
                     a.getText(com.android.internal.R.styleable.MenuItem_contentDescription);
-            itemTooltip = a.getText(com.android.internal.R.styleable.MenuItem_tooltip);
+            itemTooltipText = a.getText(com.android.internal.R.styleable.MenuItem_tooltipText);
 
             a.recycle();
 
@@ -495,7 +495,7 @@
             }
 
             item.setContentDescription(itemContentDescription);
-            item.setTooltip(itemTooltip);
+            item.setTooltipText(itemTooltipText);
         }
 
         public MenuItem addItem() {
diff --git a/core/java/android/view/MenuItem.java b/core/java/android/view/MenuItem.java
index 5ced765..3f8d089 100644
--- a/core/java/android/view/MenuItem.java
+++ b/core/java/android/view/MenuItem.java
@@ -621,9 +621,9 @@
     /**
      * Change the tooltip text associated with this menu item.
      *
-     * @param tooltip The new tooltip text.
+     * @param tooltipText The new tooltip text.
      */
-    default MenuItem setTooltip(CharSequence tooltip) {
+    default MenuItem setTooltipText(CharSequence tooltipText) {
         return this;
     }
 
@@ -632,7 +632,7 @@
      *
      * @return The tooltip text.
      */
-    default CharSequence getTooltip() {
+    default CharSequence getTooltipText() {
         return null;
     }
 }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 37dfdb9..cbcec0e 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -3718,7 +3718,7 @@
          * Text to be displayed in a tooltip popup.
          */
         @Nullable
-        CharSequence mTooltip;
+        CharSequence mTooltipText;
 
         /**
          * View-relative position of the tooltip anchor point.
@@ -4761,8 +4761,8 @@
                         forceHasOverlappingRendering(a.getBoolean(attr, true));
                     }
                     break;
-                case R.styleable.View_tooltip:
-                    setTooltip(a.getText(attr));
+                case R.styleable.View_tooltipText:
+                    setTooltipText(a.getText(attr));
                     break;
                 case R.styleable.View_keyboardNavigationCluster:
                     if (a.peekValue(attr) != null) {
@@ -24638,10 +24638,10 @@
      * menu). </li>
      * <li>On hover, after a brief delay since the pointer has stopped moving </li>
      *
-     * @param tooltip the tooltip text, or null if no tooltip is required
+     * @param tooltipText the tooltip text, or null if no tooltip is required
      */
-    public final void setTooltip(@Nullable CharSequence tooltip) {
-        if (TextUtils.isEmpty(tooltip)) {
+    public final void setTooltipText(@Nullable CharSequence tooltipText) {
+        if (TextUtils.isEmpty(tooltipText)) {
             setFlags(0, TOOLTIP);
             hideTooltip();
             mTooltipInfo = null;
@@ -24652,21 +24652,42 @@
                 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
                 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
             }
-            mTooltipInfo.mTooltip = tooltip;
+            mTooltipInfo.mTooltipText = tooltipText;
             if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
-                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltip);
+                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
             }
         }
     }
 
     /**
+     * To be removed once the support library has stopped using it.
+     *
+     * @deprecated use {@link #setTooltipText} instead
+     */
+    @Deprecated
+    public final void setTooltip(@Nullable CharSequence tooltipText) {
+        setTooltipText(tooltipText);
+    }
+
+    /**
      * Returns the view's tooltip text.
      *
      * @return the tooltip text
      */
     @Nullable
+    public final CharSequence getTooltipText() {
+        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
+    }
+
+    /**
+     * To be removed once the support library has stopped using it.
+     *
+     * @deprecated use {@link #getTooltipText} instead
+     */
+    @Deprecated
+    @Nullable
     public final CharSequence getTooltip() {
-        return mTooltipInfo != null ? mTooltipInfo.mTooltip : null;
+        return getTooltipText();
     }
 
     private boolean showTooltip(int x, int y, boolean fromLongClick) {
@@ -24676,7 +24697,7 @@
         if ((mViewFlags & ENABLED_MASK) != ENABLED) {
             return false;
         }
-        final CharSequence tooltipText = getTooltip();
+        final CharSequence tooltipText = getTooltipText();
         if (TextUtils.isEmpty(tooltipText)) {
             return false;
         }
diff --git a/core/java/com/android/internal/view/menu/ActionMenuItem.java b/core/java/com/android/internal/view/menu/ActionMenuItem.java
index c8697dd..1fce0b7 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuItem.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuItem.java
@@ -48,7 +48,7 @@
     private MenuItem.OnMenuItemClickListener mClickListener;
 
     private CharSequence mContentDescription;
-    private CharSequence mTooltip;
+    private CharSequence mTooltipText;
 
     private static final int NO_ICON = 0;
 
@@ -290,13 +290,13 @@
     }
 
     @Override
-    public MenuItem setTooltip(CharSequence tooltip) {
-        mTooltip = tooltip;
+    public MenuItem setTooltipText(CharSequence tooltipText) {
+        mTooltipText = tooltipText;
         return this;
     }
 
     @Override
-    public CharSequence getTooltip() {
-        return mTooltip;
+    public CharSequence getTooltipText() {
+        return mTooltipText;
     }
 }
diff --git a/core/java/com/android/internal/view/menu/ActionMenuItemView.java b/core/java/com/android/internal/view/menu/ActionMenuItemView.java
index 4ee5993..92e1d80 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuItemView.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuItemView.java
@@ -193,12 +193,12 @@
             setContentDescription(contentDescription);
         }
 
-        final CharSequence tooltip = mItemData.getTooltip();
-        if (TextUtils.isEmpty(tooltip)) {
+        final CharSequence tooltipText = mItemData.getTooltipText();
+        if (TextUtils.isEmpty(tooltipText)) {
             // Use the uncondensed title for tooltip, but only if the title is not shown already.
-            setTooltip(visible ? null : mItemData.getTitle());
+            setTooltipText(visible ? null : mItemData.getTitle());
         } else {
-            setTooltip(tooltip);
+            setTooltipText(tooltipText);
         }
     }
 
diff --git a/core/java/com/android/internal/view/menu/IconMenuItemView.java b/core/java/com/android/internal/view/menu/IconMenuItemView.java
index f9ebdbc..6c8f330 100644
--- a/core/java/com/android/internal/view/menu/IconMenuItemView.java
+++ b/core/java/com/android/internal/view/menu/IconMenuItemView.java
@@ -113,7 +113,7 @@
             } else {
                 setContentDescription(contentDescription);
             }
-            setTooltip(mItemData.getTooltip());
+            setTooltipText(mItemData.getTooltipText());
         }
     }
 
diff --git a/core/java/com/android/internal/view/menu/ListMenuItemView.java b/core/java/com/android/internal/view/menu/ListMenuItemView.java
index 7c9f709..43005e6 100644
--- a/core/java/com/android/internal/view/menu/ListMenuItemView.java
+++ b/core/java/com/android/internal/view/menu/ListMenuItemView.java
@@ -115,7 +115,7 @@
         setEnabled(itemData.isEnabled());
         setSubMenuArrowVisible(itemData.hasSubMenu());
         setContentDescription(itemData.getContentDescription());
-        setTooltip(itemData.getTooltip());
+        setTooltipText(itemData.getTooltipText());
     }
 
     public void setForceShowIcon(boolean forceShow) {
diff --git a/core/java/com/android/internal/view/menu/MenuItemImpl.java b/core/java/com/android/internal/view/menu/MenuItemImpl.java
index cad0276..342943f 100644
--- a/core/java/com/android/internal/view/menu/MenuItemImpl.java
+++ b/core/java/com/android/internal/view/menu/MenuItemImpl.java
@@ -94,7 +94,7 @@
     private ContextMenuInfo mMenuInfo;
 
     private CharSequence mContentDescription;
-    private CharSequence mTooltip;
+    private CharSequence mTooltipText;
 
     private static String sLanguage;
     private static String sPrependShortcutLabel;
@@ -689,8 +689,8 @@
     }
 
     @Override
-    public MenuItem setTooltip(CharSequence tooltip) {
-        mTooltip = tooltip;
+    public MenuItem setTooltipText(CharSequence tooltipText) {
+        mTooltipText = tooltipText;
 
         mMenu.onItemsChanged(false);
 
@@ -698,7 +698,7 @@
     }
 
     @Override
-    public CharSequence getTooltip() {
-        return mTooltip;
+    public CharSequence getTooltipText() {
+        return mTooltipText;
     }
 }
diff --git a/core/java/com/android/internal/widget/FloatingToolbar.java b/core/java/com/android/internal/widget/FloatingToolbar.java
index 04e09a8..58e694a 100644
--- a/core/java/com/android/internal/widget/FloatingToolbar.java
+++ b/core/java/com/android/internal/widget/FloatingToolbar.java
@@ -1591,7 +1591,7 @@
                     } else {
                         menuButton.setContentDescription(contentDescription);
                     }
-                    menuButton.setTooltip(menuItem.getTooltip());
+                    menuButton.setTooltipText(menuItem.getTooltipText());
                     menuButton.setMinimumWidth(minimumWidth);
                 }
                 return menuButton;
@@ -1642,17 +1642,17 @@
             ((ImageButton) menuItemButton
                     .findViewById(R.id.floating_toolbar_menu_item_image_button))
                     .setImageDrawable(menuItem.getIcon());
-            final CharSequence tooltip = menuItem.getTooltip();
-            if (TextUtils.isEmpty(tooltip)) {
-                menuItemButton.setTooltip(menuItem.getTitle());
+            final CharSequence tooltipText = menuItem.getTooltipText();
+            if (TextUtils.isEmpty(tooltipText)) {
+                menuItemButton.setTooltipText(menuItem.getTitle());
             } else {
-                menuItemButton.setTooltip(tooltip);
+                menuItemButton.setTooltipText(tooltipText);
             }
         } else {
             menuItemButton = LayoutInflater.from(context)
                     .inflate(R.layout.floating_popup_menu_button, null);
             ((Button) menuItemButton).setText(menuItem.getTitle());
-            menuItemButton.setTooltip(menuItem.getTooltip());
+            menuItemButton.setTooltipText(menuItem.getTooltipText());
         }
         final CharSequence contentDescription = menuItem.getContentDescription();
         if (TextUtils.isEmpty(contentDescription)) {
diff --git a/core/java/com/android/internal/widget/ScrollingTabContainerView.java b/core/java/com/android/internal/widget/ScrollingTabContainerView.java
index 4466575..311bfac 100644
--- a/core/java/com/android/internal/widget/ScrollingTabContainerView.java
+++ b/core/java/com/android/internal/widget/ScrollingTabContainerView.java
@@ -471,7 +471,7 @@
                 if (mIconView != null) {
                     mIconView.setContentDescription(tab.getContentDescription());
                 }
-                setTooltip(hasText? null : tab.getContentDescription());
+                setTooltipText(hasText? null : tab.getContentDescription());
             }
         }
 
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index a5c1a94..a401314 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -2890,7 +2890,7 @@
         <attr name="forceHasOverlappingRendering" format="boolean" />
 
         <!-- Defines text displayed in a small popup window on hover or long press. -->
-        <attr name="tooltip" format="string" localization="suggested" />
+        <attr name="tooltipText" format="string" localization="suggested" />
 
         <!-- Whether this view is a root of a keyboard navigation cluster.
              See {@link android.view.View#setKeyboardNavigationCluster(boolean)}. -->
@@ -7029,7 +7029,7 @@
         <attr name="contentDescription" format="string" />
 
         <!-- The tooltip text associated with the item. -->
-        <attr name="tooltip" format="string" />
+        <attr name="tooltipText" format="string" />
 
     </declare-styleable>
 
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 099fe08..664baa2 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2764,7 +2764,7 @@
         <public name="fontStyle" />
         <public name="font" />
         <public name="fontWeight" />
-        <public name="tooltip" />
+        <public name="tooltipText" />
         <public name="autoSizeText" />
         <public name="autoSizeStepGranularity" />
         <public name="autoSizeStepSizeSet" />
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 842b575..faf451b 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -1290,7 +1290,7 @@
     <style name="Widget.ActionButton.Overflow">
         <item name="src">@drawable/ic_menu_more</item>
         <item name="contentDescription">@string/action_menu_overflow_description</item>
-        <item name="tooltip">@string/action_menu_overflow_description</item>
+        <item name="tooltipText">@string/action_menu_overflow_description</item>
     </style>
 
     <style name="Widget.ActionButton.CloseMode">
diff --git a/core/res/res/values/styles_holo.xml b/core/res/res/values/styles_holo.xml
index 12b8164..dc32b26 100644
--- a/core/res/res/values/styles_holo.xml
+++ b/core/res/res/values/styles_holo.xml
@@ -660,7 +660,7 @@
         <item name="src">@drawable/ic_menu_moreoverflow_holo_dark</item>
         <item name="background">?attr/actionBarItemBackground</item>
         <item name="contentDescription">@string/action_menu_overflow_description</item>
-        <item name="tooltip">@string/action_menu_overflow_description</item>
+        <item name="tooltipText">@string/action_menu_overflow_description</item>
     </style>
 
     <style name="Widget.Holo.ActionButton.TextButton" parent="Widget.Holo.ButtonBar.Button" />
@@ -995,7 +995,7 @@
     <style name="Widget.Holo.Light.ActionButton.Overflow">
         <item name="src">@drawable/ic_menu_moreoverflow_holo_light</item>
         <item name="contentDescription">@string/action_menu_overflow_description</item>
-        <item name="tooltip">@string/action_menu_overflow_description</item>
+        <item name="tooltipText">@string/action_menu_overflow_description</item>
     </style>
 
     <style name="Widget.Holo.Light.ActionBar.TabView" parent="Widget.Holo.ActionBar.TabView" />
diff --git a/core/res/res/values/styles_material.xml b/core/res/res/values/styles_material.xml
index 709200e..0b326e9 100644
--- a/core/res/res/values/styles_material.xml
+++ b/core/res/res/values/styles_material.xml
@@ -944,7 +944,7 @@
         <item name="src">@drawable/ic_menu_moreoverflow_material</item>
         <item name="background">?attr/actionBarItemBackground</item>
         <item name="contentDescription">@string/action_menu_overflow_description</item>
-        <item name="tooltip">@string/action_menu_overflow_description</item>
+        <item name="tooltipText">@string/action_menu_overflow_description</item>
         <item name="minWidth">@dimen/action_button_min_width_overflow_material</item>
         <item name="minHeight">@dimen/action_button_min_height_material</item>
         <item name="paddingStart">@dimen/action_bar_overflow_padding_start_material</item>
diff --git a/core/tests/coretests/src/android/app/ApplicationPackageManagerTest.java b/core/tests/coretests/src/android/app/ApplicationPackageManagerTest.java
new file mode 100644
index 0000000..f60bf94
--- /dev/null
+++ b/core/tests/coretests/src/android/app/ApplicationPackageManagerTest.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.IPackageManager;
+import android.content.pm.PackageInfo;
+import android.os.storage.StorageManager;
+import android.os.storage.VolumeInfo;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static android.os.storage.VolumeInfo.STATE_MOUNTED;
+import static android.os.storage.VolumeInfo.STATE_UNMOUNTED;
+
+public class ApplicationPackageManagerTest extends TestCase {
+    private static final String sInternalVolPath = "/data";
+    private static final String sAdoptedVolPath = "/mnt/expand/123";
+    private static final String sPublicVolPath = "/emulated";
+    private static final String sPrivateUnmountedVolPath = "/private";
+
+    private static final String sInternalVolUuid = null; //StorageManager.UUID_PRIVATE_INTERNAL
+    private static final String sAdoptedVolUuid = "adopted";
+    private static final String sPublicVolUuid = "emulated";
+    private static final String sPrivateUnmountedVolUuid = "private";
+
+    private static final VolumeInfo sInternalVol = new VolumeInfo("private",
+            VolumeInfo.TYPE_PRIVATE, null /*DiskInfo*/, null /*partGuid*/);
+
+    private static final VolumeInfo sAdoptedVol = new VolumeInfo("adopted",
+            VolumeInfo.TYPE_PRIVATE, null /*DiskInfo*/, null /*partGuid*/);
+
+    private static final VolumeInfo sPublicVol = new VolumeInfo("public",
+            VolumeInfo.TYPE_PUBLIC, null /*DiskInfo*/, null /*partGuid*/);
+
+    private static final VolumeInfo sPrivateUnmountedVol = new VolumeInfo("private2",
+            VolumeInfo.TYPE_PRIVATE, null /*DiskInfo*/, null /*partGuid*/);
+
+    private static final List<VolumeInfo> sVolumes = new ArrayList<>();
+
+    static {
+        sInternalVol.path = sInternalVolPath;
+        sInternalVol.state = STATE_MOUNTED;
+        sInternalVol.fsUuid = sInternalVolUuid;
+
+        sAdoptedVol.path = sAdoptedVolPath;
+        sAdoptedVol.state = STATE_MOUNTED;
+        sAdoptedVol.fsUuid = sAdoptedVolUuid;
+
+        sPublicVol.state = STATE_MOUNTED;
+        sPublicVol.path = sPublicVolPath;
+        sPublicVol.fsUuid = sPublicVolUuid;
+
+        sPrivateUnmountedVol.state = STATE_UNMOUNTED;
+        sPrivateUnmountedVol.path = sPrivateUnmountedVolPath;
+        sPrivateUnmountedVol.fsUuid = sPrivateUnmountedVolUuid;
+
+        sVolumes.add(sInternalVol);
+        sVolumes.add(sAdoptedVol);
+        sVolumes.add(sPublicVol);
+        sVolumes.add(sPrivateUnmountedVol);
+    }
+
+    private static final class MockedApplicationPackageManager extends ApplicationPackageManager {
+        private boolean mForceAllowOnExternal = false;
+        private boolean mAllow3rdPartyOnInternal = true;
+
+        public MockedApplicationPackageManager() {
+            super(null, null);
+        }
+
+        public void setForceAllowOnExternal(boolean forceAllowOnExternal) {
+            mForceAllowOnExternal = forceAllowOnExternal;
+        }
+
+        public void setAllow3rdPartyOnInternal(boolean allow3rdPartyOnInternal) {
+            mAllow3rdPartyOnInternal = allow3rdPartyOnInternal;
+        }
+
+        @Override
+        public boolean isForceAllowOnExternal(Context context) {
+            return mForceAllowOnExternal;
+        }
+
+        @Override
+        public boolean isAllow3rdPartyOnInternal(Context context) {
+            return mAllow3rdPartyOnInternal;
+        }
+    }
+
+    private StorageManager getMockedStorageManager() {
+        StorageManager storageManager = Mockito.mock(StorageManager.class);
+        Mockito.when(storageManager.getVolumes()).thenReturn(sVolumes);
+        Mockito.when(storageManager.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL))
+                .thenReturn(sInternalVol);
+        Mockito.when(storageManager.findVolumeByUuid(sAdoptedVolUuid))
+                .thenReturn(sAdoptedVol);
+        Mockito.when(storageManager.findVolumeByUuid(sPublicVolUuid))
+                .thenReturn(sPublicVol);
+        Mockito.when(storageManager.findVolumeByUuid(sPrivateUnmountedVolUuid))
+                .thenReturn(sPrivateUnmountedVol);
+        return storageManager;
+    }
+
+    private void verifyReturnedVolumes(List<VolumeInfo> actualVols, VolumeInfo... exptectedVols) {
+        boolean failed = false;
+        if (actualVols.size() != exptectedVols.length) {
+            failed = true;
+        } else {
+            for (VolumeInfo vol : exptectedVols) {
+                if (!actualVols.contains(vol)) {
+                    failed = true;
+                    break;
+                }
+            }
+        }
+
+        if (failed) {
+            fail("Wrong volumes returned.\n Expected: " + Arrays.toString(exptectedVols)
+                    + "\n Actual: " + Arrays.toString(actualVols.toArray()));
+        }
+    }
+
+    public void testGetCandidateVolumes_systemApp() throws Exception {
+        ApplicationInfo sysAppInfo = new ApplicationInfo();
+        sysAppInfo.flags = ApplicationInfo.FLAG_SYSTEM;
+
+        StorageManager storageManager = getMockedStorageManager();
+        IPackageManager pm = Mockito.mock(IPackageManager.class);
+
+        MockedApplicationPackageManager appPkgMgr = new MockedApplicationPackageManager();
+
+        appPkgMgr.setAllow3rdPartyOnInternal(true);
+        appPkgMgr.setForceAllowOnExternal(true);
+        List<VolumeInfo> candidates =
+                appPkgMgr.getPackageCandidateVolumes(sysAppInfo, storageManager, pm);
+        verifyReturnedVolumes(candidates, sInternalVol);
+
+        appPkgMgr.setAllow3rdPartyOnInternal(true);
+        appPkgMgr.setForceAllowOnExternal(false);
+        candidates = appPkgMgr.getPackageCandidateVolumes(sysAppInfo, storageManager, pm);
+        verifyReturnedVolumes(candidates, sInternalVol);
+
+        appPkgMgr.setAllow3rdPartyOnInternal(false);
+        appPkgMgr.setForceAllowOnExternal(false);
+        candidates = appPkgMgr.getPackageCandidateVolumes(sysAppInfo, storageManager, pm);
+        verifyReturnedVolumes(candidates, sInternalVol);
+
+        appPkgMgr.setAllow3rdPartyOnInternal(false);
+        appPkgMgr.setForceAllowOnExternal(true);
+        candidates = appPkgMgr.getPackageCandidateVolumes(sysAppInfo, storageManager, pm);
+        verifyReturnedVolumes(candidates, sInternalVol);
+    }
+
+    public void testGetCandidateVolumes_3rdParty_internalOnly() throws Exception {
+        ApplicationInfo appInfo = new ApplicationInfo();
+        StorageManager storageManager = getMockedStorageManager();
+
+        IPackageManager pm = Mockito.mock(IPackageManager.class);
+        Mockito.when(pm.isPackageDeviceAdminOnAnyUser(Mockito.anyString())).thenReturn(false);
+
+        MockedApplicationPackageManager appPkgMgr = new MockedApplicationPackageManager();
+
+        // must allow 3rd party on internal, otherwise the app wouldn't have been installed before.
+        appPkgMgr.setAllow3rdPartyOnInternal(true);
+
+        // INSTALL_LOCATION_INTERNAL_ONLY AND INSTALL_LOCATION_UNSPECIFIED are treated the same.
+        int[] locations = {PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY,
+                PackageInfo.INSTALL_LOCATION_UNSPECIFIED};
+
+        for (int location : locations) {
+            appInfo.installLocation = location;
+            appPkgMgr.setForceAllowOnExternal(true);
+            List<VolumeInfo> candidates = appPkgMgr.getPackageCandidateVolumes(
+                    appInfo, storageManager, pm);
+            verifyReturnedVolumes(candidates, sInternalVol, sAdoptedVol);
+
+            appPkgMgr.setForceAllowOnExternal(false);
+            candidates = appPkgMgr.getPackageCandidateVolumes(appInfo, storageManager, pm);
+            verifyReturnedVolumes(candidates, sInternalVol);
+        }
+    }
+
+    public void testGetCandidateVolumes_3rdParty_auto() throws Exception {
+        ApplicationInfo appInfo = new ApplicationInfo();
+        StorageManager storageManager = getMockedStorageManager();
+
+        IPackageManager pm = Mockito.mock(IPackageManager.class);
+
+        MockedApplicationPackageManager appPkgMgr = new MockedApplicationPackageManager();
+        appPkgMgr.setForceAllowOnExternal(true);
+
+        // INSTALL_LOCATION_AUTO AND INSTALL_LOCATION_PREFER_EXTERNAL are treated the same.
+        int[] locations = {PackageInfo.INSTALL_LOCATION_AUTO,
+                PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL};
+
+        for (int location : locations) {
+            appInfo.installLocation = location;
+            appInfo.flags = 0;
+
+            appInfo.volumeUuid = sInternalVolUuid;
+            Mockito.when(pm.isPackageDeviceAdminOnAnyUser(Mockito.anyString())).thenReturn(false);
+            appPkgMgr.setAllow3rdPartyOnInternal(true);
+            List<VolumeInfo> candidates = appPkgMgr.getPackageCandidateVolumes(
+                    appInfo, storageManager, pm);
+            verifyReturnedVolumes(candidates, sInternalVol, sAdoptedVol);
+
+            appInfo.volumeUuid = sInternalVolUuid;
+            appPkgMgr.setAllow3rdPartyOnInternal(true);
+            Mockito.when(pm.isPackageDeviceAdminOnAnyUser(Mockito.anyString())).thenReturn(true);
+            candidates = appPkgMgr.getPackageCandidateVolumes(appInfo, storageManager, pm);
+            verifyReturnedVolumes(candidates, sInternalVol);
+
+            appInfo.flags = ApplicationInfo.FLAG_EXTERNAL_STORAGE;
+            appInfo.volumeUuid = sAdoptedVolUuid;
+            appPkgMgr.setAllow3rdPartyOnInternal(false);
+            candidates = appPkgMgr.getPackageCandidateVolumes(appInfo, storageManager, pm);
+            verifyReturnedVolumes(candidates, sAdoptedVol);
+        }
+    }
+}
diff --git a/tools/aapt2/util/StringPiece.h b/libs/androidfw/include/androidfw/StringPiece.h
similarity index 66%
rename from tools/aapt2/util/StringPiece.h
rename to libs/androidfw/include/androidfw/StringPiece.h
index 5144b1f..c9effd1 100644
--- a/tools/aapt2/util/StringPiece.h
+++ b/libs/androidfw/include/androidfw/StringPiece.h
@@ -14,26 +14,24 @@
  * limitations under the License.
  */
 
-#ifndef AAPT_STRING_PIECE_H
-#define AAPT_STRING_PIECE_H
+#ifndef ANDROIDFW_STRING_PIECE_H
+#define ANDROIDFW_STRING_PIECE_H
 
 #include <ostream>
 #include <string>
 
 #include "utils/JenkinsHash.h"
-#include "utils/String8.h"
 #include "utils/Unicode.h"
 
-namespace aapt {
+namespace android {
 
-/**
- * Read only wrapper around basic C strings.
- * Prevents excessive copying.
- *
- * WARNING: When creating from std::basic_string<>, moving the original
- * std::basic_string<> will invalidate the data held in a BasicStringPiece<>.
- * BasicStringPiece<> should only be used transitively.
- */
+// Read only wrapper around basic C strings. Prevents excessive copying.
+// StringPiece does not own the data it is wrapping. The lifetime of the underlying
+// data must outlive this StringPiece.
+//
+// WARNING: When creating from std::basic_string<>, moving the original
+// std::basic_string<> will invalidate the data held in a BasicStringPiece<>.
+// BasicStringPiece<> should only be used transitively.
 template <typename TChar>
 class BasicStringPiece {
  public:
@@ -53,15 +51,14 @@
   BasicStringPiece<TChar>& assign(const TChar* str, size_t len);
 
   BasicStringPiece<TChar> substr(size_t start, size_t len = npos) const;
-  BasicStringPiece<TChar> substr(
-      BasicStringPiece<TChar>::const_iterator begin,
-      BasicStringPiece<TChar>::const_iterator end) const;
+  BasicStringPiece<TChar> substr(BasicStringPiece<TChar>::const_iterator begin,
+                                 BasicStringPiece<TChar>::const_iterator end) const;
 
   const TChar* data() const;
   size_t length() const;
   size_t size() const;
   bool empty() const;
-  std::basic_string<TChar> ToString() const;
+  std::basic_string<TChar> to_string() const;
 
   bool contains(const BasicStringPiece<TChar>& rhs) const;
   int compare(const BasicStringPiece<TChar>& rhs) const;
@@ -89,17 +86,14 @@
 constexpr const size_t BasicStringPiece<TChar>::npos;
 
 template <typename TChar>
-inline BasicStringPiece<TChar>::BasicStringPiece()
-    : data_(nullptr), length_(0) {}
+inline BasicStringPiece<TChar>::BasicStringPiece() : data_(nullptr), length_(0) {}
 
 template <typename TChar>
-inline BasicStringPiece<TChar>::BasicStringPiece(
-    const BasicStringPiece<TChar>& str)
+inline BasicStringPiece<TChar>::BasicStringPiece(const BasicStringPiece<TChar>& str)
     : data_(str.data_), length_(str.length_) {}
 
 template <typename TChar>
-inline BasicStringPiece<TChar>::BasicStringPiece(
-    const std::basic_string<TChar>& str)
+inline BasicStringPiece<TChar>::BasicStringPiece(const std::basic_string<TChar>& str)
     : data_(str.data()), length_(str.length()) {}
 
 template <>
@@ -123,16 +117,14 @@
 }
 
 template <typename TChar>
-inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::assign(
-    const TChar* str, size_t len) {
+inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::assign(const TChar* str, size_t len) {
   data_ = str;
   length_ = len;
   return *this;
 }
 
 template <typename TChar>
-inline BasicStringPiece<TChar> BasicStringPiece<TChar>::substr(
-    size_t start, size_t len) const {
+inline BasicStringPiece<TChar> BasicStringPiece<TChar>::substr(size_t start, size_t len) const {
   if (len == npos) {
     len = length_ - start;
   }
@@ -171,13 +163,12 @@
 }
 
 template <typename TChar>
-inline std::basic_string<TChar> BasicStringPiece<TChar>::ToString() const {
+inline std::basic_string<TChar> BasicStringPiece<TChar>::to_string() const {
   return std::basic_string<TChar>(data_, length_);
 }
 
 template <>
-inline bool BasicStringPiece<char>::contains(
-    const BasicStringPiece<char>& rhs) const {
+inline bool BasicStringPiece<char>::contains(const BasicStringPiece<char>& rhs) const {
   if (!data_ || !rhs.data_) {
     return false;
   }
@@ -188,8 +179,7 @@
 }
 
 template <>
-inline int BasicStringPiece<char>::compare(
-    const BasicStringPiece<char>& rhs) const {
+inline int BasicStringPiece<char>::compare(const BasicStringPiece<char>& rhs) const {
   const char nullStr = '\0';
   const char* b1 = data_ != nullptr ? data_ : &nullStr;
   const char* e1 = b1 + length_;
@@ -205,15 +195,21 @@
   return static_cast<int>(length_ - rhs.length_);
 }
 
-inline ::std::ostream& operator<<(::std::ostream& out,
-                                  const BasicStringPiece<char16_t>& str) {
-  android::String8 utf8(str.data(), str.size());
-  return out.write(utf8.string(), utf8.size());
+inline ::std::ostream& operator<<(::std::ostream& out, const BasicStringPiece<char16_t>& str) {
+  const ssize_t result_len = utf16_to_utf8_length(str.data(), str.size());
+  if (result_len < 0) {
+    // Empty string.
+    return out;
+  }
+
+  std::string result;
+  result.resize(static_cast<size_t>(result_len));
+  utf16_to_utf8(str.data(), str.length(), &*result.begin(), static_cast<size_t>(result_len) + 1);
+  return out << result;
 }
 
 template <>
-inline bool BasicStringPiece<char16_t>::contains(
-    const BasicStringPiece<char16_t>& rhs) const {
+inline bool BasicStringPiece<char16_t>::contains(const BasicStringPiece<char16_t>& rhs) const {
   if (!data_ || !rhs.data_) {
     return false;
   }
@@ -224,8 +220,7 @@
 }
 
 template <>
-inline int BasicStringPiece<char16_t>::compare(
-    const BasicStringPiece<char16_t>& rhs) const {
+inline int BasicStringPiece<char16_t>::compare(const BasicStringPiece<char16_t>& rhs) const {
   const char16_t nullStr = u'\0';
   const char16_t* b1 = data_ != nullptr ? data_ : &nullStr;
   const char16_t* b2 = rhs.data_ != nullptr ? rhs.data_ : &nullStr;
@@ -233,66 +228,52 @@
 }
 
 template <typename TChar>
-inline bool BasicStringPiece<TChar>::operator<(
-    const BasicStringPiece<TChar>& rhs) const {
+inline bool BasicStringPiece<TChar>::operator<(const BasicStringPiece<TChar>& rhs) const {
   return compare(rhs) < 0;
 }
 
 template <typename TChar>
-inline bool BasicStringPiece<TChar>::operator>(
-    const BasicStringPiece<TChar>& rhs) const {
+inline bool BasicStringPiece<TChar>::operator>(const BasicStringPiece<TChar>& rhs) const {
   return compare(rhs) > 0;
 }
 
 template <typename TChar>
-inline bool BasicStringPiece<TChar>::operator==(
-    const BasicStringPiece<TChar>& rhs) const {
+inline bool BasicStringPiece<TChar>::operator==(const BasicStringPiece<TChar>& rhs) const {
   return compare(rhs) == 0;
 }
 
 template <typename TChar>
-inline bool BasicStringPiece<TChar>::operator!=(
-    const BasicStringPiece<TChar>& rhs) const {
+inline bool BasicStringPiece<TChar>::operator!=(const BasicStringPiece<TChar>& rhs) const {
   return compare(rhs) != 0;
 }
 
 template <typename TChar>
-inline typename BasicStringPiece<TChar>::const_iterator
-BasicStringPiece<TChar>::begin() const {
+inline typename BasicStringPiece<TChar>::const_iterator BasicStringPiece<TChar>::begin() const {
   return data_;
 }
 
 template <typename TChar>
-inline typename BasicStringPiece<TChar>::const_iterator
-BasicStringPiece<TChar>::end() const {
+inline typename BasicStringPiece<TChar>::const_iterator BasicStringPiece<TChar>::end() const {
   return data_ + length_;
 }
 
-inline ::std::ostream& operator<<(::std::ostream& out,
-                                  const BasicStringPiece<char>& str) {
+inline ::std::ostream& operator<<(::std::ostream& out, const BasicStringPiece<char>& str) {
   return out.write(str.data(), str.size());
 }
 
-}  // namespace aapt
-
-inline ::std::ostream& operator<<(::std::ostream& out,
-                                  const std::u16string& str) {
-  android::String8 utf8(str.data(), str.size());
-  return out.write(utf8.string(), utf8.size());
-}
+}  // namespace android
 
 namespace std {
 
 template <typename TChar>
-struct hash<aapt::BasicStringPiece<TChar>> {
-  size_t operator()(const aapt::BasicStringPiece<TChar>& str) const {
+struct hash<android::BasicStringPiece<TChar>> {
+  size_t operator()(const android::BasicStringPiece<TChar>& str) const {
     uint32_t hashCode = android::JenkinsHashMixBytes(
-        0, reinterpret_cast<const uint8_t*>(str.data()),
-        sizeof(TChar) * str.size());
+        0, reinterpret_cast<const uint8_t*>(str.data()), sizeof(TChar) * str.size());
     return static_cast<size_t>(hashCode);
   }
 };
 
 }  // namespace std
 
-#endif  // AAPT_STRING_PIECE_H
+#endif  // ANDROIDFW_STRING_PIECE_H
diff --git a/libs/androidfw/tests/Android.mk b/libs/androidfw/tests/Android.mk
index 6754cd8..650f813 100644
--- a/libs/androidfw/tests/Android.mk
+++ b/libs/androidfw/tests/Android.mk
@@ -34,6 +34,7 @@
     LoadedArsc_test.cpp \
     ResTable_test.cpp \
     Split_test.cpp \
+    StringPiece_test.cpp \
     TestHelpers.cpp \
     TestMain.cpp \
     Theme_test.cpp \
diff --git a/tools/aapt2/util/StringPiece_test.cpp b/libs/androidfw/tests/StringPiece_test.cpp
similarity index 96%
rename from tools/aapt2/util/StringPiece_test.cpp
rename to libs/androidfw/tests/StringPiece_test.cpp
index 048961d..316a5c1 100644
--- a/tools/aapt2/util/StringPiece_test.cpp
+++ b/libs/androidfw/tests/StringPiece_test.cpp
@@ -14,15 +14,15 @@
  * limitations under the License.
  */
 
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
 
 #include <algorithm>
 #include <string>
 #include <vector>
 
-#include "test/Test.h"
+#include "TestHelpers.h"
 
-namespace aapt {
+namespace android {
 
 TEST(StringPieceTest, CompareNonNullTerminatedPiece) {
   StringPiece a("hello world", 5);
@@ -92,4 +92,4 @@
   EXPECT_FALSE(text16.contains(long_needle16));
 }
 
-}  // namespace aapt
+}  // namespace android
diff --git a/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java b/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
index b327be0..6e10aab 100644
--- a/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
@@ -21,6 +21,7 @@
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Resources;
@@ -105,6 +106,12 @@
     private static final String EXTRA_CATEGORY_KEY = "com.android.settings.category";
 
     /**
+     * The key used to get the package name of the icon resource for the preference.
+     */
+    private static final String EXTRA_PREFERENCE_ICON_PACKAGE =
+        "com.android.settings.icon_package";
+
+    /**
      * Name of the meta-data item that should be set in the AndroidManifest.xml
      * to specify the key that should be used for the preference.
      */
@@ -342,6 +349,7 @@
             ActivityInfo activityInfo, ApplicationInfo applicationInfo, PackageManager pm) {
         if (applicationInfo.isSystemApp()) {
             int icon = 0;
+            Pair<String, Integer> iconFromUri = null;
             CharSequence title = null;
             String summary = null;
             String keyHint = null;
@@ -358,10 +366,10 @@
 
                 if (res != null && metaData != null) {
                     if (metaData.containsKey(META_DATA_PREFERENCE_ICON_URI)) {
-                        icon = getIconFromUri(context,
+                        iconFromUri = getIconFromUri(context, activityInfo.packageName,
                                 metaData.getString(META_DATA_PREFERENCE_ICON_URI), providerMap);
                     }
-                    if ((icon == 0) && metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
+                    if (iconFromUri == null && metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
                         icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
                     }
                     if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
@@ -401,12 +409,18 @@
             if (TextUtils.isEmpty(title)) {
                 title = activityInfo.loadLabel(pm).toString();
             }
-            if (icon == 0) {
-                icon = activityInfo.icon;
+
+            // Set the icon
+            if (iconFromUri != null) {
+                tile.icon = Icon.createWithResource(iconFromUri.first, iconFromUri.second);
+            } else {
+                if (icon == 0) {
+                    icon = activityInfo.icon;
+                }
+                tile.icon = Icon.createWithResource(activityInfo.packageName, icon);
             }
 
-            // Set icon, title and summary for the preference
-            tile.icon = Icon.createWithResource(activityInfo.packageName, icon);
+            // Set title and summary for the preference
             tile.title = title;
             tile.summary = summary;
             // Replace the intent with this specific activity
@@ -422,16 +436,33 @@
     }
 
     /**
-     * Gets the icon resource id from content provider.
+     * Gets the icon package name and resource id from content provider.
      * @param Context context
+     * @param packageName package name of the target activity
      * @param uriString URI for the content provider
      * @param providerMap Maps URI authorities to providers
-     * @return Resource id if returned by the content provider, otherwise 0
+     * @return package name and resource id of the icon specified
      */
-    public static int getIconFromUri(Context context, String uriString,
-            Map<String, IContentProvider> providerMap) {
+    public static Pair<String, Integer> getIconFromUri(Context context, String packageName,
+            String uriString, Map<String, IContentProvider> providerMap) {
         Bundle bundle = getBundleFromUri(context, uriString, providerMap);
-        return (bundle != null) ? bundle.getInt(META_DATA_PREFERENCE_ICON, 0) : 0;
+        if (bundle == null) {
+            return null;
+        }
+        String iconPackageName = bundle.getString(EXTRA_PREFERENCE_ICON_PACKAGE);
+        if (TextUtils.isEmpty(iconPackageName)) {
+            return null;
+        }
+        int resId = bundle.getInt(META_DATA_PREFERENCE_ICON, 0);
+        if (resId == 0) {
+            return null;
+        }
+        // Icon can either come from the target package or from the Settings app.
+        if (iconPackageName.equals(packageName)
+                || iconPackageName.equals(context.getPackageName())) {
+            return Pair.create(iconPackageName, bundle.getInt(META_DATA_PREFERENCE_ICON, 0));
+        }
+        return null;
     }
 
     /**
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
index d8082c4..c95cac5 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
@@ -255,6 +255,7 @@
 
         Bundle bundle = new Bundle();
         bundle.putInt("com.android.settings.icon", 161803);
+        bundle.putString("com.android.settings.icon_package", "abc");
         bundle.putString("com.android.settings.summary", "dynamic-summary");
         when(mIContentProvider.call(anyString(),
                 eq(TileUtils.getMethodFromUri(Uri.parse(URI_GET_ICON))), eq(URI_GET_ICON), any()))
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 31ecb75..7e82586 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -577,15 +577,18 @@
         public ArrayList<String> fullPackages;
         public IBackupObserver observer;
         public boolean userInitiated;
+        public boolean nonIncrementalBackup;
 
         BackupParams(IBackupTransport transport, String dirName, ArrayList<String> kvPackages,
-                ArrayList<String> fullPackages, IBackupObserver observer, boolean userInitiated) {
+                ArrayList<String> fullPackages, IBackupObserver observer, boolean userInitiated,
+                boolean nonIncrementalBackup) {
             this.transport = transport;
             this.dirName = dirName;
             this.kvPackages = kvPackages;
             this.fullPackages = fullPackages;
             this.observer = observer;
             this.userInitiated = userInitiated;
+            this.nonIncrementalBackup = nonIncrementalBackup;
         }
     }
 
@@ -794,7 +797,7 @@
                     try {
                         String dirName = transport.transportDirName();
                         PerformBackupTask pbt = new PerformBackupTask(transport, dirName,
-                                queue, oldJournal, null, null, false);
+                                queue, oldJournal, null, null, false, false /* nonIncremental */);
                         Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
                         sendMessage(pbtMessage);
                     } catch (Exception e) {
@@ -1033,7 +1036,8 @@
                 mWakelock.acquire();
 
                 PerformBackupTask pbt = new PerformBackupTask(params.transport, params.dirName,
-                    kvQueue, null, params.observer, params.fullPackages, true);
+                        kvQueue, null, params.observer, params.fullPackages, true,
+                        params.nonIncrementalBackup);
                 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
                 sendMessage(pbtMessage);
                 break;
@@ -2492,7 +2496,7 @@
         return token;
     }
 
-    public int requestBackup(String[] packages, IBackupObserver observer) {
+    public int requestBackup(String[] packages, IBackupObserver observer, int flags) {
         mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "requestBackup");
 
         if (packages == null || packages.length < 1) {
@@ -2510,6 +2514,10 @@
         ArrayList<String> fullBackupList = new ArrayList<>();
         ArrayList<String> kvBackupList = new ArrayList<>();
         for (String packageName : packages) {
+            if (PACKAGE_MANAGER_SENTINEL.equals(packageName)) {
+                kvBackupList.add(packageName);
+                continue;
+            }
             try {
                 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName,
                         PackageManager.GET_SIGNATURES);
@@ -2543,9 +2551,12 @@
             sendBackupFinished(observer, BackupManager.ERROR_TRANSPORT_ABORTED);
             return BackupManager.ERROR_TRANSPORT_ABORTED;
         }
+
+        boolean nonIncrementalBackup = (flags & BackupManager.FLAG_NON_INCREMENTAL_BACKUP) != 0;
+
         Message msg = mBackupHandler.obtainMessage(MSG_REQUEST_BACKUP);
         msg.obj = new BackupParams(transport, dirName, kvBackupList, fullBackupList, observer,
-                true);
+                true, nonIncrementalBackup);
         mBackupHandler.sendMessage(msg);
         return BackupManager.SUCCESS;
     }
@@ -2673,17 +2684,20 @@
         ParcelFileDescriptor mNewState;
         int mStatus;
         boolean mFinished;
-        boolean mUserInitiated;
+        final boolean mUserInitiated;
+        final boolean mNonIncremental;
 
         public PerformBackupTask(IBackupTransport transport, String dirName,
                 ArrayList<BackupRequest> queue, File journal, IBackupObserver observer,
-                ArrayList<String> pendingFullBackups, boolean userInitiated) {
+                ArrayList<String> pendingFullBackups, boolean userInitiated,
+                boolean nonIncremental) {
             mTransport = transport;
             mOriginalQueue = queue;
             mJournal = journal;
             mObserver = observer;
             mPendingFullBackups = pendingFullBackups;
             mUserInitiated = userInitiated;
+            mNonIncremental = nonIncremental;
 
             mStateDir = new File(mBaseStateDir, dirName);
 
@@ -2748,6 +2762,10 @@
             // the way.
             mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
 
+            // When the transport is forcing non-incremental key/value payloads, we send the
+            // metadata only if it explicitly asks for it.
+            boolean skipPm = mNonIncremental;
+
             // The app metadata pseudopackage might also be represented in the
             // backup queue if apps have been added/removed since the last time
             // we performed a backup.  Drop it from the working queue now that
@@ -2758,6 +2776,7 @@
                         Slog.i(TAG, "Metadata in queue; eliding");
                     }
                     mQueue.remove(i);
+                    skipPm = false;
                     break;
                 }
             }
@@ -2785,22 +2804,27 @@
                     }
                 }
 
-                // The package manager doesn't have a proper <application> etc, but since
-                // it's running here in the system process we can just set up its agent
-                // directly and use a synthetic BackupRequest.  We always run this pass
-                // because it's cheap and this way we guarantee that we don't get out of
-                // step even if we're selecting among various transports at run time.
-                if (mStatus == BackupTransport.TRANSPORT_OK) {
-                    PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
-                            mPackageManager);
-                    mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
-                            IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
-                    addBackupTrace("PMBA invoke: " + mStatus);
+                if (skipPm) {
+                    Slog.d(TAG, "Skipping backup of package metadata.");
+                    executeNextState(BackupState.RUNNING_QUEUE);
+                } else {
+                    // The package manager doesn't have a proper <application> etc, but since
+                    // it's running here in the system process we can just set up its agent
+                    // directly and use a synthetic BackupRequest.  We always run this pass
+                    // because it's cheap and this way we guarantee that we don't get out of
+                    // step even if we're selecting among various transports at run time.
+                    if (mStatus == BackupTransport.TRANSPORT_OK) {
+                        PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
+                                mPackageManager);
+                        mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
+                                IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
+                        addBackupTrace("PMBA invoke: " + mStatus);
 
-                    // Because the PMBA is a local instance, it has already executed its
-                    // backup callback and returned.  Blow away the lingering (spurious)
-                    // pending timeout message for it.
-                    mBackupHandler.removeMessages(MSG_TIMEOUT);
+                        // Because the PMBA is a local instance, it has already executed its
+                        // backup callback and returned.  Blow away the lingering (spurious)
+                        // pending timeout message for it.
+                        mBackupHandler.removeMessages(MSG_TIMEOUT);
+                    }
                 }
 
                 if (mStatus == BackupTransport.TRANSPORT_NOT_INITIALIZED) {
@@ -3066,6 +3090,7 @@
             if (DEBUG) Slog.d(TAG, "invokeAgentForBackup on " + packageName);
             addBackupTrace("invoking " + packageName);
 
+            File blankStateName = new File(mStateDir, "blank_state");
             mSavedStateName = new File(mStateDir, packageName);
             mBackupDataName = new File(mDataDir, packageName + ".data");
             mNewStateName = new File(mStateDir, packageName + ".new");
@@ -3088,9 +3113,10 @@
                 }
 
                 // In a full backup, we pass a null ParcelFileDescriptor as
-                // the saved-state "file". This is by definition an incremental,
-                // so we build a saved state file to pass.
-                mSavedState = ParcelFileDescriptor.open(mSavedStateName,
+                // the saved-state "file". For key/value backups we pass the old state if
+                // an incremental backup is required, and a blank state otherwise.
+                mSavedState = ParcelFileDescriptor.open(
+                        mNonIncremental ? blankStateName : mSavedStateName,
                         ParcelFileDescriptor.MODE_READ_ONLY |
                         ParcelFileDescriptor.MODE_CREATE);  // Make an empty file if necessary
 
@@ -3120,6 +3146,10 @@
                         e.toString());
                 agentErrorCleanup();
                 return BackupTransport.AGENT_ERROR;
+            } finally {
+                if (mNonIncremental) {
+                    blankStateName.delete();
+                }
             }
 
             // At this point the agent is off and running.  The next thing to happen will
diff --git a/services/backup/java/com/android/server/backup/Trampoline.java b/services/backup/java/com/android/server/backup/Trampoline.java
index 312b878..d677f5e 100644
--- a/services/backup/java/com/android/server/backup/Trampoline.java
+++ b/services/backup/java/com/android/server/backup/Trampoline.java
@@ -338,9 +338,10 @@
     }
 
     @Override
-    public int requestBackup(String[] packages, IBackupObserver observer) throws RemoteException {
+    public int requestBackup(String[] packages, IBackupObserver observer, int flags)
+            throws RemoteException {
         BackupManagerService svc = mService;
-        return (svc != null) ? svc.requestBackup(packages, observer) : null;
+        return (svc != null) ? svc.requestBackup(packages, observer, flags) : null;
     }
 
     @Override
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index ccc6a95..d28da6a 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -68,6 +68,7 @@
 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
+import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
@@ -21067,6 +21068,14 @@
                         "Cannot move system application");
             }
 
+            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
+            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
+                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
+            if (isInternalStorage && !allow3rdPartyOnInternal) {
+                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
+                        "3rd party apps are not allowed on internal storage");
+            }
+
             if (pkg.applicationInfo.isExternalAsec()) {
                 currentAsec = true;
                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
diff --git a/services/core/java/com/android/server/vr/CompatibilityDisplay.java b/services/core/java/com/android/server/vr/CompatibilityDisplay.java
new file mode 100644
index 0000000..15edaaf
--- /dev/null
+++ b/services/core/java/com/android/server/vr/CompatibilityDisplay.java
@@ -0,0 +1,119 @@
+
+package com.android.server.vr;
+
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.service.vr.IVrStateCallbacks;
+import android.service.vr.IVrManager;
+import android.util.Log;
+
+import com.android.server.vr.VrManagerService;
+
+/**
+ * Creates a 2D Virtual Display while VR Mode is enabled. This display will be used to run and
+ * render 2D app within a VR experience. For example, bringing up the 2D calculator app in VR.
+ */
+class CompatibilityDisplay {
+    private final static String TAG = "CompatDisplay";
+    private final static boolean DEBUG = false;
+
+    // TODO: Go over these values and figure out what is best
+    private final static int HEIGHT = 960;
+    private final static int WIDTH = 720;
+    private final static int DPI = 320;
+
+    private final DisplayManager mDisplayManager;
+    private final IVrManager mVrManager;
+
+    // TODO: Lock initially created when VrStateCallback was connected through Binder. This may not
+    // be necessary with the direct access to VrManager.
+    private final Object vdLock = new Object();
+
+    private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
+        @Override
+        public void onVrStateChanged(boolean enabled) {
+            if (enabled != mIsVrModeEnabled) {
+                mIsVrModeEnabled = enabled;
+                if (enabled) {
+                    // TODO: Consider not creating the display until ActivityManager needs one on
+                    // which to display a 2D application.
+                    startVirtualDisplay();
+                } else {
+                    stopVirtualDisplay();
+                }
+            }
+        }
+    };
+
+    private VirtualDisplay mVirtualDisplay;
+    private boolean mIsVrModeEnabled;
+
+    public CompatibilityDisplay(DisplayManager displayManager, IVrManager vrManager) {
+        mDisplayManager = displayManager;
+        mVrManager = vrManager;
+    }
+
+    /**
+     * Initializes the compabilitiy display by listening to VR mode changes.
+     */
+    public void init() {
+        startVrModeListener();
+    }
+
+    private void startVrModeListener() {
+        if (mVrManager != null) {
+            try {
+                mVrManager.registerListener(mVrStateCallbacks);
+            } catch (RemoteException e) {
+                Log.e(TAG, "Could not register VR State listener.", e);
+            }
+        }
+    }
+
+    private void startVirtualDisplay() {
+        if (DEBUG) {
+            Log.d(TAG, "Starting VD, DM:" + mDisplayManager);
+        }
+
+        if (mDisplayManager == null) {
+            Log.w(TAG, "Cannot create virtual display because mDisplayManager == null");
+            return;
+        }
+
+        synchronized (vdLock) {
+            if (mVirtualDisplay != null) {
+                Log.e(TAG, "Starting the virtual display when one already exists", new Exception());
+                return;
+            }
+
+            mVirtualDisplay = mDisplayManager.createVirtualDisplay("VR 2D Display", WIDTH, HEIGHT,
+                    DPI,
+                    null /* Surface */, 0 /* flags */);
+        }
+
+        if (DEBUG) {
+            Log.d(TAG, "VD created: " + mVirtualDisplay);
+        }
+    }
+
+    private void stopVirtualDisplay() {
+        if (DEBUG) {
+            Log.i(TAG, "Santos, stopping VD");
+        }
+
+        synchronized (vdLock) {
+            if (mVirtualDisplay != null) {
+                mVirtualDisplay.release();
+                mVirtualDisplay = null;
+            }
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/vr/VrManagerService.java b/services/core/java/com/android/server/vr/VrManagerService.java
index 84cf0c6..57587b0 100644
--- a/services/core/java/com/android/server/vr/VrManagerService.java
+++ b/services/core/java/com/android/server/vr/VrManagerService.java
@@ -31,6 +31,7 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.hardware.display.DisplayManager;
 import android.os.Binder;
 import android.os.Handler;
 import android.os.IBinder;
@@ -51,6 +52,7 @@
 import android.util.ArraySet;
 import android.util.Slog;
 import android.util.SparseArray;
+
 import com.android.internal.R;
 import com.android.server.LocalServices;
 import com.android.server.SystemConfig;
@@ -136,6 +138,7 @@
     private final NotificationAccessManager mNotifAccessManager = new NotificationAccessManager();
     /** Tracks the state of the screen and keyguard UI.*/
     private int mSystemSleepFlags = FLAG_NONE;
+    private CompatibilityDisplay mCompatibilityDisplay;
 
     private static final int MSG_VR_STATE_CHANGE = 0;
     private static final int MSG_PENDING_VR_STATE_CHANGE = 1;
@@ -493,6 +496,11 @@
 
                 mComponentObserver.rebuildAll();
             }
+
+            DisplayManager dm =
+                    (DisplayManager) getContext().getSystemService(Context.DISPLAY_SERVICE);
+            mCompatibilityDisplay = new CompatibilityDisplay(dm, mVrManager);
+            mCompatibilityDisplay.init();
         } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
             synchronized (mLock) {
                 mVrModeAllowed = true;
diff --git a/tools/aapt2/ConfigDescription.cpp b/tools/aapt2/ConfigDescription.cpp
index b1bd401..c97d6d4 100644
--- a/tools/aapt2/ConfigDescription.cpp
+++ b/tools/aapt2/ConfigDescription.cpp
@@ -20,15 +20,16 @@
 #include <vector>
 
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/StringPiece.h"
 
 #include "Locale.h"
 #include "SdkConstants.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
-namespace aapt {
-
 using android::ResTable_config;
+using android::StringPiece;
+
+namespace aapt {
 
 static const char* kWildcardName = "any";
 
diff --git a/tools/aapt2/ConfigDescription.h b/tools/aapt2/ConfigDescription.h
index 97d0f38..65c9617 100644
--- a/tools/aapt2/ConfigDescription.h
+++ b/tools/aapt2/ConfigDescription.h
@@ -20,8 +20,7 @@
 #include <ostream>
 
 #include "androidfw/ResourceTypes.h"
-
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
 
 namespace aapt {
 
@@ -42,7 +41,7 @@
    * The resulting configuration has the appropriate sdkVersion defined
    * for backwards compatibility.
    */
-  static bool Parse(const StringPiece& str, ConfigDescription* out = nullptr);
+  static bool Parse(const android::StringPiece& str, ConfigDescription* out = nullptr);
 
   /**
    * If the configuration uses an axis that was added after
diff --git a/tools/aapt2/ConfigDescription_test.cpp b/tools/aapt2/ConfigDescription_test.cpp
index 1d22ce0..7933568 100644
--- a/tools/aapt2/ConfigDescription_test.cpp
+++ b/tools/aapt2/ConfigDescription_test.cpp
@@ -18,9 +18,12 @@
 
 #include <string>
 
+#include "androidfw/StringPiece.h"
+
 #include "SdkConstants.h"
 #include "test/Test.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
diff --git a/tools/aapt2/Diagnostics.h b/tools/aapt2/Diagnostics.h
index 5bc86a9..50e8b33 100644
--- a/tools/aapt2/Diagnostics.h
+++ b/tools/aapt2/Diagnostics.h
@@ -22,9 +22,9 @@
 #include <string>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 
 #include "Source.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
 namespace aapt {
@@ -38,7 +38,7 @@
  public:
   DiagMessage() = default;
 
-  explicit DiagMessage(const StringPiece& src) : source_(src) {}
+  explicit DiagMessage(const android::StringPiece& src) : source_(src) {}
 
   explicit DiagMessage(const Source& src) : source_(src) {}
 
@@ -59,6 +59,12 @@
   std::stringstream message_;
 };
 
+template <>
+inline DiagMessage& DiagMessage::operator<<(const ::std::u16string& value) {
+  message_ << android::StringPiece16(value);
+  return *this;
+}
+
 struct IDiagnostics {
   virtual ~IDiagnostics() = default;
 
diff --git a/tools/aapt2/Flags.cpp b/tools/aapt2/Flags.cpp
index c98cd37..84977ab 100644
--- a/tools/aapt2/Flags.cpp
+++ b/tools/aapt2/Flags.cpp
@@ -21,20 +21,22 @@
 #include <string>
 #include <vector>
 
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
+
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 Flags& Flags::RequiredFlag(const StringPiece& name,
                            const StringPiece& description, std::string* value) {
   auto func = [value](const StringPiece& arg) -> bool {
-    *value = arg.ToString();
+    *value = arg.to_string();
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, true, 1, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, true, 1, false});
   return *this;
 }
 
@@ -42,12 +44,11 @@
                                const StringPiece& description,
                                std::vector<std::string>* value) {
   auto func = [value](const StringPiece& arg) -> bool {
-    value->push_back(arg.ToString());
+    value->push_back(arg.to_string());
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, true, 1, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, true, 1, false});
   return *this;
 }
 
@@ -55,12 +56,11 @@
                            const StringPiece& description,
                            Maybe<std::string>* value) {
   auto func = [value](const StringPiece& arg) -> bool {
-    *value = arg.ToString();
+    *value = arg.to_string();
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, false, 1, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, false, 1, false});
   return *this;
 }
 
@@ -68,12 +68,11 @@
                                const StringPiece& description,
                                std::vector<std::string>* value) {
   auto func = [value](const StringPiece& arg) -> bool {
-    value->push_back(arg.ToString());
+    value->push_back(arg.to_string());
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, false, 1, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, false, 1, false});
   return *this;
 }
 
@@ -81,12 +80,11 @@
                                const StringPiece& description,
                                std::unordered_set<std::string>* value) {
   auto func = [value](const StringPiece& arg) -> bool {
-    value->insert(arg.ToString());
+    value->insert(arg.to_string());
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, false, 1, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, false, 1, false});
   return *this;
 }
 
@@ -97,8 +95,7 @@
     return true;
   };
 
-  flags_.push_back(
-      Flag{name.ToString(), description.ToString(), func, false, 0, false});
+  flags_.push_back(Flag{name.to_string(), description.to_string(), func, false, 0, false});
   return *this;
 }
 
@@ -141,7 +138,7 @@
   for (size_t i = 0; i < args.size(); i++) {
     StringPiece arg = args[i];
     if (*(arg.data()) != '-') {
-      args_.push_back(arg.ToString());
+      args_.push_back(arg.to_string());
       continue;
     }
 
diff --git a/tools/aapt2/Flags.h b/tools/aapt2/Flags.h
index 9feff6b..3b3ae71 100644
--- a/tools/aapt2/Flags.h
+++ b/tools/aapt2/Flags.h
@@ -23,32 +23,30 @@
 #include <unordered_set>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
+
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
 class Flags {
  public:
-  Flags& RequiredFlag(const StringPiece& name, const StringPiece& description,
+  Flags& RequiredFlag(const android::StringPiece& name, const android::StringPiece& description,
                       std::string* value);
-  Flags& RequiredFlagList(const StringPiece& name,
-                          const StringPiece& description,
+  Flags& RequiredFlagList(const android::StringPiece& name, const android::StringPiece& description,
                           std::vector<std::string>* value);
-  Flags& OptionalFlag(const StringPiece& name, const StringPiece& description,
+  Flags& OptionalFlag(const android::StringPiece& name, const android::StringPiece& description,
                       Maybe<std::string>* value);
-  Flags& OptionalFlagList(const StringPiece& name,
-                          const StringPiece& description,
+  Flags& OptionalFlagList(const android::StringPiece& name, const android::StringPiece& description,
                           std::vector<std::string>* value);
-  Flags& OptionalFlagList(const StringPiece& name,
-                          const StringPiece& description,
+  Flags& OptionalFlagList(const android::StringPiece& name, const android::StringPiece& description,
                           std::unordered_set<std::string>* value);
-  Flags& OptionalSwitch(const StringPiece& name, const StringPiece& description,
+  Flags& OptionalSwitch(const android::StringPiece& name, const android::StringPiece& description,
                         bool* value);
 
-  void Usage(const StringPiece& command, std::ostream* out);
+  void Usage(const android::StringPiece& command, std::ostream* out);
 
-  bool Parse(const StringPiece& command, const std::vector<StringPiece>& args,
+  bool Parse(const android::StringPiece& command, const std::vector<android::StringPiece>& args,
              std::ostream* outError);
 
   const std::vector<std::string>& GetArgs();
@@ -57,7 +55,7 @@
   struct Flag {
     std::string name;
     std::string description;
-    std::function<bool(const StringPiece& value)> action;
+    std::function<bool(const android::StringPiece& value)> action;
     bool required;
     size_t num_args;
 
diff --git a/tools/aapt2/Locale.cpp b/tools/aapt2/Locale.cpp
index 78f56c7a..7664fac 100644
--- a/tools/aapt2/Locale.cpp
+++ b/tools/aapt2/Locale.cpp
@@ -72,7 +72,7 @@
   return std::all_of(std::begin(str), std::end(str), ::isdigit);
 }
 
-bool LocaleValue::InitFromFilterString(const StringPiece& str) {
+bool LocaleValue::InitFromFilterString(const android::StringPiece& str) {
   // A locale (as specified in the filter) is an underscore separated name such
   // as "en_US", "en_Latn_US", or "en_US_POSIX".
   std::vector<std::string> parts = util::SplitAndLowercase(str, '_');
diff --git a/tools/aapt2/Locale.h b/tools/aapt2/Locale.h
index fc6c448..3d73b2e 100644
--- a/tools/aapt2/Locale.h
+++ b/tools/aapt2/Locale.h
@@ -21,8 +21,7 @@
 #include <vector>
 
 #include "androidfw/ResourceTypes.h"
-
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
 
 namespace aapt {
 
@@ -40,7 +39,7 @@
   /**
    * Initialize this LocaleValue from a config string.
    */
-  bool InitFromFilterString(const StringPiece& config);
+  bool InitFromFilterString(const android::StringPiece& config);
 
   /**
    * Initialize this LocaleValue from parts of a vector.
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index a2b216d..74d4019 100644
--- a/tools/aapt2/Main.cpp
+++ b/tools/aapt2/Main.cpp
@@ -17,7 +17,7 @@
 #include <iostream>
 #include <vector>
 
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
 
 namespace aapt {
 
@@ -33,10 +33,10 @@
   return 0;
 }
 
-extern int Compile(const std::vector<StringPiece>& args);
-extern int Link(const std::vector<StringPiece>& args);
-extern int Dump(const std::vector<StringPiece>& args);
-extern int Diff(const std::vector<StringPiece>& args);
+extern int Compile(const std::vector<android::StringPiece>& args);
+extern int Link(const std::vector<android::StringPiece>& args);
+extern int Dump(const std::vector<android::StringPiece>& args);
+extern int Diff(const std::vector<android::StringPiece>& args);
 
 }  // namespace aapt
 
@@ -45,12 +45,12 @@
     argv += 1;
     argc -= 1;
 
-    std::vector<aapt::StringPiece> args;
+    std::vector<android::StringPiece> args;
     for (int i = 1; i < argc; i++) {
       args.push_back(argv[i]);
     }
 
-    aapt::StringPiece command(argv[0]);
+    android::StringPiece command(argv[0]);
     if (command == "compile" || command == "c") {
       return aapt::Compile(args);
     } else if (command == "link" || command == "l") {
diff --git a/tools/aapt2/Resource.cpp b/tools/aapt2/Resource.cpp
index 3eef7aa7..fdabce1 100644
--- a/tools/aapt2/Resource.cpp
+++ b/tools/aapt2/Resource.cpp
@@ -19,6 +19,8 @@
 #include <map>
 #include <string>
 
+using android::StringPiece;
+
 namespace aapt {
 
 StringPiece ToString(ResourceType type) {
diff --git a/tools/aapt2/Resource.h b/tools/aapt2/Resource.h
index 13330b5..1950ea3 100644
--- a/tools/aapt2/Resource.h
+++ b/tools/aapt2/Resource.h
@@ -24,11 +24,11 @@
 #include <tuple>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
 #include "utils/JenkinsHash.h"
 
 #include "ConfigDescription.h"
 #include "Source.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -63,13 +63,13 @@
   kXml,
 };
 
-StringPiece ToString(ResourceType type);
+android::StringPiece ToString(ResourceType type);
 
 /**
  * Returns a pointer to a valid ResourceType, or nullptr if
  * the string was invalid.
  */
-const ResourceType* ParseResourceType(const StringPiece& str);
+const ResourceType* ParseResourceType(const android::StringPiece& str);
 
 /**
  * A resource's name. This can uniquely identify
@@ -81,7 +81,7 @@
   std::string entry;
 
   ResourceName() = default;
-  ResourceName(const StringPiece& p, ResourceType t, const StringPiece& e);
+  ResourceName(const android::StringPiece& p, ResourceType t, const android::StringPiece& e);
 
   int compare(const ResourceName& other) const;
 
@@ -96,15 +96,15 @@
  * of the original string.
  */
 struct ResourceNameRef {
-  StringPiece package;
+  android::StringPiece package;
   ResourceType type = ResourceType::kRaw;
-  StringPiece entry;
+  android::StringPiece entry;
 
   ResourceNameRef() = default;
   ResourceNameRef(const ResourceNameRef&) = default;
   ResourceNameRef(ResourceNameRef&&) = default;
   ResourceNameRef(const ResourceName& rhs);  // NOLINT(implicit)
-  ResourceNameRef(const StringPiece& p, ResourceType t, const StringPiece& e);
+  ResourceNameRef(const android::StringPiece& p, ResourceType t, const android::StringPiece& e);
   ResourceNameRef& operator=(const ResourceNameRef& rhs) = default;
   ResourceNameRef& operator=(ResourceNameRef&& rhs) = default;
   ResourceNameRef& operator=(const ResourceName& rhs);
@@ -258,9 +258,9 @@
 // ResourceName implementation.
 //
 
-inline ResourceName::ResourceName(const StringPiece& p, ResourceType t,
-                                  const StringPiece& e)
-    : package(p.ToString()), type(t), entry(e.ToString()) {}
+inline ResourceName::ResourceName(const android::StringPiece& p, ResourceType t,
+                                  const android::StringPiece& e)
+    : package(p.to_string()), type(t), entry(e.to_string()) {}
 
 inline int ResourceName::compare(const ResourceName& other) const {
   int cmp = package.compare(other.package);
@@ -311,8 +311,8 @@
 inline ResourceNameRef::ResourceNameRef(const ResourceName& rhs)
     : package(rhs.package), type(rhs.type), entry(rhs.entry) {}
 
-inline ResourceNameRef::ResourceNameRef(const StringPiece& p, ResourceType t,
-                                        const StringPiece& e)
+inline ResourceNameRef::ResourceNameRef(const android::StringPiece& p, ResourceType t,
+                                        const android::StringPiece& e)
     : package(p), type(t), entry(e) {}
 
 inline ResourceNameRef& ResourceNameRef::operator=(const ResourceName& rhs) {
diff --git a/tools/aapt2/ResourceParser.cpp b/tools/aapt2/ResourceParser.cpp
index b16def4..79379fe 100644
--- a/tools/aapt2/ResourceParser.cpp
+++ b/tools/aapt2/ResourceParser.cpp
@@ -29,6 +29,8 @@
 #include "util/Util.h"
 #include "xml/XmlPullParser.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 constexpr const char* sXliffNamespaceUri =
@@ -101,7 +103,7 @@
   StringPiece trimmed_comment = util::TrimWhitespace(res->comment);
   if (trimmed_comment.size() != res->comment.size()) {
     // Only if there was a change do we re-assign.
-    res->comment = trimmed_comment.ToString();
+    res->comment = trimmed_comment.to_string();
   }
 
   if (res->symbol_state) {
@@ -297,7 +299,7 @@
     // Extract the product name if it exists.
     if (Maybe<StringPiece> maybe_product =
             xml::FindNonEmptyAttribute(parser, "product")) {
-      parsed_resource.product = maybe_product.value().ToString();
+      parsed_resource.product = maybe_product.value().to_string();
     }
 
     // Parse the resource regardless of product.
@@ -383,7 +385,7 @@
     // Items have their type encoded in the type attribute.
     if (Maybe<StringPiece> maybe_type =
             xml::FindNonEmptyAttribute(parser, "type")) {
-      resource_type = maybe_type.value().ToString();
+      resource_type = maybe_type.value().to_string();
     } else {
       diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
                    << "<item> must have a 'type' attribute");
@@ -419,7 +421,7 @@
     }
 
     out_resource->name.type = ResourceType::kId;
-    out_resource->name.entry = maybe_name.value().ToString();
+    out_resource->name.entry = maybe_name.value().to_string();
     out_resource->value = util::make_unique<Id>();
     return true;
   }
@@ -436,7 +438,7 @@
     }
 
     out_resource->name.type = item_iter->second.type;
-    out_resource->name.entry = maybe_name.value().ToString();
+    out_resource->name.entry = maybe_name.value().to_string();
 
     // Only use the implicit format for this type if it wasn't overridden.
     if (!resource_format) {
@@ -461,7 +463,7 @@
         return false;
       }
 
-      out_resource->name.entry = maybe_name.value().ToString();
+      out_resource->name.entry = maybe_name.value().to_string();
     }
 
     // Call the associated parse method. The type will be filled in by the
@@ -484,7 +486,7 @@
     }
 
     out_resource->name.type = *parsed_type;
-    out_resource->name.entry = maybe_name.value().ToString();
+    out_resource->name.entry = maybe_name.value().to_string();
     out_resource->value =
         ParseXml(parser, android::ResTable_map::TYPE_REFERENCE, kNoRawString);
     if (!out_resource->value) {
@@ -718,7 +720,7 @@
   const size_t depth = parser->depth();
   while (xml::XmlPullParser::NextChildNode(parser, depth)) {
     if (parser->event() == xml::XmlPullParser::Event::kComment) {
-      comment = util::TrimWhitespace(parser->comment()).ToString();
+      comment = util::TrimWhitespace(parser->comment()).to_string();
       continue;
     } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
       // Skip text.
@@ -754,7 +756,7 @@
 
       ParsedResource child_resource;
       child_resource.name.type = *parsed_type;
-      child_resource.name.entry = maybe_name.value().ToString();
+      child_resource.name.entry = maybe_name.value().to_string();
       child_resource.id = next_id;
       child_resource.comment = std::move(comment);
       child_resource.source = item_source;
@@ -899,7 +901,7 @@
   const size_t depth = parser->depth();
   while (xml::XmlPullParser::NextChildNode(parser, depth)) {
     if (parser->event() == xml::XmlPullParser::Event::kComment) {
-      comment = util::TrimWhitespace(parser->comment()).ToString();
+      comment = util::TrimWhitespace(parser->comment()).to_string();
       continue;
     } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
       // Skip text.
@@ -1288,7 +1290,7 @@
   const size_t depth = parser->depth();
   while (xml::XmlPullParser::NextChildNode(parser, depth)) {
     if (parser->event() == xml::XmlPullParser::Event::kComment) {
-      comment = util::TrimWhitespace(parser->comment()).ToString();
+      comment = util::TrimWhitespace(parser->comment()).to_string();
       continue;
     } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
       // Ignore text.
diff --git a/tools/aapt2/ResourceParser.h b/tools/aapt2/ResourceParser.h
index 11b1e5b..c12dacf 100644
--- a/tools/aapt2/ResourceParser.h
+++ b/tools/aapt2/ResourceParser.h
@@ -20,6 +20,7 @@
 #include <memory>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 
 #include "ConfigDescription.h"
 #include "Diagnostics.h"
@@ -27,7 +28,6 @@
 #include "ResourceValues.h"
 #include "StringPool.h"
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 #include "xml/XmlPullParser.h"
 
 namespace aapt {
@@ -101,7 +101,7 @@
   bool ParseAttrImpl(xml::XmlPullParser* parser, ParsedResource* out_resource,
                      bool weak);
   Maybe<Attribute::Symbol> ParseEnumOrFlagItem(xml::XmlPullParser* parser,
-                                               const StringPiece& tag);
+                                               const android::StringPiece& tag);
   bool ParseStyle(xml::XmlPullParser* parser, ParsedResource* out_resource);
   bool ParseStyleItem(xml::XmlPullParser* parser, Style* style);
   bool ParseDeclareStyleable(xml::XmlPullParser* parser,
diff --git a/tools/aapt2/ResourceParser_test.cpp b/tools/aapt2/ResourceParser_test.cpp
index 2463911..5762fb0 100644
--- a/tools/aapt2/ResourceParser_test.cpp
+++ b/tools/aapt2/ResourceParser_test.cpp
@@ -25,6 +25,8 @@
 #include "test/Test.h"
 #include "xml/XmlPullParser.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 constexpr const char* kXmlPreamble =
diff --git a/tools/aapt2/ResourceTable.cpp b/tools/aapt2/ResourceTable.cpp
index 4e6a50a..dd78750 100644
--- a/tools/aapt2/ResourceTable.cpp
+++ b/tools/aapt2/ResourceTable.cpp
@@ -28,6 +28,8 @@
 #include <string>
 #include <tuple>
 
+using android::StringPiece;
+
 namespace aapt {
 
 static bool less_than_type(const std::unique_ptr<ResourceTableType>& lhs,
@@ -87,7 +89,7 @@
 
   std::unique_ptr<ResourceTablePackage> new_package =
       util::make_unique<ResourceTablePackage>();
-  new_package->name = name.ToString();
+  new_package->name = name.to_string();
   return packages.emplace(iter, std::move(new_package))->get();
 }
 
diff --git a/tools/aapt2/ResourceTable.h b/tools/aapt2/ResourceTable.h
index a0c3217..0fe966c 100644
--- a/tools/aapt2/ResourceTable.h
+++ b/tools/aapt2/ResourceTable.h
@@ -25,7 +25,9 @@
 #include "StringPool.h"
 #include "io/File.h"
 
-#include <android-base/macros.h>
+#include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
+
 #include <functional>
 #include <map>
 #include <memory>
@@ -68,9 +70,8 @@
    */
   std::unique_ptr<Value> value;
 
-  ResourceConfigValue(const ConfigDescription& config,
-                      const StringPiece& product)
-      : config(config), product(product.ToString()) {}
+  ResourceConfigValue(const ConfigDescription& config, const android::StringPiece& product)
+      : config(config), product(product.to_string()) {}
 
  private:
   DISALLOW_COPY_AND_ASSIGN(ResourceConfigValue);
@@ -105,13 +106,13 @@
    */
   std::vector<std::unique_ptr<ResourceConfigValue>> values;
 
-  explicit ResourceEntry(const StringPiece& name) : name(name.ToString()) {}
+  explicit ResourceEntry(const android::StringPiece& name) : name(name.to_string()) {}
 
   ResourceConfigValue* FindValue(const ConfigDescription& config);
   ResourceConfigValue* FindValue(const ConfigDescription& config,
-                                 const StringPiece& product);
+                                 const android::StringPiece& product);
   ResourceConfigValue* FindOrCreateValue(const ConfigDescription& config,
-                                         const StringPiece& product);
+                                         const android::StringPiece& product);
   std::vector<ResourceConfigValue*> findAllValues(
       const ConfigDescription& config);
   std::vector<ResourceConfigValue*> FindValuesIf(
@@ -150,8 +151,8 @@
 
   explicit ResourceTableType(const ResourceType type) : type(type) {}
 
-  ResourceEntry* FindEntry(const StringPiece& name);
-  ResourceEntry* FindOrCreateEntry(const StringPiece& name);
+  ResourceEntry* FindEntry(const android::StringPiece& name);
+  ResourceEntry* FindOrCreateEntry(const android::StringPiece& name);
 
  private:
   DISALLOW_COPY_AND_ASSIGN(ResourceTableType);
@@ -195,22 +196,19 @@
                                                Value* incoming);
 
   bool AddResource(const ResourceNameRef& name, const ConfigDescription& config,
-                   const StringPiece& product, std::unique_ptr<Value> value,
+                   const android::StringPiece& product, std::unique_ptr<Value> value,
                    IDiagnostics* diag);
 
   bool AddResource(const ResourceNameRef& name, const ResourceId& res_id,
-                   const ConfigDescription& config, const StringPiece& product,
+                   const ConfigDescription& config, const android::StringPiece& product,
                    std::unique_ptr<Value> value, IDiagnostics* diag);
 
-  bool AddFileReference(const ResourceNameRef& name,
-                        const ConfigDescription& config, const Source& source,
-                        const StringPiece& path, IDiagnostics* diag);
+  bool AddFileReference(const ResourceNameRef& name, const ConfigDescription& config,
+                        const Source& source, const android::StringPiece& path, IDiagnostics* diag);
 
-  bool AddFileReferenceAllowMangled(const ResourceNameRef& name,
-                                    const ConfigDescription& config,
-                                    const Source& source,
-                                    const StringPiece& path, io::IFile* file,
-                                    IDiagnostics* diag);
+  bool AddFileReferenceAllowMangled(const ResourceNameRef& name, const ConfigDescription& config,
+                                    const Source& source, const android::StringPiece& path,
+                                    io::IFile* file, IDiagnostics* diag);
 
   /**
    * Same as AddResource, but doesn't verify the validity of the name. This is
@@ -219,18 +217,13 @@
    * mangled
    * names.
    */
-  bool AddResourceAllowMangled(const ResourceNameRef& name,
-                               const ConfigDescription& config,
-                               const StringPiece& product,
-                               std::unique_ptr<Value> value,
+  bool AddResourceAllowMangled(const ResourceNameRef& name, const ConfigDescription& config,
+                               const android::StringPiece& product, std::unique_ptr<Value> value,
                                IDiagnostics* diag);
 
-  bool AddResourceAllowMangled(const ResourceNameRef& name,
-                               const ResourceId& id,
-                               const ConfigDescription& config,
-                               const StringPiece& product,
-                               std::unique_ptr<Value> value,
-                               IDiagnostics* diag);
+  bool AddResourceAllowMangled(const ResourceNameRef& name, const ResourceId& id,
+                               const ConfigDescription& config, const android::StringPiece& product,
+                               std::unique_ptr<Value> value, IDiagnostics* diag);
 
   bool SetSymbolState(const ResourceNameRef& name, const ResourceId& res_id,
                       const Symbol& symbol, IDiagnostics* diag);
@@ -273,28 +266,23 @@
    * represent the
    * 'current' package before it is known to the ResourceTable.
    */
-  ResourceTablePackage* FindPackage(const StringPiece& name);
+  ResourceTablePackage* FindPackage(const android::StringPiece& name);
 
   ResourceTablePackage* FindPackageById(uint8_t id);
 
-  ResourceTablePackage* CreatePackage(const StringPiece& name,
-                                      Maybe<uint8_t> id = {});
+  ResourceTablePackage* CreatePackage(const android::StringPiece& name, Maybe<uint8_t> id = {});
 
  private:
-  ResourceTablePackage* FindOrCreatePackage(const StringPiece& name);
+  ResourceTablePackage* FindOrCreatePackage(const android::StringPiece& name);
 
   bool AddResourceImpl(const ResourceNameRef& name, const ResourceId& res_id,
-                       const ConfigDescription& config,
-                       const StringPiece& product, std::unique_ptr<Value> value,
-                       const char* valid_chars,
-                       const CollisionResolverFunc& conflict_resolver,
-                       IDiagnostics* diag);
+                       const ConfigDescription& config, const android::StringPiece& product,
+                       std::unique_ptr<Value> value, const char* valid_chars,
+                       const CollisionResolverFunc& conflict_resolver, IDiagnostics* diag);
 
-  bool AddFileReferenceImpl(const ResourceNameRef& name,
-                            const ConfigDescription& config,
-                            const Source& source, const StringPiece& path,
-                            io::IFile* file, const char* valid_chars,
-                            IDiagnostics* diag);
+  bool AddFileReferenceImpl(const ResourceNameRef& name, const ConfigDescription& config,
+                            const Source& source, const android::StringPiece& path, io::IFile* file,
+                            const char* valid_chars, IDiagnostics* diag);
 
   bool SetSymbolStateImpl(const ResourceNameRef& name, const ResourceId& res_id,
                           const Symbol& symbol, const char* valid_chars,
diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp
index fce9b33..1123967 100644
--- a/tools/aapt2/ResourceUtils.cpp
+++ b/tools/aapt2/ResourceUtils.cpp
@@ -26,6 +26,9 @@
 #include "util/Files.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+using android::StringPiece16;
+
 namespace aapt {
 namespace ResourceUtils {
 
@@ -59,7 +62,7 @@
     name_out.entry =
         util::Utf16ToUtf8(StringPiece16(name_in.name, name_in.nameLen));
   } else if (name_in.name8) {
-    name_out.entry = StringPiece(name_in.name8, name_in.nameLen).ToString();
+    name_out.entry.assign(name_in.name8, name_in.nameLen);
   } else {
     return {};
   }
@@ -303,9 +306,7 @@
     p++;
   }
 
-  ref.name =
-      ResourceName(package.ToString(), ResourceType::kAttr,
-                   name.empty() ? trimmed_str.ToString() : name.ToString());
+  ref.name = ResourceName(package, ResourceType::kAttr, name.empty() ? trimmed_str : name);
   return Maybe<Reference>(std::move(ref));
 }
 
diff --git a/tools/aapt2/ResourceUtils.h b/tools/aapt2/ResourceUtils.h
index 9766f6a..bd3a8e3 100644
--- a/tools/aapt2/ResourceUtils.h
+++ b/tools/aapt2/ResourceUtils.h
@@ -20,10 +20,11 @@
 #include <functional>
 #include <memory>
 
+#include "androidfw/StringPiece.h"
+
 #include "NameMangler.h"
 #include "Resource.h"
 #include "ResourceValues.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 namespace ResourceUtils {
@@ -37,8 +38,8 @@
  * individual extracted piece to verify that the pieces are valid.
  * Returns false if there was no package but a ':' was present.
  */
-bool ExtractResourceName(const StringPiece& str, StringPiece* out_package,
-                         StringPiece* out_type, StringPiece* out_entry);
+bool ExtractResourceName(const android::StringPiece& str, android::StringPiece* out_package,
+                         android::StringPiece* out_type, android::StringPiece* out_entry);
 
 /**
  * Returns true if the string was parsed as a resource name
@@ -46,7 +47,7 @@
  * `out_resource` set to the parsed resource name and `out_private` set to true
  * if a '*' prefix was present.
  */
-bool ParseResourceName(const StringPiece& str, ResourceNameRef* out_resource,
+bool ParseResourceName(const android::StringPiece& str, ResourceNameRef* out_resource,
                        bool* out_private = nullptr);
 
 /*
@@ -57,28 +58,27 @@
  * If '+' was present in the reference, `out_create` is set to true.
  * If '*' was present in the reference, `out_private` is set to true.
  */
-bool ParseReference(const StringPiece& str, ResourceNameRef* out_reference,
+bool ParseReference(const android::StringPiece& str, ResourceNameRef* out_reference,
                     bool* out_create = nullptr, bool* out_private = nullptr);
 
 /*
  * Returns true if the string is in the form of a resource reference
  * (@[+][package:]type/name).
  */
-bool IsReference(const StringPiece& str);
+bool IsReference(const android::StringPiece& str);
 
 /*
  * Returns true if the string was parsed as an attribute reference
  * (?[package:][type/]name),
  * with `out_reference` set to the parsed reference.
  */
-bool ParseAttributeReference(const StringPiece& str,
-                             ResourceNameRef* out_reference);
+bool ParseAttributeReference(const android::StringPiece& str, ResourceNameRef* out_reference);
 
 /**
  * Returns true if the string is in the form of an attribute
  * reference(?[package:][type/]name).
  */
-bool IsAttributeReference(const StringPiece& str);
+bool IsAttributeReference(const android::StringPiece& str);
 
 /**
  * Convert an android::ResTable::resource_name to an aapt::ResourceName struct.
@@ -90,22 +90,22 @@
  * Returns a boolean value if the string is equal to TRUE, true, True, FALSE,
  * false, or False.
  */
-Maybe<bool> ParseBool(const StringPiece& str);
+Maybe<bool> ParseBool(const android::StringPiece& str);
 
 /**
  * Returns a uint32_t if the string is an integer.
  */
-Maybe<uint32_t> ParseInt(const StringPiece& str);
+Maybe<uint32_t> ParseInt(const android::StringPiece& str);
 
 /**
  * Returns an ID if it the string represented a valid ID.
  */
-Maybe<ResourceId> ParseResourceId(const StringPiece& str);
+Maybe<ResourceId> ParseResourceId(const android::StringPiece& str);
 
 /**
  * Parses an SDK version, which can be an integer, or a letter from A-Z.
  */
-Maybe<int> ParseSdkVersion(const StringPiece& str);
+Maybe<int> ParseSdkVersion(const android::StringPiece& str);
 
 /*
  * Returns a Reference, or None Maybe instance if the string `str` was parsed as
@@ -118,8 +118,7 @@
  * ?[package:]style/<entry> or
  * <package>:[style/]<entry>
  */
-Maybe<Reference> ParseStyleParentReference(const StringPiece& str,
-                                           std::string* out_error);
+Maybe<Reference> ParseStyleParentReference(const android::StringPiece& str, std::string* out_error);
 
 /*
  * Returns a Reference if the string `str` was parsed as a valid XML attribute
@@ -128,7 +127,7 @@
  *
  * package:entry
  */
-Maybe<Reference> ParseXmlAttributeName(const StringPiece& str);
+Maybe<Reference> ParseXmlAttributeName(const android::StringPiece& str);
 
 /*
  * Returns a Reference object if the string was parsed as a resource or
@@ -137,52 +136,52 @@
  * if
  * the '+' was present in the string.
  */
-std::unique_ptr<Reference> TryParseReference(const StringPiece& str,
+std::unique_ptr<Reference> TryParseReference(const android::StringPiece& str,
                                              bool* out_create = nullptr);
 
 /*
  * Returns a BinaryPrimitve object representing @null or @empty if the string
  * was parsed as one.
  */
-std::unique_ptr<BinaryPrimitive> TryParseNullOrEmpty(const StringPiece& str);
+std::unique_ptr<BinaryPrimitive> TryParseNullOrEmpty(const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing a color if the string was parsed
  * as one.
  */
-std::unique_ptr<BinaryPrimitive> TryParseColor(const StringPiece& str);
+std::unique_ptr<BinaryPrimitive> TryParseColor(const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing a boolean if the string was
  * parsed as one.
  */
-std::unique_ptr<BinaryPrimitive> TryParseBool(const StringPiece& str);
+std::unique_ptr<BinaryPrimitive> TryParseBool(const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing an integer if the string was
  * parsed as one.
  */
-std::unique_ptr<BinaryPrimitive> TryParseInt(const StringPiece& str);
+std::unique_ptr<BinaryPrimitive> TryParseInt(const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing a floating point number
  * (float, dimension, etc) if the string was parsed as one.
  */
-std::unique_ptr<BinaryPrimitive> TryParseFloat(const StringPiece& str);
+std::unique_ptr<BinaryPrimitive> TryParseFloat(const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing an enum symbol if the string was
  * parsed as one.
  */
 std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr,
-                                                    const StringPiece& str);
+                                                    const android::StringPiece& str);
 
 /*
  * Returns a BinaryPrimitve object representing a flag symbol if the string was
  * parsed as one.
  */
 std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* enum_attr,
-                                                    const StringPiece& str);
+                                                    const android::StringPiece& str);
 /*
  * Try to convert a string to an Item for the given attribute. The attribute
  * will
@@ -191,11 +190,11 @@
  * reference to an ID that must be created (@+id/foo).
  */
 std::unique_ptr<Item> TryParseItemForAttribute(
-    const StringPiece& value, const Attribute* attr,
+    const android::StringPiece& value, const Attribute* attr,
     const std::function<void(const ResourceName&)>& on_create_reference = {});
 
 std::unique_ptr<Item> TryParseItemForAttribute(
-    const StringPiece& value, uint32_t type_mask,
+    const android::StringPiece& value, uint32_t type_mask,
     const std::function<void(const ResourceName&)>& on_create_reference = {});
 
 uint32_t AndroidTypeToAttributeTypeMask(uint16_t type);
diff --git a/tools/aapt2/ResourceUtils_test.cpp b/tools/aapt2/ResourceUtils_test.cpp
index f9c500b..048c692 100644
--- a/tools/aapt2/ResourceUtils_test.cpp
+++ b/tools/aapt2/ResourceUtils_test.cpp
@@ -48,8 +48,7 @@
   EXPECT_EQ(ResourceNameRef("android", ResourceType::kColor, "foo"), actual);
   EXPECT_TRUE(actual_priv);
 
-  EXPECT_FALSE(
-      ResourceUtils::ParseResourceName(StringPiece(), &actual, &actual_priv));
+  EXPECT_FALSE(ResourceUtils::ParseResourceName(android::StringPiece(), &actual, &actual_priv));
 }
 
 TEST(ResourceUtilsTest, ParseReferenceWithNoPackage) {
diff --git a/tools/aapt2/ResourceValues.h b/tools/aapt2/ResourceValues.h
index ea73615..d380f8d 100644
--- a/tools/aapt2/ResourceValues.h
+++ b/tools/aapt2/ResourceValues.h
@@ -22,6 +22,7 @@
 #include <vector>
 
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/StringPiece.h"
 
 #include "Diagnostics.h"
 #include "Resource.h"
@@ -73,7 +74,7 @@
    */
   const std::string& GetComment() const { return comment_; }
 
-  void SetComment(const StringPiece& str) { comment_ = str.ToString(); }
+  void SetComment(const android::StringPiece& str) { comment_ = str.to_string(); }
 
   void SetComment(std::string&& str) { comment_ = std::move(str); }
 
diff --git a/tools/aapt2/SdkConstants.cpp b/tools/aapt2/SdkConstants.cpp
index c7f920a..e806714 100644
--- a/tools/aapt2/SdkConstants.cpp
+++ b/tools/aapt2/SdkConstants.cpp
@@ -21,6 +21,8 @@
 #include <unordered_map>
 #include <vector>
 
+using android::StringPiece;
+
 namespace aapt {
 
 static const char* sDevelopmentSdkCodeName = "O";
diff --git a/tools/aapt2/SdkConstants.h b/tools/aapt2/SdkConstants.h
index 5352b53..98ba94b 100644
--- a/tools/aapt2/SdkConstants.h
+++ b/tools/aapt2/SdkConstants.h
@@ -19,6 +19,8 @@
 
 #include <utility>
 
+#include "androidfw/StringPiece.h"
+
 #include "Resource.h"
 
 namespace aapt {
@@ -52,7 +54,7 @@
 
 size_t FindAttributeSdkLevel(const ResourceId& id);
 size_t FindAttributeSdkLevel(const ResourceName& name);
-std::pair<StringPiece, int> GetDevelopmentSdkCodeNameAndVersion();
+std::pair<android::StringPiece, int> GetDevelopmentSdkCodeNameAndVersion();
 
 }  // namespace aapt
 
diff --git a/tools/aapt2/Source.h b/tools/aapt2/Source.h
index 459a8e6..d7f2a66 100644
--- a/tools/aapt2/Source.h
+++ b/tools/aapt2/Source.h
@@ -20,8 +20,9 @@
 #include <ostream>
 #include <string>
 
+#include "androidfw/StringPiece.h"
+
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -35,12 +36,11 @@
 
   Source() = default;
 
-  inline Source(const StringPiece& path)
-      : path(path.ToString()) {  // NOLINT(implicit)
+  inline Source(const android::StringPiece& path) : path(path.to_string()) {  // NOLINT(implicit)
   }
 
-  inline Source(const StringPiece& path, size_t line)
-      : path(path.ToString()), line(line) {}
+  inline Source(const android::StringPiece& path, size_t line)
+      : path(path.to_string()), line(line) {}
 
   inline Source WithLine(size_t line) const { return Source(path, line); }
 };
diff --git a/tools/aapt2/StringPool.cpp b/tools/aapt2/StringPool.cpp
index 3032829..d968d73 100644
--- a/tools/aapt2/StringPool.cpp
+++ b/tools/aapt2/StringPool.cpp
@@ -22,11 +22,13 @@
 
 #include "android-base/logging.h"
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/StringPiece.h"
 
 #include "util/BigBuffer.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 StringPool::Ref::Ref() : entry_(nullptr) {}
@@ -140,7 +142,7 @@
   }
 
   Entry* entry = new Entry();
-  entry->value = str.ToString();
+  entry->value = str.to_string();
   entry->context = context;
   entry->index = strings_.size();
   entry->ref_ = 0;
diff --git a/tools/aapt2/StringPool.h b/tools/aapt2/StringPool.h
index a4f556c..d0ce489 100644
--- a/tools/aapt2/StringPool.h
+++ b/tools/aapt2/StringPool.h
@@ -23,9 +23,10 @@
 #include <unordered_map>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
+
 #include "ConfigDescription.h"
 #include "util/BigBuffer.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -149,14 +150,14 @@
    * Adds a string to the pool, unless it already exists. Returns
    * a reference to the string in the pool.
    */
-  Ref MakeRef(const StringPiece& str);
+  Ref MakeRef(const android::StringPiece& str);
 
   /**
    * Adds a string to the pool, unless it already exists, with a context
    * object that can be used when sorting the string pool. Returns
    * a reference to the string in the pool.
    */
-  Ref MakeRef(const StringPiece& str, const Context& context);
+  Ref MakeRef(const android::StringPiece& str, const Context& context);
 
   /**
    * Adds a style to the string pool and returns a reference to it.
@@ -208,11 +209,11 @@
 
   static bool Flatten(BigBuffer* out, const StringPool& pool, bool utf8);
 
-  Ref MakeRefImpl(const StringPiece& str, const Context& context, bool unique);
+  Ref MakeRefImpl(const android::StringPiece& str, const Context& context, bool unique);
 
   std::vector<std::unique_ptr<Entry>> strings_;
   std::vector<std::unique_ptr<StyleEntry>> styles_;
-  std::unordered_multimap<StringPiece, Entry*> indexed_strings_;
+  std::unordered_multimap<android::StringPiece, Entry*> indexed_strings_;
 };
 
 //
diff --git a/tools/aapt2/StringPool_test.cpp b/tools/aapt2/StringPool_test.cpp
index e1394fc..f64a8cf 100644
--- a/tools/aapt2/StringPool_test.cpp
+++ b/tools/aapt2/StringPool_test.cpp
@@ -18,9 +18,14 @@
 
 #include <string>
 
+#include "androidfw/StringPiece.h"
+
 #include "test/Test.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+using android::StringPiece16;
+
 namespace aapt {
 
 TEST(StringPoolTest, InsertOneString) {
@@ -236,8 +241,7 @@
     EXPECT_EQ(StringPiece16(u"goodbye"), util::GetString16(test, 1));
 
     EXPECT_EQ(StringPiece(sLongString), util::GetString(test, 2));
-    EXPECT_EQ(util::Utf8ToUtf16(sLongString),
-              util::GetString16(test, 2).ToString());
+    EXPECT_EQ(util::Utf8ToUtf16(sLongString), util::GetString16(test, 2).to_string());
 
     size_t len;
     EXPECT_TRUE(test.stringAt(3, &len) != nullptr ||
diff --git a/tools/aapt2/compile/Compile.cpp b/tools/aapt2/compile/Compile.cpp
index f0b18e6..8027f42 100644
--- a/tools/aapt2/compile/Compile.cpp
+++ b/tools/aapt2/compile/Compile.cpp
@@ -19,6 +19,12 @@
 #include <fstream>
 #include <string>
 
+#include "android-base/errors.h"
+#include "android-base/file.h"
+#include "androidfw/StringPiece.h"
+#include "google/protobuf/io/coded_stream.h"
+#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
+
 #include "ConfigDescription.h"
 #include "Diagnostics.h"
 #include "Flags.h"
@@ -38,11 +44,7 @@
 #include "xml/XmlDom.h"
 #include "xml/XmlPullParser.h"
 
-#include "android-base/errors.h"
-#include "android-base/file.h"
-#include "google/protobuf/io/coded_stream.h"
-#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
-
+using android::StringPiece;
 using google::protobuf::io::CopyingOutputStreamAdaptor;
 using google::protobuf::io::ZeroCopyOutputStream;
 
@@ -103,9 +105,8 @@
     name = name.substr(0, dot_pos);
   }
 
-  return ResourcePathData{Source(path),          dir_str.ToString(),
-                          name.ToString(),       extension.ToString(),
-                          config_str.ToString(), config};
+  return ResourcePathData{Source(path),          dir_str.to_string(),    name.to_string(),
+                          extension.to_string(), config_str.to_string(), config};
 }
 
 struct CompileOptions {
diff --git a/tools/aapt2/compile/IdAssigner.h b/tools/aapt2/compile/IdAssigner.h
index 371ec01..9640eb8 100644
--- a/tools/aapt2/compile/IdAssigner.h
+++ b/tools/aapt2/compile/IdAssigner.h
@@ -19,11 +19,11 @@
 
 #include <unordered_map>
 
+#include "android-base/macros.h"
+
 #include "Resource.h"
 #include "process/IResourceTableConsumer.h"
 
-#include "android-base/macros.h"
-
 namespace aapt {
 
 /**
@@ -40,8 +40,7 @@
   bool Consume(IAaptContext* context, ResourceTable* table) override;
 
  private:
-  const std::unordered_map<ResourceName, ResourceId>* assigned_id_map_ =
-      nullptr;
+  const std::unordered_map<ResourceName, ResourceId>* assigned_id_map_ = nullptr;
 };
 
 }  // namespace aapt
diff --git a/tools/aapt2/compile/NinePatch.cpp b/tools/aapt2/compile/NinePatch.cpp
index eab5c97..c931da4 100644
--- a/tools/aapt2/compile/NinePatch.cpp
+++ b/tools/aapt2/compile/NinePatch.cpp
@@ -21,10 +21,12 @@
 #include <vector>
 
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/StringPiece.h"
 
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 // Colors in the format 0xAARRGGBB (the way 9-patch expects it).
diff --git a/tools/aapt2/compile/Png.cpp b/tools/aapt2/compile/Png.cpp
index 7ab05b5..5e15c88 100644
--- a/tools/aapt2/compile/Png.cpp
+++ b/tools/aapt2/compile/Png.cpp
@@ -15,18 +15,21 @@
  */
 
 #include "Png.h"
-#include "Source.h"
-#include "util/BigBuffer.h"
-#include "util/Util.h"
 
-#include <androidfw/ResourceTypes.h>
 #include <png.h>
 #include <zlib.h>
+
 #include <iostream>
 #include <sstream>
 #include <string>
 #include <vector>
 
+#include "androidfw/ResourceTypes.h"
+
+#include "Source.h"
+#include "util/BigBuffer.h"
+#include "util/Util.h"
+
 namespace aapt {
 
 constexpr bool kDebug = false;
diff --git a/tools/aapt2/compile/Png.h b/tools/aapt2/compile/Png.h
index aff1da3..a820051 100644
--- a/tools/aapt2/compile/Png.h
+++ b/tools/aapt2/compile/Png.h
@@ -56,7 +56,7 @@
  */
 class PngChunkFilter : public io::InputStream {
  public:
-  explicit PngChunkFilter(const StringPiece& data);
+  explicit PngChunkFilter(const android::StringPiece& data);
 
   bool Next(const void** buffer, int* len) override;
   void BackUp(int count) override;
@@ -71,7 +71,7 @@
  private:
   bool ConsumeWindow(const void** buffer, int* len);
 
-  StringPiece data_;
+  android::StringPiece data_;
   size_t window_start_ = 0;
   size_t window_end_ = 0;
   bool error_ = false;
diff --git a/tools/aapt2/compile/PngChunkFilter.cpp b/tools/aapt2/compile/PngChunkFilter.cpp
index 4cbefb9..edec123 100644
--- a/tools/aapt2/compile/PngChunkFilter.cpp
+++ b/tools/aapt2/compile/PngChunkFilter.cpp
@@ -16,8 +16,11 @@
 
 #include "compile/Png.h"
 
+#include "androidfw/StringPiece.h"
+
 #include "io/Io.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
diff --git a/tools/aapt2/compile/PseudolocaleGenerator.cpp b/tools/aapt2/compile/PseudolocaleGenerator.cpp
index 055a725..5035f81 100644
--- a/tools/aapt2/compile/PseudolocaleGenerator.cpp
+++ b/tools/aapt2/compile/PseudolocaleGenerator.cpp
@@ -23,6 +23,8 @@
 #include "ValueVisitor.h"
 #include "compile/Pseudolocalizer.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 std::unique_ptr<StyledString> PseudolocalizeStyledString(
diff --git a/tools/aapt2/compile/Pseudolocalizer.cpp b/tools/aapt2/compile/Pseudolocalizer.cpp
index f89288f..15a3d8c 100644
--- a/tools/aapt2/compile/Pseudolocalizer.cpp
+++ b/tools/aapt2/compile/Pseudolocalizer.cpp
@@ -18,6 +18,8 @@
 
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 // String basis to generate expansion
@@ -40,10 +42,8 @@
 
 class PseudoMethodNone : public PseudoMethodImpl {
  public:
-  std::string Text(const StringPiece& text) override { return text.ToString(); }
-  std::string Placeholder(const StringPiece& text) override {
-    return text.ToString();
-  }
+  std::string Text(const StringPiece& text) override { return text.to_string(); }
+  std::string Placeholder(const StringPiece& text) override { return text.to_string(); }
 };
 
 class PseudoMethodBidi : public PseudoMethodImpl {
@@ -116,7 +116,7 @@
       }
       size_t size = nextpos - lastpos;
       if (size) {
-        std::string chunk = text.substr(lastpos, size).ToString();
+        std::string chunk = text.substr(lastpos, size).to_string();
         if (pseudo) {
           chunk = impl_->Text(chunk);
         } else if (str[lastpos] == kArgStart && str[nextpos - 1] == kArgEnd) {
@@ -437,7 +437,7 @@
 
 std::string PseudoMethodAccent::Placeholder(const StringPiece& source) {
   // Surround a placeholder with brackets
-  return kPlaceholderOpen + source.ToString() + kPlaceholderClose;
+  return kPlaceholderOpen + source.to_string() + kPlaceholderClose;
 }
 
 std::string PseudoMethodBidi::Text(const StringPiece& source) {
@@ -467,7 +467,7 @@
 
 std::string PseudoMethodBidi::Placeholder(const StringPiece& source) {
   // Surround a placeholder with directionality change sequence
-  return kRlm + kRlo + source.ToString() + kPdf + kRlm;
+  return kRlm + kRlo + source.to_string() + kPdf + kRlm;
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/compile/Pseudolocalizer.h b/tools/aapt2/compile/Pseudolocalizer.h
index a6d2ad0..6cf003b 100644
--- a/tools/aapt2/compile/Pseudolocalizer.h
+++ b/tools/aapt2/compile/Pseudolocalizer.h
@@ -20,10 +20,10 @@
 #include <memory>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 
 #include "ResourceValues.h"
 #include "StringPool.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -32,8 +32,8 @@
   virtual ~PseudoMethodImpl() {}
   virtual std::string Start() { return {}; }
   virtual std::string End() { return {}; }
-  virtual std::string Text(const StringPiece& text) = 0;
-  virtual std::string Placeholder(const StringPiece& text) = 0;
+  virtual std::string Text(const android::StringPiece& text) = 0;
+  virtual std::string Placeholder(const android::StringPiece& text) = 0;
 };
 
 class Pseudolocalizer {
@@ -48,7 +48,7 @@
   void SetMethod(Method method);
   std::string Start() { return impl_->Start(); }
   std::string End() { return impl_->End(); }
-  std::string Text(const StringPiece& text);
+  std::string Text(const android::StringPiece& text);
 
  private:
   std::unique_ptr<PseudoMethodImpl> impl_;
diff --git a/tools/aapt2/compile/Pseudolocalizer_test.cpp b/tools/aapt2/compile/Pseudolocalizer_test.cpp
index 92eb3b5..d3b7b02 100644
--- a/tools/aapt2/compile/Pseudolocalizer_test.cpp
+++ b/tools/aapt2/compile/Pseudolocalizer_test.cpp
@@ -19,6 +19,8 @@
 #include "test/Test.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 // In this context, 'Axis' represents a particular field in the configuration,
diff --git a/tools/aapt2/diff/Diff.cpp b/tools/aapt2/diff/Diff.cpp
index 593e7ab..de0fe40 100644
--- a/tools/aapt2/diff/Diff.cpp
+++ b/tools/aapt2/diff/Diff.cpp
@@ -24,6 +24,8 @@
 #include "process/SymbolTable.h"
 #include "unflatten/BinaryResourceParser.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 class DiffContext : public IAaptContext {
diff --git a/tools/aapt2/dump/Dump.cpp b/tools/aapt2/dump/Dump.cpp
index 2920c2a..bcede72 100644
--- a/tools/aapt2/dump/Dump.cpp
+++ b/tools/aapt2/dump/Dump.cpp
@@ -16,6 +16,8 @@
 
 #include <vector>
 
+#include "androidfw/StringPiece.h"
+
 #include "Debug.h"
 #include "Diagnostics.h"
 #include "Flags.h"
@@ -24,7 +26,8 @@
 #include "proto/ProtoSerialize.h"
 #include "unflatten/BinaryResourceParser.h"
 #include "util/Files.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
diff --git a/tools/aapt2/flatten/Archive.cpp b/tools/aapt2/flatten/Archive.cpp
index 47de0a3..5c96a4d 100644
--- a/tools/aapt2/flatten/Archive.cpp
+++ b/tools/aapt2/flatten/Archive.cpp
@@ -22,10 +22,12 @@
 #include <vector>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 #include "ziparchive/zip_writer.h"
 
 #include "util/Files.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
@@ -36,7 +38,7 @@
   DirectoryWriter() = default;
 
   bool Open(IDiagnostics* diag, const StringPiece& out_dir) {
-    dir_ = out_dir.ToString();
+    dir_ = out_dir.to_string();
     file::FileType type = file::GetFileType(dir_);
     if (type == file::FileType::kNonexistant) {
       diag->Error(DiagMessage() << "directory " << dir_ << " does not exist");
diff --git a/tools/aapt2/flatten/Archive.h b/tools/aapt2/flatten/Archive.h
index 4fcb3ff..f0681bd 100644
--- a/tools/aapt2/flatten/Archive.h
+++ b/tools/aapt2/flatten/Archive.h
@@ -22,12 +22,12 @@
 #include <string>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
 
 #include "Diagnostics.h"
 #include "util/BigBuffer.h"
 #include "util/Files.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -46,7 +46,7 @@
  public:
   virtual ~IArchiveWriter() = default;
 
-  virtual bool StartEntry(const StringPiece& path, uint32_t flags) = 0;
+  virtual bool StartEntry(const android::StringPiece& path, uint32_t flags) = 0;
   virtual bool WriteEntry(const BigBuffer& buffer) = 0;
   virtual bool WriteEntry(const void* data, size_t len) = 0;
   virtual bool FinishEntry() = 0;
@@ -57,11 +57,11 @@
   }
 };
 
-std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(
-    IDiagnostics* diag, const StringPiece& path);
+std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(IDiagnostics* diag,
+                                                             const android::StringPiece& path);
 
-std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(
-    IDiagnostics* diag, const StringPiece& path);
+std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(IDiagnostics* diag,
+                                                           const android::StringPiece& path);
 
 }  // namespace aapt
 
diff --git a/tools/aapt2/flatten/XmlFlattener_test.cpp b/tools/aapt2/flatten/XmlFlattener_test.cpp
index 2c83bb3..ffc2de1 100644
--- a/tools/aapt2/flatten/XmlFlattener_test.cpp
+++ b/tools/aapt2/flatten/XmlFlattener_test.cpp
@@ -23,6 +23,8 @@
 #include "util/BigBuffer.h"
 #include "util/Util.h"
 
+using android::StringPiece16;
+
 namespace aapt {
 
 class XmlFlattenerTest : public ::testing::Test {
diff --git a/tools/aapt2/io/File.h b/tools/aapt2/io/File.h
index 644f59f..3d5b5b1 100644
--- a/tools/aapt2/io/File.h
+++ b/tools/aapt2/io/File.h
@@ -110,7 +110,7 @@
  public:
   virtual ~IFileCollection() = default;
 
-  virtual IFile* FindFile(const StringPiece& path) = 0;
+  virtual IFile* FindFile(const android::StringPiece& path) = 0;
   virtual std::unique_ptr<IFileCollectionIterator> Iterator() = 0;
 };
 
diff --git a/tools/aapt2/io/FileSystem.cpp b/tools/aapt2/io/FileSystem.cpp
index 828f34e..027cbd0 100644
--- a/tools/aapt2/io/FileSystem.cpp
+++ b/tools/aapt2/io/FileSystem.cpp
@@ -16,14 +16,16 @@
 
 #include "io/FileSystem.h"
 
+#include "androidfw/StringPiece.h"
 #include "utils/FileMap.h"
 
 #include "Source.h"
 #include "util/Files.h"
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 namespace io {
 
@@ -54,13 +56,11 @@
 }
 
 IFile* FileCollection::InsertFile(const StringPiece& path) {
-  return (files_[path.ToString()] =
-              util::make_unique<RegularFile>(Source(path)))
-      .get();
+  return (files_[path.to_string()] = util::make_unique<RegularFile>(Source(path))).get();
 }
 
 IFile* FileCollection::FindFile(const StringPiece& path) {
-  auto iter = files_.find(path.ToString());
+  auto iter = files_.find(path.to_string());
   if (iter != files_.end()) {
     return iter->second.get();
   }
diff --git a/tools/aapt2/io/FileSystem.h b/tools/aapt2/io/FileSystem.h
index 84f851f..dfd3717 100644
--- a/tools/aapt2/io/FileSystem.h
+++ b/tools/aapt2/io/FileSystem.h
@@ -59,8 +59,8 @@
   /**
    * Adds a file located at path. Returns the IFile representation of that file.
    */
-  IFile* InsertFile(const StringPiece& path);
-  IFile* FindFile(const StringPiece& path) override;
+  IFile* InsertFile(const android::StringPiece& path);
+  IFile* FindFile(const android::StringPiece& path) override;
   std::unique_ptr<IFileCollectionIterator> Iterator() override;
 
  private:
diff --git a/tools/aapt2/io/ZipArchive.cpp b/tools/aapt2/io/ZipArchive.cpp
index f4a128e..62b436f 100644
--- a/tools/aapt2/io/ZipArchive.cpp
+++ b/tools/aapt2/io/ZipArchive.cpp
@@ -22,6 +22,8 @@
 #include "Source.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 namespace io {
 
@@ -107,7 +109,7 @@
     std::string zip_entry_path =
         std::string(reinterpret_cast<const char*>(zip_entry_name.name),
                     zip_entry_name.name_length);
-    std::string nested_path = path.ToString() + "@" + zip_entry_path;
+    std::string nested_path = path.to_string() + "@" + zip_entry_path;
     collection->files_[zip_entry_path] = util::make_unique<ZipFile>(
         collection->handle_, zip_data, Source(nested_path));
   }
@@ -120,7 +122,7 @@
 }
 
 IFile* ZipFileCollection::FindFile(const StringPiece& path) {
-  auto iter = files_.find(path.ToString());
+  auto iter = files_.find(path.to_string());
   if (iter != files_.end()) {
     return iter->second.get();
   }
diff --git a/tools/aapt2/io/ZipArchive.h b/tools/aapt2/io/ZipArchive.h
index 85ca1ae..634adad 100644
--- a/tools/aapt2/io/ZipArchive.h
+++ b/tools/aapt2/io/ZipArchive.h
@@ -21,8 +21,9 @@
 
 #include <map>
 
+#include "androidfw/StringPiece.h"
+
 #include "io/File.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 namespace io {
@@ -64,10 +65,10 @@
  */
 class ZipFileCollection : public IFileCollection {
  public:
-  static std::unique_ptr<ZipFileCollection> Create(const StringPiece& path,
+  static std::unique_ptr<ZipFileCollection> Create(const android::StringPiece& path,
                                                    std::string* outError);
 
-  io::IFile* FindFile(const StringPiece& path) override;
+  io::IFile* FindFile(const android::StringPiece& path) override;
   std::unique_ptr<IFileCollectionIterator> Iterator() override;
 
   ~ZipFileCollection() override;
diff --git a/tools/aapt2/java/AnnotationProcessor.cpp b/tools/aapt2/java/AnnotationProcessor.cpp
index 2951e5c..a0ef00b 100644
--- a/tools/aapt2/java/AnnotationProcessor.cpp
+++ b/tools/aapt2/java/AnnotationProcessor.cpp
@@ -20,6 +20,8 @@
 
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 void AnnotationProcessor::AppendCommentLine(std::string& comment) {
@@ -54,7 +56,7 @@
   for (StringPiece line : util::Tokenize(comment, '\n')) {
     line = util::TrimWhitespace(line);
     if (!line.empty()) {
-      std::string lineCopy = line.ToString();
+      std::string lineCopy = line.to_string();
       AppendCommentLine(lineCopy);
     }
   }
diff --git a/tools/aapt2/java/AnnotationProcessor.h b/tools/aapt2/java/AnnotationProcessor.h
index 666a7f3..99cd44f 100644
--- a/tools/aapt2/java/AnnotationProcessor.h
+++ b/tools/aapt2/java/AnnotationProcessor.h
@@ -20,7 +20,7 @@
 #include <sstream>
 #include <string>
 
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
 
 namespace aapt {
 
@@ -58,7 +58,7 @@
    * configurations,
    * we need to collect all the comments.
    */
-  void AppendComment(const StringPiece& comment);
+  void AppendComment(const android::StringPiece& comment);
 
   void AppendNewLine();
 
@@ -66,7 +66,7 @@
    * Writes the comments and annotations to the stream, with the given prefix
    * before each line.
    */
-  void WriteToStream(std::ostream* out, const StringPiece& prefix) const;
+  void WriteToStream(std::ostream* out, const android::StringPiece& prefix) const;
 
  private:
   enum : uint32_t {
diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp
index f1f1f92..53d6ea1 100644
--- a/tools/aapt2/java/ClassDefinition.cpp
+++ b/tools/aapt2/java/ClassDefinition.cpp
@@ -16,7 +16,9 @@
 
 #include "java/ClassDefinition.h"
 
-#include "util/StringPiece.h"
+#include "androidfw/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
@@ -43,7 +45,7 @@
   }
   *out << "final class " << name_ << " {\n";
 
-  std::string new_prefix = prefix.ToString();
+  std::string new_prefix = prefix.to_string();
   new_prefix.append(kIndent);
 
   for (const std::unique_ptr<ClassMember>& member : members_) {
diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h
index d8b61d9..64e4b29 100644
--- a/tools/aapt2/java/ClassDefinition.h
+++ b/tools/aapt2/java/ClassDefinition.h
@@ -21,10 +21,10 @@
 #include <string>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 
 #include "Resource.h"
 #include "java/AnnotationProcessor.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 
 namespace aapt {
@@ -41,7 +41,7 @@
 
   virtual bool empty() const = 0;
 
-  virtual void WriteToStream(const StringPiece& prefix, bool final,
+  virtual void WriteToStream(const android::StringPiece& prefix, bool final,
                              std::ostream* out) const {
     processor_.WriteToStream(out, prefix);
   }
@@ -53,12 +53,12 @@
 template <typename T>
 class PrimitiveMember : public ClassMember {
  public:
-  PrimitiveMember(const StringPiece& name, const T& val)
-      : name_(name.ToString()), val_(val) {}
+  PrimitiveMember(const android::StringPiece& name, const T& val)
+      : name_(name.to_string()), val_(val) {}
 
   bool empty() const override { return false; }
 
-  void WriteToStream(const StringPiece& prefix, bool final,
+  void WriteToStream(const android::StringPiece& prefix, bool final,
                      std::ostream* out) const override {
     ClassMember::WriteToStream(prefix, final, out);
 
@@ -79,12 +79,12 @@
 template <>
 class PrimitiveMember<std::string> : public ClassMember {
  public:
-  PrimitiveMember(const StringPiece& name, const std::string& val)
-      : name_(name.ToString()), val_(val) {}
+  PrimitiveMember(const android::StringPiece& name, const std::string& val)
+      : name_(name.to_string()), val_(val) {}
 
   bool empty() const override { return false; }
 
-  void WriteToStream(const StringPiece& prefix, bool final,
+  void WriteToStream(const android::StringPiece& prefix, bool final,
                      std::ostream* out) const override {
     ClassMember::WriteToStream(prefix, final, out);
 
@@ -106,14 +106,13 @@
 template <typename T>
 class PrimitiveArrayMember : public ClassMember {
  public:
-  explicit PrimitiveArrayMember(const StringPiece& name)
-      : name_(name.ToString()) {}
+  explicit PrimitiveArrayMember(const android::StringPiece& name) : name_(name.to_string()) {}
 
   void AddElement(const T& val) { elements_.push_back(val); }
 
   bool empty() const override { return false; }
 
-  void WriteToStream(const StringPiece& prefix, bool final,
+  void WriteToStream(const android::StringPiece& prefix, bool final,
                      std::ostream* out) const override {
     ClassMember::WriteToStream(prefix, final, out);
 
@@ -147,22 +146,18 @@
 
 class ClassDefinition : public ClassMember {
  public:
-  static bool WriteJavaFile(const ClassDefinition* def,
-                            const StringPiece& package, bool final,
-                            std::ostream* out);
+  static bool WriteJavaFile(const ClassDefinition* def, const android::StringPiece& package,
+                            bool final, std::ostream* out);
 
-  ClassDefinition(const StringPiece& name, ClassQualifier qualifier,
-                  bool createIfEmpty)
-      : name_(name.ToString()),
-        qualifier_(qualifier),
-        create_if_empty_(createIfEmpty) {}
+  ClassDefinition(const android::StringPiece& name, ClassQualifier qualifier, bool createIfEmpty)
+      : name_(name.to_string()), qualifier_(qualifier), create_if_empty_(createIfEmpty) {}
 
   void AddMember(std::unique_ptr<ClassMember> member) {
     members_.push_back(std::move(member));
   }
 
   bool empty() const override;
-  void WriteToStream(const StringPiece& prefix, bool final,
+  void WriteToStream(const android::StringPiece& prefix, bool final,
                      std::ostream* out) const override;
 
  private:
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp
index 6e7c7078..b71dc48 100644
--- a/tools/aapt2/java/JavaClassGenerator.cpp
+++ b/tools/aapt2/java/JavaClassGenerator.cpp
@@ -23,6 +23,7 @@
 #include <tuple>
 
 #include "android-base/logging.h"
+#include "androidfw/StringPiece.h"
 
 #include "NameMangler.h"
 #include "Resource.h"
@@ -32,7 +33,8 @@
 #include "java/AnnotationProcessor.h"
 #include "java/ClassDefinition.h"
 #include "process/SymbolTable.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
@@ -58,7 +60,7 @@
  * Replace those with '_'.
  */
 static std::string Transform(const StringPiece& symbol) {
-  std::string output = symbol.ToString();
+  std::string output = symbol.to_string();
   for (char& c : output) {
     if (c == '.' || c == '-') {
       c = '_';
diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h
index 190e73b..5cf556e 100644
--- a/tools/aapt2/java/JavaClassGenerator.h
+++ b/tools/aapt2/java/JavaClassGenerator.h
@@ -20,10 +20,11 @@
 #include <ostream>
 #include <string>
 
+#include "androidfw/StringPiece.h"
+
 #include "ResourceTable.h"
 #include "ResourceValues.h"
 #include "process/IResourceTableConsumer.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 
@@ -69,22 +70,20 @@
    * We need to generate these symbols in a separate file.
    * Returns true on success.
    */
-  bool Generate(const StringPiece& packageNameToGenerate, std::ostream* out);
+  bool Generate(const android::StringPiece& packageNameToGenerate, std::ostream* out);
 
-  bool Generate(const StringPiece& packageNameToGenerate,
-                const StringPiece& outputPackageName, std::ostream* out);
+  bool Generate(const android::StringPiece& packageNameToGenerate,
+                const android::StringPiece& outputPackageName, std::ostream* out);
 
   const std::string& getError() const;
 
  private:
-  bool AddMembersToTypeClass(const StringPiece& packageNameToGenerate,
-                             const ResourceTablePackage* package,
-                             const ResourceTableType* type,
+  bool AddMembersToTypeClass(const android::StringPiece& packageNameToGenerate,
+                             const ResourceTablePackage* package, const ResourceTableType* type,
                              ClassDefinition* outTypeClassDef);
 
-  void AddMembersToStyleableClass(const StringPiece& packageNameToGenerate,
-                                  const std::string& entryName,
-                                  const Styleable* styleable,
+  void AddMembersToStyleableClass(const android::StringPiece& packageNameToGenerate,
+                                  const std::string& entryName, const Styleable* styleable,
                                   ClassDefinition* outStyleableClassDef);
 
   bool SkipSymbol(SymbolState state);
diff --git a/tools/aapt2/java/JavaClassGenerator_test.cpp b/tools/aapt2/java/JavaClassGenerator_test.cpp
index 3d3d24e..55c5cb2 100644
--- a/tools/aapt2/java/JavaClassGenerator_test.cpp
+++ b/tools/aapt2/java/JavaClassGenerator_test.cpp
@@ -22,6 +22,8 @@
 #include "test/Test.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 TEST(JavaClassGeneratorTest, FailWhenEntryIsJavaKeyword) {
diff --git a/tools/aapt2/java/ManifestClassGenerator.cpp b/tools/aapt2/java/ManifestClassGenerator.cpp
index db84f29..de8e59a 100644
--- a/tools/aapt2/java/ManifestClassGenerator.cpp
+++ b/tools/aapt2/java/ManifestClassGenerator.cpp
@@ -24,6 +24,8 @@
 #include "util/Maybe.h"
 #include "xml/XmlDom.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 static Maybe<StringPiece> ExtractJavaIdentifier(IDiagnostics* diag,
diff --git a/tools/aapt2/jni/aapt2_jni.cpp b/tools/aapt2/jni/aapt2_jni.cpp
index 5518fe2..b029b20 100644
--- a/tools/aapt2/jni/aapt2_jni.cpp
+++ b/tools/aapt2/jni/aapt2_jni.cpp
@@ -26,6 +26,8 @@
 
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 extern int Compile(const std::vector<StringPiece> &args);
 extern int Link(const std::vector<StringPiece> &args);
@@ -65,9 +67,8 @@
  * The returned pieces can only be used while the original ones have not been
  * destroyed.
  */
-static std::vector<aapt::StringPiece> extract_pieces(
-    const std::vector<ScopedUtfChars> &strings) {
-  std::vector<aapt::StringPiece> pieces;
+static std::vector<StringPiece> extract_pieces(const std::vector<ScopedUtfChars> &strings) {
+  std::vector<StringPiece> pieces;
 
   std::for_each(
       strings.begin(), strings.end(),
@@ -80,8 +81,7 @@
     JNIEnv *env, jclass aapt_obj, jobject arguments_obj) {
   std::vector<ScopedUtfChars> compile_args_jni =
       list_to_utfchars(env, arguments_obj);
-  std::vector<aapt::StringPiece> compile_args =
-      extract_pieces(compile_args_jni);
+  std::vector<StringPiece> compile_args = extract_pieces(compile_args_jni);
   aapt::Compile(compile_args);
 }
 
@@ -89,7 +89,7 @@
     JNIEnv *env, jclass aapt_obj, jobject arguments_obj) {
   std::vector<ScopedUtfChars> link_args_jni =
       list_to_utfchars(env, arguments_obj);
-  std::vector<aapt::StringPiece> link_args = extract_pieces(link_args_jni);
+  std::vector<StringPiece> link_args = extract_pieces(link_args_jni);
   aapt::Link(link_args);
 }
 
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/link/Link.cpp
index b525758..c3ce076 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/link/Link.cpp
@@ -23,6 +23,7 @@
 
 #include "android-base/errors.h"
 #include "android-base/file.h"
+#include "androidfw/StringPiece.h"
 #include "google/protobuf/io/coded_stream.h"
 
 #include "AppInfo.h"
@@ -51,9 +52,9 @@
 #include "split/TableSplitter.h"
 #include "unflatten/BinaryResourceParser.h"
 #include "util/Files.h"
-#include "util/StringPiece.h"
 #include "xml/XmlDom.h"
 
+using android::StringPiece;
 using ::google::protobuf::io::CopyingOutputStreamAdaptor;
 
 namespace aapt {
@@ -121,7 +122,7 @@
   }
 
   void SetCompilationPackage(const StringPiece& package_name) {
-    compilation_package_ = package_name.ToString();
+    compilation_package_ = package_name.to_string();
   }
 
   uint8_t GetPackageId() override { return package_id_; }
@@ -2011,14 +2012,14 @@
   for (std::string& extra_package : extra_java_packages) {
     // A given package can actually be a colon separated list of packages.
     for (StringPiece package : util::Split(extra_package, ':')) {
-      options.extra_java_packages.insert(package.ToString());
+      options.extra_java_packages.insert(package.to_string());
     }
   }
 
   if (product_list) {
     for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
       if (product != "" && product != "default") {
-        options.products.insert(product.ToString());
+        options.products.insert(product.to_string());
       }
     }
   }
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index 4185937..e5eaf2f 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -25,6 +25,8 @@
 #include "xml/XmlActionExecutor.h"
 #include "xml/XmlDom.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 /**
@@ -293,7 +295,7 @@
   CHECK(attr != nullptr);
 
   std::string original_package = std::move(attr->value);
-  attr->value = package_override.ToString();
+  attr->value = package_override.to_string();
 
   FullyQualifiedClassNameVisitor visitor(original_package);
   manifest_el->Accept(&visitor);
diff --git a/tools/aapt2/link/ManifestFixer_test.cpp b/tools/aapt2/link/ManifestFixer_test.cpp
index fc6970c..12a304a 100644
--- a/tools/aapt2/link/ManifestFixer_test.cpp
+++ b/tools/aapt2/link/ManifestFixer_test.cpp
@@ -18,6 +18,8 @@
 
 #include "test/Test.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 struct ManifestFixerTest : public ::testing::Test {
diff --git a/tools/aapt2/link/ReferenceLinker.cpp b/tools/aapt2/link/ReferenceLinker.cpp
index be787b2..ea68b61 100644
--- a/tools/aapt2/link/ReferenceLinker.cpp
+++ b/tools/aapt2/link/ReferenceLinker.cpp
@@ -30,6 +30,8 @@
 #include "util/Util.h"
 #include "xml/XmlUtil.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 namespace {
@@ -192,8 +194,7 @@
       const StringPiece& alias,
       const StringPiece& local_package) const override {
     if (alias.empty()) {
-      return xml::ExtractedPackage{local_package.ToString(),
-                                   true /* private */};
+      return xml::ExtractedPackage{local_package.to_string(), true /* private */};
     }
     return {};
   }
diff --git a/tools/aapt2/link/TableMerger.cpp b/tools/aapt2/link/TableMerger.cpp
index d808da3..7e7b9fb 100644
--- a/tools/aapt2/link/TableMerger.cpp
+++ b/tools/aapt2/link/TableMerger.cpp
@@ -24,6 +24,8 @@
 #include "ValueVisitor.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 TableMerger::TableMerger(IAaptContext* context, ResourceTable* out_table,
@@ -351,9 +353,8 @@
     const std::string& package, const FileReference& file_ref) {
   StringPiece prefix, entry, suffix;
   if (util::ExtractResFilePathParts(*file_ref.path, &prefix, &entry, &suffix)) {
-    std::string mangled_entry =
-        NameMangler::MangleEntry(package, entry.ToString());
-    std::string newPath = prefix.ToString() + mangled_entry + suffix.ToString();
+    std::string mangled_entry = NameMangler::MangleEntry(package, entry.to_string());
+    std::string newPath = prefix.to_string() + mangled_entry + suffix.to_string();
     std::unique_ptr<FileReference> new_file_ref =
         util::make_unique<FileReference>(
             master_table_->string_pool.MakeRef(newPath));
diff --git a/tools/aapt2/link/TableMerger.h b/tools/aapt2/link/TableMerger.h
index 4ab83c3..c96b1b0 100644
--- a/tools/aapt2/link/TableMerger.h
+++ b/tools/aapt2/link/TableMerger.h
@@ -96,8 +96,8 @@
    * An io::IFileCollection is needed in order to find the referenced Files and
    * process them.
    */
-  bool MergeAndMangle(const Source& src, const StringPiece& package,
-                      ResourceTable* table, io::IFileCollection* collection);
+  bool MergeAndMangle(const Source& src, const android::StringPiece& package, ResourceTable* table,
+                      io::IFileCollection* collection);
 
   /**
    * Merges a compiled file that belongs to this same or empty package. This is
diff --git a/tools/aapt2/link/VersionCollapser_test.cpp b/tools/aapt2/link/VersionCollapser_test.cpp
index 1b5592f..44babb2 100644
--- a/tools/aapt2/link/VersionCollapser_test.cpp
+++ b/tools/aapt2/link/VersionCollapser_test.cpp
@@ -18,6 +18,8 @@
 
 #include "test/Test.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 static std::unique_ptr<ResourceTable> BuildTableWithConfigs(
diff --git a/tools/aapt2/process/SymbolTable.cpp b/tools/aapt2/process/SymbolTable.cpp
index 767384d..1a3da73 100644
--- a/tools/aapt2/process/SymbolTable.cpp
+++ b/tools/aapt2/process/SymbolTable.cpp
@@ -25,6 +25,8 @@
 #include "ValueVisitor.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 void SymbolTable::AppendSource(std::unique_ptr<ISymbolSource> source) {
diff --git a/tools/aapt2/process/SymbolTable.h b/tools/aapt2/process/SymbolTable.h
index 25f7565..cf597bb 100644
--- a/tools/aapt2/process/SymbolTable.h
+++ b/tools/aapt2/process/SymbolTable.h
@@ -154,7 +154,7 @@
  public:
   AssetManagerSymbolSource() = default;
 
-  bool AddAssetPath(const StringPiece& path);
+  bool AddAssetPath(const android::StringPiece& path);
 
   std::unique_ptr<SymbolTable::Symbol> FindByName(
       const ResourceName& name) override;
diff --git a/tools/aapt2/proto/TableProtoSerializer.cpp b/tools/aapt2/proto/TableProtoSerializer.cpp
index 0d0e46d..7230b55 100644
--- a/tools/aapt2/proto/TableProtoSerializer.cpp
+++ b/tools/aapt2/proto/TableProtoSerializer.cpp
@@ -22,7 +22,7 @@
 #include "proto/ProtoSerialize.h"
 #include "util/BigBuffer.h"
 
-#include <android-base/logging.h>
+#include "android-base/logging.h"
 
 using google::protobuf::io::CodedOutputStream;
 using google::protobuf::io::CodedInputStream;
@@ -239,7 +239,7 @@
       if (type->id) {
         pb_type->set_id(type->id.value());
       }
-      pb_type->set_name(ToString(type->type).ToString());
+      pb_type->set_name(ToString(type->type).to_string());
 
       for (auto& entry : type->entries) {
         pb::Entry* pb_entry = pb_type->add_entries();
diff --git a/tools/aapt2/split/TableSplitter.cpp b/tools/aapt2/split/TableSplitter.cpp
index 7aad86f..38cfd2e 100644
--- a/tools/aapt2/split/TableSplitter.cpp
+++ b/tools/aapt2/split/TableSplitter.cpp
@@ -21,6 +21,7 @@
 #include <set>
 #include <unordered_map>
 #include <vector>
+
 #include "android-base/logging.h"
 
 #include "ConfigDescription.h"
diff --git a/tools/aapt2/test/Builders.h b/tools/aapt2/test/Builders.h
index 9377306..6888cf3 100644
--- a/tools/aapt2/test/Builders.h
+++ b/tools/aapt2/test/Builders.h
@@ -37,95 +37,86 @@
 
   StringPool* string_pool() { return &table_->string_pool; }
 
-  ResourceTableBuilder& SetPackageId(const StringPiece& package_name,
-                                     uint8_t id) {
+  ResourceTableBuilder& SetPackageId(const android::StringPiece& package_name, uint8_t id) {
     ResourceTablePackage* package = table_->CreatePackage(package_name, id);
     CHECK(package != nullptr);
     return *this;
   }
 
-  ResourceTableBuilder& AddSimple(const StringPiece& name,
-                                  const ResourceId& id = {}) {
+  ResourceTableBuilder& AddSimple(const android::StringPiece& name, const ResourceId& id = {}) {
     return AddValue(name, id, util::make_unique<Id>());
   }
 
-  ResourceTableBuilder& AddSimple(const StringPiece& name,
-                                  const ConfigDescription& config,
+  ResourceTableBuilder& AddSimple(const android::StringPiece& name, const ConfigDescription& config,
                                   const ResourceId& id = {}) {
     return AddValue(name, config, id, util::make_unique<Id>());
   }
 
-  ResourceTableBuilder& AddReference(const StringPiece& name,
-                                     const StringPiece& ref) {
+  ResourceTableBuilder& AddReference(const android::StringPiece& name,
+                                     const android::StringPiece& ref) {
     return AddReference(name, {}, ref);
   }
 
-  ResourceTableBuilder& AddReference(const StringPiece& name,
-                                     const ResourceId& id,
-                                     const StringPiece& ref) {
+  ResourceTableBuilder& AddReference(const android::StringPiece& name, const ResourceId& id,
+                                     const android::StringPiece& ref) {
     return AddValue(name, id,
                     util::make_unique<Reference>(ParseNameOrDie(ref)));
   }
 
-  ResourceTableBuilder& AddString(const StringPiece& name,
-                                  const StringPiece& str) {
+  ResourceTableBuilder& AddString(const android::StringPiece& name,
+                                  const android::StringPiece& str) {
     return AddString(name, {}, str);
   }
 
-  ResourceTableBuilder& AddString(const StringPiece& name, const ResourceId& id,
-                                  const StringPiece& str) {
+  ResourceTableBuilder& AddString(const android::StringPiece& name, const ResourceId& id,
+                                  const android::StringPiece& str) {
     return AddValue(
         name, id, util::make_unique<String>(table_->string_pool.MakeRef(str)));
   }
 
-  ResourceTableBuilder& AddString(const StringPiece& name, const ResourceId& id,
+  ResourceTableBuilder& AddString(const android::StringPiece& name, const ResourceId& id,
                                   const ConfigDescription& config,
-                                  const StringPiece& str) {
+                                  const android::StringPiece& str) {
     return AddValue(name, config, id, util::make_unique<String>(
                                           table_->string_pool.MakeRef(str)));
   }
 
-  ResourceTableBuilder& AddFileReference(const StringPiece& name,
-                                         const StringPiece& path) {
+  ResourceTableBuilder& AddFileReference(const android::StringPiece& name,
+                                         const android::StringPiece& path) {
     return AddFileReference(name, {}, path);
   }
 
-  ResourceTableBuilder& AddFileReference(const StringPiece& name,
-                                         const ResourceId& id,
-                                         const StringPiece& path) {
+  ResourceTableBuilder& AddFileReference(const android::StringPiece& name, const ResourceId& id,
+                                         const android::StringPiece& path) {
     return AddValue(name, id, util::make_unique<FileReference>(
                                   table_->string_pool.MakeRef(path)));
   }
 
-  ResourceTableBuilder& AddFileReference(const StringPiece& name,
-                                         const StringPiece& path,
+  ResourceTableBuilder& AddFileReference(const android::StringPiece& name,
+                                         const android::StringPiece& path,
                                          const ConfigDescription& config) {
     return AddValue(name, config, {}, util::make_unique<FileReference>(
                                           table_->string_pool.MakeRef(path)));
   }
 
-  ResourceTableBuilder& AddValue(const StringPiece& name,
-                                 std::unique_ptr<Value> value) {
+  ResourceTableBuilder& AddValue(const android::StringPiece& name, std::unique_ptr<Value> value) {
     return AddValue(name, {}, std::move(value));
   }
 
-  ResourceTableBuilder& AddValue(const StringPiece& name, const ResourceId& id,
+  ResourceTableBuilder& AddValue(const android::StringPiece& name, const ResourceId& id,
                                  std::unique_ptr<Value> value) {
     return AddValue(name, {}, id, std::move(value));
   }
 
-  ResourceTableBuilder& AddValue(const StringPiece& name,
-                                 const ConfigDescription& config,
-                                 const ResourceId& id,
-                                 std::unique_ptr<Value> value) {
+  ResourceTableBuilder& AddValue(const android::StringPiece& name, const ConfigDescription& config,
+                                 const ResourceId& id, std::unique_ptr<Value> value) {
     ResourceName res_name = ParseNameOrDie(name);
     CHECK(table_->AddResourceAllowMangled(res_name, id, config, {},
                                           std::move(value), &diagnostics_));
     return *this;
   }
 
-  ResourceTableBuilder& SetSymbolState(const StringPiece& name,
-                                       const ResourceId& id,
+  ResourceTableBuilder& SetSymbolState(const android::StringPiece& name, const ResourceId& id,
                                        SymbolState state) {
     ResourceName res_name = ParseNameOrDie(name);
     Symbol symbol;
@@ -144,8 +135,8 @@
   std::unique_ptr<ResourceTable> table_ = util::make_unique<ResourceTable>();
 };
 
-inline std::unique_ptr<Reference> BuildReference(
-    const StringPiece& ref, const Maybe<ResourceId>& id = {}) {
+inline std::unique_ptr<Reference> BuildReference(const android::StringPiece& ref,
+                                                 const Maybe<ResourceId>& id = {}) {
   std::unique_ptr<Reference> reference =
       util::make_unique<Reference>(ParseNameOrDie(ref));
   reference->id = id;
@@ -174,7 +165,7 @@
     return *this;
   }
 
-  ValueBuilder& SetComment(const StringPiece& str) {
+  ValueBuilder& SetComment(const android::StringPiece& str) {
     value_->SetComment(str);
     return *this;
   }
@@ -199,7 +190,7 @@
     return *this;
   }
 
-  AttributeBuilder& AddItem(const StringPiece& name, uint32_t value) {
+  AttributeBuilder& AddItem(const android::StringPiece& name, uint32_t value) {
     attr_->symbols.push_back(Attribute::Symbol{
         Reference(ResourceName({}, ResourceType::kId, name)), value});
     return *this;
@@ -217,18 +208,18 @@
  public:
   StyleBuilder() = default;
 
-  StyleBuilder& SetParent(const StringPiece& str) {
+  StyleBuilder& SetParent(const android::StringPiece& str) {
     style_->parent = Reference(ParseNameOrDie(str));
     return *this;
   }
 
-  StyleBuilder& AddItem(const StringPiece& str, std::unique_ptr<Item> value) {
+  StyleBuilder& AddItem(const android::StringPiece& str, std::unique_ptr<Item> value) {
     style_->entries.push_back(
         Style::Entry{Reference(ParseNameOrDie(str)), std::move(value)});
     return *this;
   }
 
-  StyleBuilder& AddItem(const StringPiece& str, const ResourceId& id,
+  StyleBuilder& AddItem(const android::StringPiece& str, const ResourceId& id,
                         std::unique_ptr<Item> value) {
     AddItem(str, std::move(value));
     style_->entries.back().key.id = id;
@@ -247,8 +238,7 @@
  public:
   StyleableBuilder() = default;
 
-  StyleableBuilder& AddItem(const StringPiece& str,
-                            const Maybe<ResourceId>& id = {}) {
+  StyleableBuilder& AddItem(const android::StringPiece& str, const Maybe<ResourceId>& id = {}) {
     styleable_->entries.push_back(Reference(ParseNameOrDie(str)));
     styleable_->entries.back().id = id;
     return *this;
@@ -262,7 +252,7 @@
   std::unique_ptr<Styleable> styleable_ = util::make_unique<Styleable>();
 };
 
-inline std::unique_ptr<xml::XmlResource> BuildXmlDom(const StringPiece& str) {
+inline std::unique_ptr<xml::XmlResource> BuildXmlDom(const android::StringPiece& str) {
   std::stringstream in;
   in << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" << str;
   StdErrDiagnostics diag;
@@ -273,7 +263,7 @@
 }
 
 inline std::unique_ptr<xml::XmlResource> BuildXmlDomForPackageName(
-    IAaptContext* context, const StringPiece& str) {
+    IAaptContext* context, const android::StringPiece& str) {
   std::unique_ptr<xml::XmlResource> doc = BuildXmlDom(str);
   doc->file.name.package = context->GetCompilationPackage();
   return doc;
diff --git a/tools/aapt2/test/Common.h b/tools/aapt2/test/Common.h
index 3689201..248921f 100644
--- a/tools/aapt2/test/Common.h
+++ b/tools/aapt2/test/Common.h
@@ -21,6 +21,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 #include "gtest/gtest.h"
 
 #include "ConfigDescription.h"
@@ -30,7 +31,6 @@
 #include "ValueVisitor.h"
 #include "io/File.h"
 #include "process/IResourceTableConsumer.h"
-#include "util/StringPiece.h"
 
 //
 // GTEST 1.7 doesn't explicitly cast to bool, which causes explicit operators to
@@ -68,23 +68,22 @@
   return &diag;
 }
 
-inline ResourceName ParseNameOrDie(const StringPiece& str) {
+inline ResourceName ParseNameOrDie(const android::StringPiece& str) {
   ResourceNameRef ref;
   CHECK(ResourceUtils::ParseResourceName(str, &ref)) << "invalid resource name";
   return ref.ToResourceName();
 }
 
-inline ConfigDescription ParseConfigOrDie(const StringPiece& str) {
+inline ConfigDescription ParseConfigOrDie(const android::StringPiece& str) {
   ConfigDescription config;
   CHECK(ConfigDescription::Parse(str, &config)) << "invalid configuration";
   return config;
 }
 
 template <typename T>
-T* GetValueForConfigAndProduct(ResourceTable* table,
-                               const StringPiece& res_name,
+T* GetValueForConfigAndProduct(ResourceTable* table, const android::StringPiece& res_name,
                                const ConfigDescription& config,
-                               const StringPiece& product) {
+                               const android::StringPiece& product) {
   Maybe<ResourceTable::SearchResult> result =
       table->FindResource(ParseNameOrDie(res_name));
   if (result) {
@@ -98,19 +97,19 @@
 }
 
 template <typename T>
-T* GetValueForConfig(ResourceTable* table, const StringPiece& res_name,
+T* GetValueForConfig(ResourceTable* table, const android::StringPiece& res_name,
                      const ConfigDescription& config) {
   return GetValueForConfigAndProduct<T>(table, res_name, config, {});
 }
 
 template <typename T>
-T* GetValue(ResourceTable* table, const StringPiece& res_name) {
+T* GetValue(ResourceTable* table, const android::StringPiece& res_name) {
   return GetValueForConfig<T>(table, res_name, {});
 }
 
 class TestFile : public io::IFile {
  public:
-  explicit TestFile(const StringPiece& path) : source_(path) {}
+  explicit TestFile(const android::StringPiece& path) : source_(path) {}
 
   std::unique_ptr<io::IData> OpenAsData() override { return {}; }
 
diff --git a/tools/aapt2/test/Context.h b/tools/aapt2/test/Context.h
index 7986329..63e5f16 100644
--- a/tools/aapt2/test/Context.h
+++ b/tools/aapt2/test/Context.h
@@ -70,8 +70,8 @@
 
 class ContextBuilder {
  public:
-  ContextBuilder& SetCompilationPackage(const StringPiece& package) {
-    context_->compilation_package_ = package.ToString();
+  ContextBuilder& SetCompilationPackage(const android::StringPiece& package) {
+    context_->compilation_package_ = package.to_string();
     return *this;
   }
 
@@ -103,9 +103,8 @@
 
 class StaticSymbolSourceBuilder {
  public:
-  StaticSymbolSourceBuilder& AddPublicSymbol(
-      const StringPiece& name, ResourceId id,
-      std::unique_ptr<Attribute> attr = {}) {
+  StaticSymbolSourceBuilder& AddPublicSymbol(const android::StringPiece& name, ResourceId id,
+                                             std::unique_ptr<Attribute> attr = {}) {
     std::unique_ptr<SymbolTable::Symbol> symbol =
         util::make_unique<SymbolTable::Symbol>(id, std::move(attr), true);
     symbol_source_->name_map_[ParseNameOrDie(name)] = symbol.get();
@@ -114,7 +113,7 @@
     return *this;
   }
 
-  StaticSymbolSourceBuilder& AddSymbol(const StringPiece& name, ResourceId id,
+  StaticSymbolSourceBuilder& AddSymbol(const android::StringPiece& name, ResourceId id,
                                        std::unique_ptr<Attribute> attr = {}) {
     std::unique_ptr<SymbolTable::Symbol> symbol =
         util::make_unique<SymbolTable::Symbol>(id, std::move(attr), false);
diff --git a/tools/aapt2/util/Files.cpp b/tools/aapt2/util/Files.cpp
index f034607..aa840e2 100644
--- a/tools/aapt2/util/Files.cpp
+++ b/tools/aapt2/util/Files.cpp
@@ -35,6 +35,8 @@
 #include <direct.h>
 #endif
 
+using android::StringPiece;
+
 namespace aapt {
 namespace file {
 
@@ -72,10 +74,9 @@
 
 inline static int MkdirImpl(const StringPiece& path) {
 #ifdef _WIN32
-  return _mkdir(path.ToString().c_str());
+  return _mkdir(path.to_string().c_str());
 #else
-  return mkdir(path.ToString().c_str(),
-               S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP);
+  return mkdir(path.to_string().c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP);
 #endif
 }
 
@@ -184,7 +185,7 @@
                         std::vector<std::string>* out_arglist,
                         std::string* out_error) {
   std::string contents;
-  if (!android::base::ReadFileToString(path.ToString(), &contents)) {
+  if (!android::base::ReadFileToString(path.to_string(), &contents)) {
     if (out_error) *out_error = "failed to read argument-list file";
     return false;
   }
@@ -192,7 +193,7 @@
   for (StringPiece line : util::Tokenize(contents, ' ')) {
     line = util::TrimWhitespace(line);
     if (!line.empty()) {
-      out_arglist->push_back(line.ToString());
+      out_arglist->push_back(line.to_string());
     }
   }
   return true;
diff --git a/tools/aapt2/util/Files.h b/tools/aapt2/util/Files.h
index a157dbd..95c492f 100644
--- a/tools/aapt2/util/Files.h
+++ b/tools/aapt2/util/Files.h
@@ -22,12 +22,12 @@
 #include <vector>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 #include "utils/FileMap.h"
 
 #include "Diagnostics.h"
 #include "Maybe.h"
 #include "Source.h"
-#include "util/StringPiece.h"
 
 namespace aapt {
 namespace file {
@@ -50,51 +50,49 @@
   kSocket,
 };
 
-FileType GetFileType(const StringPiece& path);
+FileType GetFileType(const android::StringPiece& path);
 
 /*
  * Appends a path to `base`, separated by the directory separator.
  */
-void AppendPath(std::string* base, StringPiece part);
+void AppendPath(std::string* base, android::StringPiece part);
 
 /*
  * Makes all the directories in `path`. The last element in the path
  * is interpreted as a directory.
  */
-bool mkdirs(const StringPiece& path);
+bool mkdirs(const android::StringPiece& path);
 
 /**
  * Returns all but the last part of the path.
  */
-StringPiece GetStem(const StringPiece& path);
+android::StringPiece GetStem(const android::StringPiece& path);
 
 /**
  * Returns the last part of the path with extension.
  */
-StringPiece GetFilename(const StringPiece& path);
+android::StringPiece GetFilename(const android::StringPiece& path);
 
 /**
  * Returns the extension of the path. This is the entire string after
  * the first '.' of the last part of the path.
  */
-StringPiece GetExtension(const StringPiece& path);
+android::StringPiece GetExtension(const android::StringPiece& path);
 
 /**
  * Converts a package name (com.android.app) to a path: com/android/app
  */
-std::string PackageToPath(const StringPiece& package);
+std::string PackageToPath(const android::StringPiece& package);
 
 /**
  * Creates a FileMap for the file at path.
  */
-Maybe<android::FileMap> MmapPath(const StringPiece& path,
-                                 std::string* out_error);
+Maybe<android::FileMap> MmapPath(const android::StringPiece& path, std::string* out_error);
 
 /**
  * Reads the file at path and appends each line to the outArgList vector.
  */
-bool AppendArgsFromFile(const StringPiece& path,
-                        std::vector<std::string>* out_arglist,
+bool AppendArgsFromFile(const android::StringPiece& path, std::vector<std::string>* out_arglist,
                         std::string* out_error);
 
 /*
@@ -120,7 +118,7 @@
    * - Otherwise the full string is matched.
    * - match is not case-sensitive.
    */
-  bool SetPattern(const StringPiece& pattern);
+  bool SetPattern(const android::StringPiece& pattern);
 
   /**
    * Applies the filter, returning true for pass, false for fail.
diff --git a/tools/aapt2/util/Util.cpp b/tools/aapt2/util/Util.cpp
index d5c0c8a..cf22322 100644
--- a/tools/aapt2/util/Util.cpp
+++ b/tools/aapt2/util/Util.cpp
@@ -15,9 +15,6 @@
  */
 
 #include "util/Util.h"
-#include "util/BigBuffer.h"
-#include "util/Maybe.h"
-#include "util/StringPiece.h"
 
 #include <utils/Unicode.h>
 #include <algorithm>
@@ -25,6 +22,14 @@
 #include <string>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
+
+#include "util/BigBuffer.h"
+#include "util/Maybe.h"
+
+using android::StringPiece;
+using android::StringPiece16;
+
 namespace aapt {
 namespace util {
 
@@ -36,7 +41,7 @@
   StringPiece::const_iterator current;
   do {
     current = std::find(start, end, sep);
-    parts.emplace_back(str.substr(start, current).ToString());
+    parts.emplace_back(str.substr(start, current).to_string());
     if (f) {
       std::string& part = parts.back();
       std::transform(part.begin(), part.end(), part.begin(), f);
@@ -162,7 +167,7 @@
   }
 
   if (util::IsJavaClassName(classname)) {
-    return classname.ToString();
+    return classname.to_string();
   }
 
   if (package.empty()) {
diff --git a/tools/aapt2/util/Util.h b/tools/aapt2/util/Util.h
index 05e9cc5..f8fa80e 100644
--- a/tools/aapt2/util/Util.h
+++ b/tools/aapt2/util/Util.h
@@ -24,11 +24,11 @@
 #include <vector>
 
 #include "androidfw/ResourceTypes.h"
+#include "androidfw/StringPiece.h"
 #include "utils/ByteOrder.h"
 
 #include "util/BigBuffer.h"
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 
 #ifdef _WIN32
 // TODO(adamlesinski): remove once http://b/32447322 is resolved.
@@ -44,26 +44,24 @@
 namespace aapt {
 namespace util {
 
-std::vector<std::string> Split(const StringPiece& str, char sep);
-std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep);
+std::vector<std::string> Split(const android::StringPiece& str, char sep);
+std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep);
 
 /**
  * Returns true if the string starts with prefix.
  */
-bool StartsWith(const StringPiece& str, const StringPiece& prefix);
+bool StartsWith(const android::StringPiece& str, const android::StringPiece& prefix);
 
 /**
  * Returns true if the string ends with suffix.
  */
-bool EndsWith(const StringPiece& str, const StringPiece& suffix);
+bool EndsWith(const android::StringPiece& str, const android::StringPiece& suffix);
 
 /**
  * Creates a new StringPiece16 that points to a substring
  * of the original string without leading or trailing whitespace.
  */
-StringPiece TrimWhitespace(const StringPiece& str);
-
-StringPiece TrimWhitespace(const StringPiece& str);
+android::StringPiece TrimWhitespace(const android::StringPiece& str);
 
 /**
  * UTF-16 isspace(). It basically checks for lower range characters that are
@@ -75,18 +73,18 @@
  * Returns an iterator to the first character that is not alpha-numeric and that
  * is not in the allowedChars set.
  */
-StringPiece::const_iterator FindNonAlphaNumericAndNotInSet(
-    const StringPiece& str, const StringPiece& allowed_chars);
+android::StringPiece::const_iterator FindNonAlphaNumericAndNotInSet(
+    const android::StringPiece& str, const android::StringPiece& allowed_chars);
 
 /**
  * Tests that the string is a valid Java class name.
  */
-bool IsJavaClassName(const StringPiece& str);
+bool IsJavaClassName(const android::StringPiece& str);
 
 /**
  * Tests that the string is a valid Java package name.
  */
-bool IsJavaPackageName(const StringPiece& str);
+bool IsJavaPackageName(const android::StringPiece& str);
 
 /**
  * Converts the class name to a fully qualified class name from the given
@@ -97,8 +95,8 @@
  * .a.b         --> package.a.b
  * asdf.adsf    --> asdf.adsf
  */
-Maybe<std::string> GetFullyQualifiedClassName(const StringPiece& package,
-                                              const StringPiece& class_name);
+Maybe<std::string> GetFullyQualifiedClassName(const android::StringPiece& package,
+                                              const android::StringPiece& class_name);
 
 /**
  * Makes a std::unique_ptr<> with the template parameter inferred by the
@@ -138,7 +136,7 @@
  * stored as UTF-8,
  * the conversion to UTF-16 happens within ResStringPool.
  */
-StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
+android::StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
 
 /**
  * Helper method to extract a UTF-8 string from a StringPool. If the string is
@@ -159,11 +157,11 @@
  * which will
  * break the string interpolation.
  */
-bool VerifyJavaStringFormat(const StringPiece& str);
+bool VerifyJavaStringFormat(const android::StringPiece& str);
 
 class StringBuilder {
  public:
-  StringBuilder& Append(const StringPiece& str);
+  StringBuilder& Append(const android::StringPiece& str);
   const std::string& ToString() const;
   const std::string& Error() const;
 
@@ -194,8 +192,8 @@
 /**
  * Converts a UTF8 string to a UTF16 string.
  */
-std::u16string Utf8ToUtf16(const StringPiece& utf8);
-std::string Utf16ToUtf8(const StringPiece16& utf16);
+std::u16string Utf8ToUtf16(const android::StringPiece& utf8);
+std::string Utf16ToUtf8(const android::StringPiece16& utf16);
 
 /**
  * Writes the entire BigBuffer to the output stream.
@@ -220,22 +218,22 @@
 
     iterator& operator++();
 
-    StringPiece operator*() { return token_; }
+    android::StringPiece operator*() { return token_; }
     bool operator==(const iterator& rhs) const;
     bool operator!=(const iterator& rhs) const;
 
    private:
     friend class Tokenizer;
 
-    iterator(StringPiece s, char sep, StringPiece tok, bool end);
+    iterator(android::StringPiece s, char sep, android::StringPiece tok, bool end);
 
-    StringPiece str_;
+    android::StringPiece str_;
     char separator_;
-    StringPiece token_;
+    android::StringPiece token_;
     bool end_;
   };
 
-  Tokenizer(StringPiece str, char sep);
+  Tokenizer(android::StringPiece str, char sep);
 
   iterator begin() { return begin_; }
 
@@ -246,9 +244,7 @@
   const iterator end_;
 };
 
-inline Tokenizer Tokenize(const StringPiece& str, char sep) {
-  return Tokenizer(str, sep);
-}
+inline Tokenizer Tokenize(const android::StringPiece& str, char sep) { return Tokenizer(str, sep); }
 
 inline uint16_t HostToDevice16(uint16_t value) { return htods(value); }
 
@@ -267,8 +263,8 @@
  *
  * Returns true if successful.
  */
-bool ExtractResFilePathParts(const StringPiece& path, StringPiece* out_prefix,
-                             StringPiece* out_entry, StringPiece* out_suffix);
+bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix,
+                             android::StringPiece* out_entry, android::StringPiece* out_suffix);
 
 }  // namespace util
 
diff --git a/tools/aapt2/util/Util_test.cpp b/tools/aapt2/util/Util_test.cpp
index cac3de4..e49aee5 100644
--- a/tools/aapt2/util/Util_test.cpp
+++ b/tools/aapt2/util/Util_test.cpp
@@ -20,6 +20,8 @@
 
 #include "test/Test.h"
 
+using android::StringPiece;
+
 namespace aapt {
 
 TEST(UtilTest, TrimOnlyWhitespace) {
diff --git a/tools/aapt2/xml/XmlDom.cpp b/tools/aapt2/xml/XmlDom.cpp
index 960d361..fab2f19 100644
--- a/tools/aapt2/xml/XmlDom.cpp
+++ b/tools/aapt2/xml/XmlDom.cpp
@@ -29,6 +29,9 @@
 #include "XmlPullParser.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+using android::StringPiece16;
+
 namespace aapt {
 namespace xml {
 
@@ -52,10 +55,10 @@
 
   if (*p == 0) {
     out_ns->clear();
-    *out_name = StringPiece(name).ToString();
+    out_name->assign(name);
   } else {
-    *out_ns = StringPiece(name, (p - name)).ToString();
-    *out_name = StringPiece(p + 1).ToString();
+    out_ns->assign(name, (p - name));
+    out_name->assign(p + 1);
   }
 }
 
@@ -83,11 +86,11 @@
 
   std::unique_ptr<Namespace> ns = util::make_unique<Namespace>();
   if (prefix) {
-    ns->namespace_prefix = StringPiece(prefix).ToString();
+    ns->namespace_prefix = prefix;
   }
 
   if (uri) {
-    ns->namespace_uri = StringPiece(uri).ToString();
+    ns->namespace_uri = uri;
   }
 
   AddToStack(stack, parser, std::move(ns));
@@ -117,7 +120,7 @@
   while (*attrs) {
     Attribute attribute;
     SplitName(*attrs++, &attribute.namespace_uri, &attribute.name);
-    attribute.value = StringPiece(*attrs++).ToString();
+    attribute.value = *attrs++;
 
     // Insert in sorted order.
     auto iter = std::lower_bound(el->attributes.begin(), el->attributes.end(),
@@ -153,14 +156,14 @@
     if (!currentParent->children.empty()) {
       Node* last_child = currentParent->children.back().get();
       if (Text* text = NodeCast<Text>(last_child)) {
-        text->text += StringPiece(s, len).ToString();
+        text->text.append(s, len);
         return;
       }
     }
   }
 
   std::unique_ptr<Text> text = util::make_unique<Text>();
-  text->text = StringPiece(s, len).ToString();
+  text->text.assign(s, len);
   AddToStack(stack, parser, std::move(text));
 }
 
@@ -495,15 +498,14 @@
 Maybe<ExtractedPackage> PackageAwareVisitor::TransformPackageAlias(
     const StringPiece& alias, const StringPiece& local_package) const {
   if (alias.empty()) {
-    return ExtractedPackage{local_package.ToString(), false /* private */};
+    return ExtractedPackage{local_package.to_string(), false /* private */};
   }
 
   const auto rend = package_decls_.rend();
   for (auto iter = package_decls_.rbegin(); iter != rend; ++iter) {
     if (alias == iter->prefix) {
       if (iter->package.package.empty()) {
-        return ExtractedPackage{local_package.ToString(),
-                                iter->package.private_namespace};
+        return ExtractedPackage{local_package.to_string(), iter->package.private_namespace};
       }
       return iter->package;
     }
diff --git a/tools/aapt2/xml/XmlDom.h b/tools/aapt2/xml/XmlDom.h
index 720fe35..90cdfb6 100644
--- a/tools/aapt2/xml/XmlDom.h
+++ b/tools/aapt2/xml/XmlDom.h
@@ -22,10 +22,11 @@
 #include <string>
 #include <vector>
 
+#include "androidfw/StringPiece.h"
+
 #include "Diagnostics.h"
 #include "Resource.h"
 #include "ResourceValues.h"
-#include "util/StringPiece.h"
 #include "util/Util.h"
 #include "xml/XmlUtil.h"
 
@@ -100,13 +101,13 @@
   std::string name;
   std::vector<Attribute> attributes;
 
-  Attribute* FindAttribute(const StringPiece& ns, const StringPiece& name);
-  xml::Element* FindChild(const StringPiece& ns, const StringPiece& name);
-  xml::Element* FindChildWithAttribute(const StringPiece& ns,
-                                       const StringPiece& name,
-                                       const StringPiece& attr_ns,
-                                       const StringPiece& attr_name,
-                                       const StringPiece& attr_value);
+  Attribute* FindAttribute(const android::StringPiece& ns, const android::StringPiece& name);
+  xml::Element* FindChild(const android::StringPiece& ns, const android::StringPiece& name);
+  xml::Element* FindChildWithAttribute(const android::StringPiece& ns,
+                                       const android::StringPiece& name,
+                                       const android::StringPiece& attr_ns,
+                                       const android::StringPiece& attr_name,
+                                       const android::StringPiece& attr_value);
   std::vector<xml::Element*> GetChildElements();
   std::unique_ptr<Node> Clone() override;
 };
@@ -190,8 +191,7 @@
 
   void Visit(Namespace* ns) override;
   Maybe<ExtractedPackage> TransformPackageAlias(
-      const StringPiece& alias,
-      const StringPiece& local_package) const override;
+      const android::StringPiece& alias, const android::StringPiece& local_package) const override;
 
  private:
   struct PackageDecl {
diff --git a/tools/aapt2/xml/XmlPullParser.cpp b/tools/aapt2/xml/XmlPullParser.cpp
index e59fa86..c2a9c82 100644
--- a/tools/aapt2/xml/XmlPullParser.cpp
+++ b/tools/aapt2/xml/XmlPullParser.cpp
@@ -22,6 +22,8 @@
 #include "xml/XmlPullParser.h"
 #include "xml/XmlUtil.h"
 
+using android::StringPiece;
+
 namespace aapt {
 namespace xml {
 
@@ -136,15 +138,14 @@
 Maybe<ExtractedPackage> XmlPullParser::TransformPackageAlias(
     const StringPiece& alias, const StringPiece& local_package) const {
   if (alias.empty()) {
-    return ExtractedPackage{local_package.ToString(), false /* private */};
+    return ExtractedPackage{local_package.to_string(), false /* private */};
   }
 
   const auto end_iter = package_aliases_.rend();
   for (auto iter = package_aliases_.rbegin(); iter != end_iter; ++iter) {
     if (alias == iter->prefix) {
       if (iter->package.package.empty()) {
-        return ExtractedPackage{local_package.ToString(),
-                                iter->package.private_namespace};
+        return ExtractedPackage{local_package.to_string(), iter->package.private_namespace};
       }
       return iter->package;
     }
@@ -188,19 +189,18 @@
 /**
  * Extracts the namespace and name of an expanded element or attribute name.
  */
-static void SplitName(const char* name, std::string& out_ns,
-                      std::string& out_name) {
+static void SplitName(const char* name, std::string* out_ns, std::string* out_name) {
   const char* p = name;
   while (*p != 0 && *p != kXmlNamespaceSep) {
     p++;
   }
 
   if (*p == 0) {
-    out_ns = std::string();
-    out_name = name;
+    out_ns->clear();
+    out_name->assign(name);
   } else {
-    out_ns = StringPiece(name, (p - name)).ToString();
-    out_name = p + 1;
+    out_ns->assign(name, (p - name));
+    out_name->assign(p + 1);
   }
 }
 
@@ -224,11 +224,11 @@
   EventData data = {Event::kStartElement,
                     XML_GetCurrentLineNumber(parser->parser_),
                     parser->depth_++};
-  SplitName(name, data.data1, data.data2);
+  SplitName(name, &data.data1, &data.data2);
 
   while (*attrs) {
     Attribute attribute;
-    SplitName(*attrs++, attribute.namespace_uri, attribute.name);
+    SplitName(*attrs++, &attribute.namespace_uri, &attribute.name);
     attribute.value = *attrs++;
 
     // Insert in sorted order.
@@ -245,9 +245,8 @@
                                                  int len) {
   XmlPullParser* parser = reinterpret_cast<XmlPullParser*>(user_data);
 
-  parser->event_queue_.push(
-      EventData{Event::kText, XML_GetCurrentLineNumber(parser->parser_),
-                parser->depth_, StringPiece(s, len).ToString()});
+  parser->event_queue_.push(EventData{Event::kText, XML_GetCurrentLineNumber(parser->parser_),
+                                      parser->depth_, std::string(s, len)});
 }
 
 void XMLCALL XmlPullParser::EndElementHandler(void* user_data,
@@ -257,7 +256,7 @@
   EventData data = {Event::kEndElement,
                     XML_GetCurrentLineNumber(parser->parser_),
                     --(parser->depth_)};
-  SplitName(name, data.data1, data.data2);
+  SplitName(name, &data.data1, &data.data2);
 
   // Move the data into the queue (no copy).
   parser->event_queue_.push(std::move(data));
diff --git a/tools/aapt2/xml/XmlPullParser.h b/tools/aapt2/xml/XmlPullParser.h
index ff58d60..cdeeefd 100644
--- a/tools/aapt2/xml/XmlPullParser.h
+++ b/tools/aapt2/xml/XmlPullParser.h
@@ -28,11 +28,11 @@
 #include <vector>
 
 #include "android-base/macros.h"
+#include "androidfw/StringPiece.h"
 
 #include "Resource.h"
 #include "process/IResourceTableConsumer.h"
 #include "util/Maybe.h"
-#include "util/StringPiece.h"
 #include "xml/XmlUtil.h"
 
 namespace aapt {
@@ -119,8 +119,7 @@
    * 'package' will be set to 'defaultPackage'.
    */
   Maybe<ExtractedPackage> TransformPackageAlias(
-      const StringPiece& alias,
-      const StringPiece& local_package) const override;
+      const android::StringPiece& alias, const android::StringPiece& local_package) const override;
 
   //
   // Remaining methods are for retrieving information about attributes
@@ -146,8 +145,7 @@
   const_iterator begin_attributes() const;
   const_iterator end_attributes() const;
   size_t attribute_count() const;
-  const_iterator FindAttribute(StringPiece namespace_uri,
-                               StringPiece name) const;
+  const_iterator FindAttribute(android::StringPiece namespace_uri, android::StringPiece name) const;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(XmlPullParser);
@@ -190,16 +188,16 @@
 /**
  * Finds the attribute in the current element within the global namespace.
  */
-Maybe<StringPiece> FindAttribute(const XmlPullParser* parser,
-                                 const StringPiece& name);
+Maybe<android::StringPiece> FindAttribute(const XmlPullParser* parser,
+                                          const android::StringPiece& name);
 
 /**
  * Finds the attribute in the current element within the global namespace. The
  * attribute's value
  * must not be the empty string.
  */
-Maybe<StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser,
-                                         const StringPiece& name);
+Maybe<android::StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser,
+                                                  const android::StringPiece& name);
 
 //
 // Implementation
@@ -299,13 +297,13 @@
 }
 
 inline XmlPullParser::const_iterator XmlPullParser::FindAttribute(
-    StringPiece namespace_uri, StringPiece name) const {
+    android::StringPiece namespace_uri, android::StringPiece name) const {
   const auto end_iter = end_attributes();
   const auto iter = std::lower_bound(
       begin_attributes(), end_iter,
-      std::pair<StringPiece, StringPiece>(namespace_uri, name),
+      std::pair<android::StringPiece, android::StringPiece>(namespace_uri, name),
       [](const Attribute& attr,
-         const std::pair<StringPiece, StringPiece>& rhs) -> bool {
+         const std::pair<android::StringPiece, android::StringPiece>& rhs) -> bool {
         int cmp = attr.namespace_uri.compare(
             0, attr.namespace_uri.size(), rhs.first.data(), rhs.first.size());
         if (cmp < 0) return true;
diff --git a/tools/aapt2/xml/XmlPullParser_test.cpp b/tools/aapt2/xml/XmlPullParser_test.cpp
index 4f18cd2..1cce485 100644
--- a/tools/aapt2/xml/XmlPullParser_test.cpp
+++ b/tools/aapt2/xml/XmlPullParser_test.cpp
@@ -18,8 +18,11 @@
 
 #include <sstream>
 
+#include "androidfw/StringPiece.h"
+
 #include "test/Test.h"
-#include "util/StringPiece.h"
+
+using android::StringPiece;
 
 namespace aapt {
 
diff --git a/tools/aapt2/xml/XmlUtil.cpp b/tools/aapt2/xml/XmlUtil.cpp
index d00f7f2..fb8cee8 100644
--- a/tools/aapt2/xml/XmlUtil.cpp
+++ b/tools/aapt2/xml/XmlUtil.cpp
@@ -21,6 +21,8 @@
 #include "util/Maybe.h"
 #include "util/Util.h"
 
+using android::StringPiece;
+
 namespace aapt {
 namespace xml {
 
@@ -42,7 +44,7 @@
     if (package.empty()) {
       return {};
     }
-    return ExtractedPackage{package.ToString(), false /* is_private */};
+    return ExtractedPackage{package.to_string(), false /* is_private */};
 
   } else if (util::StartsWith(namespace_uri, kSchemaPrivatePrefix)) {
     StringPiece schema_prefix = kSchemaPrivatePrefix;
@@ -52,7 +54,7 @@
     if (package.empty()) {
       return {};
     }
-    return ExtractedPackage{package.ToString(), true /* is_private */};
+    return ExtractedPackage{package.to_string(), true /* is_private */};
 
   } else if (namespace_uri == kSchemaAuto) {
     return ExtractedPackage{std::string(), true /* is_private */};
diff --git a/tools/aapt2/xml/XmlUtil.h b/tools/aapt2/xml/XmlUtil.h
index 5365401..1650ac2 100644
--- a/tools/aapt2/xml/XmlUtil.h
+++ b/tools/aapt2/xml/XmlUtil.h
@@ -74,7 +74,7 @@
  *
  * http://schemas.android.com/apk/prv/res/<package>
  */
-std::string BuildPackageNamespace(const StringPiece& package,
+std::string BuildPackageNamespace(const android::StringPiece& package,
                                   bool private_reference = false);
 
 /**
@@ -90,7 +90,7 @@
    * package declaration.
    */
   virtual Maybe<ExtractedPackage> TransformPackageAlias(
-      const StringPiece& alias, const StringPiece& local_package) const = 0;
+      const android::StringPiece& alias, const android::StringPiece& local_package) const = 0;
 };
 
 /**
@@ -100,8 +100,7 @@
  * the namespace of the package declaration was private.
  */
 void TransformReferenceFromNamespace(IPackageDeclStack* decl_stack,
-                                     const StringPiece& local_package,
-                                     Reference* in_ref);
+                                     const android::StringPiece& local_package, Reference* in_ref);
 
 }  // namespace xml
 }  // namespace aapt