<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f000"
android:orientation="vertical" >
<ImageView
android:id="@+id/id_iv_switch1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/app_name"
android:scaleType="centerInside"
android:src="@drawable/switch_camera_bg"
android:visibility="gone" />
<android.view.SurfaceView
android:id="@+id/id_camera_PreviewView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.view.SurfaceView>
<RelativeLayout
android:id="@+id/id_layout_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<ImageView
android:id="@+id/id_iv_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/app_name"
android:scaleType="centerInside"
android:src="@drawable/switch_camera_bg" />
</RelativeLayout>
<LinearLayout
android:id="@+id/id_layout_takepicture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true">
<ImageView
android:id="@+id/id_iv_takepicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:contentDescription="@string/app_name"
android:scaleType="centerInside"
android:src="@drawable/photo" />
</LinearLayout>
</RelativeLayout>
package com.huawei.colorband.af500.ui;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import com.huawei.colorband.af500.R;
import com.huawei.colorband.af500.command.XCommand;
import com.huawei.colorband.af500.utils.CommonUtil;
import com.huawei.colorband.af500.utils.LogUtils;
import android.R.integer;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
public class RemoteTakePictureActivity extends Activity implements Callback
{
protected static final String TAG = "RemoteTakePictureActivity";
protected static final boolean Debug = true;
//
public static final String SHUTTER_ACTION = "com.fenda.hwbracelet.camera.TAKEPHOTO";
public static final int MARGIN_TOP_BOTTOM = 50;
public static final int CAMERA_ZOOM_OUT = 1;
public static final int CAMERA_ZOOM_IN = 2;
private Camera mCamera;
private Camera.Parameters mCameraParams;
private ImageView mIvSwitch;
private SurfaceView mSurfaceView;
private ImageView mIvTakePicture;
private int mCameraId = 0;
private int mFrontCameraId = -1;
private int mCameraPosition = 1;// 0代表前置摄像头,1代表后置摄像头
private MediaPlayer mMediaPlayer;
private MpOnCompletionListener mMpOnCompletionListener = new MpOnCompletionListener();
private MpOnErrorListener mMpOnErrorListener = new MpOnErrorListener();
private boolean mbMusicPlaying = false;
private boolean mbTakeingPicture = false;
private boolean mbSavingFile = false;
private boolean mbExit = false;
private FdViewOnclickListener mViewOnclickListener = new FdViewOnclickListener();
private SurfaceHolder mSurfaceHolder;
protected List<Camera.Size> mPreviewSizeList;
protected List<Camera.Size> mPictureSizeList;
protected Camera.Size mPreviewSize;// 预览大小
protected Camera.Size mPictureSize;
private int miPreviewWidth;// 手机屏幕预览大小(与mPreviewSize比例一样,大小不一样)
private int miPreviewHeight;
private int miScreenWidth = 0;
private int miScreenHeight = 0;
private int miPictureFormat = 0;
private int mCurZoom = 0;// 最多放大5倍
private int miZoomMode = 0;
private float mfOldDistance;
private int miSwitchPictureWidth = 0;
private int miSwitchPictureHeight = 0;
private int miTakePictureWidth = 0;
private int miTakePictureHeight = 0;
private int miNavigation = 0;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (Debug)
{
LogUtils.i(TAG, "onCreate savedInstanceState:" + savedInstanceState);
}
/** 隐藏标题栏 **/
requestWindowFeature(Window.FEATURE_NO_TITLE);
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
{
//全屏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
else
{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/** 禁用锁屏,因为再次唤醒屏幕程序就会终止,暂时不知道怎么解决 **/
getWindow()
.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_remote_takepicture);
//
DisplayMetrics dMetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
display.getMetrics(dMetrics);
miScreenWidth = dMetrics.widthPixels; // 屏幕宽度(像素)
miScreenHeight = dMetrics.heightPixels; // 屏幕高度(像素)
// 新版本的android 系统有导航栏,造成无法正确获取高度
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.HONEYCOMB_MR2)//13
{
try
{
Method mt = display.getClass().getMethod("getRealHeight");
miScreenHeight = (Integer) mt.invoke(display);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
display.getRealMetrics(dMetrics);
miNavigation = dMetrics.heightPixels-miScreenHeight;
if (Debug)
{
LogUtils.i(TAG, "onCreate miNavigation:" + miNavigation);
}
miScreenWidth = dMetrics.widthPixels; // 屏幕宽度(像素)
miScreenHeight = dMetrics.heightPixels; // 屏幕高度(像素)
}
else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2)
{
// try
// {
// Method mt = display.getClass().getMethod("getRawHeight");
// miScreenHeight = (Integer) mt.invoke(display);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
display.getRealMetrics(dMetrics);
miNavigation = dMetrics.heightPixels-miScreenHeight;
if (Debug)
{
LogUtils.i(TAG, "onCreate miNavigation:" + miNavigation);
}
miScreenWidth = dMetrics.widthPixels; // 屏幕宽度(像素)
miScreenHeight = dMetrics.heightPixels; // 屏幕高度(像素)
}
// if (Debug)
{
LogUtils.i(TAG, "onCreate miScreenWidth:" + miScreenWidth);
LogUtils.i(TAG, "onCreate miScreenHeight:" + miScreenHeight);
}
//
mIvSwitch = (ImageView) findViewById(R.id.id_iv_switch);
mIvSwitch.setOnClickListener(mViewOnclickListener);
if (Debug)
{
LogUtils.i(TAG, "onCreate mIvSwitch:" + mIvSwitch);
}
/** 获取预览界面 **/
mSurfaceView = (SurfaceView) findViewById(R.id.id_camera_PreviewView);
if (Debug)
{
LogUtils.i(TAG, "onCreate mSurfaceView:" + mSurfaceView);
}
/** 拍照按钮 **/
mIvTakePicture = (ImageView) findViewById(R.id.id_iv_takepicture);
mIvTakePicture.setOnClickListener(mViewOnclickListener);
if (Debug)
{
LogUtils.i(TAG, "onCreate mIvTakePicture:" + mIvTakePicture);
}
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
if (Debug)
{
LogUtils.i(TAG, "onCreate mSurfaceHolder:" + mSurfaceHolder);
}
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Bitmap switchBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.camera_selected);
if (Debug)
{
LogUtils.i(TAG, "onCreate switchBitmap:" + switchBitmap);
}
miSwitchPictureWidth = switchBitmap.getWidth();
miSwitchPictureHeight = switchBitmap.getHeight();
Bitmap takeBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.photo);
if (Debug)
{
LogUtils.i(TAG, "onCreate takeBitmap:" + takeBitmap);
}
miTakePictureWidth = takeBitmap.getWidth();
miTakePictureHeight = takeBitmap.getHeight();
if (Debug)
{
LogUtils.i(TAG, "onCreate miSwitchPictureWidth:" + miSwitchPictureWidth);
LogUtils.i(TAG, "onCreate miSwitchPictureHeight:" + miSwitchPictureHeight);
LogUtils.i(TAG, "onCreate miTakePictureWidth:" + miTakePictureWidth);
LogUtils.i(TAG, "onCreate miTakePictureHeight:" + miTakePictureHeight);
}
if (Debug)
{
LogUtils.i(TAG, "onCreate exit");
}
}
@Override
protected void onStart()
{
// TODO Auto-generated method stub
super.onStart();
if (Debug)
{
LogUtils.i(TAG, "onStart ");
}
}
@Override
protected void onRestart()
{
// TODO Auto-generated method stub
super.onRestart();
if (Debug)
{
LogUtils.i(TAG, "onRestart ");
}
}
@Override
protected void onResume()
{
if (Debug)
{
LogUtils.i(TAG, "onResume ");
}
IntentFilter filter = new IntentFilter();
filter.addAction(SHUTTER_ACTION);
registerReceiver(myReceiver, filter);
XCommand.sendCameraStateMessage(true);
mbExit = false;
Toast.makeText(this, R.string.could_use_brand_photo, Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause()
{
if (Debug)
{
LogUtils.i(TAG, "onPause ");
}
unregisterReceiver(myReceiver);
XCommand.sendCameraStateMessage(false);
if (mMediaPlayer != null)
{
try
{
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mbMusicPlaying = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
mbExit = true;
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onStop()
{
// TODO Auto-generated method stub
super.onStop();
if (Debug)
{
LogUtils.i(TAG, "onStop ");
}
}
@Override
protected void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
if (Debug)
{
LogUtils.i(TAG, "onDestroy ");
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
String action = intent.getAction();
if (action == null)
{
return;
}
if (Debug)
{
LogUtils.i(TAG, "onReceive action:" + action);
}
if (action.equals(SHUTTER_ACTION))
{
mViewOnclickListener.onClick(mIvTakePicture);
}
}
};
class FdViewOnclickListener implements OnClickListener
{
@Override
public void onClick(View v)
{
if (Debug)
{
LogUtils.i(TAG, "onClick v.id:" + v.getId());
}
// TODO Auto-generated method stub
if (v == mIvSwitch)
{
if (mCamera != null)
{
mCamera.stopPreview();// 停掉原来摄像头的预览
mCamera.release();// 释放资源
mCamera = null;// 取消原来摄像头
}
int cameraCount = 1;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
{
cameraCount = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < cameraCount; i++)
{
Camera.getCameraInfo(i, info);
if (mCameraPosition == 0)// 前置
{
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
}
else
{
mCameraId = i;
mCameraPosition = 1;
break;
}
}
else if (mCameraPosition == 1)// 后置
{
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
mCameraId = i;
mCameraPosition = 0;
break;
}
}
}
if (mCameraId == mFrontCameraId)
{
mCameraPosition = 0;
}
else
{
mCameraPosition = 1;
}
mCamera = Camera.open(mCameraId);
}
else
{
mCameraId = 0;
mCameraPosition = 1;
mCamera = Camera.open();
}
if (Debug)
{
LogUtils.i(TAG, "onClick cameraCount:" + cameraCount);
LogUtils.i(TAG, "onClick mCameraId:" + mCameraId);
LogUtils.i(TAG, "onClick mCameraPosition:" + mCameraPosition);
LogUtils.i(TAG, "onClick mCamera:" + mCamera);
}
surfaceChanged(mSurfaceHolder, miPictureFormat, miScreenWidth, miScreenHeight);
}
else if (v == mIvTakePicture)
{
if (mbTakeingPicture)
{
if(!mbExit)
{
Toast.makeText(RemoteTakePictureActivity.this, "正在捕获图片,请稍候!", Toast.LENGTH_SHORT).show();
}
return;
}
if (mbSavingFile)
{
if(!mbExit)
{
Toast.makeText(RemoteTakePictureActivity.this, "正在保存图片,请稍候!", Toast.LENGTH_SHORT).show();
}
return;
}
if (!mbMusicPlaying)
{
getAvailMemory();
List<String> focusModes = mCameraParams.getSupportedFocusModes();
try
{
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
{
if (Debug)
{
LogUtils.i(TAG, "onClick FOCUS_MODE_CONTINUOUS_PICTURE");
}
mbTakeingPicture = true;
mCameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
mCamera.autoFocus(mAutoFocusCallback);
}
else
{
if (Debug)
{
LogUtils.i(TAG, "onClick not continuous!");
}
mbTakeingPicture = true;
mCamera.autoFocus(null);
mCamera.takePicture(mShutterCallback, null, mPictureCallback);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
private AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback()
{
@Override
public void onAutoFocus(boolean success, Camera camera)
{
if (Debug)
{
LogUtils.i(TAG, "onAutoFocus success: " + success);
}
// TODO Auto-generated method stub
if (success)
{
mCamera.setOneShotPreviewCallback(null);
}
try
{
mCamera.takePicture(mShutterCallback, null, mPictureCallback);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(RemoteTakePictureActivity.this, "TakePicture failed", Toast.LENGTH_SHORT).show();
}
}
};
/** 快门回调接口 **/
private ShutterCallback mShutterCallback = new ShutterCallback()
{
@Override
public void onShutter()
{
if (Debug)
{
LogUtils.i(TAG, "shootSound mMediaPlayer:" + mMediaPlayer);
}
AudioManager audioManager = (AudioManager) RemoteTakePictureActivity.this
.getSystemService(Context.AUDIO_SERVICE);
int volume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
if (volume != 0)
{
if (mMediaPlayer == null)
{
mMediaPlayer = MediaPlayer.create(RemoteTakePictureActivity.this, Uri
.parse("file:///system/media/audio/ui/camera_click.ogg"));
mMediaPlayer.reset();
}
else
{
mMediaPlayer.reset();
}
if (mMediaPlayer != null)
{
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mMpOnCompletionListener);
mMediaPlayer.setOnErrorListener(mMpOnErrorListener);
mbMusicPlaying = true;
}
}
}
};
class MpOnCompletionListener implements MediaPlayer.OnCompletionListener
{
@Override
public void onCompletion(MediaPlayer mp)
{
if (Debug)
{
Log.i(TAG, "MpOnCompletionListener onCompletion ");
}
// TODO Auto-generated method stub
if (mp == mMediaPlayer)
{
mbMusicPlaying = false;
}
}
}
class MpOnErrorListener implements MediaPlayer.OnErrorListener
{
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
if (Debug)
{
Log.i(TAG, "MpOnErrorListener onError ");
}
// TODO Auto-generated method stub
if (mp == mMediaPlayer)
{
if (mMediaPlayer != null)
{
try
{
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mbMusicPlaying = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
return false;
}
}
/** 拍照回调接口 **/
private PictureCallback mPictureCallback = new PictureCallback()
{
@Override
public void onPictureTaken(byte[] data, Camera camera)
{
if (Debug)
{
LogUtils.i(TAG, "onPictureTaken camera:" + camera);
}
mbTakeingPicture = false;
mbSavingFile = true;
mCamera.startPreview();
new SavePictureAsyncTask().execute(data);
}
};
private String msPictureFileNameString = null;
private class SavePictureAsyncTask extends AsyncTask<byte[], Void, Boolean>
{
@Override
protected Boolean doInBackground(byte[]... Params)
{
if (Debug)
{
LogUtils.i(TAG, "doInBackground ");
}
// TODO Auto-generated method stub
return savePicture(Params[0]);
}
@Override
protected void onPostExecute(Boolean result)
{
if (Debug)
{
LogUtils.i(TAG, "onPostExecute result:" + result);
}
if (result)
{
if(!mbExit)
{
Toast.makeText(RemoteTakePictureActivity.this.getApplicationContext(), RemoteTakePictureActivity.this
.getString(R.string.file_saved)
+ msPictureFileNameString, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(RemoteTakePictureActivity.this, "空间不足,照片保存失败!", Toast.LENGTH_SHORT).show();
}
mbSavingFile = false;
super.onPostExecute(result);
}
}
private boolean savePicture(byte[] bytes)
{
if (Debug)
{
LogUtils.i(TAG, "savePicture");
}
if (bytes.length < 2048)
{
return false;
}
Bitmap cameraBitmap = null;
Bitmap DestBitMap = null;
try
{
cameraBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
catch (OutOfMemoryError e)
{
// TODO: handle exception
// 内存不够
e.printStackTrace();
if (Debug)
{
LogUtils.i(TAG, "savePicture OutOfMemoryError1");
}
return false;
}
Matrix matrix = new Matrix();
matrix.reset();
if (mCameraPosition == 0)
{
matrix.postRotate(-90);
}
else
{
matrix.postRotate(90);
}
try
{
DestBitMap = Bitmap
.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
}
catch (OutOfMemoryError e)
{
// TODO: handle exception
// 内存不够时不进行旋转图片
DestBitMap = cameraBitmap;
if (Debug)
{
LogUtils.i(TAG, "savePicture OutOfMemoryError2");
}
}
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String date = sDateFormat.format(new java.util.Date());
msPictureFileNameString = CommonUtil.XBRACELET_PHOTO_PATH + "IMG_" + date + ".jpg";
CommonUtil.isExist(CommonUtil.XBRACELET_PHOTO_PATH);
if (Debug)
{
LogUtils.i(TAG, "savePicture msPictureFileNameString:" + msPictureFileNameString);
}
File filePicture = new File(msPictureFileNameString);
if (Debug)
{
LogUtils.i(TAG, "savePicture filePicture:" + filePicture);
}
try
{
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePicture));
DestBitMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
if (filePicture != null)
{
MediaScannerConnection
.scanFile(RemoteTakePictureActivity.this, new String[] { msPictureFileNameString }, null, null);
}
getAvailMemory();
if ((DestBitMap != null) && !DestBitMap.isRecycled())
{
DestBitMap.recycle();
}
// TODO: Compress bitmap to file
if ((cameraBitmap != null) && !cameraBitmap.isRecycled())
{
cameraBitmap.recycle();
}
return true;
}
catch (Exception e)
{
if ((DestBitMap != null) && !DestBitMap.isRecycled())
{
DestBitMap.recycle();
}
// TODO: Compress bitmap to file
if ((cameraBitmap != null) && !cameraBitmap.isRecycled())
{
cameraBitmap.recycle();
}
e.printStackTrace();
return false;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
if (Debug)
{
LogUtils.i(TAG, "surfaceCreated holder:" + holder);
}
int cameraCount = 1;
// TODO Auto-generated method stub
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
{
cameraCount = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < cameraCount; i++)
{
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
mFrontCameraId = i;
break;
}
}
if(mFrontCameraId >= 0)
{
mCameraId = mFrontCameraId;
mCameraPosition = 0;
}
else
{
mCameraId = 0;
mCameraPosition = 1;
}
mCamera = Camera.open(mCameraId);
}
else
{
mCameraId = 0;
mCameraPosition = 1;
mCamera = Camera.open();
}
if (cameraCount < 2)
{
mIvSwitch.setVisibility(View.INVISIBLE);
}
else
{
mIvSwitch.setVisibility(View.VISIBLE);
}
if (Debug)
{
LogUtils.i(TAG, "surfaceCreated cameraCount:" + cameraCount);
LogUtils.i(TAG, "surfaceCreated mCameraId:" + mCameraId);
LogUtils.i(TAG, "surfaceCreated mCameraPosition:" + mCameraPosition);
LogUtils.i(TAG, "surfaceCreated mCamera:" + mCamera);
}
try
{
mCamera.setPreviewDisplay(mSurfaceHolder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO)
{
mCameraParams.set("orientation", "portrait");
}
else
{
// 在2.2以上可以使用
mCamera.setDisplayOrientation(90);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// if (Debug)
{
LogUtils.i(TAG, "surfaceChanged holder:" + holder);
LogUtils.i(TAG, "surfaceChanged format:" + format);
LogUtils.i(TAG, "surfaceChanged width:" + width);
LogUtils.i(TAG, "surfaceChanged height:" + height);
}
miPictureFormat = format;
// miScreenWidth = width;
// miScreenHeight = height;
if (holder.getSurface() == null)
{
// 预览surface不存在
return;
}
// 更改时停止预览
try
{
if (mCamera == null)
{
return;
}
mCamera.stopPreview();
mCamera.autoFocus(null);
}
catch (Exception e)
{
// 忽略:试图停止不存在的预览
}
// TODO Auto-generated method stub
boolean bPortrait = this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged bPortrait:" + bPortrait);
}
// 已经获得Surface的width和height,设置Camera的参数
mCameraParams = mCamera.getParameters();
// 获取预览大小
mPreviewSizeList = mCameraParams.getSupportedPreviewSizes();
int iPictureSizeNumber = mPreviewSizeList.size();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPreviewSizeList.size:" + iPictureSizeNumber);
}
for (int num = 0; num < iPictureSizeNumber; num++)
{
Size vSize = mPreviewSizeList.get(num);
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPreviewSizeList num:" + num);
LogUtils.i(TAG, "surfaceChanged width:" + vSize.width);
LogUtils.i(TAG, "surfaceChanged height:" + vSize.height);
}
}
// 获取图片大小
mPictureSizeList = mCameraParams.getSupportedPictureSizes();
iPictureSizeNumber = mPictureSizeList.size();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPictureSizeList.size:" + iPictureSizeNumber);
}
if (mPreviewSize == null)
{
mPreviewSize = mCamera.new Size(0, 0);
}
if (mPictureSize == null)
{
mPictureSize = mCamera.new Size(0, 0);
}
else
{
mPictureSize.width = 0;
mPictureSize.height = 0;
}
for (int num = 0; num < iPictureSizeNumber; num++)
{
Size vSize = mPictureSizeList.get(num);
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPictureSizeList num:" + num);
LogUtils.i(TAG, "surfaceChanged width:" + vSize.width);
LogUtils.i(TAG, "surfaceChanged height:" + vSize.height);
}
}
long lMemory = getAvailMemory();
int iIndex = 0;
if(lMemory < 200*1024*1024)//200M
{
if(iPictureSizeNumber < 2)
{
iIndex = 0;
}
else if(mPictureSizeList.get(0).height < mPictureSizeList.get(iPictureSizeNumber-1).height)
{
iIndex = 0;
}
else
{
iIndex = iPictureSizeNumber-1;
}
}
else
{
iIndex = iPictureSizeNumber / 2;
}
Size vSize = mPictureSizeList.get(iIndex);
mPictureSize.width = vSize.width;
mPictureSize.height = vSize.height;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPictureSize.width:" + mPictureSize.width);
LogUtils.i(TAG, "surfaceChanged mPictureSize.height:" + mPictureSize.height);
}
mPreviewSize = mCameraParams.getPreviewSize();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged mPreviewSize.width:" + mPreviewSize.width);
LogUtils.i(TAG, "surfaceChanged mPreviewSize.height:" + mPreviewSize.height);
}
mCameraParams.setPictureSize(mPictureSize.width, mPictureSize.height);
float fPictureRatio = (float) mPictureSize.height / (float) mPictureSize.width;// 3120/4160 = 0.75
float fScreenRatio = (float) miScreenWidth / (float) miScreenHeight;// 1080/1920 = 0.5625
int iTopMargin = 0;
int iBottomMargin = 0;
int iLeftMargin = 0;
int iRightMargin = 0;
int iMargin = 0;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged fPictureRatio:" + fPictureRatio);
LogUtils.i(TAG, "surfaceChanged fScreenRatio:" + fScreenRatio);
}
if (fScreenRatio < fPictureRatio)
{
miPreviewWidth = miScreenWidth;
miPreviewHeight = (int) (miPreviewWidth / fPictureRatio);
iMargin = miScreenHeight - miPreviewHeight;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged iMargin:" + iMargin);
}
if(iMargin > miSwitchPictureHeight + miTakePictureHeight + miNavigation)
{
iTopMargin = iBottomMargin = (iMargin-miSwitchPictureHeight-miTakePictureHeight-miNavigation)/4;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged iTopMargin:" + iTopMargin);
}
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mIvSwitch.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams1:" + layoutParams1);
}
layoutParams1.topMargin = iTopMargin;
layoutParams1.bottomMargin = iBottomMargin;
mIvSwitch.setLayoutParams(layoutParams1);
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mIvTakePicture.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams2:" + layoutParams2);
}
layoutParams2.topMargin = iTopMargin;
layoutParams2.bottomMargin = iBottomMargin+miNavigation;
mIvTakePicture.setLayoutParams(layoutParams2);
iTopMargin = miSwitchPictureHeight + 2*iTopMargin;
iBottomMargin = miTakePictureHeight + miNavigation + 2*iBottomMargin;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged iTopMargin:" + iTopMargin);
LogUtils.i(TAG, "surfaceChanged iBottomMargin:" + iBottomMargin);
}
}
else if(iMargin > miTakePictureHeight + miNavigation)
{
iTopMargin = iBottomMargin = (iMargin-miTakePictureHeight-miNavigation)/2;
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mIvSwitch.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams3:" + layoutParams1);
}
layoutParams1.topMargin = CommonUtil.dip2px(this,MARGIN_TOP_BOTTOM);
mIvSwitch.setLayoutParams(layoutParams1);
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mIvTakePicture.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams4:" + layoutParams2);
}
layoutParams2.topMargin = iTopMargin;
layoutParams2.bottomMargin = iBottomMargin+miNavigation;
mIvTakePicture.setLayoutParams(layoutParams2);
iTopMargin = 0;
iBottomMargin = iMargin;
}
else
{
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mIvSwitch.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams5:" + layoutParams1);
}
layoutParams1.topMargin = CommonUtil.dip2px(this,MARGIN_TOP_BOTTOM);
mIvSwitch.setLayoutParams(layoutParams1);
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mIvTakePicture.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged LayoutParams6:" + layoutParams2);
}
layoutParams2.bottomMargin = CommonUtil.dip2px(this,MARGIN_TOP_BOTTOM)+miNavigation;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged bottomMargin:" + layoutParams2.bottomMargin);
}
mIvTakePicture.setLayoutParams(layoutParams2);
iTopMargin = 0;
iBottomMargin = iMargin;
}
}
else
{
miPreviewHeight = miScreenHeight;
miPreviewWidth = (int) (miPreviewHeight * fPictureRatio);
iMargin = miScreenWidth - miPreviewWidth;
if(iMargin > miSwitchPictureWidth + miTakePictureWidth)
{
iLeftMargin = iRightMargin = iMargin/2;
RelativeLayout.LayoutParams LayoutParams = (RelativeLayout.LayoutParams) mIvSwitch.getLayoutParams();
LayoutParams.leftMargin = LayoutParams.rightMargin = iRightMargin;
mIvSwitch.setLayoutParams(LayoutParams);
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mIvTakePicture.getLayoutParams();
layoutParams2.leftMargin = layoutParams2.rightMargin = iRightMargin;
mIvTakePicture.setLayoutParams(layoutParams2);
}
else
{
iRightMargin = iMargin;
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) mIvTakePicture.getLayoutParams();
layoutParams2.leftMargin = layoutParams2.rightMargin = iRightMargin;
mIvTakePicture.setLayoutParams(layoutParams2);
}
}
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged miPreviewWidth:" + miPreviewWidth);
LogUtils.i(TAG, "surfaceChanged miPreviewHeight:" + miPreviewHeight);
}
RelativeLayout.LayoutParams previewLayoutParams = (RelativeLayout.LayoutParams) mSurfaceView.getLayoutParams();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged previewLayoutParams:" + previewLayoutParams);
}
previewLayoutParams.width = miPreviewWidth;
previewLayoutParams.height = miPreviewHeight;
previewLayoutParams.topMargin = iTopMargin;
previewLayoutParams.bottomMargin = iBottomMargin;
previewLayoutParams.leftMargin = iLeftMargin;
previewLayoutParams.rightMargin = iRightMargin;
mSurfaceView.setLayoutParams(previewLayoutParams);
iPictureSizeNumber = mPreviewSizeList.size();
float fPreviewRatio = 0.0f;
float fRatio = 0.0f;
float fMinRatio = 10.0f;
iIndex = 0;
for (int num = 0; num < iPictureSizeNumber; num++)
{
Size vSize1 = mPreviewSizeList.get(num);
fPreviewRatio = (float) vSize1.height / (float) vSize1.width;
fRatio = Math.abs(fPreviewRatio-fPictureRatio);
if(fRatio < fMinRatio)
{
fMinRatio = fRatio;
iIndex = num;
}
}
mPreviewSize.width = mPreviewSizeList.get(iIndex).width;
mPreviewSize.height = mPreviewSizeList.get(iIndex).height;
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged miPreviewWidth:" + miPreviewWidth);
LogUtils.i(TAG, "surfaceChanged miPreviewHeight:" + miPreviewHeight);
}
mCameraParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
//mCameraParams.setColorEffect(Camera.Parameters.WHITE_BALANCE_AUTO);
//mCameraParams.setExposureCompensation(2);
if (bPortrait)
{
// 如果是竖屏
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO)
{
mCameraParams.set("orientation", "portrait");
}
else
{
// 在2.2以上可以使用
// mCamera.setDisplayOrientation(90);
setCameraDisplayOrientation(RemoteTakePictureActivity.this, mCameraId, mCamera);
}
}
else
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO)
{
mCameraParams.set("orientation", "landscape");
}
else
{
// 在2.2以上可以使用
// mCamera.setDisplayOrientation(0);
setCameraDisplayOrientation(RemoteTakePictureActivity.this, mCameraId, mCamera);
}
}
Size size = mCameraParams.getPreviewSize();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged PreviewSize.width:" + size.width);
LogUtils.i(TAG, "surfaceChanged PreviewSize.height:" + size.height);
}
size = mCameraParams.getPictureSize();
if (Debug)
{
LogUtils.i(TAG, "surfaceChanged PictureSize.width:" + size.width);
LogUtils.i(TAG, "surfaceChanged PictureSize.height:" + size.height);
}
mCamera.setParameters(mCameraParams);
try
{
// 设置显示
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
catch (IOException exception)
{
if (mCamera != null)
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
if (Debug)
{
LogUtils.i(TAG, "surfaceDestroyed holder:" + holder);
}
// TODO Auto-generated method stub
if (mCamera != null)
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public static void setCameraDisplayOrientation(Activity activity, int cameraId, android.hardware.Camera camera)
{
if (Debug)
{
LogUtils.i(TAG, "setCameraDisplayOrientation cameraId: " + cameraId);
}
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation)
{
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
}
else
{
// back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
miZoomMode = 1;
// mIsTakePicture = true;
break;
case MotionEvent.ACTION_UP:
miZoomMode = 0;
break;
case MotionEvent.ACTION_POINTER_UP:
miZoomMode -= 1;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mfOldDistance = getDistance(event);// 两点按下时的距离
miZoomMode += 1;
break;
case MotionEvent.ACTION_MOVE:
if (miZoomMode >= 2)
{
float newDist = getDistance(event);
if (newDist > mfOldDistance)
{
setZoom(CAMERA_ZOOM_OUT);
}
if (newDist < mfOldDistance)
{
setZoom(CAMERA_ZOOM_IN);
}
break;
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
private float getDistance(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
public void setZoom(int type)
{
if (Debug)
{
LogUtils.i(TAG, "setZoom type:" + type);
}
Camera.Parameters cameraParams = mCamera.getParameters();
int maxZoom = cameraParams.getMaxZoom();
if (Debug)
{
LogUtils.i(TAG, "setZoom maxZoom:" + maxZoom);
LogUtils.i(TAG, "setZoom mCurZoom:" + mCurZoom);
}
if (type == CAMERA_ZOOM_OUT)
{
// 放大
if (mCurZoom < maxZoom * 5)
{
mCurZoom++;
cameraParams.setZoom(mCurZoom / 5);
}
}
else
{
// 缩小
if (mCurZoom > 5)
{
mCurZoom--;
cameraParams.setZoom(mCurZoom / 5);
}
}
try
{
mCamera.setParameters(cameraParams);
}
catch (RuntimeException e)
{
// TODO: handle exception
e.printStackTrace();
}
}
private long getAvailMemory()
{
// 获取android当前可用内存大小
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
long lAvailMemory = mi.availMem;
if (Debug)
{
LogUtils.i(TAG, "getAvailMemory lAvailMemory:" + lAvailMemory);
}
// mi.availMem; 当前系统的可用内存
String sAvailMemory = Formatter.formatFileSize(getBaseContext(), mi.availMem);
if (Debug)
{
LogUtils.i(TAG, "getAvailMemory sAvailMemory:" + sAvailMemory);
}
return lAvailMemory;// 将获取的内存大小规格化
}
}