Create file as calling package before copying the file

File ownership is determined at the time of file creation. If the file
is created by shell, MediaStore will mark shell as owner of the file. To
avoid this, we now try to create file from test before copying files
using shell command.

Bug: 159412983
Test: atest android.provider.cts.media
Change-Id: Ib31c703632965e59b94403ffe00b206a0bcedf5d
Merged-In: Ib31c703632965e59b94403ffe00b206a0bcedf5d
(cherry picked from commit 1d4cf131b5ea27df6f19ed0787e0ff8ea53d94b1)
diff --git a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
index feeb87cb..deb8dfe 100644
--- a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
+++ b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
@@ -252,11 +252,21 @@
         if (userManager.isSystemUser() &&
                     FileUtils.contains(Environment.getStorageDirectory(), file)) {
             executeShellCommand("mkdir -p " + file.getParent());
+            waitUntilExists(file.getParentFile());
             try (AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId)) {
                 final File source = ParcelFileDescriptor.getFile(afd.getFileDescriptor());
                 final long skip = afd.getStartOffset();
                 final long count = afd.getLength();
 
+                try {
+                    // Try to create the file as calling package so that calling package remains
+                    // as owner of the file.
+                    file.createNewFile();
+                } catch (IOException ignored) {
+                    // Apps can't create files in other app's private directories, but shell can. If
+                    // file creation fails, we ignore and let `dd` command create it instead.
+                }
+
                 executeShellCommand(String.format("dd bs=1 if=%s skip=%d count=%d of=%s",
                         source.getAbsolutePath(), skip, count, file.getAbsolutePath()));