facebook twitter hatena line email

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

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
 
行1: 行1:
 
MainActivity.kt
 
MainActivity.kt
 
<pre>
 
<pre>
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+
Log.i("MainActivity", "freesize=" + FileStorage(this).getFreeMB()) // freesize=40121.0
    Log.i("MainActivity", "freesize=" + FileStorage(this).getFreeMB()) // freesize=40121.0
+
}
+
 
</pre>
 
</pre>
 
FileStorage.kt
 
FileStorage.kt
行15: 行13:
  
 
class FileStorage(private var context: Context) {
 
class FileStorage(private var context: Context) {
    @RequiresApi(Build.VERSION_CODES.KITKAT)
 
 
     fun getFreeMB(): Double {
 
     fun getFreeMB(): Double {
 
         var freeByteSize: Double = 0.0
 
         var freeByteSize: Double = 0.0
行21: 行18:
 
         // 外部保存領域が使用可能かチェック
 
         // 外部保存領域が使用可能かチェック
 
         if (Environment.MEDIA_MOUNTED == state || Environment.MEDIA_MOUNTED_READ_ONLY == state) {
 
         if (Environment.MEDIA_MOUNTED == state || Environment.MEDIA_MOUNTED_READ_ONLY == state) {
             var path = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
+
             var path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
 +
                context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
 +
            } else {
 +
                TODO("VERSION.SDK_INT < KITKAT")
 +
            }
 
             // 空きMBを返す
 
             // 空きMBを返す
 
             freeByteSize = Math.floor((path!!.freeSpace / 1024 / 1024).toDouble())
 
             freeByteSize = Math.floor((path!!.freeSpace / 1024 / 1024).toDouble())

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

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