在Android 10 之後的資料夾的檔案會用MediaStore 來控管,官方文件是說為了提供更好的使用者經驗,許多應用程式允許使用者訪問外部媒體。框架提供一個媒體庫。
在manifests檔中先加上外部管理權限。
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
調整一下UI ,練習用constract layout ,在textview 下加上一個button
接下來在OnSearch 的Button 中加上
public void search(View view) {
Intent it = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(it);
}
因onActivityResult方法已經棄用了,所以改用registerForActivityResult
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Intent it = result.getData();
Uri uri = it.getData();
getImage(uri);
}
}
);
撰寫一個getImage的方法
public void getImage(Uri uri){
cursor = cr.query(uri,mProjection,null,null,null);
// int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
if (cursor != null && cursor.moveToFirst()) {
// long id = cursor.getLong(idColumn);
@SuppressLint("Range") String imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
String fileName = cursor.getString(nameColumn);
Log.d(TAG, fileName);
Log.d(TAG, imgPath);
}
}
整個Activity 就會像這樣
在Android 10 的結果