2015-12-03 133 views
0

我在寫一個訪問攝像頭的程序。它工作了一段時間,但現在它是Camera API拋出異常,因爲當我試圖打開它時,相機仍在使用中。我認爲這是因爲我在onPause,onResume和我使用它的地方沒有正確處理它。這裏是我的代碼:管理攝像頭 - 無法訪問攝像頭

@Override 
protected void onResume(){ 
    if (!getPackageManager() 
      .hasSystemFeature(PackageManager.FEATURE_CAMERA)) { 
     Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG) 
       .show(); 
    } else { 
     cameraId = findFrontFacingCamera(); 
     if (cameraId < 0) { 
      Toast.makeText(this, "No front facing camera found.", 
        Toast.LENGTH_LONG).show(); 
     } else { 
      try { 
       if (camera != null) { 
        camera.release(); 
        camera = null; 
       } 
       camera = Camera.open(cameraId); 
       try { 
        camera.setPreviewTexture(cameraTexture); 
       } 
       catch(IOException e){ 
        Log.i("CameraHome", "could not set camera preview"); 
       } 
      } 
      catch (Exception e){ 

      } 
     } 
    } 
    super.onResume();} 

暫停:

@Override 
public void onPause(){ 
    stopLocationUpdates(); 
    SharedPreferences.Editor editor = sharedPreferences.edit(); 
    editor.putLong("timeLeft", timeLeft); 
    editor.putBoolean("lockedOut", lockedOut); 
    editor.apply(); 
    if (camera != null) { 
     camera.release(); 
     camera = null; 
    } 
    super.onPause(); 
} 

在使用中:

//Take picture 
    camera.startPreview(); 
    camera.takePicture(null, null, 
      new PhotoHandler(getApplicationContext())); 
    camera.stopPreview(); 
    camera.release(); 

有任何想法就是我做錯了嗎?每次我重新啓動應用程序時,即使啓動默認相機應用程序並關閉它,它也會引發異常,說明相機正在使用中。

編輯:正在訪問攝像頭,但我的回調(在PhotoHandler中的onPictureTaken)永遠不會被調用,就好像圖片沒有被正確捕獲。

+0

一切看起來都很好我已檢查它在S3和工作正常,你可以給一些樣品,可以產生你得到的錯誤,所以我可以幫助 – Sandy

+0

就是這樣。這是我在相機上調用方法的唯一例子。我有一種感覺,因爲沒有將它釋放到系統中而弄亂了相機。現在,即使我有適當的代碼,它仍然無法訪問,因爲我之前搞砸了......在這種情況下,我想知道是否有一種方法來重置相機 – sadelbrid

+0

'camera.startPreview(); camera.takePicture(null,null, new PhotoHandler(getApplicationContext())); camera.stopPreview(); camera.release();'在這裏你必須刪除'camera.stopPreview(); camera.release();' – Sandy

回答

0

原來這段代碼有效。必須卸載,重新啓動並重新安裝。然後我的onPictureTaken回調沒有被調用。我相信這是因爲我很快就打電話給stopPreview。我把它移到了我的onPause,並在takePicture調用之後拿走了釋放呼叫。現在工作正常