如何在Android设备上访问Unity中的SDCard Path?

时间:2016-10-19 20:01:34

标签: c# android unity3d

尝试将Unity中的SDCard路径作为字符串返回。

AndroidJavaObject SDPath = new AndroidJavaObject("android.os.Environment"); 
AndroidJavaObject SDPath1  = SDPath.Call<AndroidJavaObject("getExternalStorageDirectory",null);
string path_str = SDPath1.Call<string>("getAbsolutePath");

然而它似乎没有工作。我尝试将字符串传递给UI元素,但没有渲染任何内容。我已经测试了UI元素,代码的这个方面正在工作。有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

还发现这些方法调用不起作用所以我现在使用一种解决方法:你可以找到它here。我希望它有所帮助。

此外,您必须确保允许外部写作。

答案 1 :(得分:2)

我遇到了同样的问题,发现该方法有效,但不是您的期望。 “GetExternalStorageDirectory”将为您提供外部存储的可用路径之一,在大多数情况下,它是模拟外部存储的路径,而不是SD卡。

要获得SD卡的路径,您必须调用“GetExternalStorageDirectorie s ”。这将为您提供所有可用外部存储,模拟和SD卡的列表。

    AndroidJavaObject[] externalFilesDirectories = context.Call<AndroidJavaObject[]>("getExternalFilesDirs", null);

之后,您只需要使用java函数“isExternalStorageRemovable”和“isExternalStorageEmulated”来区分模拟和外部存储。如果它没有模拟和可移动,你找到了SD卡的路径。

bool isRemovable = environment.CallStatic<bool>("isExternalStorageRemovable", directory); 
bool isEmulated = environment.CallStatic<bool>("isExternalStorageEmulated", directory);

// We found the sd card!
if (isRemovable && isEmulated == false) 
    return directory;

如果你将它包装成一个函数,你会得到这样的结果:

private static string GetAndroidExternalFilesDir()
{
     using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
     {
          using (AndroidJavaObject context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
          {
               // Get all available external file directories (emulated and sdCards)
               AndroidJavaObject[] externalFilesDirectories = context.Call<AndroidJavaObject[]>("getExternalFilesDirs", null);
               AndroidJavaObject emulated = null;
               AndroidJavaObject sdCard = null;

               for (int i = 0; i < externalFilesDirectories.Length; i++)
               {
                    AndroidJavaObject directory = externalFilesDirectories[i];
                    using (AndroidJavaClass environment = new AndroidJavaClass("android.os.Environment"))
                    {
                        // Check which one is the emulated and which the sdCard.
                        bool isRemovable = environment.CallStatic<bool ("isExternalStorageRemovable", directory);
                        bool isEmulated = environment.CallStatic<bool> ("isExternalStorageEmulated", directory);
                        if (isEmulated)
                            emulated = directory;
                        else if (isRemovable && isEmulated == false)
                            sdCard = directory;
                    }
               }
               // Return the sdCard if available
               if (sdCard != null)
                    return sdCard.Call<string>("getAbsolutePath");
               else
                    return emulated.Call<string>("getAbsolutePath");
            }
      }
}