2011-11-22 2 views
5

사진을 찍기 위해 카메라를 부릅니다. 그러나 사진을 찍은 후에는 원래의 활동으로 돌아갈 수 없습니다. 뭐가 문제 야? 고맙습니다.호출 의도에서 되돌아가는 방법

public void addEntry(View view) 
{ 
       String EntryName=RegisterName.toString(); 
       Toast.makeText(this, EntryName, Toast.LENGTH_LONG); 
       Intent addEntryintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File file = new File(getFilesDir(),EntryName); 
       registeryFileUri = Uri.fromFile(file); 
       addEntryintent.putExtra(MediaStore.EXTRA_OUTPUT, registeryFileUri); 
       startActivityForResult(addEntryintent,TAKE_PICTURE);   

} 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == TAKE_PICTURE) 
     { 
      if (data != null) 
      { 
     Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_LONG); 
     ImageView Registerimage= (ImageView)findViewById(R.id.RegisterPicture); 
     Registerimage.setImageURI(registeryFileUri); 
     } 

    } 
    } 
+0

'onActivityResult()'안에'Toast.show();'호출하는 것을 잊어 버렸습니다. Toast.makeText (this, "Successfully Registered!", Toast.LENGTH_LONG) .show();' –

답변

4

대답

사용 appContext.getExternalCacheDir()및 permissons을 언급하는 것을 잊지 마세요. 일부 장치 data

@Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
       if (requestCode == TAKE_PICTURE) 
       { 
         if(resultCode==Activity.RESULT_OK) 
        { //if (data != null) 
        //{ 
        Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_LONG); 
        ImageView Registerimage= (ImageView)findViewById(R.id.RegisterPicture); 
        Registerimage.setImageURI(registeryFileUri); 
        //} 
         } 
         else 
         Toast.makeText(this, "Not Registered!", Toast.LENGTH_LONG); 
      } 
**"android.permission.CAMERA"**  

Check whether the above permission is specified in your manifest or not 

Note: It's better to use getExternalCacheDir() than getFilesDir() if you still dont get the 
     image then use that. Dont forgot to specify the permission "android.permission.WRITE_EXTERNAL_STORAGE" if you use the getExternalCacheDir(). 
+0

'onActivityResult(); 안에 Toast.show();를 호출하는 것을 잊어 버렸습니다. –

+0

맞아. 하지만 문제는 의도와 함께 그래서 나는 나머지 코드를 확인하지 않았다. –

+0

어느 쪽도 작동하지 않습니다. 4.0을 사용 중이지만 여전히 카메라 활동에서 돌아올 수 없습니다. – James

1

불행하게도 카메라 활동을 호출 한 후 onActivityResult에 null이됩니다. 따라서 액티비티 변수에 상태를 저장해야 할 수도 있으며, 액티비티 변수는 onActivityResult으로 읽습니다. 이 변수는 onSaveInstanceState에 저장하고 onCreate으로 복원하십시오.

+1

"데이터! = null"이 추가되지 않더라도, 나는 여전히 카메라 활동에 갇혀 있습니다 ... – James

7

작업을 시작하는 데 시간이 걸렸으며 몇 가지 작업을했으며 마침내 작동합니다. 내가 한 일 중 어느 것이 문제의 해결책인지 확실히 말할 수는 없지만 모두 함께 작동하는 해결책을 형성합니다.

카메라 작동이 돌아 오지 않는 데에는 여러 가지 이유가 있습니다. 새로운 사진에 대한

  1. 경로가 잘못, 또는 존재하지 않는, 또는 그것은

  2. 응용 프로그램 중지 및 저장있어 경로가 길을 잃지 만들 수 없습니다 : 두 가지 주요 것들이다.

여기 내 모든 코드를 해결하는 코드가 있습니다. 모두 함께 작동합니다.

class ImageServices { 

    private static String getTempDirectoryPath(Context ctx) { 
    File cache; 

    // SD Card Mounted 
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 
     cache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + 
       "/Android/data/" + ctx.getPackageName() + "/cache/"); 
    } 
    // Use internal storage 
    else { 
     cache = ctx.getCacheDir(); 
    } 

    // Create the cache directory if it doesn't exist 
    if (!cache.exists()) { 
     cache.mkdirs(); 
    } 

    return cache.getAbsolutePath(); 
    } 

    public static Uri getOutputImageFileUri(Context ctx) { 
    // TODO: check the presence of SDCard 

    String tstamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    File file = new File(getTempDirectoryPath(ctx), "IMG_" + tstamp + ".jpg"); 

    return Uri.fromFile(file); 

    } 
} 

코드는 부분적으로 developer.android.com에 의해 부분적으로 아파치 코르도바 프로젝트의 CameraLauncher class에서 영감 :

먼저 나는 도우미 클래스 ImageServices를 만들었습니다. 사진을 찍을 수있는 버튼에 대한 이벤트 핸들러 내 활동에

은 다음과 같습니다 imageFileUri 이미 존재하는 파일을 가리키는 필요한 렌더링이 onResume에서 이루어집니다 진짜로하지 않습니다 onActivityResult

private Uri imageFileUri; 

private static final int MAKE_PHOTO_RESULT_CODE = 100; 
private static final int PICK_PHOTO_RESULT_CODE = 101; 

public void onMakePhoto(View v) { 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    imageFileUri = ImageServices.getOutputImageFileUri(this); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); 
    Log.i("babies", "Taking picture: requested " + imageFileUri); 
    startActivityForResult(intent, MAKE_PHOTO_RESULT_CODE); 
} 

방법이 많이 포함 활동이 전경에 돌아 오면 호출 방법 : 앱이 중단됩니다로 imageFileUri가 분실로

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
    switch(requestCode) { 
     case MAKE_PHOTO_RESULT_CODE: 
     assert imageFileUri != null; 
     break; 
     case ... 
     ...other cases... 
     break; 
    } 
    } 
} 

는하지만 여전히 충분하지 않습니다. 또한 일반 장치의 경우 100 %에 가깝습니다.그래서 다음에 당신은 인스턴스 상태에 imageFileUri의 값을 저장해야합니다

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    if (imageFileUri == null) { 
    outState.putString("file-uri", ""); 
    } 
    else { 
    outState.putString("file-uri", imageFileUri.toString()); 
    } 
}; 

을하고 다시로드 - 가장 쉬운 방법은 onCreate에 직접입니다 :

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    if (savedInstanceState != null) { 
    String fileUri = savedInstanceState.getString("file-uri"); 
    if (!fileUri.equals("")) imageFileUri = Uri.parse(fileUri); 
    } 
} 

그래서 다시 다른 많은 솔루션의 상단에

  1. 스마트 getTempDirectoryPath 아파치 코르도바
  2. 에서 영감 :이 사이트에뿐만 아니라 다른 곳에서 발표, 두 가지 차이점이 있습니다
  3. imageFileUri이 일시 중지 된 응용 프로그램에서 생존 할 수 있습니다.

이제는 적어도 모든 것이 잘 작동합니다.

+0

나는 하루 종일 머리카락을 꺼내왔다. 마지막으로이 해결책을 찾았습니다. 이 댓글을 볼 가능성은 없지만 그렇다면이 기기가 작동하지 않는 기기를 찾았습니까? 멋진 콘텐츠 @Tom Burger –

+0

앱이 아직 제작되지 않았으므로 테스트 할 장치가별로 없습니다. 그러나 위의 장치가 문제가 될 수있는 장치를 만난다면 확실히 알 수 있습니다 .-) –

관련 문제