从特定文件夹中选择图像

时间:2017-09-10 04:56:22

标签: android android-external-storage

我引用此link来显示内部存储中特定路径的图像。但它只能使用 ACTION_VIEW ,但是当我使用 ACTION_PICK 时,它没有显示相同的路径,而只是它的简单开放图库。显示后有没有办法从该特定路径中选择单个图像?

public class NewActivity extends AppCompatActivity{

    private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/fun";
    private File[] allFiles ;
    private String imagepath ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File folder = new File(file_path);
        allFiles = folder.listFiles();

        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new SingleMediaScanner(NewActivity.this, allFiles[0]);

            }
        });
    }

    public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {

        private MediaScannerConnection mMs;
        private File mFile;

        public SingleMediaScanner(Context context, File f) {
            mFile = f;
            mMs = new MediaScannerConnection(context, this);
            mMs.connect();
        }

        public void onMediaScannerConnected() {
            mMs.scanFile(mFile.getAbsolutePath(), null);
        }

        public void onScanCompleted(String path, Uri uri) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setData(uri);
            startActivityForResult(intent, 100);
            mMs.disconnect();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==100 && resultCode==RESULT_OK){
            try{
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.Images.Media.DATA};
                //Cursor cursor_gallery = activity.managedQuery(selectedImageUri, projection, null, null, null);
                Cursor cursor_gallery = getContentResolver().query(selectedImageUri, projection, null, null, null);
                int column_index = 0;
                if (cursor_gallery != null) {
                    column_index = cursor_gallery.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor_gallery.moveToFirst();
                    imagepath = cursor_gallery.getString(column_index);
                    cursor_gallery.close();
                }
                System.out.println("sammy_imagepath "+imagepath);

            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

当您制作ACTION_PICK意图时,您要求另一个应用程序执行操作(让他们选择一个文件)。没有办法确保它以某种方式工作 - 用户可以很容易地添加另一个实现ACTION_PICK并执行其他操作的应用程序。所以不,没有办法确保它会从那条路上挑选。如果你绝对需要,你需要实现自己的选择器,而不是使用ACTION_PICK。