2011-04-28 11 views
5

me gustaría algo hacer algo como:¿Cómo puedo averiguar si mi aplicación se instala en la tarjeta SD

val cacheDir = if (installedOnSD) 
    { 
    getContext.getExternalCacheDir 
    } 
else 
    { 
    getContext.getCacheDir 
    } 

y yo soy un poco en una pérdida para el parte installedOnSD. ¿Alguien puede indicarme la dirección correcta?

PD: Ejemplo de pseudo-código en Scala, solo por el gusto de hacerlo.

Respuesta

9

Aquí está mi código para comprobar si la aplicación está instalada en la tarjeta SD:

/** 
    * Checks if the application is installed on the SD card. 
    * 
    * @return <code>true</code> if the application is installed on the sd card 
    */ 
    public static boolean isInstalledOnSdCard() { 

    Context context = App.getContext(); 
    // check for API level 8 and higher 
    if (VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) { 
     PackageManager pm = context.getPackageManager(); 
     try { 
     PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); 
     ApplicationInfo ai = pi.applicationInfo; 
     return (ai.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE; 
     } catch (NameNotFoundException e) { 
     // ignore 
     } 
    } 

    // check for API level 7 - check files dir 
    try { 
     String filesDir = context.getFilesDir().getAbsolutePath(); 
     if (filesDir.startsWith("/data/")) { 
     return false; 
     } else if (filesDir.contains("/mnt/") || filesDir.contains("/sdcard/")) { 
     return true; 
     } 
    } catch (Throwable e) { 
     // ignore 
    } 

    return false; 
    } 
+0

interesante. Considero que el nivel de API 7 es para teléfonos rooteados. Y las importaciones faltan. – Martin

1

Para verificar la aplicación se instala en la tarjeta SD o no, acaba de hacer esto:

ApplicationInfo io = context.getApplicationInfo(); 

if(io.sourceDir.startsWith("/data/")) { 

//application is installed in internal memory 
return false; 

} else if(io.sourceDir.startsWith("/mnt/") || io.sourceDir.startsWith("/sdcard/")) { 

//application is installed in sdcard(external memory) 
return true; 
} 
Cuestiones relacionadas