如何在Android应用程序中浏览图像?

时间:2014-03-12 06:11:54

标签: android android-layout

我有一个在桌面上正常运行的应用程序。桌面应用程序上有一个按钮,用于打开gallary选择图像。 但是,当我在webview上运行该应用程序时,当我按下该按钮时会发生什么。它会打开我们的移动图像gallary。?

1 个答案:

答案 0 :(得分:0)

我创建了一个小型开源Android库项目,简化了这个过程,同时还提供了一个内置文件浏览器(如果用户没有一个存在)。它使用起来非常简单,只需要几行代码。

你可以在GitHub找到它:aFileChooser

如果您希望用户能够选择系统中的任何文件,则需要包含您自己的文件管理器,或建议用户下载文件管理器。我相信你能做的最好的事情就是在Intent.createChooser()中寻找“可打开的”内容,如下所示:

private static final int FILE_SELECT_CODE = 0;

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) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

然后您会在Uri中收听所选文件的onActivityResult(),如下所示:

@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();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

getPath()中的FileUtils.java方法是:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    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;
}