Search Any topic , section , query

Thursday, 25 May 2017

Senior Android Interview

 An Interview in Android  , best reply

.  Ram is a Senior Android developer , He is getting into interview round. Lets see how clearly he replies to question.

Interviewer Asked

   "Explain Bound services . How it is done."

Ram replied :
"  A bound service  provides client-server interface. A bound service is the server in a client-server interface. It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (I P C). A bound service typically lives only while it serves another application component, and does not run in the background indefinitely.

     To provide binding for a service,implement the onBind() callback method. This method returns an IBinder object  that clients can use to interact with the service.

       A client can bind to a service by calling bindService(). When it does, it must provide an implementation of  ServiceConnection, which monitors the connection with the service. The bindService() method returns immediately without a value,    but when the Android system creates the connection between the client and service, it calls onServiceConnected()    on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the service.
       Multiple clients can connect to a service simultaneously. However, the system calls your service's onBind() method to retrieve  the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind,   without calling onBind() again.     When the last client unbinds from the service, the system destroys the service, unless the service was also started by startService().

Interviewer Asked :

    " What are all different ways to define services  ibinder interface and how client recieve it and make connection. "

Ram replied :
" Different ways to define services IBinder interface and pass it to client such as Activity are ,  : first is through , Extending the Binder class , second way is through Using a Messenger Class , and third way is through Android Interface Defination Language ( A I D L ) .

 Extending the binder  class , If  service is private to  application and runs in the same process as the client ,    (which is common), then interface be created    by extending the Binder class and     returning an instance of it from onBind().

         The client receives the Binder and can use it to directly access . public methods available in either the Binder implementation , or the Service.

Using a Messenger ,If you need your service to communicate with remote  processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform interprocess communication (IPC) .In above example : , Above is a simple example service that uses a Messenger interface:

    In Above :
    1,   The service implements a Handler that receives a callback for each call from a client.
  2, The service uses the Handler to create a Messenger object (which is a reference to the Handler).
 3 , The Messenger creates an IBinder that the service returns to clients from onBind().
 4 , Clients use the IBinder to instantiate the Messenger (that references the service's Handler), which the client uses to send Message objects to the service.
 5 , The service receives each Message in its Handler—specifically, in the handleMessage() method.

   Android Interface Defination Language (A I D L) .  
    A I D L allows you to define the programming interface ,  that both the client and service agree upon in order to communicate  with each other , using interprocess communication (I P C).

On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose  their objects , into primitives that the operating system can understand, and marshall the objects across that boundary    with A I D L.

      Defining an A I D L Interface
AIDL interface is define in an .aidl file using the Java programming language syntax, then save it in the source code (in the s r c directory) of both the application , hosting the service and ,  any other application that binds to the service.
when you build your application, the SDK tools generate the IBinder interface file in your project's generate  directory.
The generated file name matches the .aidl file name, but with a .java extension ,  (for example, IRemoteService dot a i d l results in IRemoteService dot java).
     Implement the Interface

       The generated interface includes a subclass named Stub that is an abstract implementation of its parent interface (for example, YourInterface.Stub)  and declares all the methods from the .aidl file.
  Now , when a client such as an activity calls bindService()  to connect to this service , the clients onServiceConnected callback receives the m Binder instance returned by the services onBind method.

Interviewer Asked :

  " What is difference between Sticky Intent and Pending Intent and their major use cases ."

Ram replied :

  "  An intent that is used with sticky broadcast, is called as sticky intent. This intent will stick with android system for future broadcast receiver requests.

sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, that is ,  the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)

One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED.  "

 When you call registerReceiver()  for that action , even with a null BroadcastReceiver , you get the Intent that was last broadcast for that action.

Pending Intent
A PendingIntent object is a wrapper around an Intent object. The primary purpose of a PendingIntent is to grant permission to a foreign application , to  use the contained Intent ,  as if it were executed from your app's own process.

 Major use cases for a pending intent include the following:

 1. Declaring an intent to be executed when the user performs an action with your Notification
 2. Declaring an intent to be executed when the user performs an action with your App Widget
 3. Declaring an intent to be executed at a specified future time (the Android system's AlarmManager executes the Intent).

Interviewer Asked :

 " Explain how intent are resolved when starting an activity ."

 Ram replied :

  When the system receives an implicit intent to start an activity, it searches for the best activity for the intent by comparing the it to intent filters based on three aspects:
Action , 
Data (both URI and data type) 
and category.

Action Test : for example to  below given filter

To pass this filter, the action specified in the Intent must match one of the actions listed in the filter.  
However, if an Intent does not specify an action, it passes the test as long as the filter contains at least one action.

 Category test : for example to given below intent filter

  For an intent to pass the category test, every category in the Intent must match a category in the filter
 The reverse is not necessary that means the intent filter may declare more categories than are specified in the Intent and the Intent still passes.
 Therefore, an intent with no categories always passes this test, regardless of what categories are declared in the filter.

  Data Test , for example to given below problem ,

  The data test compares both the URI and the MIME type in the intent to a URI and MIME type specified in the filter. The rules are as follows:

     An intent that contains neither a URI nor a MIME type passes the test only if the filter does not specify any URIs or MIME types.
    An intent that contains a URI but no MIME type (neither explicit nor inferable from the URI) passes the test only if its URI matches the filter's URI format
    An intent that contains a MIME type but not a URI passes the test only if the filter lists the same MIME type and does not specify a URI format.
    An intent that contains both a URI and a MIME type (either explicit or inferable from the URI) passes the MIME type part of the test only   if that type matches a type listed in the filter. It passes the URI part of the test   either if its URI matches a URI in the filter or if it has a content: or file:
  Interviewer Asked :

  " How activity state are saved and restore. Explain ? "

Ram replied :

    Saving and restoring activity state .
    As your activity begins to stop, the system calls the onSaveInstanceState() method so  activity can save state information with a collection of key-value pairs.
     As show in this example


Restore your activity state

  When your activity is recreated after it was previously destroyed, you can recover your saved state from  the Bundle that the system passes to your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
  Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating  a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new  instance of the activity, instead of restoring a previous one that was destroyed. 
As shown in this example .

   Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method.
     The system calls onRestoreInstanceState() only , if there is a saved state to restore, so you do not need to check whether the Bundle is null:
Example is given below.

Interview Asked : 

  " What are launch modes in android . Explain different launch modes in android ? "

Launch modes allow you to define how a new instance of an activity is associated with the current task. You can define different launch modes in two ways:

 1.  Using the manifest file
 2. Using Intent flags

 As such, if Activity A starts Activity B, Activity B can define in its manifest how it should associate  with the current task (if at all) and Activity A can also request how Activity B should associate with current task.
 If both activities define how Activity B should associate with a task, then Activity A's request  (as defined in the intent) is honored over Activity B's request (as defined in its manifest).

. There are four different launch modes
  1."standard" (the default mode)  , : The system creates a new instance of the activity in the task .
      The activity can be instantiated multiple times, each instance can belong to different tasks, and one task can have multiple instances.

        Suppose a task's back stack consists of root activity A with activities B, C, and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. If D has the default "standard" launch mode, a new instance of the class is launched and the stack becomes A ,B ,C, D,D.   as shown in figure.
2  "singleTop"
      If an instance of the activity already exists at the top of the current task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.
The activity can be instantiated multiple times, each instance can belong to different tasks, and one task can have multiple instances (but only if the activity at the top of the back stack is not an existing instance of the activity).

    if D's launch mode is "singleTop", the existing instance of D receives the intent through onNewIntent(),  because it's at the top of the stack—the stack remains A ,B ,C ,D. However, if an intent arrives for an activity of type B, then a new instance of B is added to the stack, even if its launch mode is "singleTop"

  3 "singleTask" :
   The system creates a new task and instantiates the activity at the root of the new task.

if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance. Only one instance of the activity can exist at a time.

In the above example , as there was no instance of d , so new task is created . As in other case D instance was already in task , so same D instance gets called (onNewIntent() get called)

  4 "single instance"

       Same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance.  The activity is always the single     and only member of its task , any activities started by this one open in a separate task.  
       In the above example , as there was no instance of d , so new task is created .  As in other case , from D (Single Instance) , a new Activity E , is launched  , it will be on Seperate task .

Interviewer Asked :


Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().
This produces the same behavior as the "singleTask" launchMode value

If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity.
This produces the same behavior as the "singleTop" launchMode value,

If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()).  

Interviewer Asked :

"WHAT is Difference   between parcable and serialization "

Ram replied :

"Serialize is a standard Java interface while  Parcelable is android.os interface
   Parcel is not a general-purpose serialization mechanism, and you should never store any Parcel data on disk or send it over the network.
  Serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object, can be stored into disk and send it over network.


  Interviewer Asked :

  " Define Fragments  , what  are its lifecycle method and how it coordinate with Activity LyfeCycle ? " 

Ram replied :  
" A Fragment represents a behavior or a portion of user interface in an Activity.
       You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
       A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle

  Basic Lyfe cycle method of fragment are ,
  onCreate() : the system calls this when creating the fragment , Within this implementation  , initializating essential component of fragment , that want to retain when fragment is paused or stopped , then resumed , is done.
  onCreateView(): the system call this , when its time for the fragment to draw its user interface for the first time.
  onPause() : the system calls this method as the first indication that the user is leaving the fragment ( though it does not always mean  the fragment is being destroyed)

. Coordinating with the activity lifecycle

    The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the fragment, such that each lifecycle callback for the activity results in a similar callback for each fragment.
    For example, when the activity receives onPause(), each fragment in the activity receives onPause().

    Fragments have a few extra lifecycle callbacks

onAttach() : ,Called when the fragment has been associated with the activity (the Activity is passed in here).
onCreateView() : ,Called to create the view hierarchy associated with the fragment.
onActivityCreated() :,Called when the activity's onCreate() method has returned.
onDestroyView() : ,Called when the view hierarchy associated with the fragment is being removed.
onDetach() : ,Called when the fragment is being disassociated from the activity.

Interviewer Asked :

  .  "Explain Loader , all its call back method."

Ram replied :
" The Loader API lets you load data from a content provider or other data source for display in an Activity or Fragment.
     Loaders solve these problems and includes other benefits. For example:
     Loaders run on separate threads to prevent janky or unresponsive UI.
     Loaders simplify thread management by providing callback methods when events occur.
     Loaders persist and cache results across configuration changes to prevent duplicate queries.
     Loaders can implement an observer to monitor for changes in the underlying data source. For example, CursorLoader automatically registers a ContentObserver to trigger a reload when data changes.
Starting a Loader
getLoaderManager().initLoader(0, null, this);
  here , 0 is  A unique ID that identifies the loader. In this example, the ID is 0.
   null is Optional arguments to supply to the loader at construction (null in this example).
   this is   A LoaderManager.LoaderCallbacks
   Restarting a loader
Restarting a Loader
 getLoaderManager().restartLoader(0, null, this);

 LoaderManager.LoaderCallbacks includes these methods:
        onCreateLoader() — Instantiate and return a new Loader for the given ID.
        onLoadFinished() — Called when a previously created loader has finished its load.
        onLoaderReset() — Called when a previously created loader is being reset, thus making its data unavailable.

Interviewer Asked :

  " Explain Content provider , how you can access  data through provider and also explain  insertion , deletion and updation through provider. "

Ram replied :
"Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps.
        content provider to allow other applications to securely access and modify your app data.

Accessing data , to access data in a content provider, you use the ContentResolver object in your application's Context  to communicate with the provider as a client.
        below is example is given.

 . Inserting , Updating and deleting data
      To insert data into a provider, you call the ContentResolver.insert() method.
 example is given below

 .the method used for updating is  ContentResolver.update() method.
 example is given below

 . the method used for deleting is ContentResolver.delete() method.
 example is given below

Interviewer Asked :

" what are all different methods of content provider."

Ram replied :

    " Different methods of content provider are :

        query() : Retrieve data from your provider. Use the arguments to select the table to query, the rows  and columns to return, and the sort order of the result. Return the data as a Cursor object.

        insert() : Insert a new row into your provider. Use the arguments to select the destination table and  to get the column values to use. Return a content URI for the newly-inserted row.

       update()  : Update existing rows in your provider. Use the arguments to select the table and rows to update and to get the updated column values. Return the number of rows updated.

       delete()  : Delete rows from your provider. Use the arguments to select the table  and the rows to delete. Return the number of rows deleted.

      getType() : Return the MIME type corresponding to a content URI. This method is described in more detail in the section Implementing Content Provider MIME Types.

    onCreate() : Initialize your provider. The Android system calls this method immediately after it creates your provider. Notice that your provider is not created until a ContentResolver object tries to access it.


Interviewer Asked :

   "what are all different storage options in android ?"

Ram replied :

"Different storage options are :
      Shared Preferences  : Store private primitive data in key-value pairs. below is example.
     Internal Storage   : Store private data on the device memory.  above is example
     Network Connection  : Store data on the web with your own network server.
.  External Storage : Store public data on the shared external storage.
 example for saving image in sd is given

 Sql Lite Database : stored structured data in a private database.

 saving catche files :
   If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

To open a file that represents the external storage directory where you should save catche files , call  getExternalCatcheDir() . If the user  uninstalls your application , these files will be automatically deleted.

Interviewer Asked :
     " Explain Android backup framework and how they interact with apps that support Auto Backup and Key Value Backup. "

Ram replied :

      Android provides two ways for apps to backup their data to the cloud:

 Auto Backup for Apps and Key/Value Backup.

  Auto Backup  preserves app data by uploading it to the user's Google Drive account.
  The Key/Value Backup  preserves app data by uploading it to the Android Backup Service.

 The backup manager service is an android system service , which arrange and initiates backup and restore operations. The service is accessible  through  the backup manager api.

 During a backup operation, the service queries your app for backup data, then hands it to the backup transport, which then archives the data.
During a restore operation, the backup manager service retrieves the backup data from the backup transport and restores the data to the device.

        Backup Transports are Android components that are responsible for storing and retrieving backups.

        The available backup transports may differ from device to device , but most Google Play enabled devices ship with the following transports:

        Google Transport(default) : , This transport stores Auto Backup data in a private folder in the user's Google Drive account. Key/Value Backup data is stored in the Android Backup Service.
        Local Transport - stores backup data locally on the device. This transport is typically used for development/debugging purposes and is not useful in the real world.

Interviewer Asked :

"   Explain Auto back up and key value backup thoroughly ."

Ram replied :

  "   Auto Backup for Apps
          Auto Backup preserves app data by uploading it to the user's Google Drive account, where it is protected by the user's Google account credentials.

         Files that are backed up
Auto Backup includes files in most of the directories that are assigned to your app by the system:

   Shared preferences files.
             Files in the directory returned by getFilesDir().
             Files in the directory returned by getDatabasePath(String), which also includes files created with the SQLiteOpenHelper class.
             Files in directories created with getDir(String, int).
             Files on external storage in the directory returned by getExternalFilesDir(String).

Auto Backup excludes files in directories returned by getCacheDir(), getCodeCacheDir(), or getNoBackupFilesDir().

      Enabling and disabling Auto backup
        The android:allowBackup attribute, which enables/disables backup, defaults to true if omitted, below is example .

Including and excluding files
By default, the system backs up almost all app data
custom XML rules to control what gets backed up.

1. In AndroidManifest.xml, add the android:fullBackupContent attribute to the <application> element. This attribute points to an XML file that contains backup rules. For example:

2: Create an XML file called my_backup_rules.xml in the res/xml/ directory. Inside the file, add rules with the <include> and <exclude> elements. The following sample backs up all shared preferences except device.xml , below is example .


 Key Value backup
        To backup  application data,  backup agent need to implement . Your backup agent is called by the Backup Manager both during backup and restore.

       To implement a backup agent, you must:
       first ,  Declare your backup agent in your manifest file with the android:backupAgent attribute.
second , Register your application with Android Backup Service
  third , Define a backup agent by either:

         Extending BackupAgent , or Extending BackupAgentHelper

      Declaring the backup agent in your manifest
         example is given below

        Registering for Android Backup Service
         To perform backup using Android Backup Service , application  must be registered with the service  to receive a Backup Service Key, then declare the Backup Service Key in your Android manifest.
  example is given below.
  Extending the backup agent .
    create a backup agent by extending BackupAgent,  and implement the following callback methods:

         The Backup Manager calls this method after you request a backup. In this method, you read your application data from the device and pass the data you want to back up to the Backup Manager.

         The Backup Manager calls this method during a restore operation. When it calls this method, the Backup Manager delivers your backup data, which you then restore to the device.

Interviewer Asked :

    " Explain Alarm Manager , its characterstics  and how it is implemented . "

Ram replied : 

 " The Alarm Manager is intended for cases where you want to have your application code run at a specific time,  even if your application is not currently running.
    For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

    Alarms have these characteristics:

They let you fire Intents at set times and/or intervals.
You can use them in conjunction with broadcast receivers to start services and perform                          other operations.

             They operate outside of your application, so you can use them to trigger events or actions                    even   when your app is not running,and even if the device itself is asleep.

              They help you to minimize your app's resource requirements.

            You can schedule operations without relying on timers or continuously running background                services.

  example of how to use alarm manager is given below.

Interviewer Asked :

." Explain in detail Bluetooth Functionality and how to connect and transfer data over two devices."

Ram replied :
" Application framework provides access to the Bluetooth functionality (  which allows a device to wirelessly exchange data with other Bluetooth devices) through the Android Bluetooth APIs.

Using the Bluetooth APIs,

  1.Scan for other Bluetooth devices
 2.  Query the local Bluetooth adapter for paired Bluetooth devices
  3 . Establish RFCOMM channels
4. Connect to other devices through service discovery
  5 . Transfer data to and from other devices
 6. Manage multiple connections
    In order for Bluetooth-enabled devices to transmit data between each other, they must first form a channel of   communication using a pairing process.
     One device, a discoverable device, makes itself available for incoming  connection requests.

Another device finds the discoverable device using a service discovery process.
     After the discoverable device accepts the pairing request, the two devices complete a bonding process  where they exchange security keys.

The devices cache these keys for later use.

After the pairing and   bonding processes are complete, the two devices exchange information.

 . Here is a complete example
      step 1: Declare bluetooth permission in your application manifest
     example given below :

         step 2:   Setting up bluetooth
                1.  Getting the Bluetooth Adapter
                 The bluetooth adapter is required for any and all bluetooth activity
 To get all the Bluetooth Adapter call the static get Default Adapter method.
  example is given below.

        2 ,   to ensure that Bluetooth is enabled. Call isEnabled() to check whether Bluetooth is currently enabled


 To make  Bluetooth enabled, call startActivityForResult(), passing in an ACTION_REQUEST_ENABLE intent action.
      A dialog will appear requesting user permission to enable Bluetooth
        step 3:

       Finding Devices

Using the BluetoothAdapter, you can find remote Bluetooth devices either through device discovery or by querying the list of paired devices.
Before performing device discovery,   check  before  whether devices all  already paired or not
example is given below .


To start discovering devices, simply call startDiscovery()
      Below is example .
  In order to receive information about each device discovered,  application must register a BroadcastReceiver for the ACTION_FOUND intent.
       Given below code showing  how information is retrieves in reciver .

  Connecting devices
            In order to create a connection between two devices, you must implement both the server-side and client-side mechanisms because one device must open a server socket, and the other one must initiate the connection using the server device's MAC address.

   The server and client are considered connected to each other when they each have a connected BluetoothSocket on the same RFCOMM channel.

     Now , Connecting as a server.
     When you want to connect two devices, one must act as a server by holding an open BluetoothServerSocket. The purpose of the server  socket is to listen for incoming connection  requests and provide a connected BluetoothSocket after a request is accepted.

      To set up a server socket and accept a connection,  these 3 steps followed :

     step first , Get a BluetoothServerSocket by calling listenUsingRfcommWithServiceRecord().
     step two,  Start listening for connection requests by calling accept().
     step three , Unless you want to accept additional connections, call close().

 Example , this thread is for the server component that accepts incoming connection.

. Now , Connecting as a client

   In order to initiate a connection with a remote device that is accepting connections on an open server socket, you must first obtain a BluetoothDevice object that represents the remote device.
then  Using the BluetoothDevice, get a BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID).

    and then Initiate the connection by calling connect().

. Example given below for connecting as client

      Step 5 .     Managing the connection 

      After you have successfully connected multiple devices, each one has a connected BluetoothSocket.

             Step first , Get the InputStream and OutputStream that handle transmissions through the                                 socket using getInputStream() and getOutputStream(), respectively.

             Step two ,  Read and write data to the streams using read(byte[]) and write(byte[]).

       Here's an example of how you can transfer data between two devices connected over Bluetooth:



  1. This was a really wonderful post. Thank you for providing.
    Watch online cricket on CricHD

  2. Thanks a lot for sharing such a good source with all, i appreciate your efforts taken for the same. I found this worth sharing and must share this with all.

    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

  3. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.