创建图像文件夹时崩溃

时间:2014-10-27 08:15:03

标签: android

我正在创建一个Android应用,它会截取屏幕截图并将其保存在App图像文件夹中,这是我用来创建文件夹并保存屏幕截图的代码:

            String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/Porte3D");    
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        // Write your image name here
        String fname = "Image-"+ n +".jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete (); 
        try {
               FileOutputStream out = new FileOutputStream(file);
               bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
               out.flush();
               out.close();

        } catch (Exception e) {
               e.printStackTrace();
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

我正在使用2个设备测试,一个三星Galaxy S2和一个moto G,在S2上创建文件夹并正确存储图像但是moto G崩溃时出现以下错误:

10-27 09:09:41.422: A/libc(12069): Fatal signal 6 (SIGABRT) at 0x00002f25 (code=-6), thread 12435 (Thread-62263)

有人知道如何解决这个问题,以便在每台设备上运行吗?

3 个答案:

答案 0 :(得分:1)

首先,您必须检查目录是否存在然后创建它。替换

myDir.mkdirs();

通过

if (! myDir.exists()){
        if (! myDir.mkdirs()){
            Log.d("MyAPp", "failed to create directory");
            return null;
        }
    }

您的代码中的另一个问题是,在KitKat中,您的代码将无效(这就是为什么它不能在moto g中工作)

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
   Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
  // File f = new File("folderPATH", "fileName");
   Uri contentUri = Uri.fromFile(myDir);
   mediaScanIntent.setData(contentUri);
   sendBroadcast(mediaScanIntent);
 } 
 else {
       sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +Environment.getExternalStorageDirectory() + "/" + "FOLDER_TO_REFRESH")));
    }

您的完整代码将是这样的

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/Porte3D");    
    if (! myDir.exists()){
      if (! myDir.mkdirs()){
        Log.d("MyAPp", "failed to create directory");
        return null;
       }
    }
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    // Write your image name here
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
      File f = new File(myDir, fname);
      Uri contentUri = Uri.fromFile(f);
      mediaScanIntent.setData(contentUri);
      sendBroadcast(mediaScanIntent);
     } 
   else {
     sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
   }

答案 1 :(得分:0)

我不知道你的代码存在实际问题,但值得一试

   MediaScannerConnection.scanFile(this,
          new String[] { file.toString() }, null,
          new MediaScannerConnection.OnScanCompletedListener() {
      public void onScanCompleted(String path, Uri uri) {
          Log.i("ExternalStorage", "Scanned " + path + ":");
          Log.i("ExternalStorage", "-> uri=" + uri);
      }
 });

确保您具有读写外部商店的正确权限 并传递您要扫描的文件名

答案 2 :(得分:0)

确定它会帮助你的人

   public class FileCache {

    /** The cache dir. */
    private File cacheDir;

    /**
     * Instantiates a new file cache.
     *
     * @param context the context
     */
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TempImages");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    /**
     * Gets the file.
     *
     * @param url the url
     * @return the file
     */
    public File getFile(String url){
        String filename=String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;

    }

    /**
     * Clear.
     */
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}