facebook twitter hatena line email

「Android/kotlin/ストレージ/残り容量」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「MainActivity.kt <pre> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Log.i("MainActivity", "freesize=" + FileStorage(this).getFreeMB()) // freesize=40121....」)
 
行29: 行29:
 
}
 
}
 
</pre>
 
</pre>
 +
 +
参考:http://truthfullscore.hatenablog.com/entry/2014/01/07/121157

2020年3月25日 (水) 18:45時点における版

MainActivity.kt

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    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) {
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    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 = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            // 空きMBを返す
            freeByteSize = Math.floor((path!!.freeSpace / 1024 / 1024).toDouble())
        }
        return freeByteSize
    }
}

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