現在手機很多都可以用插拔式sd卡用來擴充存儲大小,但這些外接設備也會引發一些未知的app運行問題,先看一下sd類型
可見不同sd卡對io速度也不同,所以對app的影響也又所有不同,
在此送上一份可信的數據來看下影響層面
上圖可以看出資源下載在不同的存儲位置,反應的加載資源卡住的比例
在外置sd比內置存儲要高出1倍。
對此我們做了玩家友情提示和資源搬家功能,主要是讓玩家知道資源放在內置存儲更好,廢話不多,上代碼
1:GetExternalSDCardRootPath 這個方法用來獲取外置外置sd卡的路徑,如果沒有外置sd卡就返回null,可以用這個字符串來比對你的資源下載路徑如果存在sd卡路徑字符,那麼你的資源就在外置sd卡上面了
private static AndroidJavaObject GetReflectMethod(string className, string methodName)
{
AndroidJavaObject method;
using (AndroidJavaClass Class = new AndroidJavaClass("java.lang.Class"))
using (AndroidJavaObject classObject = Class.CallStatic<AndroidJavaObject>("forName", className))
{
method = classObject.Call<AndroidJavaObject>("getDeclaredMethod", methodName, null);
method.Call("setAccessible", true);
}
return method;
}
public static string GetExternalSDCardRootPath()
{
AndroidJavaClass buildVersion = new AndroidJavaClass("android.os.Build$VERSION");
if (buildVersion.GetStatic<int>("SDK_INT") >= 23)
{
AndroidJavaObject method_getExternalDirs = GetReflectMethod("android.os.Environment$UserEnvironment", "getExternalDirs");
AndroidJavaObject method_myUserId = GetReflectMethod("android.os.UserHandle", "myUserId");
AndroidJavaClass class_UserHandle = new AndroidJavaClass("android.os.UserHandle");
AndroidJavaObject mUserId = method_myUserId.Call<AndroidJavaObject>("invoke", class_UserHandle, null);
int userId = mUserId.Call<int>("intValue");
AndroidJavaObject env = new AndroidJavaObject("android.os.Environment$UserEnvironment", userId);
AndroidJavaObject rawfilesArray = method_getExternalDirs.Call<AndroidJavaObject>("invoke", env, null);
AndroidJavaObject[] fileArray = AndroidJNIHelper.ConvertFromJNIArray<AndroidJavaObject[]>(rawfilesArray.GetRawObject());
AndroidJavaClass Environment = new AndroidJavaClass("android.os.Environment");
for (int i = 0; i < fileArray.Length; i++)
{
AndroidJavaObject file = fileArray[i];
bool removable = Environment.CallStatic<bool>("isExternalStorageRemovable", file);
if (removable)
{
string path = file.Call<string>("getAbsolutePath");
return path;
}
}
}
else
{
using (AndroidJavaClass system = new AndroidJavaClass("java.lang.System"))
{
string secondaryStoragePath = system.CallStatic<string>("getenv", "SECONDARY_STORAGE");
if (secondaryStoragePath != null)
{
AndroidJavaObject file = new AndroidJavaObject("java.io.File", secondaryStoragePath);
bool canRead = file.Call<bool>("canRead");
if (canRead)
{
return secondaryStoragePath;
}
}
}
}
return null;
}
2:GetInternalPersisteDataPath這個方法用來,百分百返回手機的內置存儲路徑並判定是否可讀寫。
public static string GetInternalPersisteDataPath()
{
string storagePath = GetStoragePathCS(false);
if (!string.IsNullOrEmpty(storagePath))
{
string forceInternalForcePath = storagePath + "/Android/Data/" + Application.identifier + "/files";
AndroidJavaObject file = new AndroidJavaObject("java.io.File", forceInternalForcePath);
if (!file.Call<bool>("exists"))
{
file.Call<bool>("mkdirs");
}
if (file.Call<bool>("canRead") && file.Call<bool>("canWrite"))
{
return file.Call<string>("getAbsolutePath");
}
}
return null;
}
private static string GetStoragePathCS(bool is_removale)
{
using (AndroidJavaClass playerCls = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using (AndroidJavaObject activity = playerCls.GetStatic<AndroidJavaObject>("currentActivity"))
using (AndroidJavaObject mStorageManager = activity.Call<AndroidJavaObject>("getSystemService", "storage"))
{
AndroidJavaObject method_getVolumeList = GetReflectMethod("android.os.storage.StorageManager", "getVolumeList");
AndroidJavaObject method_getPath = GetReflectMethod("android.os.storage.StorageVolume", "getPath");
AndroidJavaObject method_isRemovable = GetReflectMethod("android.os.storage.StorageVolume", "isRemovable");
AndroidJavaObject rawVolumeList = method_getVolumeList.Call<AndroidJavaObject>("invoke", mStorageManager, null);
AndroidJavaObject[] VolumeList = AndroidJNIHelper.ConvertFromJNIArray<AndroidJavaObject[]>(rawVolumeList.GetRawObject());
for (int i = 0; i < VolumeList.Length; i++)
{
AndroidJavaObject storageVolumeElement = VolumeList[i];
string path = method_getPath.Call<string>("invoke", storageVolumeElement, null);
AndroidJavaObject java_removable = method_isRemovable.Call<AndroidJavaObject>("invoke", storageVolumeElement, null);
bool removable = java_removable.Call<bool>("booleanValue");
if (is_removale == removable)
{
return path;
}
}
}
return null;
}
3:進行資源搬家邏輯,根據上面1,2的邏輯,符合搬家標準的,我們就進行搬家
CopyDirectoryWorker類提供了資源搬家的方法和進度,參數只需要原文件路徑和新文件夾路徑即可
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CopyDirectoryWorker {
public delegate void GetProgressEventHandler(int Index, int Count, string SourceFile, string AimFile);
public event GetProgressEventHandler OnGetProgress;//定義一個事件,在Copy文件夾時觸發
public delegate void CopyFileEventHandler(long lngHad, long lngCount, string SourceFile ,string AimFile);
public event CopyFileEventHandler OnCopyFile;//定義一個事件,在Copy文件時觸發
public delegate void WorkOverEventHandler();//定義一個委託
public event WorkOverEventHandler WorkOvered;//定義一個事件,在Copy文件完成時觸發
public bool isDelete = false;
public CopyDirectoryWorker(bool _isDelete, string _sourceDirectory, string _aimDirectory)
{
isDelete = _isDelete;
SourceDirectory = _sourceDirectory;
AimDirectory = _aimDirectory;
}
public string SourceDirectory;
public string AimDirectory;
/// <summary>
/// 遞歸拷貝文件,把源目錄下所有文件和文件夾拷貝到目標目錄
/// </summary>
/// <param name="sourceDirectory">源路徑</param>
/// <param name="aimDirectory">目標路徑</param>
public void CopyFiles()
{
if (SourceDirectory.Substring(SourceDirectory.Length - 1, 1) == "/")
{
SourceDirectory = SourceDirectory.Substring(0, SourceDirectory.Length - 1);
}
if (!System.IO.Directory.Exists(AimDirectory))
{
System.IO.Directory.CreateDirectory(AimDirectory);
}
if (!System.IO.Directory.Exists(SourceDirectory))
return ;
sourceAllFile.Clear();
RecursionCopyFiles(SourceDirectory, AimDirectory);
RunCopyFiles();
if (isDelete)
{
DeleteFile();
}
if (WorkOvered!=null)
WorkOvered();
}
public void DeleteFile()
{
for (int i = 0; i < sourceAllFile.Count; i++)
{
if (sourceAllFile[i] != null && sourceAllFile[i].sFile != "")
try
{
System.IO.File.Delete(sourceAllFile[i].sFile);
}
catch { }
}
sourceAllFile.Clear();
}
class FileMove
{
public string sFile = "";
public string aFile = "";
public FileMove(string _sFile, string _aFile)
{
sFile = _sFile;
aFile = _aFile;
}
}
List<FileMove> sourceAllFile = new List<FileMove>();
/// <summary>
/// 二進制讀取文件,任何文件
/// </summary>
private void CopyFile(string SourceFile, string AimFile)
{
byte[] bytTemp = new byte[4096];//字節數組
long lngHad = 0;
long lngCount;
int z = 5000;
System.IO.FileStream fsSource = new System.IO.FileStream(SourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4);
System.IO.BinaryReader bRead = new System.IO.BinaryReader(fsSource);
bRead.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
if (fsSource.Position > 0)
fsSource.Position = 0;
lngCount = fsSource.Length;
if (System.IO.File.Exists(AimFile))
System.IO.File.Delete(AimFile);
System.IO.FileStream fsAim = new System.IO.FileStream(AimFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Write, 4);
System.IO.BinaryWriter bWrite = new System.IO.BinaryWriter(fsAim);
while (z >= 4096)
{
z = (int)bRead.Read(bytTemp, 0, bytTemp.Length);
bWrite.Write(bytTemp, 0, bytTemp.Length);
lngHad += z;
if (OnCopyFile!=null)
{
OnCopyFile(lngHad, lngCount, SourceFile, AimFile);
}
}
//清理緩存區
bWrite.Flush();
bWrite.Close();
bRead.Close();
fsAim.Close();
fsSource.Close();
}
/// <summary>
/// 遞歸拷貝文件,把源目錄下所有文件和文件夾拷貝到目標目錄
/// </summary>
/// <param name="sourceDirectory">源路徑</param>
/// <param name="aimDirectory">目標路徑</param>
private bool RecursionCopyFiles(string sourceDirectory, string aimDirectory)
{
if (!System.IO.Directory.Exists(sourceDirectory) & !System.IO.Directory.Exists(aimDirectory))//
return false;
try
{
string[] directories = System.IO.Directory.GetDirectories(sourceDirectory);
if (directories.Length > 0)
{
foreach (string dir in directories)
{
string dirNew = dir.Replace(@"\", "/");
string dirTemp = dirNew.Substring(dirNew.LastIndexOf(@"/"));
RecursionCopyFiles(dirNew, aimDirectory + dirTemp);
}
}
if (!System.IO.Directory.Exists(aimDirectory))
{
System.IO.Directory.CreateDirectory(aimDirectory);
}
string[] files = System.IO.Directory.GetFiles(sourceDirectory);
if (files.Length > 0)
{
foreach (string file in files)
{
string sourceFile = file.Replace(@"\", "/");
sourceAllFile.Add(new FileMove(sourceFile, aimDirectory));
}
}
return true;
}
catch
{
return false;
}
}
private void RunCopyFiles()
{
if (sourceAllFile.Count > 0)
{
for (int i = 0; i < sourceAllFile.Count; i++)
{
if (sourceAllFile[i] != null && sourceAllFile[i].sFile != "")
{
try
{
string aimFile = sourceAllFile[i].aFile + sourceAllFile[i].sFile.Substring(sourceAllFile[i].sFile.LastIndexOf(@"/"));
if (OnGetProgress != null)
{
OnGetProgress(i + 1, sourceAllFile.Count, sourceAllFile[i].sFile, aimFile);
}
CopyFile(sourceAllFile[i].sFile, aimFile);
}
catch
{
}
}
}
}
}
}