【问题标题】:Crash when creating image folder创建图像文件夹时崩溃
【发布时间】:2014-10-27 08:15:03
【问题描述】:

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

            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)

有谁知道如何解决这个问题以便在每台设备上都能正常工作?

【问题讨论】:

  • 使用前必须确保 ExternalStorage 可用
  • 这不是错误,ExternalStorage 在我的 Moto G 上可用
  • 还有一件事 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));这在 KitKat 中已被弃用,尽管这不是你崩溃的原因,但我只是跳出来,粘贴你的完整崩溃日志
  • 您是否允许在清单中使用外部存储?
  • 是的,@GeorgeThomas 我收到的崩溃日志只是我发布的那一行,我没有收到任何其他错误

标签: android


【解决方案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())));
   }

【讨论】:

  • 使用此代码应用程序不会崩溃,但在 Moto G 上我看不到文件夹上的屏幕截图,我没有传递 FolderPath 和 FileName 的变量,我应该创建它们?
  • @Signo 编辑了我的代码。如果您遇到其他问题,请尝试让我知道
  • 不,画廊仍然没有出现.. 非常感谢您的帮助 :)
  • 是的,现在它可以工作了,我一定是因为错误而改变了一些东西,我正在疯狂地试图解决这个问题:) 非常感谢!
【解决方案2】:

我不知道这是您代码的实际问题,但值得一试

   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);
      }
 });

确保您有正确的权限来读取和写入外部存储 并传递您要扫描的文件名

【讨论】:

    【解决方案3】:

    肯定会帮到你

       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();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多