ภาพรวม
ตัวอย่างนี้สาธิตวิธีอ่านไฟล์รูปภาพจาก External Storage พร้อมการขอ Runtime Permission สำหรับ Android 6.0+
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → กรอกรายละเอียด
ขั้นตอนที่ 2: ออกแบบ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/read"
android:text="Read"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ขั้นตอนที่ 3: เขียน MainActivity.java (แก้ไขโค้ดให้ถูกต้อง)
package com.example.andy.myapplication;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 100;
Button read;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
read = findViewById(R.id.read);
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (Build.VERSION.SDK_INT >= 23) {
// Android 6.0+ ต้องขอ Runtime Permission
if (checkPermission()) {
loadImageFromExternalStorage();
} else {
requestPermission();
}
} else {
// Android 5.1 ลงมา
loadImageFromExternalStorage();
}
} else {
Toast.makeText(MainActivity.this, "External Storage ไม่พร้อมใช้งาน", Toast.LENGTH_SHORT).show();
}
}
});
}
private void loadImageFromExternalStorage() {
// สมมติไฟล์อยู่ที่ Root ของ External Storage ชื่อ images.jpeg
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/images.jpeg");
if (dir.exists()) {
Log.d("path", dir.toString());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// โหลดรูปภาพ
Bitmap bitmap = BitmapFactory.decodeFile(dir.getAbsolutePath(), options);
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "ไม่พบไฟล์ images.jpeg ใน External Storage", Toast.LENGTH_SHORT).show();
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(this, "ต้องการสิทธิ์อ่าน External Storage กรุณาอนุญาตใน Settings", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted");
loadImageFromExternalStorage();
} else {
Log.e("value", "Permission Denied");
Toast.makeText(this, "ไม่ได้รับอนุญาต ไม่สามารถอ่านไฟล์ได้", Toast.LENGTH_SHORT).show();
}
}
}
}
หมายเหตุ: โค้ดต้นฉบับมีข้อผิดพลาดหลายจุด (ตัวดำเนินการ < แทน =, && แทน &&) โค้ดข้างบนได้แก้ไขให้ถูกต้องแล้ว
ขั้นตอนที่ 4: กำหนดสิทธิ์ใน AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.andy.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_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>
การทดสอบและผลลัพธ์


ข้อมูลสำคัญสำหรับ Android 10+ (API 29+)
Scoped Storage การเปลี่ยนแปลง
- Android 10 (API 29): Scoped Storage เริ่มใช้งาน ตั้งค่า
android:requestLegacyExternalStorage="true"ใน Manifest ยังใช้วิธีเก่าได้ - Android 11 (API 30+): Scoped Storage บังคับ ไม่สามารถเข้าถึงไฟล์โดยตรงด้วย File API ได้แล้ว
วิธีที่แนะนำสำหรับ Android 10+
// ใช้ MediaStore API
Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
String[] projection = new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(collection, projection, null, null, null);
// หรือใช้ Storage Access Framework (SAF)
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
ใช้ getExternalFilesDir() (ไม่ต้อง Permission)
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "images.jpeg");
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageView.setImageBitmap(bitmap);
}
สรุป
การอ่านรูปภาพจาก External Storage ต้องขอ READ_EXTERNAL_STORAGE Permission สำหรับ Android 6.0-9.0 แต่สำหรับ Android 10+ ควรเปลี่ยนไปใช้ MediaStore API หรือเก็บไฟล์ใน App-specific Directory (getExternalFilesDir()) ที่ไม่ต้องการ Permission