Friday, July 05, 2013

The importance of automating test cases

To maintain legacy code for a longer period of time, it is best to write automated Unit testing,

     This will maintains product quality from the situation where the fresher/ new developer has added code without understanding.
 
     In my work environment,  Once the code is committed to repository, Hudson server triggers the build, test for automated Unit testing cases. If all the Unit testing cases are passed, then only it will allow us to submit.

    One new guy has modified some code, it is affecting some functionality. This error was captured while running the automated test cases.

In Android to automate test cases, InstrumentationTest Runner is available.

Example for writing UnitTesting[UT]:

In case of UT, we can mock objects instead of testing with real object. I encountered the problem in getting an IP address when wifi and wifi direct is on.

   So To solve this problem, I mocked the wifi, wifi direct scenario in UT cases, so that it wont never happen again and if some one is modifying the source code, his source code should pass my testcase,Then only he can submit the source code to repository.

            

  




Wednesday, June 26, 2013

Android App Development 5


Reference: Professional Android 2 Application development by Reto meier


1)AIDL
2)IPC,Process,Thread
3)Bluetooth
4)Fragments
5)NDK

You need to use AIDL if you want a class outside of your application's process to access the Service.
If you're only using the service from inside your application, you can use a local service.

Remote procedure calls:
========================
AIDL:

  In RPC, only methods are exposed.we cannot expose variabls.
All RPC methods are synchronous. Calling process gets blocked
until the remote method finishes execution.
   
AIDL generated Javainterface is shared between server and client.
Server implements java interface. client invokeds java interface methods.


uses proxy class[stub] to pass values between server and client.

Server Side steps:
=====================
1)create the .aidl file & declare RPC interfaces
2)AIDL ->generates the java interfaces stub [.java file] from .aidl
   
3)use stub class to implement RPC methods
    ->Stub class is derived from IBinder interface
4)Expose RPC methods via Service
    -> service will be started if it is a background task
    -> Here we will bind to the service if it is a interface
   

    in, out, inout parameters

Few rules are implementing your interface:
=============================================
1)client has to call the RPC methods in a separate thread
if particular RPC method is taking time or complex calculation   
2)No exceptions from RPC methods to caller. It wont be passed to
client, handle the exception locally dont throw it to caller
3)only methods can be exposed, data cannot be exposed in RPC
4)To make the service available to other or make it as public service,
 we have to add action in intent filter. the client will make use of this action
in Intent & start the service.



Client side steps:
===================
0)Stub class is shared across clients
1)Declare the interface variable
2)Implement ServiceConnection interface
    onServiceConnected(componentName name, IBinder binder)
    onServiceDisconnected()
3)bindService (intent,serviceConnectionObject, flag);//while binding, if the service is not running,
  it will create the service and bind to it
    bindService will call bind() method of the service.
Once service connected, onServiceConnected() called. We will typecast
IBinder object to our interface variable.
4) call the methods on your interface
5) To disconnec call Context.unbindService() with the instance of the service connection.
    ->This will triggers onServiceDisconnected() method will be triggered




Bluetooth:
=========
Range 10 meters.it will makes use of MAC address.

1)setting up bluetooth
2)find available devices or paired devices
3)connect with the device
4)Transfer data


classes to be used:   
===============
1)BluetoothAdapter
    ->represents local bluetooth adapter/bluetooth radio
2)BluetoothDevice
3)BluetoothSocket
4)BluetoothServerSocket
5)Bluetooth class

permission:
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN-> modify settings/discovering devices


1)Bluetooth application to take attendance of students in classroom automatically.



Sensors:
=============
1) measure motion,orientation and various environmental conditions [pressure,temparature,light]


sensor types:
============
1)Motion sensors
    acclerometers-> how fast the phone is moving,monitoring device movement
    gravity sensors->
    rotational vector sensors->
2)Environmental sensors
    barometers
    thermameters
3)Position sensors


sensor framework android:
1) Determine available sensors on a device
2) Determine the sensors capabilities power,range...
3) acquire raw sensor data frequency of the data you want[ for every minute...]
4) Register and unregister sensor event listeners



location,Bluetooth & sensors


Based on accelerometer, detect whether the phone has fallen or the old person has fallen down...
and send the location details to provided contact number as SMS, trigger the call to predefined number and
enable the phone


GPS phones to track the travel buses and its locations from Travels company




Fragments:
============
  --> Actitvity is a container for views.
Fragments
    - address large screen devices like tablet
    - introduced Android 3.0 HoneyComb
    - one or more fragments can be combined to an activity
    ->mini activities with its own set of view
        ->can reuse fragments in multiple activities
        -> multipane UI



Localization of UI resources are important.
onCreate()
{
 setcontentview(r.id.abc);
}


res/layout/abc.xml-> two  fragments for normal phone
res/layout-port/abc.xml- can have many fragments
Android will decide dynamically at runtime... if it is a portrait mode, it will load
the abc.xml from res/layout-port/ path. User doesnt need to add code for it.



Lifecycle of a fragment:
   depends upon the activity. if the activity is paused, all the fragments are paused
if the activity is running,all the fragments are running.
if the activity is stopped,all the fragments are stopped.


Backstack:...
 

Fragment inside Activity:
    1)Fragment can be in any ViewGroup
   
DialogFragment, ListFragment, PreferenceFragment, WebViewFragment

Fragment's onCreateView()->Load the UI layout or create it dynamically.



android's Inflate() method will read xml and create UI resources.

Dynamically adding fragments to an Activity:
  1)via FragmentTransaction


Emulator ->press ctrl+F11 to move to portrait mode in emulator

Try this

    res/layout/abc.xml-> UI for  landscape mode
    res/layout-port/abc.xml- UI for portrait mode

FragmentManager,FragmentTransaction classes are important;



Localization qualitifier for tablet:
1) screen width
2) screen size


NDK:
=========
    1)NDK development in practice
    c/c++ ->business logic
    java  ->

    1)porting the existing C/C++ source to Android only activity we have to develop it in java.
    2)Execution is faster since it is converted to assembly language
       Skips Dalvik VM, byte code to assembly language code.

C/C++ functions are invoked from Java via JNI calls.



java -> output ->.dex
c/cpp=> output ->library
Final apk => .dex + library done by NDK tool

For Windows, cygwin 1.7 or higher is required to build NDK [binutils,gcc-g++,make,splint]


NDK Project:
    src-> java files
    res
    jni-> .c/.cpp files & Android.mk-> output: library file copied under "lib" folder.
        jni/Application.mk ->optional
   

cd NDKProject
NDK-build clean
NDK-build
  =>This will build the C/C++ source code, copy it to libs folder
  =>After this open the project in eclipse, and compile it to create the apk file   


static block is executed before loading the activity or creating an object.

static
{
  System.loadLibrary("fileloader"); //for loading fileloader.so
}

JNI function name:


Java_<packageName>_<ClassName>_loadFile()


className-> where we declared the loadFile() as native
PackageName-> where the class belongs to


JNIEnv-> from Java environment
     Conversion of java string to C/C++ string or C/C++ string to java string done by Java environment


Android.mk:
===============
LOCAL_PATH->Current project source directory
CLEAR_VARS->Earlier variables are cleared
LOCAL_MODULE :=fileloader #creates libfileloader.so
LOCAL_LDLIBS=>used to specify linking libraries and system libraries
LOCAL_LDLIBS := -llog

BUILD_SHARED_LIBRARY
BUILD_STATIC_LIBRARY



 samsung android reference:

http://developer.samsung.com/android/samples









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.
     


Android App Development notes 3

DataStorage:
   persistent storage of data

persistent storage:
  1)Shared preferences- stores key value pair in xml
            can save states of UI or UI data   
            Limit:Only primitive datatypes [booleans,floats,ints,
                            longs and strings]
            getSharedPreferences(filename,mode)->can be shared by other activities & and other activities
            getPreferences()->cant be used by other activities

    Ex:read from the preferences:
    SharedPreferences prefs = getSharedPreferences("UserFilename",0);
    boolean bSignIn = prefs.getBoolean("staySignIn",false);//false is the default value if the value doesnt exist

    write to preferences:
    onStop() fn:
    SharedPreferences prefs = getSharedPreferences("UserFilename",0);
    prefs.putBoolean("staySignIn",bSignIn);
    prefs.commit();//To store the value
   
    xml file path:data/data/com.app/shared_prefs/UserFilename.xml
    once we uninstall application, shared_preferences file will be deleted.
  2)Internal Storage
    -Save files directly on the device's internal storage

  3)External storage
   
  4)SQLite databases
    Helper classes: SQLiteOpenHelper,SQLiteDatabase,Cursor
    Any DB
    4.1) Create DB
    4.2) Create table with schema
    4.3)Insert,Update,Delete,query
   
       4.1,4,2 can be performed by SQLiteOpnenHelper class
       4.3 can be performed by SQLiteDatabase class    

  It will create data/data/com.app/shared_prefs/UserFilename.db. we can pull it from device
and can see the data using any SqlReader.




ContentProviders -required to make your DB as public
         -access to contacts possible by contacts contentprovider

Implement new content provider:
=================================
  1) set up system for storing the data with SQLiteOpenHelper & SQLiteDatabase to manage DB operations
  2) Extend the ContentProvider class to provide access to the data
  3) Declare the contentprovider in AndroidManifest.xml


  ContentProvider implementor, ContentProvider client

  ContentProvider client refer via Content URI. Ex "content://contacts/people"


 content://com.example.transportationprovider/trains/122


 content://-standard prefix
 com.example.transportationprovider - authority part of URI, identity of DB, it identified the content provider
 trains - identifier of table name
 122 - rowid of the table

  Declare the contentprovider in AndroidManifest.xml:
    <provide name= "TransportationProvider" authorities="com.example.transportationprovider" ... >


Ex:
    android.provider.ContactsContract.Contacts.CONTENT_URI

ContentProvider must implement
  1)query(Uri...) - From this URI, it has to identify which table client requires...
  2)Insert()
  3)update()
  4)delete()
  5)getType()
  6)onCreate()


ContentProvider client use ContentResolver class.

    ContentResolver cr = getContentResolver();
        cr.query(CONTENT_URI,...);
    cr.insert(CONTENT_URI...);
 
From CONTENT_URI's authority, it will find out which class & perform query() or insert()... operations.




Querying a contentprovider:

For querying a contentprovider, ContentProvider Client requires 3 information;
   1)what is the content_URI of ContentProvider
   2)Column names of ContentProvider
   3)what are all the datatypes of ContentProvider
    so that he can decide whether to use cursor.getString or cursor.getInt() or cursort.getBoolean()

   1) ContentResolver.query()
   2) Activity.managedQuery()
    - Best practice is invoking managedQuery() from Activity. so that cursor will be aligned to
      lifecycle of an activity

Uri insertedRowIdUri=  contentResolver.insert()//returns the URi of row id

To delete the row,
    contentResolver.delete(rowIdUri)
Delete multiple rows:
    contentResolver.delete(condition);

 
MediaStore is a content provider to acccess multimedia.


SQLiteDatabase.query() has where class and selectionArgs;

we can give our conditions like this in where clause;
   

    String where = "username='sundar'";
              or
        String where = "username='" + stringSundar+"'";
   
If we have multipe where conditions, do the following:
    String where = "username=? AND password=?";
        String selectionArgs[] = {"sundar","password"};

& pass it in query( ...where,selectionArgs...);





Security in Android:
  1) it is above Linux. it has all features like one process cannot access another process's memory
  2) permissions {READ_CONTACTS, internet  permission};
        while instlallation, if that application is using CONTACTS or
        when we allow, the permission is granted and APK will be installed.
        permission is granted during installation time by package installer.
        uses_permission tag.
        we can also create new permissions using permission tag.

  3) Every Android App. should be signed with digital certificate
        [Application signing is must]
 

How to sign the application in Android:
1) we can create our own digital certificate [self signed certificate]
2) Normal application is certified with debug certificate.
   otherwise it wont run in emulator
3)To release it in google playstore, we should not use debug certificate.

    3.1)Create private and public key [keystore]
        3.2)sign application with certificate
   
   
   
 
 

if we want to make my activity public, we have to declare IntentFilter for that activity.

<activity name ="sundar">
  <Intent-Filter>
    <action name = "com.sundar.app.sundar">
    <category    = DEFAULT> //without DEFAULT category it is not working.
    <data>


if anyone trigger/send this action "com.sundar.app.sundar", the activity "sundar" will be launched.


permission = normal -> autogranted during installation
             dangerous ->request the user response while installation
         Signature -> if two activities have the same certificate,one activity can access another activity
              or the inbuilt application.
             secure system functions, our activity, service,contentprovider and broadcast receiver by
             including android:permission attribute.
      

   
          
Sign certificate in the application:
 1) File->export->Export Android Application->Select the application
 2) select create new keystore 

if my application validity will expire tomorrow, what will happen if I installed my application today ? will it run
or it wont run?

Android application validity,
Multiple applications can have the same keystore.
Certificate validity is checked at the time of installation only. not every time it is running.
So if I have installed today, it will run fine tomorrow also. Tomorrow if any device is trying to install
it, it wont install because of validity expiration.



if we have not added uses-permission for reading contacts, if we try to read contacts,
it will give security exception and show force close dialog.


How to secure public activity:
==============================
    using permissions.
Server application has to create the permission using permission tag to allow access the activity.
Client application should use uses-permission tag to launch the server application's activity.

       



While creating the permission, the user should add it as signature level permission. so that the created permission
can be accessed


Resources:
============   
     7 primary resource types;
    1) Simple values - /res/values/
             - R.<resource type>.<name of resource>

        Externalizing strings helps to localize it    
        Reuse it easily
               

    2) Drawables -   
        3) Layouts
        4) Animations
    5) Menu
    6) Styles
    7) Raw
    8) XML

    Resource files should contain lowercase letters,numbers,peroids(.) and underscores (_).

    Resource inside resource access can be done by     @<ResourceType>/<ResourceName>.


Animation:
===========
    1)Tweened animation
        -ops:rotate,stretch,move,fade
    2)Frame animation-> sequence of animations in order


Menu XMLs can be loaded by MenuInflater class.



Resources:
=============

ResourceType ResourceName


filename as resourceName
 layout
 drawable
 menu
 animation

name as resourcename
  string
  color
  dimen
  styles


Resources can be accessed by
  1) R.in java code
  2) in XML
        @<resourceType>/<ResourceName>


AAPT will create R class.

 For each resource type, there is a subclass in  R class.

  Syntax:[packagename.]R.<resource_type>.<resource_name>


Resource res = getResources() //get resources object

String[] planets= res.getStringArray(R.array.planets_array);
String title    = res.getText(R.string.main_title);



if we are using resource in another resource,

    syntax:@[packagename:]resourceType.resourceName

Native resources can be found from android.R class.

Localization:
    res/values/strings.xml
    res/values-fr/strings.xml
    res/values-fr-rCA/strings.xml



 
     

   

     

Android App Development 2

Steps to add new activity in Android Application:

Register the activity in AndroidManifest.xml.
finish() is used to close the activity.
 



1) Activity which has launcher category and MAIN action
 will be showed on screen first.
This is called the main activity.

2) Menu
    Menu items can have shortcuts or icons with text.
    Icons are supported only in first 6 items.

By pressing menu button,menu will be displayed.

    2.1) options menu - 6 items are supported in single screen
              - if we have more than 6 items, last item will be shown as more...   
                          - while clicking more, it will show expanded menu  
           Options menu belongs to Activity.
       
    If we want to add options menu in our activity:
    we have to implement the following:
    while clicking menu key, onCreateOptionsMenu() fn will be invoked.

        1) onCreateOptionsMenu() returns true menu will appear on screen
                           returns false menu wont appear on screen
        2)onOptionItemSelected() - if we handled the selected menu item, return true
                 if we have not handled the selected menu item,return false.the base class version of
                          onOptionItemSelected() will be invoked
   
       
 
  menu.add(groupid,ItemId,order,menuText)


                
    2.2) context menu
               - will be displayed if we do long press on any view
           - belongs to the view
               - register the view by registerForContextMenu
           - Dont have support for icons or shortcuts
       implement:
        onCreateContextMenu()            
        onContextItemSelected()
   
        2.3) SubMenu
        - part of another menu item
                - it can be options menu or
              context menu
        - submenu is supported only one level...
          Nested submenus are not supported
            implement:
        onCreateOptionsMenu()
            SubMenu fileMenu =menu.addSubMenu("File");               
        SubMenu editMenu = menu.addSubMenu("Edit");
                fileMenu.add(itemId,"new");
        fileMenu.add(itemid,"open");
 
   

Develop sample application for context menu and submenu.

Notifying user:
===============
    1)Toast notification
        - no user interaction
        - used from activity or service
        - Acivity stills active while displaying toast & responsive
        - Doesn't accept interaction events
        2)StatusBar notification
        - Persistent reminders
        - alert remains as long as user have not seen or visited it
        - need interaction from user
        - Ex: SMS, low battery,download status, once content is downloaded, download complete notification
        - used from activity or service

        it requires:
        -icon for the status bar
        -title,expanded message, expanded view
            -Pending intent triggered to launch the application or activity
        -on user action, we can launch activity or service or broadcast receiver
               

    2.1)Get a reference to the notification manager:
        NotificationManger mNotificationMgr=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    2.2)Create notification:
        String tickerText = "hello";
        Notification notification= new Notification(R.drawable.ic_launcher,tickerText ,System.currentTimeMillis());
    2.3)Define the notification's expanded message and Intent:
        //wrap the intent object inside pending intent
        Intent notificationIntent= new Intent(this,Myclass.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
        notification.setLatestEventInfo(this,contentTitle, contentText,pendingIntent);

        For service:
            PendingIntent.getService()
        For broadcast:
            PendingIntent.getBroadcast()

       
    2.4)Pass the notification to Notification manager
        mNotificationMgr.notify(notificationId,notification);   

        once application is launched, clear the notification in system.   
       
   
    who will trigger the pending intent in notification ???
            It will be done by Notification manager.


    3)Dialog notification
        - used only from activity
        - Current Activity will be in Pause state
        - AlertDialog
            - max. selectable 3buttons
            - buttons appear on dialog bottom
            - checkboxes or radio buttons allowed
            -
   
        - ProgressDialog
        - DatePickerDialog
        - TimePickerDialog

    Add dialog to activity:
        1) implement onCreateDialog(dialogId)[create & return dialog]   
            Every dialog has its own unique id.
            Called only once
           
        2)when we want to display a dialog
           call showDialog(dialogId);
            showDialog internally calls onCreateDialog(withIdArg)
        3) remove dialog can be done by removeDialog();

        AlertDialog.Builder class can be used to configure the dialog properties.
        By default all dialogs are cancelable.




   Two types of dialog box:
    1) Spinning wheel dialog- Dont know when it will end we will go for the spinning wheel dialog
    2) Progress dialog - know when the task will end
                 For download status, we are sure when download will end.
        horizontal

Spinning Wheel dialog:
   
    boolean iscancelable= true;
         ProgressDialog pDialog = ProgressDialog.show(MyActivity.this,"","Loading please wait..",isCancelable);
    when everything ends,
    call progressDialog.cancel()...

   
Horizontal dialog:
   


Adapters and Adapter views:
=============================
Adapter
   1)provides data to AdapterView [listview,gallery,spinners];
   2)responsible for making a View for each item
 
Two types of adapter:
    1) array adapter
    2) cursor adapter   
     
Adapter:
   1)supply data
   2)handles UI view

   listView.setAdapter()

Adapter base class:BaseAdapter
ArrayAdapter - Array data
SimpleCursorAdapter - handle database related data


Intent:
    -message passing mechansism that workes  both within application and between applications
Types of intents:
    1) Explicit intent- launching the activities of same application
        2) Implicit intent -launch the activity of other application



Example for implicit intent:
    Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse('tel:555-1234"));
    startActivity(i);

Explicit intent syntax:
    Intent i = new Intent(Action, data)
    Action - mandatory
    data - optional

 It will find out the activity which can perform the ACTION on that data.if it finds the activity,
it will launch activity.

  Resolving implicit intent at runtime is called as Intent resolution.


Android registry:
====================
    contains classname action and datatype.

At run time, it looks into the registry & decide which activity launch.
If  multiple activities can perform the same action, Android will popup the dialog to user for selecting the right application.

If there are no application match found, then it will crash and give force close dialog.


Any ways to update Android registry??


Native android actions:
    ACTION_ANSWER
    ACTION_DIAL
    ACTION_EDIT - Activity that can edit data specified in the intent
    ACTION_PICK - pick an item from the content provider in the intent
    ACTION_VIEW-Activity that can view data specified in the intent
    ACTION_SENDTO
   
Contacts DB is exposed publicly to others by content providers.

Intent i = new Intent(ACTION_VIEW,Uriparse("http://google.com"); #launch the browser

Intent i = new Intent(ACTION_VIEW,Uriparse("tel:123456");#???


From parent activity, we can get child activity information if

 1)child activity launched with startActivityForResult()
 2)Once the child activity is closed, it will triggers the parent activity's
  onActivityResult()
    requestcode let us know from which child activity, we are getting results

 
IntentFilter:
===============
    intentfilter contains
        1)action
        2)category
        3)data

        Activity.Action
       

In AndroidManifest.xml
    <data androidscheme="abc" />

During installation, Android manifest file is checked. Installer will update the android registry.
Activity without intentfilters, we can say without private Activity which can be launched only from that application.

Activity with intentfilters can be accessed from any application.


refer OpenIntents.org defines the already available intents from other apps in google play or playstore.
openintents.org

Broadcast Receiver:
===================
  Android uses broadcast intents to broadcast system events like battery low,battery level, network connections etc

 Intent i = new Intent(action);
 sendBroadcast(i);
   
 i-Broadcast intent
 action-Broadcast action


  Mainly used from services

Native Android Broadcast Actions:
    Android broadccasts intents for many of the system services primarily to
track device status changes.

   
1)ACTION_BOOT_COMPLETED
2)ACTION_CAMERA_BUTTON
3)ACTION_MEDIA_MOUNTED
4)ACTION_MEDIA_EJECT
5)ACTION_DATE_CHANGED
6)ACTION_TIME_CHANGED

Time limit in onReceive() is 10 seconds.

Two types of broadcast:
1)order broadcast
    based on highest priority
2)

Broadcast is not visible to user whereas status bar notification is visible to user.

In AndroidManifest.xml, register the broadcast action for broadcast receiver.

Static registration


Register by code:
===================
Dynamic registration of broadcast receiver:

if register it in code, usually add it in OnCreate() of launcher activity.

IntentFilter filter= new IntentFilter("com.test.action.newLocation");
LocationUpdater recvr= new LocationUpdater();
RegisterReceiver(recvr,filter);


Unregister by code:
=================
unregisterReceiver(recvr); #if forgotten, it will give


Diff static registration and dynamic registration:
===================================================

static registration:
   If my application is not available, it will be able to receive broadcast action
   Ex; BOOT_COMPLETED

Dynamic registration:
====================
   If my application is not available, it wont be able to receive broadcast action

For system events, go for static registration.
For Application specific events, go for dynamic registration.


Same BroadcastReceiver can be used to register for multiple broadcast intents;


 In onReceive()
{
    string action= intent.getAction();
    if(action == BOOT_COMPLETED)
    {
    handleBootCompleted();   
    }
    else if(action ==BATTERY_LOW )
    {
    handleBatteryLow();
    }
         
}


Service:
===========
two ways of service:
    1)background and long running task &  No UI
    2use service as interface [IPC]
======>    AIDL


Activity and Service is running in the same thread.
while launch a service, new thread will not be created.
Service is not a separate process, it is belonging to the activity process and running in the same thread.


Service:
  1)Create service class
  2)register the service in AndroidManifest.xml
  3) if you want to make it public, register the intent filter for the service so that others can use ur service



Creating a service:
 1)startService & stopService
 2) In case of interface or IPC, use bindService(), unbindService() fn


  single service instance used for serving multiple applications.
if one application is using the service, onCreate() onStart() is called.
Second application is creating the service, then it wont call onCreate(), onStart() will be called repeatedly.


Always create thread

1)less chance the service will get killed compare to background process
2)Even though the activity will be killed, still the service will run in background


Actvity will start the service.
Service will broadcast the receiver.
Activity will receive the broadcast.
           


       
   

       








Android App Development

1)TVS motors-mp3 player in android for indonesian client
2)Samsung has printer with android os
3) GE healthcare scanning - with android Os
4) ATM also has android OS

Windows Phone or iOS is tightly coupled with OEMs/manufacturers.


Advantages:
1) Google map applications
2) Background services and applications { ex: image download in background}
3) Shared data and Interprocess commn
4) All applications[in-built application/third party app. no difference] have all apis.

if we want to make our DB public, we have to implement content provider , so that others can make use of it.

Application framework - List of classes & APIs available for developers

dvm:
   -Allows multiple instances of virtual machine
   -less Binary size

    java -> .class -> .dex
    .apk -> dex + resources
   

    accelerometer-> rotation,tilt motion sensors

Idea:
  Set training mode in mobile,when the user is calling
the caller should receive message/voice message about the user's scenario.



 while pressing BACK button, by default it will goes to previous activity.This is done by Activity manager.
Activitymanger has backstack to perform this.


View manager does the drawing job/control or draw the views[button/combo box any control] on screeen.

Any code apart from java is called as resource.Ex. XML,photo,image,audio/video
Via Resource manager, we will access the resources


Android Application:

Package manger name should be unique.
while creating the process by android kernel, it will makes use of package name as identifier.
So no two applications should not have the same package name.




gen folder- autogenerated files are available in this folder.


Entry point for the Android application is who has action.MAIN in androidmanifest.xml
<action android:name="android.intent.action.MAIN" />
 & LAUNCHER flag.

During installation, AndroidManifest.xml is checked. if the minSDK criteria is not satisfied application wont be installed.





Android Application blocks:
==============================
   1)Activity-Single Screen
   2)BroadCastReceiver- to receive external events
   3)Service
   4)ContentProvider

Except broadcast reciever, we must register it in AndroidManifest.xml.


 Difference between actions and broadcast receivers?
 Diff service and midl service?

 Intent,action

   
Activating components:
=======================
  Intent can
    i) start an activity [startActivity(new Intent(this,NewActivity.class));]
        ii) start a service  [Context.startService() ]
        iii)can send broadcast[context.sendBroadcast() ..]

           Activity class is derived from context. So whenever context is needed, we can use Activity object or Activity's this pointer.




Shutting down components:
==========================
 
 1) ContentProviders and broadcastReceivers - No need to shut down explicitly shutdown
 2) Shutdown activity
    finish() or finitshActivity() [Parent activity will call finishActivity() of child activity]

 3)Shutdown service
    - Context.stopService() or stopSelf()
 


Lifecycle of an android application:
=======================================
    process's lifetime is not controlled by the application itself.
Android will decide when to kill or stop process.

The order of killing processes will be decided by
        1) How mportant [importance hierarchy]
        2) memory need

Importance hierarchy:
     1)Foreground process- visible to user and having focus
     2)Visible process - visible to the user but not having focus. [onPause state] Activitylaunches the dialog. Activity is visible but not focus.
     3)Service process - not visible to user. it is in running
     4)background process- not visible to the user.it is in  stopped state.
     5)Empty process - doesnt hold any acctive application components[as a cache to improve startup time]    

First android will try to kill empty proces, background process...foreground process until required memory is available.

aapt is used to construct apk file.


State of activity:
==================
1)Running -focused screen
2)Paused - visible to user but not focused
3)Stopped- not visible to user and it is in stopped state.
4)Inactive - when we finish() activity, it will goes to Inactive

Callbacks of activity:
========================
OnCreate()
onStart()
onResume()
OnPause()
OnStop()
onDestroy()
onRestart()


onPause() & onStop() will be called if activity is going to stopped state.



finish() activity will invoke
   1)onPause
   2)onStop()
   3)onDestroy()


Save your user data to persistent storage in onPause() .
Load your user data to persistent storage in onResume().


Lifecycle methods:(onPause/onResume...)

For all lifecycle methods, we should call super version of it.

  ex:
    onPause()
   {
     super.onPause()...
   }


Activity manager is responsible for handling acitivity's lifecycle.




while launching activity-> onCreate(), onStart() ,onResume()
pressed HOME button     -> OnPause(),OnStop()


UI is based on View and ViewGroup classes.

SetContentView(R.id.activity_main);

It is loading activity_main.xml file for displaying UI content.

ViewGroup->View or ViewGroup...



Through DDMS's Emulator control, we can make a call or SMS to emulator. Try it...

Layout:
  FrameLayout: pins each child view to top left corner
          --->add controls dynamically this will be used
  LinerarLayout-aligns each other in either vertical or horizontal
  Relativelayout-defines position of each view relative to others and to the screen boundaries
                 rightof, leftof,below,above
  TablelLayout - lays out view using grid of rows and columns
  Gallery -  displays single row of items in horizontal scrolling list



We have to implement onTouch or OnClick ? what is the best practice??

Android best practice is always assume that there is a keyboard.
If touch listener is not available, android will convert the touch listener to click listener.


So as a practice, we have to implement onClick().



Adding new activity:

 1) Create XML UI layout [/Res/layout/auth.xml]
 2) Create activity class & setContentView(xmlUILayout);
 3) Register the activity in Androidmanifest.xml

Wednesday, January 16, 2013

Nice Article about Improvise/adapt/overcome:
www.peakprosperity.com/blog/improvise-adapt-overcome/52001

Wednesday, December 19, 2012

How to check whether the TV remote control's battery drained or not ?
       If the battery power is good,It will emits Infra Red rays. We can't see infrared rays normally.There is a way to see
this infrared rays. How???
Place the remote control's Infra red LED facing to the mobile camera, run the mobile camera in preview mode and press the keys in remote.
See the mobile camera's preview. If the battery charge is good, Infra red LED will emits light 

Wednesday, December 12, 2012



Competition Sites:
1) ACM ICPC
2) codeforces
3) topcoder
4) codechef
5) google code jam
6) Saratov university [espl for tricky testcases]


To do:
===========
0) Study and practice
1)Always read a chapter from algorithm and do problems in book
2)Solve the related problems in contest sites
3)Solve the related problems available in all text books
4)Always choose hard problems and try to solve it...
5)Solve interview problems related with it
6) Read topcoder articles and solve problems related with it...



1) Trees
http://codeforces.com/problemset/tags/trees
2) Graphs
http://codeforces.com/problemset/tags/graphs

3) Datastructures
heaps,segment trees,BST, HashTable
http://codeforces.com/problemset/tags/data%20structures

4)Expression Parsing
http://codeforces.com/problemset/tags/expression%20parsing

5) Hashing
http://codeforces.com/problemset/tags/hashing

6) strings
http://codeforces.com/problemset/tags/strings

7) string suffix:
http://codeforces.com/problemset/tags/string%20suffix%20structeres


8) greedy
http://codeforces.com/problemset/tags/greedy
9) dynamic programming problems list:
http://codeforces.com/blog/entry/325
http://codeforces.com/problemset/tags/dp
10)Divide and conquer
http://codeforces.com/problemset/tags/divide%20and%20conquer


11) Mathematics
http://codeforces.com/problemset/tags/math
12)geometry
http://codeforces.com/problemset/tags/geometry
13) probablilities
http://codeforces.com/problemset/tags/probabilities

14) combinatorics
http://codeforces.com/problemset/tags/combinatorics

Above are from codeforces...
Below are from topcoder
15.Recursion
16.sorting
17.String manipulation/string parsing
18.Encryption and compression
19.advanced math
20. sortings..
21.maze
22.BackTracking
23.Maximum flow problem

Best resources for competition programming preparation:
http://problemclassifier.appspot.com/
http://emiraga.wikispaces.com/Problems+by+topics
https://github.com/BrockCSC/acm-icpc/wiki/Online-Resources
http://www.stanford.edu/class/cs97si/
http://webcourse.cs.technion.ac.il/234900/Spring2012/en/ho.html


Monday, December 10, 2012

What I have done and what I have learnt from comptetition problems:

From Codeforces,I solved the following problems:

1) Files list
    Previously in OS or c program, we can have 8 characters filename and 3 characters for extension.
I felt that design in this problem
   http://codeforces.com/problemset/problem/174/B

2)cd and pwd commands
http://codeforces.com/problemset/problem/158/C
 From this problem, I learnt that how we can implement cd and pwd commands in shell.
How it will remembers the user's present working directory especially the user is doing cd ..

3)BHTML & BCSS
http://codeforces.com/problemset/problem/172/E

  From this problem, I learnt that How css is applied with HTML tags. How we can highlight the tags with user's choices.

4)Simple XML
http://codeforces.com/problemset/problem/125/B

  From this problem I learnt that How XML tags can be aligned or C/C++ source code is aligned based on {} brackets in editor

5)try... catch problem
http://codeforces.com/problemset/problem/195/C

From this problem, I learnt how compilers will execute exceptions with try ... catch blocks
It is one of awesome reallife problem.

How to change android system volume Up/Down ???

    Through AudioManager, we can set the volume up/down.


Today I faced this issue while working with media-volume-control
1)http://stackoverflow.com/questions/8446337/how-to-solve-error-this-attribute-must-be-localized-at-text-with-value-top
2) R.java:10: duplicate class error
  I just removed the R.java and compilation is going smooth

3) How to copy the eclipse project into android source code and compile it ???
 copy the application project into android source code's packages/apps/ folder
within the application project,Add Android.mk with below contents:

 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 LOCAL_MODULE_TAGS := optional
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_PACKAGE_NAME := VolumeControl_S #Target package name
 include $(BUILD_PACKAGE)

 From android folder give source build/envsetup.sh,lunch and then
 cd to packages/apps/yourApplication/ and give mm command. This will build the application code & create the APK file.

Tuesday, December 04, 2012

Problems faced while compiling android application with old version to ICS/JB:

1)http://stackoverflow.com/questions/8446337/how-to-solve-error-this-attribute-must-be-localized-at-text-with-value-top

2) I got Android APK compilation Error: R.java:10: duplicate class

Solution:  I just removed the R.java file and compilation is going smooth
How to copy the eclipse Android Application project into android source code and compile it ???

 copy the application project into android source code's packages/apps/ folder
within the application project,Add Android.mk with below contents:

 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 LOCAL_MODULE_TAGS := optional
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_PACKAGE_NAME := VolumeControl_S #Target package name
 include $(BUILD_PACKAGE)

 From android folder give source build/envsetup.sh,lunch and then
 cd to packages/apps/yourApplication/ and give mm command. This will build the application code & create the APK file.

ICS features:

From ICS onwards, Android by default handles Keyboard/mouse input events... No need to do anything extra to make it work...



To know more about how to handle keyboard events/Simulate keyboard events:
 http://thecodeartist.blogspot.in/2011/03/simulating-keyevents-on-android-device.html