OSDN Git Service

Don't crash when external storage is unmounted
authorChristopher Tate <ctate@google.com>
Thu, 13 Jul 2017 22:18:38 +0000 (15:18 -0700)
committerChristopher Tate <ctate@google.com>
Fri, 14 Jul 2017 23:00:36 +0000 (16:00 -0700)
In particular, don't NPE if an app calls getExternalFilesDir() while
external storage is unmounted.  We were making assumptions about the
length of the array returned by the "tell me about all the external
locations" method, but in unmounted cases that array can be zero-sized.

(And similar for getObbDir() and getExternalCacheDir().)

Bug: 63604311
Test: manual
Change-Id: I4dec828161245047182e6fd39a0df10dd1681ba2

core/java/android/app/ContextImpl.java

index 9c9d655..c48be77 100644 (file)
@@ -60,12 +60,10 @@ import android.os.Looper;
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceManager;
-import android.os.SystemProperties;
 import android.os.Trace;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.os.storage.IStorageManager;
-import android.os.storage.StorageManager;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
@@ -621,7 +619,8 @@ class ContextImpl extends Context {
     @Override
     public File getExternalFilesDir(String type) {
         // Operates on primary external storage
-        return getExternalFilesDirs(type)[0];
+        final File[] dirs = getExternalFilesDirs(type);
+        return (dirs != null && dirs.length > 0) ? dirs[0] : null;
     }
 
     @Override
@@ -638,7 +637,8 @@ class ContextImpl extends Context {
     @Override
     public File getObbDir() {
         // Operates on primary external storage
-        return getObbDirs()[0];
+        final File[] dirs = getObbDirs();
+        return (dirs != null && dirs.length > 0) ? dirs[0] : null;
     }
 
     @Override
@@ -672,7 +672,8 @@ class ContextImpl extends Context {
     @Override
     public File getExternalCacheDir() {
         // Operates on primary external storage
-        return getExternalCacheDirs()[0];
+        final File[] dirs = getExternalCacheDirs();
+        return (dirs != null && dirs.length > 0) ? dirs[0] : null;
     }
 
     @Override