Search This Blog

Showing posts with label Android Camera. Show all posts
Showing posts with label Android Camera. Show all posts

Monday, 22 July 2013

Example with source code of Reading call History from android phone


This tutorial teach you to fetch all call from android phone (Outgoing call, Incoming call, Missed Call) with information like call duration, user, call type etc

Because this whole process is very simple so i just make one method to read all call log and save them inside a vector of HasMap.

Android provide CallLog.Calls.CONTENT_URI content provider to read and write about calls. Every attribute has a call name inside data base of call content provider. Read those column and iterate through the loop

This need some permission in android manifest

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />

Function to read everything about calls

/** Result HasMap **/
    Vector<HashMap<String, Object>> mCallHostory = new Vector<HashMap<String, Object>>();
    private String name = "name", date = "date", duration = "duration",
            isRead = "is_read", type = "type";

    /** Function to read all calls **/

    public void getCallHistory() {
        Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
                null, null, null, null);
        cursor.moveToFirst();
        do {
            HashMap<String, Object> mTemp = new HashMap<String, Object>();
            /* Reading Name */
            String nameTemp = cursor.getString(cursor
                    .getColumnIndex(CallLog.Calls.CACHED_NAME));
            if (name.equalsIgnoreCase(""))
                mTemp.put(name, "Unknown");
            else
                mTemp.put(name, nameTemp);
            /* Reading Date */
            long dateTemp = cursor.getLong(cursor
                    .getColumnIndex(CallLog.Calls.DATE));
            mTemp.put(date, dateTemp);

            /* Reading duration */
            long durationTemp = cursor.getLong(cursor
                    .getColumnIndex(CallLog.Calls.DURATION));
            mTemp.put(duration, durationTemp);

            /* Reading already user see it or not */
            long IS_READ = cursor.getLong(cursor
                    .getColumnIndex(CallLog.Calls.IS_READ));
            mTemp.put(isRead, IS_READ);

            /* Reading Date */
            int typeTemp = cursor.getInt(cursor
                    .getColumnIndex(CallLog.Calls.TYPE));
            mTemp.put(type, typeTemp);

            /* Add one call Detail to Vector */
            mCallHostory.add(mTemp);
        } while (cursor.moveToNext());

        Log.e("Check", "Data");
    }

Reference Link

Android Developer

Saturday, 1 December 2012

Video recording application in android

We can take video from android default intent also but customization becomes impossible as it has its own limitation. So we need to make our own camera application in android to capture video. It will work as camcorder also. Making camera application in android , is bit complicated task if we do not understand it step by step

It need these three thing


  • SurfaceView to give one platform to show material
  • Camera to show material on surface provided by surfaceview
  • And a media recorder to record the video provided by camera and surface view

So let make one layout, which have one surfaceview class inside it and start with surfaceview


  • surfaceview called surfaceCreated(SurfaceHolder arg0) very first time. So we need to open camera here. Handle the case where camera is not able to work properly
 @Override
 public void surfaceCreated(SurfaceHolder arg0) {
  camera = openFrontFacingCamera();
  if (camera != null) {
   try {
    camera.setPreviewDisplay(holder);
   } catch (IOException e) {
    camera.release();
    camera = null;
   }
  } else {
   Toast.makeText(act, "Problem in opening Camera.", Toast.LENGTH_LONG)
     .show();
   act.finish();
  }
 }

  • Now camera is ready. Once surfaceChanged(SurfaceHolder arg0, int format, int height,int width), we will instantiate the MediaRecorder and attach all thing to capture video properly. It important to remember that camera attribute is need to be set in a order but their value may differ

 @Override
 public void surfaceChanged(SurfaceHolder arg0, int format, int height,
   int width) {
  Camera.Size previewSize = null;
  try {
   Camera.Parameters parameters = camera.getParameters();
   List<Camera.Size> supportSize = parameters
     .getSupportedPreviewSizes();
   if (supportSize != null) {
    previewSize = getOptimalPreviewSize(supportSize, width, height);
   }
   parameters.setPreviewSize(previewSize.width, previewSize.height);
   parameters.set("orientation", "portrait");
   camera.setPreviewDisplay(arg0);
   camera.setParameters(parameters);
   camera.startPreview();
   camera.unlock();
   m_recorder.setPreviewDisplay(arg0.getSurface());
   m_recorder.setCamera(camera);
   m_recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
   m_recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
   m_recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
   m_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
   m_recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
   m_recorder.setMaxDuration(90000);
   m_recorder.setOnInfoListener(oninfoLis);
   m_recorder.setVideoSize(previewSize.width, previewSize.height);
   m_recorder.setVideoFrameRate(30);

   m_recorder.setVideoEncodingBitRate(500);
   m_recorder.setAudioEncodingBitRate(128);
   m_recorder.setOutputFile("/mnt/sdcard/myfile"
     + SystemClock.elapsedRealtime() + ".mp4");
   m_recorder.prepare();
   m_recorder.start();
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.getMessage();
  }
 } 
  • But most important is to get optimal preview display to camera. For one device there may be more than one preview display so we need use best among them to capture good quality video


         private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
  final double ASPECT_TOLERANCE = 0.1;
  double targetRatio = (double) w / h;
  if (sizes == null)
   return null;
  Size optimalSize = null;
  double minDiff = Double.MAX_VALUE;
  int targetHeight = h;
  for (Size size : sizes) {
   double ratio = (double) size.width / size.height;
   if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
    continue;
   if (Math.abs(size.height - targetHeight) < minDiff) {
    optimalSize = size;
    minDiff = Math.abs(size.height - targetHeight);
   }
  }
  if (optimalSize == null) {
   minDiff = Double.MAX_VALUE;
   for (Size size : sizes) {
    if (Math.abs(size.height - targetHeight) < minDiff) {
     optimalSize = size;
     minDiff = Math.abs(size.height - targetHeight);
    }
   }
  }
  return optimalSize;
 }

So this article shows how to capture video with out default intent. Video quality may vary according to device resolution. and you need to set Video Frame Rate according to you device type. I have found this limit on android developer site



SD (Low quality)SD (High quality)HD (Not available on all devices)
Video codecH.264 Baseline ProfileH.264 Baseline ProfileH.264 Baseline Profile
Video resolution176 x 144 px480 x 360 px1280 x 720 px
Video frame rate12 fps30 fps30 fps
Video bitrate56 Kbps500 Kbps2 Mbps
Audio codecAAC-LCAAC-LCAAC-LC
Audio channels1 (mono)2 (stereo)2 (stereo)
Audio bitrate24 Kbps128 Kbps192 Kbps

 Download Source Code

Sunday, 6 May 2012

Taking picture and Video from Camera and displaying or playing in android

Taking picture in android has two way to achieve it

1) Using  Surface view with Camera integration
2)Starting Default Camera Activity that will return an intent with picture

first way i have discussed in How to take picture with surface View and camera .Now i am going to discuss second way of taking picture from android camera. And In code you will also know how to take Video in android and Playing it. I will display taken image in ImageView and video will be start paying in a videoview. User Interface will be similar to this when you will run code


Source code and screen shot are available at the end of article

private void dispatchTakePictureIntent(int actionCode) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = null;
            try {
                f = setUpPhotoFile();
                mCurrentPhotoPath = f.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            } catch (IOException e) {
                e.printStackTrace();
                f = null;
                mCurrentPhotoPath = null;
       } // switch
startActivityForResult(takePictureIntent, actionCode);
    }

This method will dispatch a intent and will start an Camera Activity . In my code i have two option weather you want to take big picture or small one (to avoid memory error ). So you will get a switch case there. actioncode is decide, we will have to handle big Image or small Image.

Here are the step to create file path to save image

setUpPhotoFile() this method is used to create a file for saving image

 mCurrentPhotoPath = f.getAbsolutePath(); // this will save the file path and will pass into intent so that it will take it to save image later on

finally we will start activity

startActivityForResult(takePictureIntent, actionCode);

Now if we click picture then we have to handle intent data inside the onActivityResult()

private void handleSmallCameraPhoto(Intent intent) {
  Bundle extras = intent.getExtras();
  mImageBitmap = (Bitmap) extras.get("data");
  mImageView.setImageBitmap(mImageBitmap);
  mVideoUri = null;
  mImageView.setVisibility(View.VISIBLE);
  mVideoView.setVisibility(View.INVISIBLE);
 }

In activity result i have three method  one for handle small picture intent, second to handle big picture then one for handle Video .If you are taking video or big picture then study these method


 private void handleBigCameraPhoto() {

  if (mCurrentPhotoPath != null) {
   setPic();
   galleryAddPic();
   mCurrentPhotoPath = null;
  }
 }



      private void handleCameraVideo(Intent intent) {
  mVideoUri = intent.getData();
  mVideoView.setVideoURI(mVideoUri);
  mImageBitmap = null;
  mVideoView.setVisibility(View.VISIBLE);
  mImageView.setVisibility(View.INVISIBLE);
 }

                                                        Screen shot of this project



    

Source Code

Android News and source code