Android saving file to external storage

后端 未结 12 748
抹茶落季
抹茶落季 2020-11-22 03:12

I have a little issue with creating a directory and saving a file to it on my android application. I\'m using this piece of code to do this :

String filename         


        
12条回答
  •  鱼传尺愫
    2020-11-22 03:41

    This code is Working great & Worked on KitKat as well. Appreciate @RajaReddy PolamReddy
    Added few more steps here and also Visible on Gallery as well.

    public void SaveOnClick(View v){
    File mainfile;
    String fpath;
    
    
        try {
    //i.e  v2:My view to save on own folder     
            v2.setDrawingCacheEnabled(true);
    //Your final bitmap according to my code.
            bitmap_tmp = v2.getDrawingCache();
    
    File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+File.separator+"/MyFolder");
    
              Random random=new Random();
              int ii=100000;
              ii=random.nextInt(ii);
              String fname="MyPic_"+ ii + ".jpg";
                File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
    
                if (!direct.exists()) {
                    File wallpaperDirectory = new File("/sdcard/MyFolder/");
                    wallpaperDirectory.mkdirs();
                }
    
                mainfile = new File(new File("/sdcard/MyFolder/"), fname);
                if (mainfile.exists()) {
                    mainfile.delete();
                }
    
                  FileOutputStream fileOutputStream;
            fileOutputStream = new FileOutputStream(mainfile);
    
            bitmap_tmp.compress(CompressFormat.JPEG, 100, fileOutputStream);
            Toast.makeText(MyActivity.this.getApplicationContext(), "Saved in Gallery..", Toast.LENGTH_LONG).show();
            fileOutputStream.flush();
            fileOutputStream.close();
            fpath=mainfile.toString();
            galleryAddPic(fpath);
        } catch(FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    

    This is Media scanner to Visible in Gallery.

    private void galleryAddPic(String fpath) {
        Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        File f = new File(fpath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }
    

提交回复
热议问题