facebook twitter hatena line email

Android/kotlin/ストレージ/残り容量

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

MainActivity.kt

Log.i("MainActivity", "freesize=" + FileStorage(this).getFreeMB()) // freesize=40121.0

FileStorage.kt

package com.example.sampleapplication

import android.content.Context
import android.os.Build
import android.os.Environment
import androidx.annotation.RequiresApi

class FileStorage(private var context: Context) {
    fun getFreeMB(): Double {
        var freeByteSize: Double = 0.0
        val state = Environment.getExternalStorageState()
        // 外部保存領域が使用可能かチェック
        if (Environment.MEDIA_MOUNTED == state || Environment.MEDIA_MOUNTED_READ_ONLY == state) {
            var path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            } else {
                TODO("VERSION.SDK_INT < KITKAT")
            }
            // 空きMBを返す
            freeByteSize = Math.floor((path!!.freeSpace / 1024 / 1024).toDouble())
        }
        return freeByteSize
    }
}

参考:http://truthfullscore.hatenablog.com/entry/2014/01/07/121157