假设现在有这样一个需求需要一直开着手机摄像头 但是不做任何拍照动作
但是每个手机的相机分辨率都不同
而默认预览的时候参数是最大分辨率 这样有时候就回导致电量损耗的加快
所以我们可以采取降低相机分辨率的方法 这样既达到了目标 又节省了电量
package com.example.camerbatterytest; import java.io.IOException;
import java.util.List; import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button; public class CamerActivity extends Activity implements SurfaceHolder.Callback{ Button takephoto;//未实现
private SurfaceView mySurfaceView;
private SurfaceHolder mysurfaceHolder;
Camera camera;//5.0以后这个camera已经不推荐使用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camer);
takephoto=(Button)findViewById(R.id.takephoto);
mySurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
mysurfaceHolder=mySurfaceView.getHolder();
mysurfaceHolder.addCallback(this); }
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d("huang","surfaceCreated");
camera = Camera.open(); }
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("huang","surfaceview width="+width+" and height="+height);
Camera.Parameters parameters = camera.getParameters();
Camera.Size bestSize=getBestPreviewSize(width,height,parameters);
parameters.setPreviewSize(bestSize.width, bestSize.height);
camera.setParameters(parameters); try {
camera.setPreviewDisplay(mysurfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.setDisplayOrientation(90);//显示的方向旋转角度
camera.startPreview(); }
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
Log.d("huang","surfaceDestroyed");
if (camera != null)
{
camera.stopPreview();
camera.release();
} } private Camera.Size getBestPreviewSize(int surfaceViewWidth, int surfaceViewHeight, Camera.Parameters parameters) {
Camera.Size bestSize=null;
//不同机器 尺寸大小排序方式不一样 有的从小到大有的从大到小
for (Camera.Size size : parameters.getSupportedPreviewSizes())
{
if (size.width <= surfaceViewWidth && size.height <= surfaceViewHeight)
{
if (bestSize == null) //初始化一个值
bestSize=size;
else
{
int tempArea=bestSize.width * bestSize.height;
int newArea=size.width * size.height; if (newArea > tempArea) //取满足条件里面最大的
bestSize=size;
}
}
} return bestSize;
} }
主要是
getBestPreviewSize()方法获得了最合适的分辨率 即既小于当前surfaceview的width height又取支持分辨率里面最大的