9

我正在编写一个存储大量媒体文件的 android 应用程序。它们不是那种会弄乱用户通知或其他媒体目录的类型(而且太多了),但它们也必须是用户可更新的,所以我不能把它们放在资源中。我可以使用 getExternalFilesDir 来获取 sdcard 上的路径,但我只想在应用程序本身安装在 sdcard 上时这样做。如果应用程序是在内部安装的,我想将媒体放在内部存储器中。

那么如何确定我的应用程序是在内部存储器还是外部存储器中运行呢?

4

3 回答 3

9

您可以使用 PackageManager 获取 ApplicationInfo,然后从那里检查FLAG_EXTERNAL_STORAGE的“标志” 。

这是我为演示而制作的一个简单示例:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PackageManager pm = getPackageManager();
    try {
       PackageInfo pi = pm.getPackageInfo("com.totsp.helloworld", 0);
       ApplicationInfo ai = pi.applicationInfo;
       // this only works on API level 8 and higher (check that first)
       Toast
                .makeText(
                         this,
                         "Value of FLAG_EXTERNAL_STORAGE:"
                                  + ((ai.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE),
                         Toast.LENGTH_LONG).show();
    } catch (NameNotFoundException e) {
       // do something
    }
}

尽管如此,根据您的情况(无论您是否预先拥有所有“媒体”,或者用户在使用应用程序时获取/创建它),您可能都希望将其放在外部存储上。许多用户不赞成大型内部应用程序(并且许多内部媒体可能会使它变得庞大)。

于 2010-10-23T17:26:43.320 回答
3

这是我检查应用程序是否安装在 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 = MbridgeApp.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;
  }
于 2011-06-21T13:20:35.353 回答
0

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

ApplicationInfo io = context.getApplicationInfo();

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

//application is installed in internal memory

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

//application is installed in sdcard(external memory)

}
于 2013-03-29T06:00:46.713 回答