2014-04-23 2 views
0

i 안드로이드에서 이미지를 저장할 때 안드로이드에서 이미지를 저장할 때 안드로이드 2.3에서 4.2.0까지는 완벽한 작업이지만 안드로이드 kitkat 버전은 작동하지 않습니다. 문제가 있습니다. 아래 내 맞춤 카메라 활동 코드.크래시 앱 안드로이드 용 안드로이드 카메라 패키지의 kitkat

도와주세요!

public class CameraActivity extends Activity { 

    Camera mCamera; 
    CameraPreview mCameraPreview; 
    protected static final int MEDIA_TYPE_IMAGE = 0; 
    static String FilePAth = ""; 
    Button takePicture, btnGlr, btnCancelCamera; 
    static String base64string = ""; 
    String ImageType; 
    Boolean isSDPresent; 
    final int RESULT_LOAD_IMAGE = 1; 
    File file; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.camera_preview); 
     isSDPresent = android.os.Environment.getExternalStorageState().equals(
       android.os.Environment.MEDIA_MOUNTED); 
     mCamera = getCameraInstance(); 

     mCameraPreview = new CameraPreview(CameraActivity.this, mCamera); 
     FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); 
     preview.addView(mCameraPreview); 

     takePicture = (Button) findViewById(R.id.btnTakePicture); 
     takePicture.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       mCamera.takePicture(null, null, mPicture); 
      } 
     }); 

     Intent intent = getIntent(); 

     if (intent.hasExtra("ImageType")) { 
      ImageType = getIntent().getStringExtra("ImageType").toString(); 

      Log.v("log", " ImageType in Camera Activity -- > " + ImageType); 
     } 

     btnGlr = (Button) findViewById(R.id.btnGallary); 
     btnGlr.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       Intent i = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       startActivityForResult(i, RESULT_LOAD_IMAGE); 

      } 
     }); 

     btnCancelCamera = (Button) findViewById(R.id.btnCancelCamera); 
     btnCancelCamera.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       Intent intent = new Intent(getApplication(), 
         MarketPlaceActivity.class); 
       startActivity(intent); 
      } 
     }); 

    } 

    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     releaseCamera(); 
    } 

    private void releaseCamera() { 
     if (mCamera != null) { 
      mCamera.release(); // release the camera for other applications 
      mCamera = null; 
     } 
    } 

    private Camera getCameraInstance() { 

     try { 
      Log.v("log_tag", "camera try:::" + mCamera); 
      mCamera = Camera.open(); 

     } catch (Exception e) { 
      // cannot get camera or does not exist 
      Log.v("log_tag", "camera catch:::" + mCamera); 
      releaseCamera(); 
     } 
     return mCamera; 
    } 

    private static File getOutputMediaFile() { 
     File mediaStorageDir = new File(
       Environment 
         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
       "MyCameraApp"); 

     if (!mediaStorageDir.exists()) { 
      if (!mediaStorageDir.mkdirs()) { 
       Log.d("MyCameraApp", "failed to create directory"); 
       return null; 
      } 
     } 
     // Create a media file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") 
       .format(new Date()); 

     FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_" 
       + timeStamp + ".jpg"; 

     Log.v("log", " FilePAth " + FilePAth); 

     File mediaFile; 
     mediaFile = new File(FilePAth); 

     return mediaFile; 
    } 

    /*private String SaveImage_Sta(Bitmap finalBitmap, String name) { 

     if (isSDPresent) { 
      Log.i("isSDPresent yes", " path is==> " + isSDPresent); 
      String root = Environment.getExternalStorageDirectory().toString() 
        + "/profile"; 
      File myDir = new File(root); 
      myDir.mkdirs(); 
      Random generator = new Random(); 
      int n = 10000; 
      n = generator.nextInt(n); 
      String fname = name + ".jpg"; 
      file = new File(myDir, fname); 
      if (file.exists()) 
       file.delete(); 
      try { 
       FileOutputStream out = new FileOutputStream(file); 
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
       out.flush(); 
       out.close(); 

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

      Log.i("isSDPresent no ", " path is==> false "); 
      ContextWrapper cw = new ContextWrapper(getApplicationContext()); 
      // path to /data/data/yourapp/app_data/imageDir 
      File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); 
      // Create imageDir 
      file = new File(directory, "profile.jpg"); 

      if (file.exists()) 
       file.delete(); 
      try { 
       FileOutputStream fos = new FileOutputStream(file); 
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); 
       fos.flush(); 
       fos.close(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return file.toString(); 
    }*/ 

    PictureCallback mPicture = new PictureCallback() { 
     @Override 
     public void onPictureTaken(byte[] data, Camera camera) { 
      File pictureFile = getOutputMediaFile(); 
      if (pictureFile == null) { 
       return; 
      } 
      try { 

       FileOutputStream fos = new FileOutputStream(pictureFile); 
       fos.write(data); 
       fos.close(); 

       if (ImageType.equals("AddPicture")) { 
        Intent i = new Intent(getBaseContext(), 
          MarketPlaceActivity.class); 
        i.putExtra("data", data); 
        startActivity(i); 
       } else { 
        Intent returnIntent = new Intent(); 
        returnIntent.putExtra("data", data); 
        setResult(RESULT_OK, returnIntent); 
        CameraActivity.this.finish(); 
       } 

       // mCamera.startPreview(); 
      } catch (FileNotFoundException e) { 

      } catch (IOException e) { 
      } 
     } 
    }; 

    public void onBackPressed() { 
     Intent returnIntent = new Intent(); 
     returnIntent.putExtra("path", FilePAth); 
     setResult(RESULT_OK, returnIntent); 
     finish(); 
    }; 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK 
       && null != data) { 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      cursor.moveToFirst(); 
      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String picturePath = cursor.getString(columnIndex); 
      Log.v("log", " picturePath --> selected Gallary Image path --> " 
        + picturePath); 
      cursor.close(); 

      InputStream iStream; 
      byte[] inputData = null; 

      try { 
       iStream = getContentResolver().openInputStream(selectedImage); 
       inputData = getBytes(iStream); 

       Log.v("log", " selected Gallary Image ByteArray --> " 
         + inputData); 

      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      if (ImageType.equals("AddPicture")) { 
       Intent i = new Intent(getBaseContext(), 
         MarketPlaceActivity.class); 
       i.putExtra("data", inputData); 
       i.putExtra("image_from", "Gallary"); 
       startActivity(i); 
      } else { 
       Intent returnIntent = new Intent(); 
       returnIntent.putExtra("data", inputData); 
       returnIntent.putExtra("image_from", "Gallary"); 
       setResult(RESULT_OK, returnIntent); 
       CameraActivity.this.finish(); 
      } 

      // ImageView imageView = (ImageView) findViewById(R.id.imgView); 
      // imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 
     } 
    } 

    public byte[] getBytes(InputStream inputStream) throws IOException { 
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
     int bufferSize = 1024; 
     byte[] buffer = new byte[bufferSize]; 

     int len = 0; 
     while ((len = inputStream.read(buffer)) != -1) { 
      byteBuffer.write(buffer, 0, len); 
     } 
     return byteBuffer.toByteArray(); 
    } 

} 
+1

을 충돌이 있다면, 스택 추적 – shkschneider

+0

를 게시 난 더 킷캣의 vesion 장치 그러나 클라이언트 확인이 장치에 카메라가 충돌 열 수 없다. – crickpatel0024

+0

나는 그것이 누락 된 권한으로 인해 생긴 것 같아요 android.permission.WRITE_EXTERNAL_STORAGE 권한을 추가해보십시오 - 에뮬레이터를 사용하여 다른 API 버전의 앱을 테스트하십시오. –

답변

3

나는 권한이 SD 카드에 처리하는 방법, 안드로이드 4.4 (킷캣)이 변경되었습니다 내 댓글에 말했듯이. 이제 SD 카드에 자신의 디렉토리를 만들어 앱이 작성해야하는 모든 파일을 처리하는 것이 가장 좋습니다. 지금은 앱에서 소유하거나 생성하지 않은 Pictures 폴더에 액세스하려고합니다. 이에 getOutputMediaFile() 내용을 변경 :

private static File getOutputMediaFile() { 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/MyCameraApp/"); 
    if (!mediaStorageDir.exists()) { 
     mediaStorageDir.mkdir(); 
    } 
    return mediaStorageDir; 
}