在往SD卡中写东西的时候SD卡突然不可用,系统会直接把程序给杀掉重新运行,没有异常,想通过广播处理也不行, 广播有延迟  ,有没有遇到过这种问题的,教教我怎么处理啊

解决方案 »

  1.   

    操作SD卡上的文件总需要各种状态的判断:    private void writeFileToSD() {
         String sdStatus = Environment.getExternalStorageState();
         if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
         Log.d("TestFile", "SD card is not avaiable/writeable right now.");
         return;
         }
         try {
         String pathName="/sdcard/test/";
         String fileName="file.txt";
         File path = new File(pathName);
         File file = new File(pathName + fileName);
         if( !path.exists()) {
         Log.d("TestFile", "Create the path:" + pathName);
         path.mkdir();
         }
         if( !file.exists()) {
         Log.d("TestFile", "Create the file:" + fileName);
         file.createNewFile();
         }
         FileOutputStream stream = new FileOutputStream(file);
         String s = "this is a test string writing to file.";
         byte[] buf = s.getBytes();
         stream.write(buf);    
         stream.close();
        
         } catch(Exception e) {
         Log.e("TestFile", "Error on writeFilToSD.");
         e.printStackTrace();
         }
        }
      

  2.   

    这种写法只能判断写文件之前SD卡是可用的,如果是在写的过程中插上数据线选择大容量存储或者拔掉了SD卡就没法判断了,我试过在写循环里的out.write(mBlock, 0, readSize)之前就用Environment.getExternalStorageState()获取SD卡的状态也不行
    while((readSize = is.read(mBlock)) != -1) {

    out.write(mBlock, 0, readSize);


    }
    }
      

  3.   


    可以监听
    ACTION_MEDIA_EJECT
    ACTION_MEDIA_REMOVED
    这类广播,在收到广播后120毫秒内把文件读写操作停止并关闭文件,这样程序是不会被关闭了的。
    120毫秒这个处理时间是某款手机上面测试得出来的时间,不同的机器可能会有些出入,也有可能会在收到这些广播之前应用程序就已经被关闭。