Wednesday, June 26, 2013

Android App Development notes 4

Android Media Apis:


1)Play audio and video with mediaplayer
2)Recording audio and video with media recorder
3)Recording video and taking pictures using Intents
4)Previewing recorded video
5)Taking pictures and controlling camera
6)How to get thumbnail ??? through media scanner ???


MediaPlayer:
video/audio file can be from
  1)sdcard
  2)resource [res/raw] - For video file, we cant have it in resource.
  3)network [http://]
  4)content provider



MediaPlayer.create() will internally calls the prepare() function.


To display video, we should add one of the below control:

    1)VideoView 
        2)SurfaceView - More control on playback, we can go for surface view
            we are allowed to increase the volume... 



without mediaplayer, we can use VideoView.
VideoView has inbuilt mediaplayer to manage the playback.



VideoView videoView = (VideoView) findViewById(R.id.surface);
videoView.setKeepScreenOn(true); //screen wont be locked.
videoView.setVideoPath("/sdcard/test.3gp");

if( videoView.canSeekForward())
{
  videoView.seekTo(videoView.getDuration()/2);
}
videoView.start();


videoView.stopPlayback();

            


SurfaceView doesn't have the mediaplayer inbuilt.





public class videpPlayer extends Activity implements SurfaceHolder.Callback
{
    MediaPlayer mediaPlayer;

  onCreate()
 {
         mediaPlayer = new MediaPlayer();
  SurfaceView surface - (Surfa
  SurfaceHolder holder = surface.getHolder();
  holder.
 }
 
 onSurfaceCreated(SurfaceHolder holder)
 {
  mediaplayer.setDisplay(holder); //before prepare, call set display()
  mediaPlayer.setDataSource("/sdcard/test.mp4");
  mediaplayer.prepare();
  mediaplayer.start();
  
 }
 onSurfaceChanged()
{
 //width, height or surface is changed
}

 onSurfaceDestroyed(SurfaceHolder holder)
 {

    mediaPlayer.release();

 }
 

}





2) Audio and Video recording: MediaRecorder
   
  Add uses-permissions in AndroidManifest.xml:
     android.permission.RECORD_AUDIO
     android.permission,RECORD_VIDEO    

  Add uses-permission for WRITE_EXTERNAL_STORAGE

   1) Create MediaRecorder
   2) InputSources->SetAudioSource(MIC) or SetVideoSource(CAMERA)
   3) OutputFormat->setOutputFormat()
   4) Encoders ->setAudioEncoder()
                 setVideoEncoder()
   5)location of the recorded file->setOutputFile("/sdcard/video.mp4")

   6) mediaRecorder.prepare()
   7) mediaRecorder.start()
   8) mediaRecorder.stop()
   9) Release media recorder by mediaRecorder.release()

3)Preview video recording:
    we have to add surfaceview in XML layout.


  MyActivity extends  Activity implement SurfaceHolder.Callback
  {
    MediaPlayer mediaplayer;

    onCreate()
    {
    }
   
   onSurfaceCreated()
   {
      mediaRecorder.setPreviewDisplay(holder.getSurface());   
      mediaRecorder.prepare();
   }
   onSurfaceDestroyed()
   {
    mediaRecorder.release();
   }
   onSurfaceChanged()
   {
   
   }
   
  }


Pass data to intent using extra like putExtra();
startActivityForResult(intent,requestCode); requestCode is used to identify the child.



4) Using intents to record video

    Intent recordingIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    recordingIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        recordingIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0 or 1); //0 for MMS 1- video
    startActivityForResult(recordingIntent,RECORD_VIDEO);


      we will get the output in onActivityResult()

    onActivityResult(int requestCode,int resultCode,Intent data)
    {
      if (requestCode == RECORD_VIDEO && resultCode == RESULT_OK)
      {
        Uri recordedVideoPath = data.getData();
      }
    }

  This will launch the native video camera activtiy and allow the users to start,stop  recording.



5) on Emulator,we can record audio.

   
   Objective:
       1)Create a project to record audio
       2)playback the recorded audio
       3)       
 
5) using intents for image capture:
    void takeThumbnail(){
 
    Intent takingPhoto = new Intent(MediaStore.ACTION.IMAGE_CAPTURE);
    startActivityForResult(takingPhoto, TAKE_PICTURE);
    //It will create thumbnails
       }



6)  Controlling camera and taking picture:

    6.1)Add uses-permission android.permission.CAMERA
    6.2)Camera class
        Camera camera = Camera.open();
        ...
        camera.release();
    6.3) Camera.Parameters params = Camera.getParameters() ;//get existing settings
         camera.setParameters(params);

         we can change
        6.3.1) SCENE_MODE
        6.3.2) FLASH_MODE
        6.3.3) WhiteBalance
        6.3.4) ColorEffect
        6.3.5) focusmode
        6.3.5) setJpegQuality(),setJpegThumbnailQuality()
        6.3.6) Image, preview and thumbnail size
            setPictureSize(), setPreviewSize()
        6.3.7)Image and preview format:
            setPictureFormat()
            setPreviewFormat()

        6.3.8)setPreviewFrameRate()
           
       

Previewing camera:
   

MyActivity implements SurfaceHolder.callback
{
     onCreate()
      {
   
      } 
}



Location based services:
==========================

Location and Sensors:
======================
1)Location providers
    - Location Manager
    - Location Providers

    Two common location providers:
    1) GPS provider
        *will gives more accuracy than network providers
        * consume more battery
        * no cost involved
    2) Network providers [ coming from carrier service like Airtel,] [with internet]
        * need internet connection
        * pay for carrier service
   
       
2)obtaining current location
    Location location= LocationManager.getLastKnownLocation(string.GPS_PROVIDER);
3) Proximity alert in android
    ->once the user enters into another state, we will get alert message like "welcome to tamilnadu from airtel".
    ->1 km radius of the tamilnadu, location manager triggers the proximity alert.

4)Ex: Put the proximity alert while travelling...
    Before entering the radius of the location, proximity alert receiver should trigger
alerts

5)Geocoder:
    street addresses and map coordinates
   
    Forward geocoding->find coordinates of an address
    Reverse geocoding->finds street address of co-ordinates
   
 Latitude of bangalore:12.78
 longitude           :77.56


geocoder class is going to use internet & connect to google server to
get address,coordinate conversion




Google maps API v2:
===================

Process,Thread & IPC:
========================
  we can specify the service on which process it should run or create a new process for service.

By default, All the components belong to same process.
we can specify the  process in AndroidManifest.xml for activity/service/broadcast receiver/content provider.


 when the process will be killed:
   Android system may decide to shut down the process based on available memory and importancy of process.

Service:
    onCreate/onStart/onStop


Thread creation in Activity/service/Receiver.onReceive() should finish within 10 seconds.
Java threads can be used for thread creation.


Thread creation:
 1)Thread,Runnable
 2)AsyncTask [Android]
 3)Implement threads and use the Handler class to synchronize with
   the GUI thread before updating the UI
    Handler ->synchronization mechanism, update UI thread can be done via Handler.
  one thread can access another thread via synchronization mechanism.


AsyncTask:
============
    1)handles thread creation
    2)Thread management
    3)synchronization

class myTask extends AsyncTask<InputType, Progress,Result>

    if we dont want progress, make Progress as void.

String ... parameter - > Array of Strings in  Java

class myTask extends AsyncTask<String, Integer,Integer>
{
    protected Integer  doInBackground(String ... parameter) //parameter is inputtype, return value is Integer specified in AsyncTask
      {
    //Called in New Thread
    //Dont have access to UI thread


    int progress =0;
         PublishProgress(progress);

     return result;
      }       

    onPostExecuted(Integer result)
    {
    //called on Main thread or UI thread
    //This will be called after we returned result from doInBackground();
    //whatever doInBackground() function returns, it will be available in the onPostExecuted() fn argument "result".
        //can access UI elements   

    }   
    onProgressUpdate()
    {
      //Called on UI/main thread
      //can access UI elements   
      //This will be called once PublishProgress() is invoked   
   
    }       
       
}



Executing an asynchronous tasl:

    new MyAsyncTask.execute("inputString1", "inputString2");
   

execute()-> will create the new thread automatically,doInBackground() will be called




Handler mhandler = new Handler();

child Thread or Runnable's Run()
 {
    mHandler.post(doUpdateGUI);
 }

Runnable doUpdateGUI= new Runnable()
{
   public void run() {
    //access or update UI elements
   }   
   
}



Advantages of Java thread :
======================
   1)we can schedule your threads using timer
   2)we have more control in threads
   3)Synchronization is our responsibility
     AsyncTask doesnt have the access to thread control.
     


No comments: