Android:相机ui在相机上消失,但预览仍然存在

时间:2014-01-07 07:49:39

标签: android camera

这是启动XML文件的主要活动:VideoCaptureActivity.java:

public class VideoCaptureActivity extends Activity 
{
    private static final String TAG = "VideoCaptureActivity";

    Camera camera;
    ImageButton recordButton;
    ImageButton stopButton;enter code here
    ImageButton back;
    Button flash;
    Button flashoff;
    Button flip;
    SeekBar sb;
    FrameLayout cameraPreviewFrame;
    CameraPreview cameraPreview;
    MediaRecorder mediaRecorder;
    private Spinner spinner1;
    private Timer myTimer;
    File file;
    int currentZoomLevel = 0;
    int maxZoomLevel = 0;
    int MAX_ZOOM=15;
    int fcamera =0;
    Size temp;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        super.setContentView(R.layout.video_capture);

        //      this.mediaRecorder = new MediaRecorder();
        //      this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        //      this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //      this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //      this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        //      this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        this.cameraPreviewFrame = (FrameLayout)super.findViewById(R.id.camera_preview);
        this.recordButton = (ImageButton)super.findViewById(R.id.recordButton);
        this.stopButton = (ImageButton)super.findViewById(R.id.stopButton);
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        back =(ImageButton)findViewById(R.id.back);
        this.flash=(Button)findViewById(R.id.flashon);
        this.flashoff=(Button)findViewById(R.id.fashoff);
        this.sb = (SeekBar) findViewById(R.id.seekBar1);
        this.sb.setOnSeekBarChangeListener( new seekListener() );

        this.toggleButtons(false);
        // we'll enable this button once the camera is ready
        this.recordButton.setEnabled(false);

        //  this.flash.setEnabled(false);       
        stopButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                stopRecording(v);
            }
        });

        flash.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                flashLightOn(v );
            }
        });
        flashoff.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                flashLightOff(v );
            }
        });


        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
                Intent intent = new Intent(VideoCaptureActivity.this ,MainGrid.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                startActivity(intent);              
            }
        });
    }

    void toggleButtons(boolean recording) {
        this.recordButton.setEnabled(!recording);
        this.recordButton.setVisibility(recording ? View.GONE : View.VISIBLE);
        this.stopButton.setEnabled(recording);
        this.stopButton.setVisibility(recording ? View.VISIBLE : View.GONE);
    }


    public void flashLightOn(View view) {
        // this.flash.setVisibility(View.INVISIBLE);
        this.flash.setVisibility(View.INVISIBLE);

        try {
            if (getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_CAMERA_FLASH)) {
                //  camera = Camera.open();
                Parameters p = camera.getParameters();    

                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                camera.setParameters(p);
                //                camera.startPreview();


            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Exception flashLightOn()",
                    Toast.LENGTH_SHORT).show();
        }
    }
    public void flashLightOff(View view) {
        // this.flash.setVisibility(View.VISIBLE);
        this.flash.setVisibility(View.VISIBLE);
        try {
            if (getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_CAMERA_FLASH)) {
                Parameters p = camera.getParameters();    

                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                camera.setParameters(p);

            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Exception flashLightOff",
                    Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();

        // initialize the camera in background, as this may take a while
        //        try {
        //            Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        //            sb.setMax(camera.getParameters().getMaxZoom());
        //            sb.setProgress(0);
        //        //    Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
        //          
        //        } catch (RuntimeException e) {
        //            Log.wtf(TAG, "Failed to get camera", e);
        //        }
        //        if (camera == null) {
        //            Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
        //                    Toast.LENGTH_SHORT).show();
        //        } else {
        //            VideoCaptureActivity.this.initCamera(camera);
        //        }
        new AsyncTask<Void, Void, Camera>() {

            @Override
            protected Camera doInBackground(Void... params) {
                try {
                    Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                    sb.setMax(camera.getParameters().getMaxZoom());
                    sb.setProgress(0);
                    //  Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
                    return camera == null ? Camera.open(0) : camera;

                } catch (RuntimeException e) {
                    Log.wtf(TAG, "Failed to get camera", e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Camera camera) {
                if (camera == null) {
                    Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
                            Toast.LENGTH_SHORT).show();
                } else {
                    initCamera(camera);
                }
            }
        }.execute();
    }

    void initCamera(Camera camera) {
        // we now have the camera
        Camera.Parameters params = camera.getParameters();
        List<Size> previewSize = params.getSupportedPreviewSizes();
        temp = previewSize.get(0);
        //        for (int i =0; i<previewSize.size(); i++)
        //        {
        //          
        //        }
        this.camera = camera;
        // create a preview for our camera
        this.cameraPreview = new CameraPreview( VideoCaptureActivity.this,camera);
        // add the preview to our preview frame
        this.cameraPreviewFrame.addView(this.cameraPreview);
        // enable just the record button
        this.recordButton.setEnabled(true);
    }

    void releaseCamera() {
        if (this.camera != null) {
            //            this.camera.lock(); // unnecessary in API >= 14
            //            //this.camera.stopPreview();
            this.camera.release();
            this.camera = null;
            this.cameraPreviewFrame.removeView(this.cameraPreview);
        }
    }

    void releaseMediaRecorder() {
        if (this.mediaRecorder != null) {
            this.mediaRecorder.reset(); // clear configuration (optional here)
            this.mediaRecorder.release();
            this.mediaRecorder = null;
        }
    }

    void releaseResources() {
        this.releaseMediaRecorder();
        this.releaseCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        this.releaseResources();
    }
    @Override
    public void onStop()
    {
        super.onStop();
        this.releaseCamera();
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        this.releaseCamera();
    }

    // gets called by the button press
    public void startRecording(final View v) {
        Log.d(TAG, "startRecording()");
        // we need to unlock the camera so that mediaRecorder can use it\\
        //      this.camera.unlock(); // unnecessary in API >= 14
        // now we can initialize the media recorder and set it up with our
        // camera
        this.camera.stopPreview();
        this.camera.release();
        this.mediaRecorder = new MediaRecorder();
        //        this.mediaRecorder.setCamera(this.camera);
        this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        ////        this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        this.mediaRecorder.setProfile(CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_BACK,
                CamcorderProfile.QUALITY_HIGH));
        //        this.mediaRecorder.setVideoSize(320, 240);
        //       this.mediaRecorder.setVideoFrameRate(15);
        //        this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //        this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        //        this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //        this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        //        if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_1080P))
        //          this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
        //        else
        //            if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_720P))
        //              this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
        //            else
        //                if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P))
        //                  this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
        this.mediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
        this.mediaRecorder.setPreviewDisplay(this.cameraPreview.getHolder().getSurface());
        //      mediaRecorder.setMaxDuration((int) 1800);
        try {      
            //this.toggleButtons(true);

            String sec=String.valueOf(spinner1.getSelectedItem()) ;
            //int seconds =Integer.parseInt(sec);

            String toast =String.valueOf(spinner1.getSelectedItem()) +" Recording"; 
            Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
            if(sec.equals("1")){

                this.recordButton.setVisibility(View.INVISIBLE);

                this.mediaRecorder.setMaxDuration(1000);
                this.mediaRecorder.prepare();
                // start the actual recording
                // throws IllegalStateException if not prepared
                this.mediaRecorder.start();
                // this.recordButton.setVisibility(View.VISIBLE);
                this.recordButton.setVisibility(View.VISIBLE);
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stopRecording(v);
                    }
                },1000);
            }
            else if(sec.equals("2")){

                this.recordButton.setVisibility(View.INVISIBLE);

                this.mediaRecorder.setMaxDuration(2000);
                this.mediaRecorder.prepare();
                // start the actual recording
                // throws IllegalStateException if not prepared
                this.mediaRecorder.start();

                // this.recordButton.setVisibility(View.VISIBLE);
                this.recordButton.setVisibility(View.VISIBLE);


                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stopRecording(v);
                    }
                },2000);
            }

            else{

                //this.mediaRecorder.setMaxDuration(5000);
                this.toggleButtons(true);
                this.mediaRecorder.prepare();
                //start the actual recording
                // throws IllegalStateException if not prepared
                this.mediaRecorder.start();
                // stopRecording(v);
                // enable the stop button by indicating that we are recording
            }

        } catch (Exception e) {
            Log.wtf(TAG, "Failed to prepare MediaRecorder", e);
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            this.releaseResources();
        }
    }

    // gets called by the button press
    public void stopRecording(View v) {
        Log.d(TAG, "stopRecording()");
        assert this.mediaRecorder != null;
        try {
            this.mediaRecorder.stop();
            Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
            // we are no longer recording
            this.toggleButtons(false);
        } catch (RuntimeException e) {
            // the recording did not succeed
            Log.w(TAG, "Failed to record", e);
            if (this.file != null && this.file.exists() && this.file.delete()) {
                Log.d(TAG, "Deleted " + this.file.getAbsolutePath());
            }
            return;
        } finally {
            this.releaseMediaRecorder();
        }
        if (this.file == null || !this.file.exists()) {
            Log.w(TAG, "File does not exist after stop: " + this.file.getAbsolutePath());
        } else {
            Log.d(TAG, "Going to display the video: " + this.file.getAbsolutePath());
            Intent intent = new Intent(this, VideoPlaybackActivity.class);
            intent.setData(Uri.fromFile(file));
            super.startActivity(intent);
        }
    }

    private File initFile() {
        File dir = new File(
                Environment.getExternalStorageDirectory().toString() +
                Utils.OUR_TEMP_FOLDER);
        if (!dir.exists() && !dir.mkdirs()) {
            Log.wtf(TAG, "Failed to create storage directory: " + dir.getAbsolutePath());
            Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record, Toast.LENGTH_SHORT).show();
            this.file = null;
        } else {
            this.file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
                    "yyyyMMddHHmmss'.mp4'").format(new Date()));
        }
        return this.file;
    }

    private class seekListener implements SeekBar.OnSeekBarChangeListener
    {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            if (fromUser == true)
            {
                Parameters p = camera.getParameters();
                p.setZoom(progress);
                camera.setParameters(p);
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
    }
}

我的相机预览如下

 CameraPreview.java:

 public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
     private static final String TAG = "CameraPreview";

     private final Camera camera;

     @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
         super(context);
         Camera.Parameters params = camera.getParameters();
         List<String> focusModes = params.getSupportedFocusModes();
         if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) 
             params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
         else
             if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) 
                 params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
         camera.setParameters(params);
         this.camera = camera;
         super.getHolder().addCallback(this);
         // required for API <= 11
         super.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     }

     public void surfaceCreated(SurfaceHolder holder) {
         Log.d(TAG, "surfaceCreated()");
         // now that we have the surface, we can start the preview
         try {

             this.camera.setPreviewDisplay(holder);
             this.camera.startPreview();
         } catch (IOException e) {
             Log.wtf(TAG, "Failed to start camera preview", e);
         }
     }

     public void surfaceDestroyed(SurfaceHolder holder) {
         // we will release the camera preview in our activity before this
         // happens
         Log.d(TAG, "surfaceDestroyed()");
     }

     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
         // our activity runs with screenOrientation="landscape" so we don't
         // care about surface changes
        Parameters params = camera.getParameters();



         Log.d(TAG, "surfaceChanged()");
     }
 }

我不知道出了什么问题相机工作正常但是UI在开始时是可见的但是在一段时间后看不见但是预览仍然存在,如果我点击不可见的按钮就可以工作。所以控制工作但是看不到

0 个答案:

没有答案