How to write a file using Intent.ACTION_CREATE_DOCUMENT

眉间皱痕 提交于 2019-12-04 06:23:43

问题


In simple words, I want to convert a viewgroup to a jpg image file. As Environment.getExternalStorageDirectory is deprecated, I use this intent Intent.ACTION_CREATE_DOCUMENT

private void createFile(String mimeType, String fileName) {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType(mimeType);
        intent.putExtra(Intent.EXTRA_TITLE, fileName);
        startActivityForResult(intent, WRITE_REQUEST_CODE);
    }

In the onActivityResult(); I get the Uri returned by the result. My problem is that with getExternalStorage() I'd use

Bitmap bitmap = Bitmap.createBitmap(
                    containerLayout.getWidth(),
                    containerLayout.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            containerLayout.draw(canvas);
            FileOutputStream fileOutupStream = null;


            try {
                fileOutupStream = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutupStream);
                fileOutupStream.flush();
                fileOutupStream.close();
                Toast.makeText(this, "saved " + fileName, Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "something went wrong" + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

Now I get the Uri returned by the result but, I don't know how to write the desired bitmap into this Uri

@Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if (resultCode == RESULT_OK && requestCode == WRITE_REQUEST_CODE) {
                Uri resultUri = data.getData();
//need help

}
}

回答1:


You need to use getContentResolver().openOutputStream

        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if (resultCode == RESULT_OK && requestCode == WRITE_REQUEST_CODE) {
                FileOutputStream fileOutupStream = getContentResolver().openOutputStream(data.getData());
            try {
                fileOutupStream = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutupStream);
                fileOutupStream.flush();
                fileOutupStream.close();
                Toast.makeText(this, "saved " + fileName, Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "something went wrong" + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

}
}


来源:https://stackoverflow.com/questions/58166061/how-to-write-a-file-using-intent-action-create-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!