ぴよログ

↓に移転したのでこっちは更新されません、多分。

iOS、Androidの空き容量をコードで調べる

移転しました →

iOS

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:nil];

if (dictionary) {
    int GiB = 1024*1024*1024;
    float free = [[dictionary objectForKey: NSFileSystemFreeSize] floatValue]/GiB;
    float total = [[dictionary objectForKey: NSFileSystemSize] floatValue]/GiB;
    NSLog(@"Space: %.3f", free);
    NSLog(@"Total: %.3f", total);
}

Android

ディレクトリのパスはいくつかとれますが、デバイスによって使われ方がどうも違うっぽい感じがしました。

写真のデータ置き場はgetDataDirectoryで取れるパスが正解のような感じ。

  • Environment.getDataDirectory()
  • Environment.getExternalStorageDirectory()
  • Environment.getRootDirectory()

参考

データ/キャッシュ/外部ストレージ/システムのパスを取得するには - 逆引きAndroid入門

long MEGA_BYTE = 1048576;
String path = Environment.getDataDirectory().getAbsolutePath();

StatFs statFs = new StatFs(path);
long availableBlocks = statFs.getAvailableBlocks();
long blockSize = statFs.getBlockSize();
long freeBytes = availableBlocks * blockSize;

Log.d("MyApp", "Free:" + (freeBytes / MEGA_BYTE));