Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบพื้นที่ว่างในหน่วยความจำ Android ด้วย Kotlin

ตัวอย่างนี้สาธิตวิธี ตรวจสอบพื้นที่จัดเก็บที่ว่างอยู่ (Available Storage) ใน Android โดยใช้ StatFs และ Formatter.formatFileSize()

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Storage Space Checker"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvStorageInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAlignment="center"
        android:textSize="18sp"
        android:textStyle="bold"
        android:lineSpacingExtra="8dp" />

</RelativeLayout>

ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.kt)

import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.text.format.Formatter
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.File

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "Storage Info"

        val tvStorage = findViewById(R.id.tvStorageInfo)

        // 1. External Storage (Public/Shared - Photos, Downloads)
        val extPath = Environment.getExternalStorageDirectory()
        val extStat = StatFs(extPath.path)
        val extTotal = extStat.blockSizeLong * extStat.blockCountLong
        val extAvailable = extStat.blockSizeLong * extStat.availableBlocksLong

        // 2. Internal Storage (App Private Data)
        val intPath = Environment.getDataDirectory()
        val intStat = StatFs(intPath.path)
        val intTotal = intStat.blockSizeLong * intStat.blockCountLong
        val intAvailable = intStat.blockSizeLong * intStat.availableBlocksLong

        // 3. App Specific Cache Directory
        val cachePath = cacheDir
        val cacheStat = StatFs(cachePath.path)
        val cacheAvailable = cacheStat.blockSizeLong * cacheStat.availableBlocksLong

        // Format ให้อ่านง่าย
        val formatter = Formatter.getInstance()
        val sb = StringBuilder()
        sb.appendLine("📱 External Storage (Shared)")
        sb.appendLine("   Total: ${formatter.formatFileSize(this, extTotal)}")
        sb.appendLine("   Free:  ${formatter.formatFileSize(this, extAvailable)}")
        sb.appendLine("")
        sb.appendLine("💾 Internal Storage (System)")
        sb.appendLine("   Total: ${formatter.formatFileSize(this, intTotal)}")
        sb.appendLine("   Free:  ${formatter.formatFileSize(this, intAvailable)}")
        sb.appendLine("")
        sb.appendLine("🗂️ App Cache Directory")
        sb.appendLine("   Free:  ${formatter.formatFileSize(this, cacheAvailable)}")
        sb.appendLine("")
        sb.appendLine("📂 App Files Dir: ${filesDir.absolutePath}")
        sb.appendLine("📂 App Cache Dir: ${cacheDir.absolutePath}")

        tvStorage.text = sb.toString()
    }
}

📊 StatFs Fields สำคัญ

Method คำอธิบาย
blockSizeLong ขนาดบล็อกหนึ่งบล็อก (Bytes)
blockCountLong จำนวนบล็อกทั้งหมด
availableBlocksLong จำนวนบล็อกที่ว่าง (สำหรับแอปทั่วไป)
freeBlocksLong จำนวนบล็อกที่ว่างทั้งหมด (รวม System)

🔐 Permission (Android 10+ / API 29+)

  • Scoped Storage: แอปเข้าถึงได้เฉพาะโฟลเดอร์ตัวเอง (filesDir, cacheDir)
  • Environment.getExternalStorageDirectory() **Deprecated** ให้ใช้ context.getExternalFilesDirs()
  • ต้องขอ MANAGE_EXTERNAL_STORAGE สำหรับเข้าถึงทั้งเครื่อง (Special Permission)

📱 Storage Paths สำคัญ

Path Method คำอธิบาย
App Files context.filesDir Private, ลบเมื่อ Uninstall
App Cache context.cacheDir Private, ระบบอาจลบเมื่อพื้นที่น้อย
External Files context.getExternalFilesDir(null) Public-ish, ลบเมื่อ Uninstall
External Cache context.getExternalCacheDir() Public-ish, ระบบอาจลบ
Downloads Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS) Public, ต้อง Permission

ขั้นตอนที่ 4: AndroidManifest.xml

<!-- สำหรับ Android 9 และต่ำกว่า -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!-- Android 10 (API 29) Scoped Storage -->
<application android:requestLegacyExternalStorage="true" ...>

<!-- Android 11+ (API 30+) All Files Access -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

ทดสอบ

  1. รันแอป → แสดงพื้นที่ Internal/External/Cache ที่ว่าง
  2. ลอง Clear Cache ของแอปใน Settings → รันใหม่ Cache Free จะเพิ่มขึ้น