Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8939525
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T10:50:41+00:00 2026-06-15T10:50:41+00:00

I have implement code Record video in Android Phone . This code is working

  • 0

I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 .

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>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T10:50:42+00:00Added an answer on June 15, 2026 at 10:50 am

    this may helps you,i have recently working on it and works but here i m using Intent, here getting video from Camera and write it in sdcard folder and using that path this video play.hop it helps full

    private final int VIDEO_RESULT = 1;
    
    Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
        btnOk.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // mpopup.dismiss(); //dismissing the popup
                mpopup.dismiss();
                PackageManager pm = getPackageManager();
                if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
    
                    try{
                        Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
                        //i.putExtra(MediaStore.EXTRA_OUTPUT,MyFileContentProviderVideo.CONTENT_URI);
                        startActivityForResult(i, VIDEO_RESULT);
    
                    }catch(Exception e){
    
                    }                   
                } else {
                    Toast.makeText(getBaseContext(), "Camera is not available",Toast.LENGTH_LONG).show();
                }
    
            }
        });
    
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        selectedVideos = new ArrayList<String>();       
    
        if (resultCode == RESULT_OK && requestCode == VIDEO_RESULT) {
            try {           
    
                uriVideo = data.getData();
                //Toast.makeText(ProfileVideo.this,uriVideo.getPath(), Toast.LENGTH_LONG).show();
    
                selectedImagePath = uriVideo.getPath();
                //selectedImages = new ArrayList<String>();
    
                byte[] ba = getCapturedVideoStream(ProfileVideo.this, data);
                MyWrite(ba);
    
    
                //selectedImagePath = Base64.encodeBytes(ba);           
                selectedVideos.add(selectedImagePath);
    
        }       
    
    }
    
    
    
    
    public void MyWrite(byte[] buffer)
        {       
            File sdCard = Environment.getExternalStorageDirectory();
            File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
            directory.mkdirs();
            //Now create the file in the above directory and write the contents into it
            File file = new File(directory, "sample.mp4");      
            selectedImagePath = file.getAbsolutePath();     
            FileOutputStream fOut = null;
            try {
                fOut = new FileOutputStream(file);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    
            BufferedOutputStream osw = new BufferedOutputStream(fOut);
            try {
                //osw.write(path);
                osw.write(buffer);
                //osw.write(buffer, offset, length);            
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                osw.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                osw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       
        }
    
    
    
    
    public static byte[] getCapturedVideoStream(Context ctx, Intent data)
    {       
        try 
        {
            AssetFileDescriptor videoAsset = ctx.getContentResolver().openAssetFileDescriptor(data.getData(), "r");
            FileInputStream fis = videoAsset.createInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try 
            {
                for (int readNum; (readNum = fis.read(buf)) != -1;)                
                    bos.write(buf, 0, readNum);
            } 
            catch (IOException e) 
            {
               // CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
            }
            byte[] bytes = bos.toByteArray();
            return bytes;
        } 
        catch (IOException e) 
        {
            //CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
            return null;
        }       
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have implemented code like here but it's not working for iOS 5.0, it
I have Googled merge+cell+Javascript but did not find any suitable code to implement merge
I have this code here: while ($record = mysql_fetch_array($itemavailablequeryres)) { echo <tr> <td>$record['itemid']</td> <td>$record['code']</td>
I have been using this code to implement a Popup JDialog of sorts, like
I have created a function to implement the regex.split in sql. Here's the code:
I have a question about how to implement this code public void setFieldAccess() {
I have some code that I absolutely must implement using goto . For example,
I want to implement singleten design pattern in iphone code I have one array.
I have this piece of code: @Entity @Table(name = MOVERS) public class MOVers implements
Here is a overview of my code. User press a record button and it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.