Android鎖屏出現java.lang.RuntimeException: Camera is being used after Camera.release() was called
阿新 • • 發佈:2019-01-05
java.lang.RuntimeException: Camera is being used after Camera.release() was called
在相機開發中,開啟相機顯示預覽,然後按關機鍵鎖屏,出現上述錯誤,程式崩潰。
原來程式碼如下:
@Override public void surfaceDestroyed(SurfaceHolder arg0) { // TODO Auto-generated method stub //super.onDestroy(); if(camera != null) { // holder.removeCallback(this); // camera.setPreviewCallback(null); camera.stopPreview(); } holder = null; }
@Override
protected void onPause() {
super.onPause();
finish();//如果點home鍵,銷燬當前頁,返回前一頁。
}
@Override
protected void onDestroy() {
super.onDestroy();
if(camera != null) {
camera.release();
}
finish();
}
之前如果點選home鍵,再點APP圖示進入程式,相機預覽介面黑屏,要返回上一頁再重新進入當前頁相機預覽介面才正常顯示。後來我想了個偷懶的做法,在onPause方法裡新增finish()方法,如果點home鍵,則銷燬當前頁,返回前一頁。
現在又出現了一個新問題,如果按關機鍵鎖屏,就會出現上面的錯誤。想到應該是activity的生命週期問題,就在清單檔案裡配置了禁止橫豎屏切換,還是出現上述錯誤。然後網上搜解決方法,有的說在surfaceDestroyed()新增holder.removeCallback(this),有的說新增holder.removeCallback(this)。經測試,無效。後來在onDestroy方法裡camera.release()後新增camera = null,問題解決。
修改後的程式碼:
@Override
protected void onDestroy() {
super.onDestroy();
if(camera != null) {
camera.release();
camera = null;
}
finish();
}
相關帖子:java.lang.RuntimeException: Camera is being used after Camera.release() was called