2016-08-24 7 views
0

Google PhotoIntentActivity 샘플을 사용하여 내 앱에 기본 Android 카메라를 구현하고 있습니다. 이 샘플에서는 주 활동 (PhotoIntentActivity)에서 버튼을 클릭하면 카메라가 시작되고 사진을 찍은 다음 사진이 항상 동일한 활동에 배치 된 ImageView로 시각화됩니다. 거기에 머물지 않고 새로운 활동으로 사진을 의도적으로 시각화하고 싶습니다.Android 카메라로 사진을 찍은 후 새로운 활동 시작

주 활동에서 사진이 다시 전달되는 위치와 새로운 의도를 시작해야하는 위치를 이해할 수 없습니다. 다음 코드입니다.

public class PhotoIntentActivity extends Activity { 

    private static final int ACTION_TAKE_PHOTO = 1; 

    private static final String BITMAP_STORAGE_KEY = "viewbitmap"; 
    private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility"; 
    private ImageView mImageView; 
    private Bitmap mImageBitmap; 

    private static final String VIDEO_STORAGE_KEY = "viewvideo"; 
    private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility"; 
    private VideoView mVideoView; 
    private Uri mVideoUri; 

    private String mCurrentPhotoPath; 

    private static final String JPEG_FILE_PREFIX = "IMG_"; 
    private static final String JPEG_FILE_SUFFIX = ".jpg"; 

    private AlbumStorageDirFactory mAlbumStorageDirFactory = null; 


    /* Photo album for this application */ 
    private String getAlbumName() { 
     return getString(R.string.album_name); 
    } 


    private File getAlbumDir() { 
     File storageDir = null; 

     if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 

      storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName()); 

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

     } else { 
      Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE."); 
     } 

     return storageDir; 
    } 

    private File createImageFile() throws IOException { 
     // Create an image file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_"; 
     File albumF = getAlbumDir(); 
     File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF); 
     return imageF; 
    } 

    private File setUpPhotoFile() throws IOException { 

     File f = createImageFile(); 
     mCurrentPhotoPath = f.getAbsolutePath(); 

     return f; 
    } 

    private void setPic() { 

     /* There isn't enough memory to open up more than a couple camera photos */ 
     /* So pre-scale the target bitmap into which the file is decoded */ 

     /* Get the size of the ImageView */ 
     int targetW = mImageView.getWidth(); 
     int targetH = mImageView.getHeight(); 

     /* Get the size of the image */ 
     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     bmOptions.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
     int photoW = bmOptions.outWidth; 
     int photoH = bmOptions.outHeight; 

     /* Figure out which way needs to be reduced less */ 
     int scaleFactor = 1; 
     if ((targetW > 0) || (targetH > 0)) { 
      scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
     } 

     /* Set bitmap options to scale the image decode target */ 
     bmOptions.inJustDecodeBounds = false; 
     bmOptions.inSampleSize = scaleFactor; 
     bmOptions.inPurgeable = true; 

     /* Decode the JPEG file into a Bitmap */ 
     Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 

     /* Associate the Bitmap to the ImageView */ 
     mImageView.setImageBitmap(bitmap); 
     mVideoUri = null; 
     mImageView.setVisibility(View.VISIBLE); 
     mVideoView.setVisibility(View.INVISIBLE); 
    } 

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

    private void dispatchTakePictureIntent(int actionCode) { 

     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

     switch(actionCode) { 
      case ACTION_TAKE_PHOTO: 
       File f = null; 

       try { 
        f = setUpPhotoFile(); 
        mCurrentPhotoPath = f.getAbsolutePath(); 
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        f = null; 
        mCurrentPhotoPath = null; 
       } 
       break; 

      default: 
       break; 
     } // switch 

     startActivityForResult(takePictureIntent, actionCode); 
    } 



    private void handleBigCameraPhoto() { 

     if (mCurrentPhotoPath != null) { 
      setPic(); 
      galleryAddPic(); 
      mCurrentPhotoPath = null; 
     } 

    } 

    private void handleCameraVideo(Intent intent) { 
     mVideoUri = intent.getData(); 
     mVideoView.setVideoURI(mVideoUri); 
     mImageBitmap = null; 
     mVideoView.setVisibility(View.VISIBLE); 
     mImageView.setVisibility(View.INVISIBLE); 
    } 

    Button.OnClickListener mTakePicOnClickListener = 
      new Button.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        dispatchTakePictureIntent(ACTION_TAKE_PHOTO); 
       } 
      }; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mImageView = (ImageView) findViewById(R.id.imageView1); 
     mVideoView = (VideoView) findViewById(R.id.videoView1); 
     mImageBitmap = null; 
     mVideoUri = null; 

     Button picBtn = (Button) findViewById(R.id.btnIntend); 
     setBtnListenerOrDisable(
       picBtn, 
       mTakePicOnClickListener, 
       MediaStore.ACTION_IMAGE_CAPTURE 
     ); 


     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { 
      mAlbumStorageDirFactory = new FroyoAlbumDirFactory(); 
     } else { 
      mAlbumStorageDirFactory = new BaseAlbumDirFactory(); 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch (requestCode) { 
      case ACTION_TAKE_PHOTO: { 
       if (resultCode == RESULT_OK) { 
        handleBigCameraPhoto(); 
       } 
       break; 
      } // ACTION_TAKE_PHOTO 

     } // switch 
    } 

    // Some lifecycle callbacks so that the image can survive orientation change 
    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap); 
     outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri); 
     outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null)); 
     outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null)); 
     super.onSaveInstanceState(outState); 
    } 

    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) { 
     super.onRestoreInstanceState(savedInstanceState); 
     mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY); 
     mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY); 
     mImageView.setImageBitmap(mImageBitmap); 
     mImageView.setVisibility(
       savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? 
         ImageView.VISIBLE : ImageView.INVISIBLE 
     ); 
     mVideoView.setVideoURI(mVideoUri); 
     mVideoView.setVisibility(
       savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ? 
         ImageView.VISIBLE : ImageView.INVISIBLE 
     ); 
    } 

    /** 
    * Indicates whether the specified action can be used as an intent. This 
    * method queries the package manager for installed packages that can 
    * respond to an intent with the specified action. If no suitable package is 
    * found, this method returns false. 
    * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html 
    * 
    * @param context The application's environment. 
    * @param action The Intent action to check for availability. 
    * 
    * @return True if an Intent with the specified action can be sent and 
    *   responded to, false otherwise. 
    */ 
    public static boolean isIntentAvailable(Context context, String action) { 
     final PackageManager packageManager = context.getPackageManager(); 
     final Intent intent = new Intent(action); 
     List<ResolveInfo> list = 
       packageManager.queryIntentActivities(intent, 
         PackageManager.MATCH_DEFAULT_ONLY); 
     return list.size() > 0; 
    } 

    private void setBtnListenerOrDisable(
      Button btn, 
      Button.OnClickListener onClickListener, 
      String intentName 
    ) { 
     if (isIntentAvailable(this, intentName)) { 
      btn.setOnClickListener(onClickListener); 
     } else { 
      btn.setText(
        getText(R.string.cannot).toString() + " " + btn.getText()); 
      btn.setClickable(false); 
     } 
    } 

} 

아무도 도와 줄 수 있습니까? 감사합니다

+0

[: 새 Activity에서이 경로를 검색 할 수 있습니다 그리고

Intent intent = new Intent(this, ViewActivity.class); intent.setData(Uri.parse(mCurrentPhotoPath)); startActivity(intent); 

시나리오입니다] (https://github.com/commonsguy/cw-omnibus/tree/master/Camera/FileProvider). – CommonsWare

+0

매우 흥미 롭습니다. 감사! – andraga91

답변

1

파일은 createImageFile() 메서드에서 가져온 경로에 저장되며 mCurrentPhotoPath으로 저장됩니다. setPic() 에서처럼 BitmapFactory.decodeFile()과 같이 언제든지이 경로에서 사진을 검색 할 수 있습니다. 따라서, 새로운 Activity의 이미지를 볼 수, 당신은 단지에 해당 경로를 통과해야 IntentonActivityResult()에 : 여기

String photoPath = getIntent().getData().toString(); 
+0

@Bryan 응답을 완료하려면 onActivityResult 메소드에서 startActivity (intent)를 호출하십시오. – ingyesid

+0

내가 제안한 것을 구현했지만, 오류가 발생했습니다. 'intent.setData (Uri.parse (mCurrentPhotoPath)); ' 해당 행을 삭제하면 새로운 활동이 올바르게 시작됩니다. 안드로이드 모니터에서 나는 다음을 얻습니다 : '.... : java.lang.NullPointerException : uriString' '원인 : java.lang.NullPointerException : uriString' at android.net.Uri $ StringUri. (Uri.java:470) android.net.Uri $ StringUri에서 ' '. (Uri.java:460) android.net.Uri.parse (Uri.java:432)의 ' '은 – andraga91

+0

@ andraga91입니다. 즉,'mCurrentPhotoPath'는'null'입니다. onActivityResult()에서이 코드를 호출 했습니까? 'createImageFile()'메서드를 호출 한 후에 만 ​​호출해야합니다.이 메서드는'mCurrentPhotoPath'를 설정 한 곳이기 때문에'null'이 아니어야합니다. – Bryan

관련 문제