Wednesday, 6 March 2013


1. Describe Architecture of Android 
A.

Linux Kernel Core services (including hardware drivers, process and memory management,
Security, network, and power management) are handled by a Linux 2.6 kernel. The kernel also
Provides an abstraction layer between the hardware and the remainder of the stack.
Libraries running on top of the kernel, Android includes various C/C++ core libraries such
as libc and SSL, as well as:
❑ A media library for playback of audio and video media
❑ A Surface manager to provide display management
❑ Graphics libraries that include SGL and OpenGL for 2D and 3D graphics
❑ SQLite for native database support
❑ SSL and Web Kit for integrated web browser and Internet security
Android Run Time What makes an Android phone an Android phone rather than a mobile
Linux implementation is the Android run time. Including the core libraries and the Dalvik virtual
machine, the Android run time is the engine that powers your applications and, along with
the libraries, forms the basis for the application framework.
Dalvik Virtual Machine Dalvik is a register-based virtual machine that’s been optimized
to ensure that a device can run multiple instances efficiently. It relies on the
Linux kernel for threading and low-level memory management.
Application Framework The application framework provides the classes used to create
Android applications. It also provides a generic abstraction for hardware access and manages
the user interface and application resources.
Application Layer All applications, both native and third party, are built on the application
layer using the same API libraries. The application layer runs within the Android run time
using the classes and services made available from the application framework

2. What is the role of Dalvik Virtual machine? 
A.Dalvik Virtual Machine plays a key role in android app. Development, Rather than use a traditional Java virtual machine (VM) such as Java ME (Java Mobile Edition), Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device.
     The Dalvik VM executes Dalvik executable files, a format optimized to ensure minimal memory footprint. The .dex executables are created by transforming Java language compiled classes using the tools supplied within the SDK.

3. What is the view hierarchy of Android? 
A. View: Views are the basic User Interface class for visual interface elements (commonly known as controls or widgets). All User Interface controls, and the layout classes, are derived from Views.

ViewGroups: View Groups are extensions of the View class that can contain multiple child
Views. By extending the ViewGroup class, you can create compound controls that are made up
of interconnected child Views. The ViewGroup class is also extended to provide the layout managers,
Such as LinearLayout, that helps you compose User Interfaces.





5. Describe Activity. How do you create a activity. 
A. To create user-interface screens for your applications, you extend the Activity class, using Views to provide user interaction. 
Each Activity represents a screen (similar to the concept of a Form in desktop development) that an application can present to its users. The more complicated your application, the more screens you are likely to need. 

Creating an Activity:

To create a new Activity, you extend the Activity class, defining the user interface and implementing your functionality.

Sample code:

public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate (icicle);
}
}

6. What is the importance of Android Manifest file? 
A. Each Android project includes a manifest file, AndroidManifest.xml, stored in the root of the project hierarchy. The manifest lets you define the structure and metadata of your application and its components.

It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast Receivers) that make up your application and, using Intent Filters and Permissions, determines how they interact with each other and other applications.
It also offers attributes to specify application metadata (like its icon or theme), and additional top-level nodes can be used for security settings and unit tests as described below.

<manifest xmlns:android=http://schemas.android.com/apk/res/android
       package=”com.my_domain.my_app”>
          [ ... manifest nodes ... ]
</manifest>

7. What is Intent? Describe Intent filters
A. Intents are used as a message-passing mechanism that lets you declare your intention that an action be performed, usually with (or on) a particular piece of data.

Intent Filters:

Intent Filters are used to register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data.

Using the following tags (and associated attributes) within the Intent Filter node, you can specify a component’s supported actions, categories, and data:
      Action: Use the android: name attribute to specify the name of the action being serviced.

      category :Use the android: category attribute to specify under which circumstances
         Each Intent Filter tag can include multiple category tags some of them are
    ALTERNATIVE: The alternative category specifies that this action should   be available as an alternative to the default                                                                    action  performed on an

    SELECTED_ALTERNATIVE: SELECTED_ALTERNATIVE is used when a list of possibilities is required.
BROWSABLE Specifies an action available from within the browser            

DEFAULT Set this to make a component the default action for the data values defi ned
by the Intent Filter. This is also necessary for Activities that are launched using an
explicit Intent.
GADGET By setting the gadget category, you specify that this Activity can run embedded
inside another Activity.
HOME The home Activity is the fi rst Activity displayed when the device starts (the
launch screen). By setting an Intent Filter category as home without specifying an
action, you are presenting it as an alternative to the native home screen.
LAUNCHER :using this category makes an Activity appear in the application launcher.

data The <data> tag lets you specify matches for data your component can act on; you can
include several schemata if your component is capable of handling more than one. You can
use any combination of the following attributes to specify the data that your component
supports:
❑ android:host Specifi es a valid host name (e.g., com.google).
❑ android:mimetype Lets you specify the type of data your component is capable of
handling. For example, <type android:value=”vnd.android.cursor.dir/*”/>
would match any Android cursor.
❑ android:path Valid “path” values for the URI (e.g., /transport/boats/)
❑ android:port Valid ports for the specifi ed host
❑ android:scheme Requires a particular scheme (e.g., content or http).

The following code snippet shows how to confi gure an Intent Filter for an Activity

<activity android:name=”.”
android:label=”          ”>
<intent-filter>
<action
android:name=”   ”>
</action>
<category android:name=”android.intent.category.DEFAULT”/>
<category
android:name=”android.intent.category.ALTERNATIVE_SELECTED”
/>
<data android:mimeType=”    /*”/>
</intent-filter>
</activity> 


9. Describe life cycle of an activity.  

A. Activity lifecycle :

An activity has essentially three states:
      It is active or running when it is in the foreground of the screen (at the top of the activity stack for the current task). This is the activity that is the focus for the user's actions.
      It is paused if it has lost focus but is still visible to the user. That is, another activity lies on top of it and that activity either is transparent or doesn't cover the full screen, so some of the paused activity can show through. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
      It is stopped if it is completely obscured by another activity. It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

As an activity transitions from state to state, it is notified of the change by calls to the following protected methods:
void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

10. What is a service? Write a sample code to declare and use a service 
A       Services are designed to run in the background, so they need to be started, stopped, and controlled by other application components.

To define a Service, create a new class that extends the Service base class. You’ll need to override onBind and onCreate, as shown in the following skeleton class:

    public class MyService extends Service {
   @Override
   public void onCreate() {
   }
  @Override
   public IBinder onBind(Intent intent) {
  // TODO: Replace with service binding implementation.
   return null;
}
}
In most cases, you’ll also want to override onStart.
The snippet below shows the skeleton code for overriding the onStart method:

@Override
Public void onStart (Intent intent, int startId) {
// TODO: Actions to perform when service is started.
}
Once you’ve constructed a new Service, you have to register it in the application 
<service android: enabled=”true” android: name=”.MyService”></service> 
// Implicitly start a Service
startService (new Intent(MyService.MY_ACTION));
// Explicitly start a Service
startService (new Intent(this, MyService.class));
  
11. Describe the life cycle of a service

A. Service lifecycle :

A service can be used in two ways:
      It can be started and allowed to run until someone stops it or it stops itself. In this mode, it's started by calling Context. StartService() and stopped by calling Context.stopService(). It can stop itself by calling Service.stopSelf() or Service.stopSelfResult(). Only one stopService() call is needed to stop the service, no matter how many times startService() was called.
      It can be operated programmatically using an interface that it defines and exports. Clients establish a connection to the Service object and use that connection to call into the service. The connection is established by calling Context.bindService(), and is closed by calling Context.unbindService(). Multiple clients can bind to the same service. If the service has not already been launched, bindService() can optionally launch it.

      Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewer than the activity methods — only three — and they are public, not protected:
      void onCreate()
void onStart(Intent intent)
void onDestroy()

If a service permits others to bind to it, there are additional callback methods for it to implement:
IBinder onBind(Intent intent)
boolean onUnbind(Intent intent)
void onRebind(Intent intent)

Service Life-Cycle Diagram;


12 What is a broadcast receiver? Write a sample code to declare and use a broadcast receiver?
A        Broadcast Receivers is a mechanism to listen for Broadcast Intents. To enable a Broadcast Receiver, it needs to be registered, either in code or within the application manifest.
BroadcastReceiver is a class given in  android.content.BroadcastReceiver;

To create a new Broadcast Receiver, extend the BroadcastReceiver class and override the onReceive

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
Public void onReceive (Context context, Intent intent) {
          }
}

The following code snippet shows how to register a Broadcast Receiver using an IntentFilter:

// Create and register the broadcast receiver.
IntentFilter filter = new IntentFilter(NEW_LIFEFORM_DETECTED);
LifeformDetectedBroadcastReceiver r = new LifeformDetectedBroadcastReceiver();
registerReceiver(r, filter);

To unregister a Broadcast Receiver, use the unregisterReceiver method on your application context,
passing in a Broadcast Receiver instance, as shown below:
unregisterReceiver(r);

Registering Broadcast Receivers in Your Application Manifest:

To include a Broadcast Receiver in the application manifest, add a receiver tag within the application node specifying the class name of the Broadcast Receiver to register.

<receiver android:name=”.LifeformDetectedBroadcastReceiver”>
<intent-filter>
<action android:name=”com.paad.action.NEW_LIFEFORM”/>
</intent-filter>
</receiver>


13. Life cycle of a broadcast receives. 

A. Broadcast receiver lifecycle :

A broadcast receiver has single callback method:
void onReceive(Context curContext, Intent broadcastMsg)
When a broadcast message arrives for the receiver, Android calls its onReceive() method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive () returns, it is inactive.
There are five levels in the hierarchy. The following list presents them in order of importance:
1         A foreground process is one that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions hold:
    It is running an activity that the user is interacting with (the Activity object's onResume() method has been called).
    It hosts a service that's bound to the activity that the user is interacting with.
    It has a Service object that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
    It has a BroadcastReceiver object that's executing its onReceive() method.

   2.  A visible process is one that doesn't have any foreground components, but still can affect             what the user sees on screen. A process is considered to be visible if either of the following conditions holds:
      It hosts an activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to be seen behind it.
      It hosts a service that's bound to a visible activity.
3.A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.
4.A service process is one that is running a service that has been started with the startService()
5.A background process is one holding an activity that's not currently visible to the user (the Activity object's onStop()method has been called)
An empty process is one that doesn't hold any active application components

14. Describe in detail the different layouts. 
A. The Android SDK includes some simple layouts to help you construct your UI. It’s up to you to select
the right combination of layouts to make your interface easy to understand and use.
The following list includes some of the more versatile layout classes available:
FrameLayout The simplest of the Layout Managers, the Frame Layout simply pins each child
view to the top left corner. Adding multiple children stacks each new child on top of the previous,
with each new View obscuring the last.
LinearLayout A Linear Layout adds each child View in a straight line, either vertically or horizontally.
A vertical layout has one child View per row, while a horizontal layout has a single row
of Views. The Linear Layout Manager allows you to specify a “weight” for each child View that
controls the relative size of each within the available space.
Relative Layout Using the Relative Layout, you can defi ne the positions of each of the child
Views relative to each other and the screen boundaries.
Table Layout The Table Layout lets you lay out Views using a grid of rows and columns. Tables
can span multiple rows and columns, and columns can be set to shrink or grow.
Absolute Layout In an Absolute Layout, each child View’s position is defi ned in absolute coordinates. Using this class, you can guarantee the exact layout of your components, but at a price. Compared to the previous managers, describing a layout in absolute terms means that your layout can’t dynamically adjust for different screen resolutions and orientations.

15. Describe in detail the process of binding data to a view using adapter.  
A. Using Adapters for Data Binding
To apply an Adapter to an AdapterView-derived class, you call the View’s setAdapter method, passing in an Adapter instance, as shown in the snippet below:

Array List<String> myStringArray = new ArrayList<String>();
ArrayAdapter<String> myAdapterInstance;
int layoutID = android.R.layout.simple_list_item_1;
myAdapterInstance = new ArrayAdapter<String>(this, layoutID,
myListView.setAdapter(myAdapterInstance);

16. Describe in detail shared preferences. Write code snippet to declare a shared preference, and how to assign values and get values from shared preferences. 
A. shared preferences are a light-weight mechanism to store ui-states, user preferences, or application settings. In the form of key/value pairs of primitive data as named preferences.

To create or modify a Shared Preference, call getSharedPreferences on the application Context, passing in the name of the Shared Preferences to change. Shared Preferences are shared across an application’s components but aren’t available to other applications.

public static final String MYPREFS = “mySharedPreferences”;
protected void savePreferences(){
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);
// Commit the changes.
editor.commit();
}

17. What is the role of permissions and describe in detail the permissions in android. 

A. Permissions in android:

A permission is a restriction limiting access to a part of the code or to data on the device. The limitation is imposed to protect critical data and code that could be misused to distort or damage the user experience.
Each permission is identified by a unique label. Often the label indicates the action that's restricted. For example, here are some permissions defined by Android:

android.permission.CALL_EMERGENCY_NUMBERS
android.permission.READ_OWNER_DATA
android.permission.SET_WALLPAPER
android.permission.DEVICE_POWER
If an application needs access to a feature protected by a permission, it must declare that it requires that permission with a <uses-permission> element in the manifest.

A new permission is declared with the <permission> element. For example, an activity could be protected as follows:
<manifest . . . >
    <permission android:name="com.example.project.DEBIT_ACCT" . . . />
    . . .
    <application . . .>
        <activity android:name="com.example.project.FreneticActivity"
                  android:permission="com.example.project.DEBIT_ACCT"
                  . . . >
            . . .
        </activity>
    </application>
    . . .
    <uses-permission android:name="com.example.project.DEBIT_ACCT" />
    . . .
</manifest>

18. Describe in detail the media player class in android. 
A. Multimedia playback in Android is handled by the MediaPlayer class. You can play back media stored
as application resources, local files, or from a network URI.
To play a media resource, create a new Media Player instance, and assign it a media source to play
using the setDataSource method. Before you can start playback, you need to call prepare, as shown below,


String MEDIA_FILE_PATH = Settings.System.DEFAULT_RINGTONE_URI.toString();
MediaPlayer mpFile = new MediaPlayer();
try {
mpFile.setDataSource(MEDIA_FILE_PATH);
mpFile.prepare();
mpFile.start();
}
catch (IllegalArgumentException e) {}
catch (IllegalStateException e) {}
catch (IOException e) {}

Alternatively, the static create methods work as shortcuts, accepting media resources as a parameter and
preparing them for playback, as shown in the following example, which plays back an application resource:
MediaPlayer mpRes = MediaPlayer.create(context, R.raw.my_sound);
Once a Media Player is prepared, call start as shown below to begin playback of the associated
media resource.
mpRes.start();
mpFile.start();
Once you’ve fi nished with the Media Player, be sure to call release to free the associated resources, as
shown below:
mpRes.release();
mpFile.release();

19. What is ADT in Eclipse.  
A. Using Eclipse with the ADT plug-in for your Android development offers some signifi cant advantages.
Eclipse is an open source IDE (integrated development environment) particularly popular for Java development. It’s available to download for each of the development platforms supported by Android (Windows, Mac OS, and Linux) from the Eclipse foundation homepage.

            The ADT plug-in for Eclipse simplifies your Android development by integrating the developer tools, including the emulator and .class-to-.dex converter, directly into the IDE. While you don’t have to use the ADT plug-in, it does make creating, testing, and debugging your applications faster and easier.

20. Describe in detail the installation procedure of android SDK and eclipse. 

A. After downloading the zip file of android-sdk-windows file, unpack the Android SDK archive to a suitable location on your machine. By default, the SDK files are unpacked into a directory named android-sdk-<machine-platform>. Make a note of the name and location of the unpacked SDK directory on your system — you will need to refer to the SDK directory later, when setting up the ADT plugin or when using the SDK tools.

Adding tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory.
      On Linux, edit your ~/.bash profile or ~/.bashrc file. Look for a line that sets the PATH environment variable and add the full path to the tools/ directory to it. If you don't see a line setting the path, you can add one:
export PATH=${PATH}:<your_sdk_dir>/tools
      On a Mac OS X, look in your home directory for .bash profile and proceed as for Linux. You can create the .bash profile if you haven't already set one up on your machine.
      On Windows, right-click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path (under System Variables). Add the full path to the tools/ directory to the path.
21 What is ADB and why is it used ? 
A. The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. It’s made up of three components: a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service.

22.difference between handler and AsyncTask in Android ?
A. 

  • The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
  • AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
It is better to use an async task to load a listview so you dont block the main UI

23. what is AsyncTask in android ??
A. AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor and FutureTask.
When an asynchronous task is executed, the task goes through 4 steps:
  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.


More Questions on java and android:

1. Difference between activity and activity manager ?

2. Collections : Difference
a. hashmap and hashset
b. ArrayList and Vector
c. List and Set

3.Collection Frameworks?

4.What SYSTEM.OUT.PRINTLN means ?

5. Broadcastreceiver types and there differences?

6. Services?

7. types of database and there uses in android application. Meaning how to use them ?

8. Types of intent ?

9. Fragments ?

10. on Tab widgets ?

11. why java does not support multi-inheritance concepts ?

12. Write a snipnet for alarm and notification manager.

13. write a snippet for Thread and instead of run(), if I use ran() what exception it will throw ?

14. Exceptions in java. What is finally() and when it will be used ? What happen if we get exception, does it stops or prints next system.out.println statement ?

15. Regarding version code and version name android manifest

16. Difference between MaxSDKVersion and TargetSDKVersion

17. Difference between AsyncTask and Handler

18. Java Factory Method and Race Condition