如何确定我的应用程序是否安装在SD卡上

时间:2011-04-28 06:22:54

标签: android

我想做点什么之类的事情:

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

我对 installedOnSD 部分感到有些不知所措。有人能指出我正确的方向吗?

PS:Scala中的伪代码示例,只是为了它的乐趣。

2 个答案:

答案 0 :(得分:9)

这是我的代码,用于检查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;
  }

答案 1 :(得分:1)

要检查应用程序是否安装在SD卡中,请执行以下操作:

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