Fix Camera.setPreview() crash

I was playing around with the camera capabilities in one of my apps when I encountered repeated crashes with error on my HTC Magic:

java.lang.RuntimeException: startPreview
failed at android.hardware.Camera.startPreview(Native Method)

It seems that when the screen orientation changed, the reported preview dimension did not synchronize with the new rotated screen size. I tried many different approaches to ensure that the dimension was was properly set, to no avail.

There is a report of the issue here. It seems to be an issue with API version 7 (android 2.1 update) on HTC phones. The solution is to simply not call the Camera.setPreview().

So a working ( albeit a bit hacky ) solution would be:

private void startCamera(int width, int height) {
	if ( _isPreview == true )
	{
		camera.stopPreview();
	}

	Camera.Parameters params = camera.getParameters();
	// * Should set the preview size, but crashes on android 2.1
	// removing it make it work
	// http://code.google.com/p/android/issues/detail?id=7909
	//
	//params.setPreviewSize(width, height);
	params.setPictureFormat(PixelFormat.JPEG);
	camera.setParameters(params);
	camera.startPreview();
	_isPreview = true;
}

protected void onPause() {
	super.onPause();
	stopCamera();
	_paused = true;
}

private void stopCamera() {
	if ( camera != null )
	{
		camera.stopPreview();
		camera.release();
		camera = null;
		_isPreview = false;
	}
}

If you absolutely must set a preview size. I heard from the grapevines that calling Camera.stopPreview() before setting the preview size should fix the problem. But I already tried this and it doesn’t seem to work. However reloading the Camera object may be another approach. I have not tried it yet, let me know if it works.

This entry was posted in Android. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Tom
    Posted April 10, 2011 at 11:27 pm | Permalink

    Thank you very much! I was bashing my head against the wall before I saw your post. I observed the same problem on my HTC MyTouch 3G with API Level 7.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>