IT story

Android 파일 선택기 [닫힘]

hot-time 2020. 8. 5. 07:45
반응형

Android 파일 선택기 [닫힘]


파일 업 로더를 만들고 싶습니다. 따라서 파일 선택기가 필요하지만 직접 작성하고 싶지 않습니다. OI 파일 관리자를 찾은 후 본인에게 적합하다고 생각합니다. 그러나 사용자가 OI 파일 관리자를 설치하도록하려면 어떻게해야합니까? 내가 할 수 없다면 내 앱에 파일 관리자를 포함시키는 더 좋은 방법이 있습니까? 고마워


편집 ( 2012 년 1 월 2 일 ) :

이 프로세스를 간소화하는 작은 오픈 소스 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();
    }
}

선택한 파일의에 대한 당신은 듣지도 않을거야 UrionActivityResult()이렇게 같은 :

@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;
} 

나는이 목적으로 AndExplorer를 사용했으며 솔루션은 대화 상자가 표시된 다음 시장에 리디렉션되어 누락 된 응용 프로그램을 설치합니다.

내 startCreation이 외부 파일 / 디렉토리 선택기를 호출하려고합니다. 누락 된 경우 show installResultMessage 함수를 호출하십시오.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

이 methos는 대화 상자를 선택하고 사용자가 시장에서 외부 응용 프로그램을 설치하려는 경우

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

참고URL : https://stackoverflow.com/questions/7856959/android-file-chooser

반응형