1

私は SurfaceView を使用してビデオを録画し、HTC および SAMSUNG デバイスではうまく動作しますが、MIUI デバイスでは動作せず、次のように例外をスローします: 04-28 11:45:12.869: E/MediaRecorder(28941): setOutputFormat が無効な状態で呼び出されました: 4 04-28 11:45:12.869: W/System.err(28941): java.lang.IllegalStateException 04-28 11:45:12.869: W/System.err(28941): android.media.MediaRecorder で。 setOutputFormat(Native Method) 04-28 11:45:12.869: W/System.err(28941): com.dream.gushihui.TakeVideoActivity.onClick(TakeVideoActivity.java:416) 04-28 11:45:12.869:W /System.err(28941): android.view.View.performClick(View.java:2486) 04-28 11:45:12.869: W/System.err(28941): android.view.View$PerformClick で。実行 (View.java:9130) 04-28 11:45:12.869: W/System.err(28941): android.os.Handler.handleCallback(Handler.java:587) 04-28 11:45:12.869: W/System.err(28941):android.os.Handler.dispatchMessage(Handler.java:92) 04-28 11:45:12.869: W/System.err(28941): android.os.Looper.loop(Looper.java:130) 04- 28 11:45:12.869: W/System.err(28941): android.app.ActivityThread.main(ActivityThread.java:3703) 04-28 11:45:12.869: W/System.err(28941): でjava.lang.reflect.Method.invokeNative(ネイティブ メソッド) 04-28 11:45:12.869: W/System.err(28941): java.lang.reflect.Method.invoke(Method.java:507) 04- 28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 04-28 11:45:12.869: W/システム。エラー (28941): com.android.internal.os.ZygoteInit.main (ZygoteInit.java:624) 04-28 11:45:12.869: W/System.err (28941): dalvik.system.NativeStart.main で(ネイティブメソッド)err(28941): android.os.Looper.loop(Looper.java:130) 04-28 11:45:12.869: W/System.err(28941): android.app.ActivityThread.main(ActivityThread.java で:3703) 04-28 11:45:12.869: W/System.err(28941): java.lang.reflect.Method.invokeNative(ネイティブ メソッド) 04-28 11:45:12.869: W/System.err( 28941): java.lang.reflect.Method.invoke(Method.java:507) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit$MethodAndArgsCaller で.run(ZygoteInit.java:866) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11 :45:12.869: W/System.err(28941): dalvik.system.NativeStart.main(ネイティブ メソッド) でerr(28941): android.os.Looper.loop(Looper.java:130) 04-28 11:45:12.869: W/System.err(28941): android.app.ActivityThread.main(ActivityThread.java で:3703) 04-28 11:45:12.869: W/System.err(28941): java.lang.reflect.Method.invokeNative(ネイティブ メソッド) 04-28 11:45:12.869: W/System.err( 28941): java.lang.reflect.Method.invoke(Method.java:507) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit$MethodAndArgsCaller で.run(ZygoteInit.java:866) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11 :45:12.869: W/System.err(28941): dalvik.system.NativeStart.main(ネイティブ メソッド) で869: W/System.err(28941): java.lang.reflect.Method.invokeNative(Native Method) 04-28 11:45:12.869: W/System.err(28941): java.lang.reflect で。 Method.invoke(Method.java:507) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 04 -28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11:45:12.869: W/System.err (28941): dalvik.system.NativeStart.main(ネイティブ メソッド) で869: W/System.err(28941): java.lang.reflect.Method.invokeNative(Native Method) 04-28 11:45:12.869: W/System.err(28941): java.lang.reflect で。 Method.invoke(Method.java:507) 04-28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 04 -28 11:45:12.869: W/System.err(28941): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11:45:12.869: W/System.err (28941): dalvik.system.NativeStart.main(ネイティブ メソッド) でcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11:45:12.869: W/System.err(28941): dalvik.system.NativeStart.main(ネイティブ メソッド) でcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 04-28 11:45:12.869: W/System.err(28941): dalvik.system.NativeStart.main(ネイティブ メソッド) で

enter code here
public class TakeVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback {

    private static final int REQUEST_CODE_GET_LOCAL_VIDEO = 11;
    //默认录制视频的时长-3分钟
    private static final int DEFAULT_RECORD_TIME = 180;

    private TextView mTextViewControlLight, mTextViewControlCamera, mTextViewBack, 
                        mTextViewChooseLocalVideo, mTextViewControlVideo, mTextViewRecordPrompt;
    private SurfaceView surfaceview;// 显示视频的控件
    // 用来显示视频的一个接口,我靠不用还不行,也就是说用mediarecorder录制视频还得给个界面看
    // 想偷偷录视频的同学可以考虑别的办法。。嗯需要实现这个接口的Callback接口
    private SurfaceHolder surfaceHolder;
    //获取屏幕的宽和高,用于设置视频的尺寸大小
    private int screenWidth, screenHight;
    private MediaRecorder mediarecorder;// 录制视频的类

    private boolean isRecording = false;
    public static String VIDEO_RECORD_PATH = Environment.getExternalStorageDirectory().toString()+"/12fou/videoRecord/";
//  public static String VIDEO_TEMP_NAME = "video_tmp.mp4";
    private String videoName;

    private AlertDialog dialog;

    private Camera camera;
    //闪光灯是否开启
    private boolean isFlashLight = false;
    //当前的camera是否是前置摄像头
    private boolean isFacingCamera = false;

    private TextView mTextViewRecordTime;
    private Timer timer = new Timer();
    //视频剩余的时间
    private int recordRemainTime = 0;

    private boolean isSuccess = false;
    private String message = "";

    private ProgressDialog mProgressDialog;

    private final static int UPLOAD_VIDEO_END = 1;
    private static final int SHOW_PROGRESS_DIALOG = 2;
    private static final int DISMISS_PROGRESS_DIALOG = 3;

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SHOW_PROGRESS_DIALOG:
                try {
                    if (mProgressDialog != null) {
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        mProgressDialog = null;
                    }
                    mProgressDialog = new ProgressDialog(TakeVideoActivity.this);
                    mProgressDialog.setIndeterminate(true);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.setMessage((String) msg.obj);
                    mProgressDialog.show();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                break;

            case DISMISS_PROGRESS_DIALOG:
                try {
                    if ((mProgressDialog != null)
                            && mProgressDialog.isShowing())
                        mProgressDialog.dismiss();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                break;

            case UPLOAD_VIDEO_END:
                try {
                    if(isSuccess){
                        Utils.showToast(TakeVideoActivity.this, "上传视频成功");

                    }else{
                        Utils.showToast(TakeVideoActivity.this, message);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                break;

            default:
                break;
            }
        }

    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 选择支持半透明模式,在有surfaceview的activity中使用。  
        getWindow().setFormat(PixelFormat.TRANSLUCENT); 

        setContentView(R.layout.take_video_activity);

        initViews();

        DisplayMetrics displayMetrics = new DisplayMetrics(); 
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 
        screenWidth = displayMetrics.widthPixels;
        screenHight = displayMetrics.heightPixels;
        System.out.println("****screen width="+screenWidth+",screen hight="+screenHight);

//        initValues();
    }

    private void initViews(){
        mTextViewControlLight = (TextView) findViewById(R.id.textview_control_light);
        mTextViewControlCamera = (TextView) findViewById(R.id.textview_control_camera);
        mTextViewBack = (TextView) findViewById(R.id.textview_back);
        mTextViewChooseLocalVideo = (TextView) findViewById(R.id.textview_choose_local_video);
        mTextViewControlVideo = (TextView) findViewById(R.id.textview_video_control);
        mTextViewRecordPrompt = (TextView) findViewById(R.id.textview_record_prompt);
        mTextViewRecordTime = (TextView) findViewById(R.id.textview_record_time);

        surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview);
        SurfaceHolder holder = surfaceview.getHolder();// 取得holder
        holder.addCallback(this); // holder加入回调接口
        // setType必须设置,要不出错.
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.setKeepScreenOn(true);

        mTextViewControlLight.setOnClickListener(this);
        mTextViewControlCamera.setOnClickListener(this);
        mTextViewBack.setOnClickListener(this);
        mTextViewChooseLocalVideo.setOnClickListener(this);
        mTextViewControlVideo.setOnClickListener(this);
    }

    private void initValues(){
        try {
            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            if(camera != null){
                Camera.Parameters parameters = camera.getParameters();
                parameters.setRotation(90);
                if(isFlashLight)
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                else
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(parameters);
                camera.setDisplayOrientation(90);//摄像图旋转90度
                camera.unlock();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub
        // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
        surfaceHolder = holder;
        /*try {
            camera = Camera.open();
            if(camera != null){
                Camera.Parameters parameters = camera.getParameters();
                parameters.setRotation(90);
                if(isFlashLight)
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                else
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(parameters);
                camera.setDisplayOrientation(90);//摄像图旋转90度
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }*/
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
        surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try {
            if(camera != null){
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        surfaceview = null;
        surfaceHolder = null;
        mediarecorder = null;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        try {
            Intent intent;
            switch (v.getId()) {
            case R.id.textview_back: //返回
                try {
                    if (mediarecorder != null) {
                        // 停止录制
                        mediarecorder.stop();
                        // 释放资源
                        mediarecorder.release();
                        mediarecorder = null;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                finish();
                break;

            case R.id.textview_control_light: //控制是否开启闪光灯
                if (isFlashLight) {
                    turnOffFlashLight();
                } else {
                    turnOnFlashLight();
                }
                break;

            case R.id.textview_control_camera: //控制是前置还是后置摄像头
                controlCamera();
                break;

            case R.id.textview_record_prompt: //摄像机如何放置的提示信息

                break;

            case R.id.textview_choose_local_video: //选择本地视频
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("video/*");
                startActivityForResult(intent, REQUEST_CODE_GET_LOCAL_VIDEO);
                break;

            case R.id.textview_video_control: //控制是拍摄还是暂停录视频
                if(isRecording){//现在在录制,暂停录制
                    try {
                        if (mediarecorder != null) {
                            // 停止录制
                            mediarecorder.stop();
                            // 释放资源
                            mediarecorder.release();
                            mediarecorder = null;
                            File file4 = new File(VIDEO_RECORD_PATH+videoName);
//                          File file4 = new File(Environment.getExternalStorageDirectory().toString()+"/delete_red_bg.png");
                            if(file4.exists()){
                                /*AlertDialog.Builder builder = new AlertDialog.Builder(TakeVideoActivity.this);
                                builder.setTitle("属性");
                                builder.setItems(R.array.take_video_menu_option, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // TODO Auto-generated method stub
                                        switch (which) {
                                        case 0: //预览

                                            break;

                                        case 1: //上传
                                            final Intent intent = new Intent();
                                            intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
                                            intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, VIDEO_RECORD_PATH+videoName);
                                            startActivity(intent);
                                            break;

                                        case 2: //放弃

                                            break;

                                        default:
                                            break;
                                        }
                                    }
                                });
                                dialog = builder.create();
                                dialog.setCancelable(false);
                                dialog.show();*/
                                intent = new Intent();
                                intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
                                intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, VIDEO_RECORD_PATH+videoName);
                                startActivity(intent);
                            }
                        }
                        mTextViewControlVideo.setBackgroundResource(R.drawable.tabbar_camera_recording);
                        showViewWhenRecordEnd();
                        isRecording = false;
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }else{//未录视频,开始录视频
                    mTextViewRecordPrompt.setVisibility(View.GONE);
                    videoName = getDateString()+".mp4";
                    mediarecorder = new MediaRecorder();// 创建mediarecorder对象
                    mediarecorder.setOrientationHint(90);////视频旋转90度
                    try {
                        if(camera != null){
                            camera.stopPreview();
                            camera.release();
                            camera = null;
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                    if(isFacingCamera)
                        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
                    else
                        camera = Camera.open();
                    if(camera != null){
                        Camera.Parameters parameters = camera.getParameters();
                        parameters.setRotation(90);
                        if(isFlashLight)
                            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        else
                            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        camera.setParameters(parameters);
                        camera.setDisplayOrientation(90);//摄像图旋转90度
                        camera.unlock();
                        mediarecorder.setCamera(camera);
                    }

                    /*recordVideo();
                    isRecording = true;*/
                    /*if(camera != null){
                        camera.unlock();
                        mediarecorder.setCamera(camera);
                    }*/
                    // 设置录制视频源为Camera(相机)
                    mediarecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

                    mediarecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
                    CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
                    mediarecorder.setProfile(cpHigh);

                    // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
                    mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    mediarecorder.setMaxDuration(180000); //Set max duration 300 sec
                    mediarecorder.setMaxFileSize(20000000); // Set max file size 20M
                    // 设置录制的视频编码h263 h264
                    mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
                    // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
//                   mediarecorder.setVideoSize(176, 144);
                    // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
//                  mediarecorder.setVideoFrameRate(24);
                    mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
                    // 设置视频文件输出的路径
                    File file = new File(VIDEO_RECORD_PATH+videoName);
                    if(!file.exists())
                        file.mkdirs();
                    file.delete();
                    mediarecorder.setOutputFile(VIDEO_RECORD_PATH+videoName);
                    try {
                        // 准备录制
                        mediarecorder.prepare();
                        // 开始录制
                        mediarecorder.start();
                        isRecording = true;
                        mTextViewControlVideo.setBackgroundResource(R.drawable.tabbar_camera_stop);
                        hideViewWhenRecording();
                        recordRemainTime = DEFAULT_RECORD_TIME;
                        timer.schedule(task, 1000, 1000);
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                break;



            default:
                break;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    private void recordVideo(){
        try {
             mediarecorder = new MediaRecorder();// 创建mediarecorder对象 
             // 设置录制视频源为Camera(相机) 
             mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 
             // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4 
             mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
             // 设置录制的视频编码h263 h264 
             mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); 
             // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错 
             mediarecorder.setVideoSize(176, 144); 
             // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错 
             mediarecorder.setVideoFrameRate(20); 
             mediarecorder.setPreviewDisplay(surfaceHolder.getSurface()); 
             // 设置视频文件输出的路径 
             mediarecorder.setOutputFile(VIDEO_RECORD_PATH+videoName); 
             try { 
                 // 准备录制 
                 mediarecorder.prepare(); 
                 // 开始录制 
                 mediarecorder.start(); 
             } catch (IllegalStateException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
             } catch (IOException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
             } 
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 将当前的时间转换成为年月日时分秒毫秒 的格式
     * @return
     */
    private String getDateString(){
        Date current = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String s = sdf.format(current);
        return s; 
    }

    /**
     * 调整camera是指不会选择90度
     * @param activity
     * @param cameraId
     * @param camera
     */
    public static void setCameraDisplayOrientation ( Activity activity ,
              int cameraId , android.hardware.Camera camera ) {
        try {
            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 );
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 设置开启或者关闭闪光灯
     * @param isEnable
     */
    private void setFlashlightEnabled(boolean isEnable) {
        try {
            Method method = Class.forName("android.os.ServiceManager")
                    .getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null,new Object[] { "hardware" });
            IHardwareService localhardwareservice = IHardwareService.Stub
                    .asInterface(binder);
            localhardwareservice.setFlashlightEnabled(isEnable);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 打开闪光灯
     */
    private void turnOnFlashLight(){
        try {
            if(camera == null)
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            Camera.Parameters mParameters;  
            mParameters = camera.getParameters();  
            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);  
            camera.setParameters(mParameters);  
            isFlashLight = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 关闭闪光灯
     */
    private void turnOffFlashLight(){
        try {
            Camera.Parameters mParameters;
            camera.reconnect();
            mParameters = camera.getParameters();  
            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);  
            camera.setParameters(mParameters);  
//            camera.release(); 
            isFlashLight = false;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
//      super.onBackPressed();

    }

    /**
     * 控制前置或后置摄像头的切换
     * http://www.cnblogs.com/stay/archive/2011/06/24/2089129.html
     */
    private void controlCamera(){
        try {
            try {
                if(camera != null){
                    camera.stopPreview();
                    camera.release();
                    camera = null;
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD){
                //2.3以上的手机
                Utils.logDebug("*****camera number="+Camera.getNumberOfCameras());
                for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                    CameraInfo info = new CameraInfo();
                    Camera.getCameraInfo(i, info);
                    Utils.logDebug("*****camera info="+info.facing);
                    if (!isFacingCamera && info.facing == CameraInfo.CAMERA_FACING_FRONT) {// 这就是前置摄像头,亲。
                        camera = Camera.open(i);
                        isFacingCamera = true;
                        break;
                    }else if(isFacingCamera && info.facing == CameraInfo.CAMERA_FACING_BACK){
//                      camera = Camera.open(i);
                        camera = Camera.open();
                        isFacingCamera = false;
                        break;
                    }
                }
            }else{
                //2.3及其以下的版本

            }
            if (camera == null) {
                camera = Camera.open();
            }
            try {
                if(camera != null){
                    Camera.Parameters parameters = camera.getParameters();
                    parameters.setRotation(90);
                    if(isFlashLight)
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    else
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    camera.setParameters(parameters);
                    camera.setDisplayOrientation(90);//摄像图旋转90度
                    camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }


    /**
     * 上传视频线程
     * @author Xiang Yong
     *
     */
    private class UploadVideoThread extends Thread{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();

            Message msg = new Message();
            msg.what = SHOW_PROGRESS_DIALOG;
            msg.obj = "视频上传中...";
            myHandler.sendMessage(msg);

            isSuccess = false;

            String videoUrl = "";
            try {
                String result = UploadFileThread.uploadFile("http://api.12fou.net/api.php/user/upvideo", VIDEO_RECORD_PATH+videoName, null);
                if(result != null && !"".equals(result)){
                    JSONObject jsonObject = new JSONObject(result);
                    String statu = jsonObject.getString("result");
                    if("true".equalsIgnoreCase(statu)){
                        videoUrl = jsonObject.getString("video");
                    }
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            myHandler.sendEmptyMessage(UPLOAD_VIDEO_END);

            myHandler.sendEmptyMessage(DISMISS_PROGRESS_DIALOG);

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if(resultCode == RESULT_OK){
                switch (requestCode) {
                case REQUEST_CODE_GET_LOCAL_VIDEO: //获取本地视频
                    Uri uri = data.getData();
                    String path = getPath(uri);
                    Utils.logDebug("***on activity result data="+data.getData()+",path="+path);
                    if(path != null && !"".equals(path)){
                        Intent intent = new Intent();
                        intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
                        intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, path);
                        startActivity(intent);
                    }else{
                        Utils.showToast(TakeVideoActivity.this, "文件不存在");
                    }
                    break;

                default:
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }


    public String getPath(Uri uri) {
        try {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            startManagingCursor(cursor);
            int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "";
    }

    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                runOnUiThread(new Runnable() {
                    public void run() {
                        recordRemainTime--;
                        mTextViewRecordTime.setText(Utils.formatSecondToMMSS(recordRemainTime));
                        if(recordRemainTime < 0){
                            timer.cancel();
                            mTextViewControlVideo.performClick();
                        }
                    }
                });
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    };

    private void hideViewWhenRecording(){
        try {
            mTextViewChooseLocalVideo.setVisibility(View.INVISIBLE);
            mTextViewControlLight.setVisibility(View.GONE);
            mTextViewControlCamera.setVisibility(View.GONE);
            mTextViewRecordTime.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    private void showViewWhenRecordEnd(){
        try {
            mTextViewChooseLocalVideo.setVisibility(View.VISIBLE);
            mTextViewControlLight.setVisibility(View.VISIBLE);
            mTextViewControlCamera.setVisibility(View.VISIBLE);
            mTextViewRecordTime.setVisibility(View.GONE);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
4

1 に答える 1