Android FileChooser的存儲(chǔ)路徑如何設(shè)置

小樊
82
2024-09-15 22:52:15
欄目: 云計(jì)算

在 Android 中,F(xiàn)ileChooser 的存儲(chǔ)路徑可以通過(guò) Intent 來(lái)設(shè)置。以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用 FileChooser 選擇一個(gè)文件并指定存儲(chǔ)路徑:

  1. 首先,在 AndroidManifest.xml 文件中添加讀取外部存儲(chǔ)的權(quán)限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. 然后,在你的 Activity 或 Fragment 中創(chuàng)建一個(gè)方法來(lái)啟動(dòng) FileChooser:
private static final int FILE_PICK_REQUEST_CODE = 1;

private void openFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "選擇文件"),
                FILE_PICK_REQUEST_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "請(qǐng)安裝文件管理器", Toast.LENGTH_SHORT).show();
    }
}
  1. 接下來(lái),重寫(xiě) onActivityResult 方法以處理 FileChooser 的結(jié)果:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == FILE_PICK_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
        Uri uri = data.getData();
        if (uri != null) {
            // 獲取到文件的 Uri,可以根據(jù)需要進(jìn)行處理
            String filePath = getPathFromUri(this, uri);
            // 使用 filePath 進(jìn)行相應(yīng)操作
        }
    }
}
  1. 最后,實(shí)現(xiàn)一個(gè)輔助方法 getPathFromUri 來(lái)獲取文件的路徑:
public String getPathFromUri(Context context, Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = null;

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(columnIndex);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return null;
}

現(xiàn)在,當(dāng)你調(diào)用 openFileChooser() 方法時(shí),將會(huì)彈出一個(gè)文件選擇器,用戶(hù)可以從中選擇一個(gè)文件。所選文件的路徑將通過(guò) onActivityResult 方法返回。

0