Camera preview is completely black after screen off, screen on

丶灬走出姿态 提交于 2019-12-12 02:36:42

问题


I'm working with the CameraPreview in the API Demos that comes with the Android SDK. While the camera preview is running, if I turn off my screen and turn it on again, the camera preview is completely black. The device's camera application somehow manages to restore the camera preview, so there must be a way.

Not all devices I've tried exhibit this behavior. I can't confirm, but it seems like the OS version matters.


回答1:


You need to release and reacquire the camera in pause/resume. Here's some code from my CameraView widget:

public void onPause(){
    if(camera != null){
        camera.release();
        camera = null;
    }
}

public void onResume(){
    //Need to release if we already have one, or we won't get the camera
    if(camera != null){
        camera.release();
        camera = null;          
    }
    try {
        camera = Camera.open(); 
    }
    catch (Exception e){
    }

}



回答2:


What helped me was setContentView() in onResume().

It can be either

protected void onResume() {
    super.onResume();
    setContentView(R.layout.xxx);
    // ...
}

or

private View cachedContentView;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    cachedContentView = doCreateContentView(getLayoutInflater());
    // ...
}
protected void onResume() {
    super.onResume();
    setContentView(cachedContentView);
    // ...
}

Both of them work.




回答3:


I had the same problem. Maybe, it isn't the best solution, but it works for me. In onPause() method restart your camera activity.

private boolean isBackPreesed = false;

@Override
public void onPause() {
    if (camera != null) {
        camera.release();
        camera = null;
    }

    if (!isBackPreesed) {
        finish();
        Intent restart = new Intent(this, this.getClass());
        startActivity(restart);
    }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        isBackPreesed = true;
    }       
    return super.onKeyDown(keyCode, event);
}



回答4:


My solution is release camera in surfaceDestroyed method not in onPause method and restart camera in surfaceCreated method .The result is fine.



来源:https://stackoverflow.com/questions/13385839/camera-preview-is-completely-black-after-screen-off-screen-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!