Video Recording Not Working in ICS
- by Nirav Ranpara
I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 . not in ICS
But when I checked in ICS code is not working ?
here I posted code and xml file.
videorecord.java
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class videorecord extends Activity{
    SharedPreferences.Editor pre;
    String filename;
    CountDownTimer t;
    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    Integer cnt=0;
    LinearLayout myButton;
    TextView myButton1;
    SurfaceHolder surfaceHolder;
    boolean recording;
    private TextView txtcount;
    private ImageView btnplay;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recording = false;
        setContentView(R.layout.videorecord);
        init();
        myCamera = getCameraInstance();
        if(myCamera == null){
        }
        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        Display display = getWindowManager().getDefaultDisplay(); 
           int width = display.getWidth();
           int height = display.getHeight();
        myCameraSurfaceView.setLayoutParams(new LinearLayout.LayoutParams(width, height-60));
        myCameraPreview.addView(myCameraSurfaceView);
        myButton = (LinearLayout)findViewById(R.id.mybutton);
        btnplay.setOnClickListener(myButtonOnClickListener);
    }
    private void init() {
        txtcount = (TextView) findViewById(R.id.txtcounter);
        //myButton1 = (TextView) findViewById(R.id.mybutton1);
        btnplay = (ImageView)findViewById(R.id.btnplay);
        t = new CountDownTimer( Long.MAX_VALUE , 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                cnt++;
                String time = new Integer(cnt).toString();
                long millis = cnt;
                   int seconds = (int) (millis / 60);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;
                   txtcount.setText(String.format("%d:%02d:%02d", minutes, seconds,millis));
            }
            @Override
            public void onFinish() {            }
        };
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
         if ((keyCode == KeyEvent.KEYCODE_BACK)) 
         {
             if(recording)
             {
                 new AlertDialog.Builder(videorecord.this).setTitle("Do you want to save Video ?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            filename();
                            //finish();
                        }
                    }).setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).show();
             }
             else
             {
                 if ((keyCode == KeyEvent.KEYCODE_BACK))
                 {
                            //Intent homeIntent= new Intent(Intent.ACTION_MAIN);
                        //homeIntent.addCategory(Intent.CATEGORY_HOME);
                        //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //startActivity(homeIntent);
                        //this.finishActivity(1);
                     finish();
                }
                 //moveTaskToBack(true);
            //   finish();
                        return super.onKeyDown(keyCode, event);
                    }
             }
         else
         {
            // Toast.makeText(getApplicationContext(), "asd", Toast.LENGTH_LONG).show();
             android.os.Process.killProcess(android.os.Process.myPid()) ;
         }
        return super.onKeyDown(keyCode, event);
    }
    ImageView.OnClickListener myButtonOnClickListener
    = new ImageView.OnClickListener(){
        public void onClick(View v) {
                    if(recording){
                Log.e("Record error", "error in recording .");   
                mediaRecorder.stop();  
                t.cancel();
                filename();
                releaseMediaRecorder(); 
            }else{
                releaseCamera();
                   Log.e("Record Stop error", "error in recording .");
                //
                if(!prepareMediaRecorder()){
                    prepareMediaRecorder();
                    finish();
                }
                mediaRecorder.start();
                recording = true;
            //  myButton1.setText("STOP Recording");
            //  btnplay.setImageResource(android.R.drawable.ic_media_pause);
                btnplay.setImageResource(R.drawable.stoprec);
                t.start();
            }
        }};
    private Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); 
        }
        catch (Exception e){
        }
        return c; 
    }
    private void filename()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Save Video");
        alert.setMessage("Enter File Name");
        final EditText input = new EditText(this);
        alert.setView(input);
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if(input.getText().length()>=1)
            {
                filename = input.getText().toString();
                File sdcard = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");
                File from = new File(sdcard,"null.mp4");
                File to = new File(sdcard,filename+".mp4");
                from.renameTo(to);
                SharedPreferences sp = videorecord.this.getSharedPreferences("data", MODE_WORLD_WRITEABLE);
                pre = sp.edit();
                pre.clear();
                pre.commit();
                pre.putString("lastvideo", filename+".mp4");
                pre.commit();
                //btnplay.setImageResource(android.R.drawable.ic_media_play);
                btnplay.setImageResource(R.drawable.startrec);
            //  Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);
                Intent myIntent = new Intent(getApplicationContext(), StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(myIntent);
            }
            else
            {
                filename();
            }
          }
        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
             // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);
              File file = new File(Environment.getExternalStorageDirectory() + "/VideoRecord/null.mp4");
              //boolean deleted = file.delete();
              file.delete();
              finish();
          }
        });
        alert.show();
    }
    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();
        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        File folder = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");
        boolean success = false;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (!success) {
        } else {
        }
        mediaRecorder.setOutputFile("/sdcard/VideoRecord/"+filename+".mp4");
        mediaRecorder.setMaxDuration(60000); 
        mediaRecorder.setMaxFileSize(5000000); 
        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getHeight();
        int height = display.getWidth();
        String s = new String();
        s= s.valueOf(width);
        String s1 = new String();
        s1= s1.valueOf(height);
      //  Toast.makeText(videorecord.this, "Width : " + s , Toast.LENGTH_LONG).show();
      //  Toast.makeText(videorecord.this, "Height : " +  s1 , Toast.LENGTH_LONG).show();
        mediaRecorder.setVideoSize(height, width);
        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;
    }
    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();    
        releaseCamera();           
    }
    private void releaseMediaRecorder()
    {
        if (mediaRecorder != null) {
            mediaRecorder.reset();   
            mediaRecorder.release(); 
            mediaRecorder = null;
            myCamera.lock();           
        }
    }
    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();      
            myCamera = null;
        }
    }
    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
        private SurfaceHolder mHolder;
        private Camera mCamera;
        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;
            mHolder = getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {
            if (mHolder.getSurface() == null){
              return;
            }
            try {
                mCamera.stopPreview();
            } catch (Exception e){
            }
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            } catch (Exception e){
            }
        }
        public void surfaceCreated(SurfaceHolder holder) {
               try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }
        public void surfaceDestroyed(SurfaceHolder holder) {
        }
    }
}
videorecord.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    >
    <FrameLayout android:layout_width="fill_parent" 
    android:layout_height="fill_parent" >
    <FrameLayout 
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"></FrameLayout>
    <LinearLayout 
       android:id="@+id/mybutton" 
     android:layout_width="fill_parent" 
     android:layout_marginBottom="0dip" 
    android:layout_height="wrap_content" android:orientation="horizontal"
     android:layout_weight="0" >
<!-- 
    <TextView  
       android:text="START Recording"
        android:id="@+id/mybutton1"
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"
        style="@style/savestyle"
         android:layout_weight="1"
        android:gravity="left"
         >
         </TextView>
     -->
    <ImageView   android:layout_height="wrap_content" android:id="@+id/btnplay"
    android:padding="5dip"
     android:background="#A0000000"
        android:textColor="#ffffffff"
        android:layout_width="wrap_content" android:src="@drawable/startrec" />
     </LinearLayout>
     <TextView 
    android:text="00:00:00"
    android:id="@+id/txtcounter"
          android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="right|bottom"
        android:padding="5dip"
        android:background="#A0000000"
        android:textColor="#ffffffff"
     />
    </FrameLayout>
    <RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@color/bgcolor" >
<LinearLayout android:layout_above="@+id/mybutton"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
</LinearLayout>
</RelativeLayout>
</LinearLayout>