欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 文件选择的实现代码

程序员文章站 2023-11-25 10:25:58
打开文件选择器复制代码 代码如下:private void showfilechooser() {    intent intent = ne...

打开文件选择器

复制代码 代码如下:

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/