Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 文件選擇的實現代碼

Android 文件選擇的實現代碼

編輯:關於Android編程

打開文件選擇器
復制代碼 代碼如下:
private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();
    }
}

選擇的結果
復制代碼 代碼如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)  {
    switch (requestCode) {
        case FILE_SELECT_CODE:     
        if (resultCode == RESULT_OK) { 
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String path = FileUtils.getPath(this, uri);
        }          
        break;
    }
super.onActivityResult(requestCode, resultCode, data);
}

FileUtils文件
復制代碼 代碼如下:
public class FileUtils {
    public static String getPath(Context context, Uri uri) {

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection,null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        }

        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
}

這個很簡單。


出處:http://www.cnblogs.com/linlf03/

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved