简体   繁体   中英

How can i find out if my app is installed on SD card

I would like something do something like:

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

and I am a bit at a loss for the installedOnSD part. Can anybody point me to the right direction?

PS: Pseudo-Code sample in Scala, just for the fun of it.

Here is my code for checking if app is installed on SD card:

 /**
   * 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;
  }

To Check application is installed in SD Card or not, just do this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM