Android 文件选择 Android 文件选择的实现代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android 文件选择 Android 文件选择的实现代码

  2021-03-21 我要评论
想了解Android 文件选择的实现代码的相关内容吗,在本文为您仔细讲解Android 文件选择的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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/

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们