Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Tạo thư mục (directory) lập trình trên Android

Giới thiệu

Ví dụ này minh họa cách tạo thư mục trên bộ nhớ ngoài (External Storage) bằng class java.io.File và Environment.getExternalStorageDirectory().

Bước 1: Tạo dự án mới

Tạo project Android Studio: File → New Project.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: MainActivity - Tạo thư mục

Lưu ý: Từ Android 10 (API 29), Environment.getExternalStorageDirectory() bị deprecated và truy cập bộ nhớ chung (shared storage) bị hạn chế (Scoped Storage). Nên dùng getExternalFilesDir() (app-specific directory) hoặc Storage Access Framework.

package com.app.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import java.io.File;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Cách cũ (Android 9 trở xuống): thư mục công khai
        File file = new File(Environment.getExternalStorageDirectory(), "Sample Directory");

        // Cách hiện đại (Android 10+): thư mục riêng của app - không cần quyền WRITE_EXTERNAL_STORAGE
        // File file = new File(getExternalFilesDir(null), "Sample Directory");

        if (!file.exists()) {
            boolean success = file.mkdirs(); // mkdirs() tạo cả thư mục cha nếu chưa có
            if (success) {
                Toast.makeText(getApplicationContext(), "Đã tạo thư mục: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Tạo thư mục thất bại", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Thư mục đã tồn tại: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        }
    }
}

Bước 4: Manifest - Quyền lưu trữ (Android 9 trở xuống)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Chạy app, Toast sẽ báo kết quả tạo thư mục.

Lưu ý quan trọng về Scoped Storage (Android 10+)

  • App-specific directory (getExternalFilesDir(), getExternalCacheDir()): Không cần quyền, tự động xóa khi uninstall app. Khuyến nghị dùng cách này.
  • MediaStore: Để lưu ảnh/video/audio công khai, dùng MediaStore.Images.Media.insertImage() hoặc ContentResolver.insert().
  • Storage Access Framework (SAF): Dùng ACTION_OPEN_DOCUMENT_TREE để người dùng chọn thư mục, app được quyền truy cập thư mục đó.
  • Environment.getExternalStorageDirectory() và WRITE_EXTERNAL_STORAGE bị restricted từ Android 11 (API 30). Chỉ dùng cho app hệ thống hoặc qua SAF.