Android write files to USB via OTG cable

后端 未结 2 365
闹比i
闹比i 2020-12-17 06:22

I\'ve been searching for many topics about android file writing, yet most of them wanted to write files to android internal storage. Others who wanted to write files on exte

2条回答
  •  天涯浪人
    2020-12-17 07:17

    From android 4.4, you can use Storage Access Framework to access to removable media (see https://commonsware.com/blog/2014/04/09/storage-situation-removable-storage.html). For example, I tried with success to copy a pdf file from local memory to removable memory connected by OTG adapter. The only limitation: the user has to choose a destination folder.

    1) call Intent.ACTION_CREATE_DOCUMENT:

    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.setType("application/pdf");
    intent.putExtra(Intent.EXTRA_TITLE, file.getName());
    startActivityForResult(intent, REQUEST_CODE);
    

    2) intercept the return intent

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE) {
            if (resultCode != RESULT_OK) return;
            copyFile(fileToCopy, data.getData());
        }
    }
    

    3) use the ContentResolver to open the outputStream and use it to copy the file

    private void copyFile(File src, Uri destUri) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
    
        try {
            bis = new BufferedInputStream(new FileInputStream(src));
            bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
            byte[] buf = new byte[1024];
            bis.read(buf);
            do {
                bos.write(buf);
            } while(bis.read(buf) != -1);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) bis.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题